<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />

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

  import { getDeptList, addDept, updateDept } from '@/api/demo/system';
  import {getAiShape,getTif,addTask} from '@/api/task'

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

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

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

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

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }

    const treeData = await getDeptList();

    
    console.log("treeData",treeData);

    const shapefiles = await getAiShape();

    const tifs = await getTif();

    let afterTifs = handleDealTifTree(tifs)


    // 更新字段值
    updateSchema([

      {
        field: 'shpId',
        componentProps: { options:shapefiles },
      },{
        field: 'previousPhase',
        componentProps: { treeData:afterTifs },
      },{
        field: 'laterPhase',
        componentProps: { treeData:afterTifs },
      }
    ]);
  });

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

  function handleDealTifTree(tifs){
    let handlerAfterTifs =[];
    tifs.forEach((item,index)=>{
      let obj = {
        id:item.areaName,
        key:item.areaName,
        level:0,
        parentId:index,
        name:item.areaName,
        children:[]
      }
      item.tifDateGroups.forEach((it,idx)=>{
        let data = {
          id:it.tifDate,
          key:it.tifDate,
          level:1,
          parentId:index,
          name:it.tifDate,
          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);
    })
    return handlerAfterTifs;

  }
  async function handleSubmit() {
    try {
      const values = await validate();
      let query = values;
      if (query.id) {
        query.id = Number(query.id);
      } else {
        query.id = 0;
      }
      // 调用接口
      if (!unref(isUpdate)) {
        const data = await addTask(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          return createMessage.success('创建成功');
        } else {
          return createMessage.error('创建失败');
        }
      } else {
        const data = await updateDept(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          return createMessage.success('编辑成功');
        } else {
          return createMessage.error('编辑失败');
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style>
::v-deep .update-button{
  background:#408eff;
}
</style>