<template>
  <SysDialog class="special-parameter" :title="getBindValue.title" :width="getBindValue.width"
    :height="getBindValue.height" :visible="dialog.visible" @onClose="clearClose" @onConfirm="confirm">
    <template #content>
      <vxe-table ref="ruleSpecialparameterFormTableRef" :data="tableSpecialParameterZoning.dataSource"
        :edit-rules="specialparameterDetailTableRule" max-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', autoClear: false, showIcon: false, showAsterisk: false }">
        <!-- 费用类型 -->
        <vxe-column field="feeItemId" :width="140" fixed="left" title="费用类型" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ feeItemFindName(row.feeItemId, feeItemsList) }}</span>
          </template>
          <template #edit="scoped">
            <el-select v-model="scoped.row.feeItemId" placeholder="请选费用类型" @change="updateStatus(scoped)">
              <el-option v-for="item in feeItemsList" :key="item.id" :label="item.itemName" :value="item.id" />
            </el-select>
          </template>
        </vxe-column>
        <!-- 参数名称 -->
        <vxe-column field="specialParametersId" :width="140" fixed="left" title="参数名称" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ deal_FindItemName(String(row.specialParametersId), specialParametersList) }}</span>
          </template>
          <template #edit="scoped">
            <el-select v-model="scoped.row.specialParametersId" placeholder="请选特殊参数" @change="updateStatus(scoped)">
              <el-option v-for="item in specialParametersList" :key="item.value" :label="item.label"
                :value="Number(item.value)" />
            </el-select>
          </template>
        </vxe-column>
        <!-- 动态分区列表 -->
        <template v-for="(item, index) in columnsDynamicMeterHead" :key="`${index}_`">
          <vxe-column :field="item.slotName" :width="90" :title="item.label" :edit-render="{ autofocus: '.vxe-input--inner', autoselect: true }">
            <template #edit="scoped">
              <vxe-input v-model="scoped.row[item.slotName]" type="text" @change="updateStatus(scoped)" />
            </template>
          </vxe-column>
        </template>
        <vxe-column title="操作" fixed="right" :width="80">
          <template #header>
            <el-button type="primary" class="add-columns" link :icon="Plus" @click="hanleAddSpecialParameter" />
          </template>
          <template #default="scope">
            <el-button type="success" link :icon="Plus" @click="hanleAddSpecialParameter" />
            <el-button type="danger" link :icon="Delete" @click="hanleDeleteSpecialParameter(scope)" />
          </template>
        </vxe-column>
      </vxe-table>
    </template>
  </SysDialog>
</template>
<script lang="ts" setup>
import { ref, computed, watchEffect, unref } from 'vue';
import SysDialog from '@/components/SysDialog.vue';
import useDialog from '@/hooks/useDialog';
import { useZoningModel } from '@/composables/business/zoning/useZoningModel';
import { Plus, Delete } from '@element-plus/icons-vue'
import { useDealDynamicMeterHead } from '@/hooks/useDynamicMeterHead';
import { ListIitem } from '@/api/base/BaseDataModel';
import { v4 as uuidv4 } from 'uuid';
import { cloneDeep } from '@/utils/cloneDeep';
import { PartitionList } from '@/api/customerfee/CustomerFeeSetModel';
import { useDealHeaderData } from '@/utils/dealHeaderData';
import { isArrayLength } from '@/utils/is';
import { deal_FindItemName } from '@/utils/dealFindData';
import { feeItemFindName } from '@/utils/feeSeting/data';
import { VxeTableInstance } from '@/components/VxeTable';
import { fee_deal_FilterValidate } from '@/utils/feeSeting/dealData';
import { useVxeGridHanleHooks } from '@/components/VxeTable/hooks';
/**
 * 费用编号
   private Integer feeItemId; ==> 主要在费用设置有数据 ==》 才显示有选中的列表数据
 */
