<template>
  <n-form label-width="auto">
    <n-grid :cols="12" :x-gap="12">
      <n-form-item-gi v-for="(item, index) of formValue.formList" :key="item.T_VerifyTemplateMap_id" :span="12"
        :label="item.T_name">
        <!-- 多选id -->
        <n-select v-model:value="item.T_value" multiple label-field="T_id" value-field="T_sn" max-tag-count="responsive"
          :options="classList" v-if="item.T_label === 3">
          <template #action>
            <n-space>
              <n-button class="underline" text @click="handleSelectAll(index)">全选</n-button>
              <n-button class="underline" text @click="handleSelectReverse(index)">反选</n-button>
            </n-space>
          </template>
        </n-select>
        <!-- 单选id -->
        <n-select v-model:value="item.T_value" label-field="T_id" value-field="T_sn" :options="classList"
          v-else-if="item.T_label === 4"/>
        <!-- 时间 -->
        <n-date-picker @focus="focusFun(item,index)" @blur="blurFun" v-model:formatted-value="item.T_value" value-format="yyyy-MM-dd HH:mm" type="datetime" clearable
          class="w-full" v-else-if="item.T_label === 7" />
        <!-- 时间区间 -->
        <n-date-picker @focus="focusFun(item,index)" @blur="blurFun" v-model:formatted-value="item.T_value" value-format="yyyy-MM-dd HH:mm" type="datetimerange"
          clearable class="w-full" v-else-if="item.T_label === 9" />
        <!-- 图片 -->
        <template v-else-if="item.T_label === 10">
          <n-image class="mr-5" width="100" :src="item.T_value" />
          <n-upload list-type="image-card" @change="(options) => handleChangeByIndex(options, index)"
            :default-upload="false" :max="1">
            点击上传
          </n-upload>
        </template>
        <!-- CAD -->
        <template v-else-if="item.T_label === 11">
          <n-image class="mr-5" width="100" :src="item.T_value" />
          <n-space>
            <n-button @click="() => handleEdit(item)">编辑</n-button>
            <n-button @click="() => handleRefresh(index)">刷新</n-button>
          </n-space>
        </template>

         <!-- 时间 注释 -->
         <template v-else-if="item.T_label === 12">
          <n-space vertical class="w-full">
            <n-date-picker @focus="focusFun(item,index)" @blur="blurFun"
              v-model:formatted-value="item.T_value[0]"
              format="yyyy-MM-dd HH:mm"
              :time-picker-props="{ format: 'HH:mm' }"
              type="datetime"
              clearable
            />
            <n-input v-model:value="item.T_value[1]" type="text" />
          </n-space>
        </template>
        <!-- 时间区间 注释 -->
        <template v-else-if="item.T_label === 13">
          <n-space vertical class="w-full">
            <n-date-picker
            @focus="focusFun(item,index)" @blur="blurFun"
              v-model:formatted-value="item.T_value[0]"
              format="yyyy-MM-dd HH:mm"
              :time-picker-props="{ format: 'HH:mm' }"
              type="datetimerange"
              clearable
            />
            <n-input v-model:value="item.T_value[1]" type="text" />
          </n-space>
        </template>


        <!-- 可输入的表单项 -->
        <template v-else>
          <n-input v-model:value="item.T_value" />
        </template>
        <!-- 描述 -->
        <!-- <n-popover trigger="hover">
          <template #trigger>
            <n-icon size="24" class="ml-3">
              <InformationCircleOutline />
            </n-icon>
          </template>
          <n-image width="200" :src="item.T_text" v-if="item.T_label === 10 || item.T_label === 11" />
          <span v-else>{{ item.T_text }}</span>
        </n-popover> -->
      </n-form-item-gi>
    </n-grid>
  </n-form>
</template>

<script setup>

import { getVerifyTemplateMapDataList,putVerifyTemplateMapData} from '@/api';
import { getToken } from '@/utils/storage/sessionToken';
import { ref, watch ,onUnmounted} from 'vue';
import emitter from "@/plugin/bus";
import { InformationCircleOutline } from '@vicons/ionicons5';
import { TimeDate } from '@/plugin/timeFun';
import {useStore} from "vuex"
const store = useStore()
const props = defineProps({
  task: {
    type: Object,
    default: () => ({}),
  },
  classList: {
    type: Array,
    default: () => [],
  },
  time: {
    type: String,
    default: null,
  },
  temporalInterval: {
    type: Array,
    default: () => [],
  },
});
const focusData = reactive({
  fNum:null,
  obj:{}
})
watch(() => focusData.fNum,(newValue) => {//有焦点时存
  console.log('开始存',newValue)
    store.commit('setfocuFun',newValue)
},{deep:true,immediate:true});

onUnmounted(() => {//卸载把焦点设置为null
  store.commit('setfocuFun',null) 
})
// 表单对象
const formValue = reactive({
  formList: [],
});


emitter.emit("onFormData",focusData);

