<template>
    <hc-drawer v-model="isShow" to-id="hc-main-box" is-close @close="drawerClose">
        <hc-body split :options="splitOptions">
            <template #left>
                <hc-card scrollbar>
                    <hc-table-form
                        v-if="tableShow"
                        ref="excelRef"
                        :html="excelHtml"
                        @tap="excelClick"
                    />
                </hc-card>
            </template>
            <hc-card>
                <el-form ref="formRef" :model="formModel" label-position="top" label-width="auto" size="large">
                    <el-form-item label="选择表单">
                        <el-select v-model="formModel.formVal" placeholder="请选择" @change="changeform">
                            <el-option
                                v-for="item in formoptions"
                                :key="item.initTabId"
                                :label="item.tabName"
                                :value="item.initTabId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择元素">
                        <el-select v-model="formModel.eleVal" placeholder="请选择" filterable @change="changeEle">
                            <el-option
                                v-for="item in eleOptions"
                                :key="item.ekey"
                                :label="item.eName"
                                :value="item.ekey"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
                <hc-card-item title="映射数据来源">
                    <h4>表单名称：</h4>{{ infoDetail?.tabName }}
                    <h4 class="mt-4">元素字段：</h4>{{ infoDetail?. elementName }}
                </hc-card-item>
            </hc-card>
        </hc-body>
    </hc-drawer>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue, getObjVal, getObjValue, isArrIndex } from 'js-fast-way'
import mainApi from '~api/desk/test-collect'
import { setStoreValue } from '~uti/storage'

const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
})

const emit = defineEmits(['close'])


//页面分割
const splitOptions = { sizes: [70, 30], snapOffset: 0, minSize: [300, 300] }

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})
  //获取当前清表表所有已匹配的映射字段列表
  const linkedData = ref({})
const getLinkedData = async ()=>{
    const { code, data } = await mainApi.getLinkData({
                id:dataInfo.value.id,
          })
          if (code === 200) {
            linkedData.value = getArrValue(data)
           const mappedObject = Object.fromEntries(data.map(item => [item.htmlKeyName, item.elementValue]))
          linkedData.value = mappedObject
          setStoreValue('tableId', linkedData.value)
          } else {
          linkedData.value = []
        }
      
}
//监听数据
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = data
  
}, { immediate: true, deep: true })
watch(() =>linkedData.value, (data) => {
  setStoreValue('tableId,data')
  
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) getDataApi()
})
//表单相关
const excelRef = ref(null)
const excelHtml = ref('')


//获取属性
const getAttribute = async (dom, key) => {
    try {
        return dom?.getAttribute(`data-${key}`)
    } catch (e) {
        return null
    }
}
//框框被点击
const keys = [
    'type',
    'key',
    'tr',
    'td',
    'index',
    'x1',
    'y1',
    'x2',
    'y2',
    'name',
    'text',
    'rows',
    'format',
    'tip',
    'weighing',
    'label',
    'value',
    'src',
    'val',
    'contractid',
    'pkeyid',
    'objs',
    'range',
    'def',
    'max',
]
//
const tableShow = ref(true)
const refreshTable = async ()=>{
    tableShow.value = false
  
   
    setTimeout(async ()=>{
        await getDataApi()
        tableShow.value = true
      
       
    }, 1000)
}
//元素被点击
const excelClick = async (item) => {
    const dom = item?.target
    let obj = { zdom: item }
    for (let i = 0; i < keys.length; i++) {
        obj[keys[i]] = await getAttribute(dom, keys[i])
    }
  curItem.value.htmlKeyName = obj.key
  getLinkDetailData( obj.key)

}

const clickArr = ref([])
//获取表单数据
const getHtmlData = async ()=>{
    const { data } = await mainApi.getLinkHtml({
        classId:dataInfo.value.id,
    })
    excelHtml.value = data || ''
 
}
const formRef = ref(null)
const formModel = ref({})
const formoptions = ref([])
const getDataApi = async ()=>{
    await getFormoptions()
    await getHtmlData()
  await getLinkedData()

 
}
//获取元素映射

