<template>
  <SysDialog
    :visible="dialog.visible"
    v-bind="getBindValue"
    @onClose="clearClose"
    @onConfirm="confirm"
  >
    <template #content>
      <div
        v-loadings="baseData.loading"
        class="customerfeeset-content"
      >
        <el-form
          ref="ruleFormFeeBasicDataRef"
          :inline="true"
          :model="customerFeeSetParams.feeBasicData"
          class="fesset-from"
        >
          <el-form-item
            label="产品名称："
            style="min-width: 135px;"
          >
            <div class="single-line">
              {{ baseData.baseFeeset.productName }}
            </div>
          </el-form-item>
          <template
            v-for="schema in schemasFormFeeset"
            :key="schema.field"
          >
            <el-form-item
              :prop="schema.field"
              :label-width="schema.labelWidth"
              :label="schema.label"
              :rules="ruleFormFeeBasicData[schema.field]"
            >
              <el-input
                v-model="customerFeeSetParams.feeBasicData[schema.field]"
                oninput="value = value.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')"
                v-bind="schema"
                :style="{ minWidth: schema.minWidth ? schema.minWidth + 'px' : '', width: schema.width ? schema.width + 'px' : '' }"
              />
            </el-form-item>
          </template>
          <!-- <el-form-item
            label="大货起始重量："
            style="width: 175px;"
          >
            <el-input
              v-model="customerFeeSetParams.feeBasicData.bigGoodsBeginWeight"
              v-clear-only-regex="/^\d*\.?\d{0,3}$/"
            />
          </el-form-item> -->
          <el-form-item 
            label="大货比价类型："
            style="width: 210px;"
          >
            <BaseSelect
              v-model:modelValue="customerFeeSetParams.feeBasicData.compareType"
              :options="compareTypeList"
              clearable
            />
          </el-form-item>
          <el-form-item 
            label="比对费用："
            class="item-feeItemIdList"
          >
            <BaseSelect
              v-model:modelValue="customerFeeSetParams.feeBasicData.feeItemIdList"
              :options="oldFeeItemList"
              :fields-obj="{ valueField: 'id', labelField: 'itemName' }"
              :collapse-tags="true"
              :multiple="true"
              :clearable="true"
            />
          </el-form-item>
          <el-form-item 
            label="是否计抛："
            prop="lightFlag"
            class="item-formItem168"
            :rules="getLightFlagRule"
          >
            <BaseSelect
              v-model:modelValue="customerFeeSetParams.feeBasicData.lightFlag"
              :options="baseData.lightFlagList"
              :clearable="false"
              :filterable="false"
            />
          </el-form-item>
          <!-- label="计抛系数：" -->
          <el-form-item
            class="item-formItem168"
          >
            <div class="flex">
              <BaseSelect
                v-model:modelValue="baseData.remoteFlag"
                class="remote-survey-type"
                :clearable="false"
                :filterable="false"
                :options="remoteSurveyTypeList"
                @change="changeRemoteFlag"
              />
              <el-input
                v-model="baseData.weightRateModelList[baseData.remoteFlagIndex].weightRatio"
                v-clear-only-regex="/^\d*\.?\d{0,3}$/"
                class="flex-1"
              />
            </div>
          </el-form-item>
          <el-form-item 
            label="计费货币："
            class="item-formItem180"
          >
            <BaseSelect
              v-model:modelValue="customerFeeSetParams.feeBasicData.currencyCode"
              :options="currencyList"
              :clearable="false"
              :filterable="true"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="cursor"
              @click="hanleOpenOneVote"
            >
              更多设置
              <el-icon>
                <Setting />
              </el-icon>
            </div>
          </el-form-item>
        </el-form>
        <div class="table-warp">
          <div class="title">
            费用设置
            <el-tooltip
              effect="dark"
              content="点击单行唤醒编辑表格"
              placement="top-start"
            >
              <el-button
                :icon="QuestionFilled"
                link
              />
            </el-tooltip>
          </div>
          <!-- 动态-费用表单 -->
          <VxeBasicTable
            v-bind="feesetSetingGridOptions"
            ref="ruleFormFeesetSetingTableRef"
            @cell-click="hanleCellClick"
          >
            <!-- 费用类型 -->
            <template #default_feeItemId="{ row }">
              {{ feeItemFindName(row.feeItemId, feeItemLists) }}
            </template>
            <template #edit_feeItemId="scope">
              <div v-if="scope.row.feeItemId">
                <el-select
                  v-model="scope.row.feeItemId"
                  filterable
                  @visible-change="hanleRowDblclick($event, scope.row)"
                >
                  <el-option
                    v-for="item in filterOnFeeItemList(scope.row.feeItemId)"
                    :key="item.id"
                    :label="item.itemName"
                    :value="item.id"
                  />
                </el-select>
              </div>
              <div v-else>
                <el-select
                  v-model="scope.row.feeItemId"
                  filterable
                  @change="() => { hanleChangeFeeItem(scope.row, feeItemLists); updateStatus(scope); }"
                >
                  <el-option
                    v-for="item in newFeeItemList"
                    :key="item.id"
                    :label="item.itemName"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </template>
            <!-- 计量单位 -->
            <!-- <template #default_originalCalculateUnit="{ row }">
              {{ deal_FindItemName(row.originalCalculateUnit, calculateUnitList) }}
            </template>
            <template #edit_originalCalculateUnit="scope">
              <el-select v-model="scope.row.originalCalculateUnit" @change="updateStatus(scope)">
                <el-option v-for="item in calculateUnitList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template> -->
            <!-- 算法 -->
            <template #default_countModel="{ row }">
              {{ deal_FindItemName(row.countModel.countType, countTypeList) }}
            </template>
            <template #edit_countModel="scope">
              <el-select
                v-model="scope.row.countModel.countType"
                @change="updateStatus(scope)"
              >
                <el-option
                  v-for="item in countTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @click="hanleBlurCalculator(scope.row)"
                />
              </el-select>
            </template>
            <!-- 计算优先级 -->
            <template #edit_countOrderNumber="scope">
              <el-input
                v-model="scope.row.countOrderNumber"
                v-clear-only-regex="/^\d*\.?\d{0,0}$/"
                @change="updateStatus(scope)"
              />
            </template>
            <!-- 费用 -->
            <template #edit_offerPrice="scope">
              <el-input
                v-model="scope.row.offerPrice"
                v-clear-only-regex="/^\d*\.?\d{0,3}$/"
                @change="updateStatus(scope)"
              />
            </template>
            <!-- 最低折扣 -->
            <template #edit_discount="scope">
              <el-input
                v-model="scope.row.discount"
                v-clear-only-regex="/^\d*\.?\d{0,0}$/"
                @change="updateStatus(scope)"
              />
            </template>
            <!-- 币种 -->
            <template #default_currencyCode="{ row }">
              {{ deal_FindItemName(row.currencyCode, currencyList) }}
            </template>
            <template #edit_currencyCode="scope">
              <el-select
                v-model="scope.row.currencyCode"
                filterable
                @change="updateStatus(scope)"
              >
                <el-option
                  v-for="item in currencyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
            <!-- 取值类型 -->
            <template #default_feeItemGetType="{ row }">
              {{ deal_FindItemName(row.feeItemGetType, feeItemGetTypeList) }}
            </template>
            <template #edit_feeItemGetType="scope">
              <el-select
                v-model="scope.row.feeItemGetType"
                filterable
                @change="updateStatus(scope)"
              >
                <el-option
                  v-for="item in feeItemGetTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
            <!-- 操作 -->
            <template #header_actions>
              <el-button
                class="add-columns"
                type="primary"
                :icon="Plus"
                link
                @click="hanleFeesetTableAdd"
              />
            </template>
            <template #default_actions="scope">
              <template v-if="isActiveStatus(scope.row)">
                <el-button
                  class="add-columns"
                  type="primary"
                  :icon="Select"
                  link
                  @click="cancelRowEvent(scope.row)"
                />
              </template>
              <template v-else>
                <el-button
                  class="add-columns"
                  type="danger"
                  :icon="SemiSelect"
                  link
                  @click="hanleFeesetTableDelete(scope)"
                />
              </template>
            </template>
            <!-- 备注 -->
            <template #edit_remark="scope">
              <el-input
                v-model="scope.row.remark"
              />
            </template>
          </VxeBasicTable>
        </div>
        <div class="table-warp2">
          <div class="title flex align-center">
            <div>
              费用明细设置
            </div>
            <div class="flex align-center pl-20">
              <span class="pl-20">包装类型：</span>
              <el-select
                v-model="baseData.packageType"
                class="m-2"
                placeholder="包装类型"
                @change="hanleChangePackageType"
              >
                <el-option
                  v-for="item in packageTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="pl-20">
              费用类型: {{ baseData.feeItemRow?.itemName || '' }}
            </div>
            <div class="pl-20">
              <el-button @click="hanleExportExpense">
                快速导入
              </el-button>
            </div>
            <div class="flex-1 flex justify-end align-center">
              <div>分区管理:</div>
              <div class="pl-20">
                <el-select
                  v-model="baseData.zoningType"
                  class="m-2"
                  placeholder="分区操作"
                >
                  <el-option
                    v-for="item in zoningActionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @click="changeZoningAction(item.value)"
                  />
                </el-select>
              </div>
            </div>
          </div>
          <!-- 动态-费用表单 -->
          <vxe-table
            ref="xFeesetSetingDetailTableRef"
            :data="feesetSetingDetailTable.dataSource"
            :edit-rules="feesetSetingDetailTableRule"
            :height="380"
            border
            show-overflow
            :row-config="{ isHover: true }"
            :cell-style="{ height: '38px', padding: 0 }"
            :column-config="{ resizable: true }"
            :header-row-style="{ background: '#fff', color: '#909399', borderRight: '1px solid #ccc' }"
            :edit-config="{ trigger: 'click', mode: 'row', showIcon: false, showAsterisk: false }"
          >
            <vxe-column
              field="originalBeginWeight"
              :width="125"
              title="起始重量（>）"
              :fixed="getIsFixedLeft"
              :edit-render="{ autofocus: '.original-beginweight .vxe-input--inner', autoselect: true }"
            >
              <template #edit="scoped">
                <vxe-input
                  v-model="scoped.row.originalBeginWeight"
                  v-clear-only-regex="/^\d*\.?\d{0,3}$/"
                  type="text"
                  class="original-beginweight"
                  @change="detailUpdateStatus(scoped)"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="originalEndWeight"
              :width="130"
              title="结束重量（<=）"
              :fixed="getIsFixedLeft"
              :edit-render="{ autofocus: '.original-endweight .vxe-input--inner', autoselect: true }"
            >
              <template #edit="scoped">
                <vxe-input
                  v-model="scoped.row.originalEndWeight"
                  v-clear-only-regex="/^\d*\.?\d{0,3}$/"
                  type="text"
                  class="original-endweight"
                  @change="detailUpdateStatus(scoped)"
                />
              </template>
            </vxe-column>
            <!-- <vxe-column field="originalCalculateUnit" width="125" title="计量单位" fixed="left" :edit-render="{}">
              <template #header>
                计量单位
                <el-tooltip effect="dark" content="点击拷贝数据" placement="top-start">
                  <el-button type="primary" :icon="List" link @click="hanleChangeCalculateUnitList" />
                </el-tooltip>
              </template>
              <template #default="{ row }">
                <span>{{ deal_FindItemName(row.originalCalculateUnit, calculateUnitList) }}</span>
              </template>
              <template #edit="scoped">
                <vxe-select v-model="scoped.row.originalCalculateUnit" transfer @change="detailUpdateStatus(scoped)">
                  <vxe-option v-for="item in calculateUnitList" :key="item.value" :value="item.value"
                    :label="item.label"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column> -->
            <vxe-column
              field="countModel.countType"
              :width="125"
              title="算法"
              :fixed="getIsFixedLeft"
              :edit-render="{}"
            >
              <template #header>
                算法
                <el-tooltip
                  effect="dark"
                  content="点击拷贝数据"
                  placement="top-start"
                >
                  <el-button
                    type="primary"
                    :icon="List"
                    link
                    @click="hanleChangeCountTypeList"
                  />
                </el-tooltip>
              </template>
              <template #default="{ row }">
                <span>{{ deal_FindItemName(row.countModel.countType, countTypeList) }}</span>
              </template>
              <template #edit="scoped">
                <vxe-select
                  v-model="scoped.row.countModel.countType"
                  transfer
                  @change="detailUpdateStatus(scoped)"
                >
                  <vxe-option
                    v-for="item in countTypeList"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  >
                    <div @click="hanleBlurCalculator(scoped.row)">
                      {{ item.label }}
                    </div>
                  </vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <template
              v-for="(item, index) in columnsDynamicMeterHead"
              :key="`feeset-table-${index}`"
            >
              <vxe-column
                :field="item.slotName"
                :min-width="100"
                :title="item.label"
                :edit-render="{ autofocus: '.input_ .vxe-input--inner', autoselect: true }"
              >
                <template #header>
                  {{ item.label }}
                  <el-tooltip
                    effect="dark"
                    content="点击拷贝数据"
                    placement="top-start"
                  >
                    <el-button
                      type="primary"
                      :icon="List"
                      link
                      @click="hanleInitRefresh(item.slotName)"
                    />
                  </el-tooltip>
                </template>
                <template #edit="scoped">
                  <vxe-input
                    v-model="scoped.row[item.slotName]"
                    type="text"
                    class="input_"
                    @change="detailUpdateStatus(scoped)"
                  />
                </template>
              </vxe-column>
            </template>
            <vxe-column
              title="操作"
              fixed="right"
              :width="60"
            >
              <template #header>
                <el-button
                  class="add-columns"
                  type="primary"
                  link
                  :icon="Plus"
                  @click="hanleFeesetDetailsTableAdd"
                />
              </template>
              <template #default="scope">
                <el-button
                  class="add-columns"
                  type="danger"
                  :icon="SemiSelect"
                  link
                  @click="hanleFeesetDetailsTableDelete(scope)"
                />
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <!-- 一票多件 -->
        <MpsData
          ref="mpsdataRef"
          @save-mps-data="hanleSaveMpsData"
        />
        <!-- 分区操作 -->
        <BasicZoning
          ref="zoningActionsRef"
          @save-zoning="hanleSaveZoning"
        />
        <!-- 分区特殊参数设置 -->
        <SpecialParameter
          ref="specialParameterRef"
          :special-parameters-list="specialParametersList"
          :fee-items-list="oldFeeItemList"
          :partition-list="customerFeeSetParams.partitionList"
          @save-special-parameter="hanleSaveSpecialParameter"
        />
        <!-- 计算公式-弹框 -->
        <FormulaModle
          ref="formulaModle"
          @save="hanleSaveFormula"
        />
        <!-- 导出分区模版 -->
        <ZoningExportTemplate ref="zoningExportTemplateRef" />
        <!-- 分区模版加载 -->
        <ZoningLoadTemplate
          ref="zoningLoadTemplateRef"
          @save-load-partition="hanleSaveLoadPartition"
        />
        <!-- 快速导入费用 -->
        <ExportExpense
          ref="exportExpenseRef" 
          :zone-list="feesetSetingDetailTable.columns"
          :original-calculate-unit="originalCalculateUnit"
          :count-type-list="countTypeList" 
          :fee-item-row="baseData.feeItemRow"
          :feeset-seting-data-source="feesetSetingGridOptions.data" 
          @save-expense="hanleSaveExpense"
        />
      </div>
    </template>
    <template #defineFooter>
      <div class="customer-feeSet-footer">
        <el-button
          type="danger"
          @click="clearClose"
        >
          {{ isActionsType ? '取消' : '关闭' }}
        </el-button>
        <el-button
          v-show="isActionsType"
          :loading="dialog.confirmLoading"
          type="primary"
          @click="confirm"
        >
          保存
        </el-button>
      </div>
    </template>
  </SysDialog>