const blurFun = () =>{
  console.log('失去------------------------')
  focusData.fNum = null
}
const focusFun = (obj,index)=>{
  console.log('获得++++++++++++++++++++++++')
  focusData.fNum = index
  focusData.obj = obj
}
//监听单个时间点击赋值
watch(
  () => props.time,
  (newValue) => {
    console.log('单击',TimeDate(newValue),focusData.fNum)
    if(focusData.fNum==null){
      return
    }else{
      console.log('继续单击',newValue,focusData.fNum,focusData.obj)
      if (focusData.obj.T_label === 7) {
        formValue.formList[focusData.fNum].T_value = TimeDate(newValue)
      }
      if (focusData.obj.T_label === 12) {
        formValue.formList[focusData.fNum].T_value[0] = TimeDate(newValue)
      }
      
    }
    focusData.fNum = null
    
  }
);
//监听框选时间区间选择时间
emitter.on("onSelectionTime", (val) => {
    console.log('读取',val,parseInt(val[0].min),parseInt(val[0].max))    
    let staTime = TimeDate(parseInt(val[0].min))
    let endTime = TimeDate(parseInt(val[0].max))
    if(focusData.fNum==null){
      return
    }
    if(focusData.obj.T_label === 9){
      formValue.formList[focusData.fNum].T_value = [staTime,endTime]
    }
    if(focusData.obj.T_label === 13){
      formValue.formList[focusData.fNum].T_value[0] = [staTime,endTime]
    }
    // focusData.fNum = null
});
//关闭
onBeforeUnmount(() => {
    emitter.off("onSelectionTime");
});


watch(()=>formValue.formList, async(newValue,old)=>{
  console.log('最新',newValue,old)
  if(old.length!=0){
    const res = await dataPicker()
    const token = getToken();
  putVerifyTemplateMapData({
      User_tokey: token,
      T_source: queryData.T_source,
      T_task_id: queryData.T_task_id,
      T_VerifyTemplate_id: queryData.T_VerifyTemplate_id,
      VerifyTemplateMapData:res
    });
    console.log('修改值',res)
  }
 
},{deep:true})

const dataPicker = ()=>{
  let arr = []
  return new Promise(resolve=>{
    formValue.formList.forEach(item=>{
      let obj = {...item}
      if(obj.T_label==3 || obj.T_label==9){//多选id  sn|sn|      
        obj.T_value!=null? obj.T_value = obj.T_value.join("|"): obj.T_value = null
      }else if(obj.T_label==12){
        // console.log('当前为12',obj.T_value)
        obj.T_value = obj.T_value.join("/")
       
      }else if(obj.T_label==13){
        // console.log('当前为13',obj.T_value)
        if(obj.T_value[0]!=null && obj.T_value[1]!=null){
          obj.T_value = obj.T_value[0].join("|") + '/' + obj.T_value[1]
        }else if(obj.T_value[0]==null && obj.T_value[1]!=null){
          obj.T_value =  '/'+ obj.T_value[1]
        }else if(obj.T_value[0]!=null && obj.T_value[1]==null){
          obj.T_value = obj.T_value[0].join("|") + '/'
        }else{
          obj.T_value = ''
        }
      }
      arr.push(obj)
    })
    resolve(arr)
  })
}
//
const queryData = reactive({
  T_source: 3,
  T_task_id: props.task.T_task_id,
  T_VerifyTemplate_id: props.task.T_VerifyTemplate_id,
});

// 全选
const handleSelectAll = (i) => {
  if (formValue.formList[i].T_value.length !== 0) {
    return (formValue.formList[i].T_value = []);
  }
  formValue.formList[i].T_value = props.classList.map((item) => item.T_sn);
};

// 反选
const handleSelectReverse = (i) => {
  const arr = props.classList.map((item) => item.T_sn);
  formValue.formList[i].T_value = arr.filter(
    (item) => !formValue.formList[i].T_value.includes(item)
  );
};

// 模板标签数据（列表）
const getTemplateList = async () => {
  try {
    const { data: res } = await getVerifyTemplateMapDataList(queryData);
    formValue.formList = res.Data || [];
    formValue.formList.forEach(item => {
      if (item.T_label === 3){
        if(item.T_value=='' || item.T_value==null){
          item.T_value = []
        }else{
          item.T_value = item.T_value.split('|')
        }
      }else if(item.T_label == 9){
        if(item.T_value=='' || item.T_value==null){
          item.T_value = null
        }else{
          item.T_value = item.T_value.split('|')
        }
      }else if (item.T_label === 12) {
        // item.T_value = item.T_value = [null,null]
        if(item.T_value=='' || item.T_value==null){
          item.T_value = [null,null]
        }else{
          if(item.T_value.split('/')[0]==""){
            item.T_value = [null, item.T_value.split('/')[1]]
          }else{
            item.T_value = [item.T_value.split('/')[0], item.T_value.split('/')[1]]
          }
        }
      } else if (item.T_label === 13) {
        if(item.T_value=='' || item.T_value==null || item.T_value=='null'){
          item.T_value = [null,null]
        }else{
          if(item.T_value.split('/')[0]==""){//前面时间区间没选
            item.T_value = [null, item.T_value.split('/')[1]]
          }else{//前面时间区间已经选
            item.T_value = [item.T_value.split('/')[0].split('|'), item.T_value.split('/')[1]]
          }
        }
      } else {
        item.T_value = item.T_value ? item.T_value : null;
      }
    });
  } catch (e) {
    console.log(e);
  }
};

getTemplateList();
</script>

<style lang="scss" scoped></style>