const getLinkDetailData = async (keyName)=>{
    const { code, data } = await mainApi.getLinkDetail({
            classId:dataInfo.value.id,
            keyName,
          })
          if (code === 200) {
           infoDetail.value.tabName = data?.tabName
           infoDetail.value.elementName = data?.elementName
       
          } else {
            infoDetail.value = { tabName:'',
            elementName:'' }
        }
        if (data) {
            formoptions.value.forEach((ele)=>{
                if (ele.tabName === data?.tabName) {
                formModel.value.formVal = ele.initTabId
                console.log( formModel.value.formVal, ' formModel.value.formVal')
                changeform(formModel.value.formVal)
                
                }
            })
         
        } else {
            formModel.value = {}
        }
}
const getFormoptions = async ()=>{
    const { data } = await mainApi.getLinkTablist({ classId:dataInfo.value.id })
    formoptions.value = getArrValue(data)
}
const getEleOptions = async ()=>{
    const { data } = await mainApi.getLinkElelist({ id:formModel.value.formVal })
    eleOptions.value = getArrValue(data)
    eleOptions.value.forEach((ele)=>{
                if (ele.eName === infoDetail.value.elementName) {
                formModel.value.eleVal = ele.ekey
                }
            })
}
const eleOptions = ref([])
const infoDetail = ref({
    tabName:'',
    elementName:'',
})
const curItem = ref({
        elementId:'',
        elementKey:'',
        htmlKeyName:'',
        trialTabId:'',
        trialTabName:'',
})

watch(curItem.value, (val) => {
  
    const { elementId, elementKey, htmlKeyName, trialTabId, trialTabName } = val
    if (elementId && elementKey && htmlKeyName && trialTabId && trialTabName) {
          const newItem = Object.assign({}, val)
          let variable
         variable = isArrIndex(clickArr.value, 'htmlKeyName', newItem.htmlKeyName, variable) 
          if (variable) {
            clickArr.value.forEach((ele)=>{
              if (ele.htmlKeyName === newItem.htmlKeyName) {
                ele.elementId = newItem.elementId
                ele.elementKey = newItem.elementKey
                ele.htmlKeyName = newItem.htmlKeyName
                ele.trialTabId = newItem.trialTabId
                ele.trialTabName = newItem.trialTabName

              }
            })
          } else {
            clickArr.value.push(newItem)
          }


        }
})
const changeform = (val)=>{
    getEleOptions()
    formModel.value.eleVal = ''
    formoptions.value.forEach((ele)=>{
        if (ele.initTabId === val) {
        infoDetail.value.tabName = ele.tabName
        curItem.value.trialTabId = ele.pkeyId
        curItem.value.trialTabName = ele.initTableName
        }
    })
}
const changeEle = (val)=>{
    eleOptions.value.forEach((ele)=>{
        if (ele.ekey === val) {
            infoDetail.value.elementName = ele.eName
         
            curItem.value.elementKey = val
            curItem.value.elementId = ele.id
        }
      })
}
//映射数据保存
const saveLoading = ref(false)
const saveInfo = async ()=>{
    if (clickArr.value.length === 0) {
      window.$message.warning('请进行数据映射配置')
      return
    }
    saveLoading.value = true
        const { msg, code, error } = await mainApi.saveLinkDetail({
                    classId:dataInfo.value.id,
                    reflectionBeanList:clickArr.value,
        })
        saveLoading.value = false
        if (code === 200 && !error) {
            window.$message.success(msg)
           
            refreshTable()
            clickArr.value = []
        }
}
//关闭抽屉
const drawerClose = () => {
    isShow.value = false
    clickArr.value = []
    emit('close')
}
</script>

<style lang="scss">

</style>