</template>
<script lang="ts" setup>
import { reactive, computed } from "vue";
import useBusinessFeesetModel from "@/composables/business/useBusinessFeesetModel";
import MpsData from "@/components/MpsData/index.vue";
import FormulaModle from '@/components/feeset/FormulaModle.vue';

// 分区操作
import BasicZoning from '@/components/Zoning/src/BasicZoning.vue';
import ZoningExportTemplate from '@/components/Zoning/src/components/ZoningExportTemplate.vue'
import ZoningLoadTemplate from '@/components/Zoning/src/components/ZoningLoadTemplate.vue';
import SpecialParameter from '@/components/Zoning/src/components/SpecialParameter.vue';
import ExportExpense from '@/components/Zoning/src/components/exportExpense.vue';

import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import { useBusinessFeesetDetailRote } from "@/composables/business/useBusinessFeesetDetailRote";
import { ListIitem } from "@/api/base/BaseDataModel";
import { List, Plus, Select, SemiSelect, QuestionFilled } from "@element-plus/icons-vue";
import { deal_FindItemName } from "@/utils/dealFindData";
import { VxeBasicTable } from "@/components/VxeTable";
import { useVxeGridHanleHooks } from "@/components/VxeTable/hooks";
import { feeItemFindName } from "@/utils/feeSeting/data";
import BaseSelect from '@/components/QuerySelect/BaseSelect.vue';
import { menuStore } from "@/store/menu";

