<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" width="1300px">
    
    <BasicForm @register="registerForm" v-show="false" />
    
    <a-descriptions
    :column="2"
    bordered
    size="small"
    :contentStyle="{
      'text-align': 'center',
      'min-width': '400px',
      'word-break': 'break-all',
    }"
  >
    <a-descriptions-item label="任务名称">
      {{ taskInfo.taskName }}
    </a-descriptions-item>
    <a-descriptions-item label="AI解释成果">
      {{ taskInfo.shpName }}
      <a-button type="link" @click="copyToClipboard(taskInfo.shpName)">复制</a-button>
    </a-descriptions-item>
    <a-descriptions-item label="前时相">
      <p
        v-for="nextPhase in taskInfo.nextPhaseList"
        :key="nextPhase"
        :style="{ 'margin-bottom': 0 }"
      >
        {{ nextPhase }}
        <a-button type="link" @click="copyToClipboard(nextPhase)">复制</a-button>
      </p>
    </a-descriptions-item>
    <a-descriptions-item label="后时相">
      <p
        v-for="prePhase in taskInfo.prePhaseList"
        :key="prePhase"
        :style="{ 'margin-bottom': 0 }"
      >
        {{ prePhase }}
        <a-button type="link" @click="copyToClipboard(prePhase)">复制</a-button>
      </p>
    </a-descriptions-item>
    <a-descriptions-item label="任务创建时间">
      {{ taskInfo.taskCreateTime }}
    </a-descriptions-item>
    <a-descriptions-item label="任务说明">
      {{ taskInfo.taskRemark }}
    </a-descriptions-item>
    <a-descriptions-item label="任务状态">
      <a-tag color="red" v-if="taskInfo.taskIsCompleted == 0">进行中</a-tag>
      <a-tag color="green" v-if="taskInfo.taskIsCompleted == 1">已完成</a-tag>
    </a-descriptions-item>
    <a-descriptions-item label="领取状态">
      <a-tag color="orange" v-if="taskInfo.taskState == 0">待领取</a-tag>
      <a-tag color="blue" v-if="taskInfo.taskState == 1">领取中</a-tag>
      <a-tag color="green" v-if="taskInfo.taskState == 2">已领完</a-tag>
    </a-descriptions-item>
    <a-descriptions-item label="领取人">
      {{ taskInfo.reciveUser }}
    </a-descriptions-item>
    <a-descriptions-item label="分属小组">
      {{ taskInfo.groupName }}
    </a-descriptions-item>
    <a-descriptions-item label="领取任务状态">
      <a-tag color="red" v-if="taskInfo.isComplate == 0">进行中</a-tag>
      <a-tag color="green" v-if="taskInfo.isComplate == 1">已完成</a-tag>
    </a-descriptions-item>
    <a-descriptions-item label="领取图斑数量">
      {{ taskInfo.tubanNum }}
      （{{ taskInfo.beginNum }}-{{ taskInfo.endNum }}）
    </a-descriptions-item>
    <a-descriptions-item label="领取时间">
      {{ taskInfo.reciveTime }}
    </a-descriptions-item>
    <a-descriptions-item label="领取人备注">
      {{ taskInfo.remark }}
    </a-descriptions-item>
    <a-descriptions-item label="创建人">
      {{ taskInfo.createUserName }}
    </a-descriptions-item>
    <a-descriptions-item label="创建时间">
      {{ taskInfo.createTime }}
    </a-descriptions-item>
  </a-descriptions>


    <a-descriptions title="" bordered v-if="false">

      <a-descriptions-item label="任务名称" :span="2">{{taskInfo.taskName}}</a-descriptions-item>
      <a-descriptions-item label="AI解译成果" :span="2">{{taskInfo.shpName}}</a-descriptions-item>
      <a-descriptions-item label="前时项" :span="2">
        <p v-for="(item,index) in taskInfo.prePhaseList" :key="index">
          {{ item }}
        </p>
      </a-descriptions-item>
      <a-descriptions-item label="后时项" :span="2">
        <p v-for="(item,index) in taskInfo.nextPhaseList" :key="index">
          {{ item }}
        </p>
      </a-descriptions-item>
      <a-descriptions-item label="图斑数量" :span="2">{{taskInfo.tubanNum}}</a-descriptions-item>
      <a-descriptions-item label="任务进度" :span="2">
        <a-tag color="green" v-if="taskInfo.isComplate">已完成</a-tag>
        <a-tag color="red" v-else>未完成</a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="备注/说明" :span="6">{{taskInfo.remark}}</a-descriptions-item>
      
    </a-descriptions>

    <template #footer>
      <a-form ref="formRef" name="dynamic_rule" :model="form" style="width: calc( 100% - 200px);display:inline;">
        <a-form-item
          label=""
          name="remark"
          :rules="[{ required: true, message: '请输入备注/说明' }]"
        >
          <a-input 
            v-model:value="form.remark" 
            placeholder="请输入备注/说明"
            allowClear />
        </a-form-item>
      </a-form>
      
      <a-button type="error" @click="handleReturnTask">退回任务</a-button>
      <a-button type="primary" @click="handleSubmitTask" >完成任务</a-button>
    </template>

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

  import { getDeptList, addDept, updateDept } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import type { FormInstance } from 'ant-design-vue';
  defineOptions({ name: 'DeptModal' });

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

  const isUpdate = ref(true);

  const form = ref({
    remark:null,
    taskGroupId:null,
  })


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



  const taskInfo = ref({})
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
   
    taskInfo.value = data.record;
    form.value.taskGroupId = taskInfo.value.taskGroupId;
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

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

    const treeData = await getDeptList();
    updateSchema({
      field: 'parentId',
      componentProps: { treeData },
    });
  });

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

  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 addDept(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          form.value.remark = null;
          return createMessage.success('创建成功');


        } else {
          return createMessage.error('创建失败');
        }
      } else {
        const data = await updateDept(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          form.value.remark = null;
          return createMessage.success('编辑成功');
        } else {
          return createMessage.error('编辑失败');
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }



  const formRef = ref<FormInstance>();


  const handleReturnTask =async  ()=>{

    try {
      const values = await formRef.value.validateFields();
      if(values){
        returnTask(form.value).then(res=>{
          if(res){
            closeModal();
            emit('success');
            form.value.remark = null;
            createMessage.success("操作成功!")
          }else{
            createMessage.error("操作失败!");
          }
        })
      }else{
        
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }

const handleSubmitTask = async ()=>{
  submitTask(form.value).then(res=>{
    if(res){
      closeModal();
      emit('success');
      form.value.remark = null;
      createMessage.success("操作成功!")
    }else{
      createMessage.error("操作失败!");
    }
  })
}


  // 复制到剪贴板
  const copyToClipboard = async (record) => {
    try {
      await navigator.clipboard.writeText(record);
      createMessage.success('文本已复制到剪贴板');
    } catch (err) {
      createMessage.error('无法复制文本');
    }
  };

</script>

<style scoped>
::v-deep .ant-form-item-explain-error{
  text-align: left;
}
</style>