<template>
  <el-scrollbar max-height="350px">
    <el-form size="small" label-width="60px">
      <template v-for="(item, index) in configList" :key="item.time">
        <ConfigFormItem :item="item" :index="index" @remove="removeMapField" />
        <el-divider v-if="index + 1 != configList.length"> 第{{ index + 2 }}映射字段 </el-divider>
      </template>
    </el-form>
  </el-scrollbar>
  <el-row type="flex" justify="center">
    <el-button size="small" type="primary" @click="emits('confirm', configList)">确认</el-button>
    <el-button size="small" type="primary" @click="addFormItem">添加字段</el-button>
    <el-button size="small" @click="emits('cancel')">取消</el-button>
  </el-row>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import type { Recordable } from '@/types/global'
import ConfigFormItem from './ConfigFormItem.vue'
import { cloneDeep } from 'loadsh'
import { ElMessage } from 'element-plus'
import { apiGetOrderField, apiGetScript, getVariableField } from '@/api/excel'
import { useVariableExcelChangeStore } from '@/stores/excel'

/**
 * 数据结构
 * {templateFileId: '', confs: [{title: '',filedConfs: [{mapField: '',orderFiled: {}, scripts: {}}], templateFileId: ''}]}
 */
const props = defineProps<{ title: string; currentRow: Recordable; currentConf: Recordable }>()
const emits = defineEmits(['cancel', 'confirm'])
const excelChangeStore = useVariableExcelChangeStore()
const configList = ref<Recordable[]>([])

// 添加映射字段表单对象
const addFormItem = () => {
  configList.value.push({
    time: Date.now(),
    mapField: '',
    orderFiled: {},
    scripts: [],
    filterFiled: '',
    filterScripts: []
  })
}
const removeMapField = (index: number) => {
  configList.value.splice(index, 1)
}

const getScriptList = async () => {
  const { data } = await apiGetScript()
  excelChangeStore.setScriptList(data.result)
}


watch(
  () => props.currentConf.title,
  (val) => {
    configList.value = cloneDeep(props.currentConf).filedConfs.map((item, i) => {
      item.time = Date.now() + i
      return item
    })
  },
  {
    immediate: true
  }
)

watch(
  configList,
  (val) => {
    excelChangeStore.setUsedFieldList(val)
  },
  { deep: true }
)

onMounted(() => {
  getScriptList()
})
</script>