const menustore = menuStore();
const getIsFixedLeft = computed(() => {
  return !menustore.getIsPhone ? 'left' : null
});
//弹框属性
const { dialog, onClose, onShow, setLoading } = useDialog();
// 弹框一些配置
const getBindValue = reactive({
  title: "费用计算公式",
  top: "2vh",
  width: 1520,
  height: 0,
  isFooter: true,
  fullscreen: true,
  overflowHidden: true
});
const emit = defineEmits(['saveFeeBase'])

// 基础数据
const {
  feesetSetingGridOptions,
  feesetSetingGridRules,
  feesetSetingDetailTable,
  schemasFormFeeset,
  zoningActionOptions,
  ruleFormFeeBasicData,
  feesetSetingDetailTableRule
} = useBusinessFeesetModel();
// 费用明细-表格设置

// 处理费用设置详情事件
const {
  hanleFeesetTableDelete,
  hanleFeesetTableAdd,
  hanleFeesetDetailsTableAdd,
  hanleFeesetDetailsTableDelete,
  changeZoningAction,
  hanleOpenOneVote,
  hanleSaveFormula,
  hanleBlurCalculator,
  hanleSaveZoning,
  hanleSaveMpsData,
  hanleChangeFeeItem,
  hanleSaveLoadPartition,
  hanleSaveSpecialParameter,
  hanleChangePackageType,
  hanleRowDblclick,
  hanleChangeCountTypeList,
  hanleExportExpense,
  hanleSaveExpense,
  hanleInitRefresh,
  hanleCellClick,
  confirm,
  show,
  clearClose,
  ruleFormFeeBasicDataRef,
  zoningActionsRef,
  specialParameterRef,
  mpsdataRef,
  ruleFormFeesetSetingTableRef,
  xFeesetSetingDetailTableRef,
  zoningExportTemplateRef,
  zoningLoadTemplateRef,
  exportExpenseRef,
  formulaModle,
  columnsDynamicMeterHead,
  feeItemLists,
  newFeeItemList,
  oldFeeItemList,
  filterOnFeeItemList,
  countTypeList,
  packageTypeList,
  specialParametersList,
  customerFeeSetParams,
  feeItemGetTypeList,
  compareTypeList,
  currencyList,
  baseData,
  isActionsType,
  originalCalculateUnit,
  remoteSurveyTypeList,
  changeRemoteFlag
} = useBusinessFeesetDetailRote(onShow, onClose, setLoading, feesetSetingGridOptions, feesetSetingDetailTable, emit, ruleFormFeeBasicData, feesetSetingGridRules);
// vxe-grid操作事件
const { isActiveStatus, cancelRowEvent, updateStatus } = useVxeGridHanleHooks(ruleFormFeesetSetingTableRef)
const { updateStatus: detailUpdateStatus } = useVxeGridHanleHooks(xFeesetSetingDetailTableRef)
// 计抛校验提示
const getLightFlagRule = computed(() => {
  if (isActionsType.value) return [{ required: true, message: '请选择是否计抛', trigger: 'change' }]
  return [{ required: false, message: '请选择是否计抛', trigger: 'change' }]
})
//父组件调用子组件显示弹框
//暴露出去给外部使用
defineExpose({
  show
});
</script>

