<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
    >
      <a-form-item label="选择AI解译成果" name="shpId" required>
        <a-row :gutter="12">
          <a-col :span="17">
            <a-select 
              v-model:value="form.shpId" 
              placeholder="请选择AI解译成果"
              :fieldNames="{
                label: 'shpName',
                key: 'id',
                value: 'id',
              }"
              :options="shapefiles"
              show-search
              allowClear
              @search="handlerOnSearch"
              :filterOption="false"
              >
            </a-select>
          </a-col>
          <a-col :span="7">
            <a-button type="primary" @click="handlerUpdateAiShape">更新数据</a-button>
          </a-col>
        </a-row>
      </a-form-item>


      <a-form-item label="选择前时项" required name="previousPhase">
        <a-row :gutter="12">
          <a-col :span="17">
            <a-tree-select
              v-if="false"
              v-model:value="form.previousPhase"
              placeholder="选择前时项"
              allow-clear
              multiple
              :tree-default-expand-all="false"
              defaultExpandAll
              :tree-data="afterTifs"
              tree-node-filter-prop="label"
              :fieldNames="{
                label: 'name',
                key: 'id',
                value: 'id',
              }"
            >
            </a-tree-select>

            <a-select
              v-model:value="form.previousPhase"
              mode="multiple"
              style="width: 100%"
              disabled
              placeholder="选择前时项"
              :fieldNames="{
                label: 'tifName',
                key: 'id',
                value: 'id',
              }"
              :options="previousPhaseOptions"
            ></a-select>

          </a-col>
          <a-col :span="7">
            <!-- <a-button type="primary" @click="handlerUpdateTif">更新数据</a-button> -->
            <a-button type="primary" @click="handlerSelectTif('选择前时项')">选择数据</a-button>
          </a-col>
        </a-row>
        
      </a-form-item>

      <a-form-item label="选择后时项" required name="laterPhase">
        <a-row :gutter="12">
          <a-col :span="17">
            <a-select
              v-model:value="form.laterPhase"
              mode="multiple"
              style="width: 100%"
              placeholder="选择后时项"
              :fieldNames="{
                label: 'tifName',
                key: 'id',
                value: 'id',
              }"
              disabled
              :options="laterPhaseOptions"
            ></a-select>
          </a-col>
          <a-col :span="7">
            <!-- <a-button type="primary" @click="handlerUpdateTif">更新数据</a-button> -->
            <a-button type="primary" @click="handlerSelectTif('选择后时项')">选择数据</a-button>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item ref="taskName" label="任务名称" name="taskName" required>
        <a-input v-model:value="form.taskName" />
      </a-form-item>

      <a-form-item ref="remark" label="备注/说明" name="remark" >
        <a-textarea v-model:value="form.remark" />
      </a-form-item>

    </a-form>

    <a-modal v-model:open="tifListVisible" :title="tifListTitle" width="600px" @ok="handlerReturnTif">
      <TifSelect ref="TifSelectComponent" v-if="tifListVisible" ></TifSelect>

    </a-modal>

  </BasicModal>

</template>
<script lang="ts" setup>
  import { ref, computed, unref ,reactive,watch} from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import TifSelect from "./tifselect.vue"
  // import { BasicForm, useForm } from '@/components/Form';
  // import { formSchema } from './dept.data';

  // import { getDeptList, addDept, updateDept } from '@/api/demo/system';
  import {getAiShape,updateShape,getTifByTime,updateTif,addTask,updateTask} from '@/api/task'

  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  defineOptions({ name: 'DeptModal' });

  const form = ref({
    shpId:null
  })

  const queryForm = ref({
    
  })



  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);


  const shapefiles = ref();

    getAiShape({name:null}).then(res=>{
      shapefiles.value = res;
    })


  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      form.value = data.record;
      previousPhaseOptions.value = data.record.previousPhaseInfo;
      laterPhaseOptions.value = data.record.laterPhaseInfo;
    }else{
      form.value  = {}
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '创建任务' : '编辑任务'));

  function generateUUID() {
    var d = new Date().getTime(); //Timestamp
    var d2 = (performance && performance.now && (performance.now()*1000)) || 0; //Time in microseconds since page-load or 0 if unsupported
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16; //random number between 0 and 16
        if(d > 0) { //Use timestamp until depleted
            r = (d + r)%16 | 0;
            d = Math.floor(d/16);
        } else { //Use microseconds since page-load if supported
            r = (d2 + r)%16 | 0;
            d2 = Math.floor(d2/16);
        }
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

  function handleDealTifTree(tifs){
    let handlerAfterTifs =[];
    tifs.forEach((item,index)=>{
      let obj = {
        id:generateUUID(),
        level:0,
        parentId:null,
        name:item.areaName,
        selectable:false,
        children:[]
      }
      item.tifDateGroups.forEach((it,idx)=>{
        let data = {
          id:generateUUID(),
          level:1,
          parentId:obj.id,
          name:it.tifDate,
          selectable:false,
          children:[]
        }
        it.tifDatas.forEach((tifItem,i)=>{
          let tifObj = {
            id:tifItem.id,
            key:tifItem.id,
            level:2,
            parentId:idx,
            name:tifItem.tifName,
          }
          data.children.push(tifObj);
        })
        obj.children.push(data)
      })
      handlerAfterTifs.push(obj);
    })
    console.log("handlerAfterTifs",handlerAfterTifs)
    return handlerAfterTifs;

  }

  const formRef = ref(null);
  async function handleSubmit() {
    try {
      // const values = await validate();
      formRef.value.validate().then(() => {
        let query = form.value;
        if (!unref(isUpdate)) {
          addTask(query).then(data=>{
            if (data) {
              setModalProps({ confirmLoading: true });
              closeModal();
              emit('success');
              return createMessage.success('创建成功');
            } else {
              return createMessage.error('创建失败');
            }
          })
        } else {
          updateTask(query).then(data=>{
            if (data) {
              setModalProps({ confirmLoading: true });
              closeModal();
              emit('success');
              return createMessage.success('编辑成功');
            } else {
              return createMessage.error('编辑失败');
            }
          });
        }
      }).catch(() => {
         
      });



    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleConfirm(){

  }

  function handlerOnSearch(value){
    getAiShape({name:value}).then(res=>{
      shapefiles.value = res;
    })
  }

  function handlerUpdateAiShape(){
    updateShape().then(res=>{
      if(res){
        createMessage.success("更新数据成功！");
      }else{
        createMessage.error("更新数据失败！");
      }
    })
  }



  const tifListVisible = ref(false);
  const tifListTitle = ref("")


  function handlerSelectTif(type){
    tifListTitle.value = type;
    tifListVisible.value =true;
  }
  
  const previousPhaseOptions = ref([]);
  const laterPhaseOptions = ref([]);


  const TifSelectComponent = ref(null);

  const handlerReturnTif = ()=>{
    let info = TifSelectComponent.value.getSelectedInfo();

    if(tifListTitle.value == "选择前时项"){
      form.value.previousPhase = info.selectedRowKeys;
      previousPhaseOptions.value = info.selectedRows;
      console.log("previousPhaseOptions",form.value.previousPhase,previousPhaseOptions.value)
      tifListTitle.value = false;
    }else if(tifListTitle.value=="选择后时项"){
      form.value.laterPhase = info.selectedRowKeys;
      laterPhaseOptions.value = info.selectedRows;
    }

    tifListVisible.value = false;
  };




</script>
<style>
::v-deep .update-button{
  background:#408eff;
}
</style>