//弹框属性
const { dialog, onClose, onShow } = useDialog()
const getBindValue = ref<Recordable>({
  title: '分区特殊参数设置',
  width: 1420,
  height: 0
})
// 表单Ref
const ruleSpecialparameterFormTableRef = ref<VxeTableInstance>()

const props = defineProps<{
  specialParametersList: ListIitem[],
  feeItemsList: Recordable[],
  partitionList?: PartitionList[],
}>()

const emit = defineEmits(['saveSpecialParameter'])

// 基础数据
const { tableSpecialParameterZoning } = useZoningModel()
const { updateStatus } = useVxeGridHanleHooks(ruleSpecialparameterFormTableRef)
// 初始化动态表头
const { initDynamicMeterHead, columnsDynamicMeterHead } = useDealDynamicMeterHead()

// 拷贝原始表格表头数据
const cloneData = cloneDeep(tableSpecialParameterZoning.columns)
const zoningdata = computed(() => props.partitionList)
// 表格校验
const getRules = (message: string) => [{ required: true, message }]
const specialparameterDetailTableRule = computed(() => {
  const result = tableSpecialParameterZoning.columns.reduce((acc, curr) => {
    curr.prop !== 'feeItemId' && (acc[curr.prop] = getRules("请输入内容！"))
    if (curr.prop === 'specialParametersId') acc[curr.prop] = getRules("请选择内容！");
    return acc;
  }, {});
  return result
})

// 处理表头数据
const { dealHeaderSpecialParameterTrget } = useDealHeaderData()

// 监听分区数据变化
watchEffect(() => {
  const zoningData = unref(zoningdata) as Recordable[]
  if (isArrayLength(zoningData)) {
    tableSpecialParameterZoning.columns = []
    const headData = initDynamicMeterHead(zoningData)
    // 合并多个分区表头
    const columns = [...cloneData, ...headData]
    tableSpecialParameterZoning.columns = columns
  }
})

// 添加特殊参数
const hanleAddSpecialParameter = async () => {
  // 校验
  const $tableSpecialparameter = ruleSpecialparameterFormTableRef.value
  const validateRes = await $tableSpecialparameter?.validate(true)
  const isValidate = await fee_deal_FilterValidate([validateRes])
  if (!isValidate) return
  tableSpecialParameterZoning.dataSource.push({ id: uuidv4() })
}
// 删除特殊参数
const hanleDeleteSpecialParameter = (scope: Recordable) => {
  const index = scope.rowIndex
  tableSpecialParameterZoning.dataSource.splice(index, 1)
}


// 确定
const confirm = async () => {
  // 校验
  const $tableSpecialparameter = ruleSpecialparameterFormTableRef.value
  const validateRes = await $tableSpecialparameter?.validate(true)
  const isValidate = await fee_deal_FilterValidate([validateRes])
  if (!isValidate) return
  // 获取特殊参数数据
  const specialParameterDataSource = tableSpecialParameterZoning.dataSource
  const partitionExcludeKeys = zoningdata.value && zoningdata.value.map(item => item.id)
  const targetArr = dealHeaderSpecialParameterTrget(specialParameterDataSource, partitionExcludeKeys as string[])
  // console.log(tableSpecialParameterZoning.dataSource, "<=原数据 == 获取特殊参数数据 == 目标数据 =>", targetArr);
  emit('saveSpecialParameter', targetArr)
  clearClose()
}

// 取消清空
const clearClose = () => {
  const $tableSpecialparameter = ruleSpecialparameterFormTableRef.value
  $tableSpecialparameter?.clearValidate()
  onClose()
}

// 显示
const show = (list: Recordable[]) => {
  isArrayLength(list) ?
    tableSpecialParameterZoning.dataSource = list : tableSpecialParameterZoning.dataSource = []
  onShow()
}

//父组件调用子组件显示弹框
//暴露出去给外部使用
defineExpose({
  show
})
</script>
<style lang="scss" scoped>
.special-parameter {
  .form-table-specialparameter {
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }

  .add-columns {
    width: 100%;
  }
}
</style>