<style lang="scss" scoped>
.fesset-from {
  :deep(.el-form-item) {
    margin-right: 10px;
  }

  :deep(.el-form-item__label) {
    padding-right: 0;
    // padding-left: 8px;
  }

  .item-feeItemIdList {
    width: 248px;
  }
  .item-formItem168 {
    width: 168px;
  }
  .item-formItem180 {
    width: 180px;
  }
  .remote-survey-type {
    width: 80px;
  }
}

.table-warp {
  margin-bottom: 20px;

  .title {
    padding-bottom: 10px;
  }

  .add-columns {
    display: block;
    width: 100%;
  }

  .el-table {

    :deep(td.el-table__cell) {
      // padding-bottom: 0;
      padding: 5px 0;

      .el-input__wrapper {
        border: none;
      }
    }

    :deep(.el-table__row) {
      user-select: none;
    }

    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.cell) {
      padding: 0 3px;
    }
  }

  :deep(.col--actived) {
    background-color: #f5f7fa;
  }
}

.table-warp2 {

  // margin-bottom: 20px;
  .title {
    padding-bottom: 10px;
  }

  .el-table {
    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.cell) {
      padding: 0 3px;
    }
  }

  .add-columns {
    display: block;
    width: 100%;
  }

  .state-more-h {
    margin-top: 8px;
    height: 22px;
    line-height: 22px;
    text-align: center;
  }

  :deep(.col--actived) {
    background-color: #f5f7fa;
  }
}

.customerfeeset-content {
  padding-bottom: 28px;
}

.customer-feeSet-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-right: 15px;
  padding-bottom: 20px;
  z-index: 3999;
  background-color: #fff;
}
</style>
