<template>
  <!-- 新增待办 -->
  <div class="gl-page-content">
    <demandTable
      showIndex
      ref="tableRef"
      tableName="SIMULATION_TASK_DEMAND_CREATE"
      :params="{type:0}"
      :api="demandListApi"
      :actionsWidth="tableActionsLength['2-2']"
      exportFileName="新增待办需求"
    >
      <template #leftOptions>
        <el-button icon="plus" type="primary" @click="visibleDialog(true)">创建需求</el-button>
      </template>
      <template #tableActions="slotProps">
        <div class="gl-table-actions">
          <el-link type="primary" @click="visibleDialog(false,(slotProps as any).row)">编辑</el-link>
          <el-popconfirm
            title="确认删除吗？"
            @confirm="deleteDemandFun((slotProps as any).row.uuid)"
          >
            <template #reference>
              <el-link type="danger" >删除</el-link>
            </template>
          </el-popconfirm>
        </div>
      </template>
    </demandTable>
    <Dialog
      v-model="formVisible"
      :loading="loadingInterface"
      :diaTitle="isCreateDialog?'创建需求':'编辑需求'"
      :width="800"
      :height="500"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_TASK_DEMAND_CREATE"
        @change="changeFun($event,'form')"
        @remove="removeFileFun"
        @load="loadTableForm"
        :colNum="2"
      >
        <slot name="tableFormSlot"></slot>
      </TableForm>
      <template #footer>
        <div>
          <el-button @click="closeFun">取消</el-button>
          <el-button :loading="loadingInterface" type="primary" @click="confirmFun">确认</el-button>
        </div>
      </template>
    </Dialog>
  </div>
  <attachments :demandId="demandInfo.uuid" v-model:visible="attachmentsVisible" ></attachments>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import TableForm from '@/components/common/table/tableForm.vue';
import { addDemandApi, deleteDemandApi, demandListApi, editDemandApi } from '@/api/project/demand';
import { getChildrenNodeList } from '../../projectDetail/components/projectApi';
import { NODE_TYPE } from '@/utils/enum/node';
import { upload } from '@/api/request';
import { CommonStore } from '@/stores/common';
import attachments from '@/views/task/simulationTask/components/attachments.vue';
import { FILE_TYPE } from '@/utils/enum/file';
import { ElMessage } from 'element-plus';
import { dataDelFileApi, dataQueryDirApi } from '@/api/data/data';
import demandTable from '../components/demandTable.vue';
import { tableActionsLength } from '@/utils/common';
import { getMemberListIds } from '@/utils/task';

const env = import.meta.env;
const PREFIX = env.VITE_API_PREFIX_PROJECT;

const emits = defineEmits(['visibleDialog', 'loadTableForm']);

const commonStore = CommonStore();

const loadingInterface = ref(false);

const formVisible = ref(false);
const closeFun = () => {
  formVisible.value = false;
  attachmentsVisible.value = false;
  // 清空删除的文件
  deleteFileList.value = [];
};

const attachmentsVisible = ref(false);

const tableRef = ref();

const tableFormRef = ref();

const demandInfo = reactive({
  id: 0,
  uuid: '',
});

// SIMULATION_TASK_DEMAND_CREATE
// const headData = ref<any[]>([
//   { title: '任务名称', key: 'demandName', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '任务状态', key: 'taskStatus', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '风险状态', key: 'achievement', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '任务进度', key: 'progress', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '审批状态', key: 'approvalStatus', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '仿真负责人', key: 'simLeader', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '项目', key: 'projectId', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '阶段', key: 'phaseId', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '学科', key: 'nodeId', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '计划开始时间', key: 'beginTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '计划结束时间', key: 'endTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '实际结束时间', key: 'actualEndTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
// ]);

const isCreateDialog = ref(true);

const visibleDialog = async( visible:boolean, row?: any) => {
  console.log('row', row);
  formVisible.value = true;
  isCreateDialog.value = visible;
  if (!isCreateDialog.value) {
    const res:any = await dataQueryDirApi({ nodeId: row.id, current: 1, size: 99 });
    row.attachments = res.data?.data?.map((item: { originalName: any; fileSize: any;id:number }) => {
      return {
        name: item.originalName,
        size: item.fileSize,
        id: item.id,
      };
    }
    ) || [];
    let phaseList = [];
    if (row.phaseId) {
      phaseList = await getChildrenNodeList(NODE_TYPE.PHASE, row.projectId );
      phaseList = phaseList.map((item: any) => {
        return {
          label: item.nodeName,
          value: item.uuid,
        };
      });
    }
    let simList:any ;
    if (row.simType) {
      simList = commonStore.getDictData(row.demandType);
    }
    nextTick(() => {
      console.log('tableFormRef.value', tableFormRef.value);
      tableFormRef.value.setOptionsFun('phaseId', phaseList);
      tableFormRef.value.setOptionsFun('simType', simList.A);
      let pMemberList = '';
      if (row.pMemberList) {
        pMemberList = getMemberListIds(row.pMemberList);
      }
      tableFormRef.value.setFormDataFun({ ...row, pMemberList });
    });
  } else {
    nextTick(() => {
      tableFormRef.value.resetFun();
    });
  }
  emits('visibleDialog', { visible, row });
};

const deleteDemandFun = async (uuid: number) => {
  const res:any = await deleteDemandApi({ deleteNodeIdList: [uuid] });
  if (res.code === 200) {
    ElMessage.success('删除成功');
    tableRef.value.tableRef.resetFun();
  }
};

const confirmFun = async() => {
  if (await tableFormRef.value.validateFun()) {
    loadingInterface.value = true;
    const fromData:any = tableFormRef.value.getFormDataFun();
    console.log('fromData', fromData);
    if (fromData.planTime) {
      fromData.beginTime = fromData.planTime[0];
      fromData.endTime = fromData.planTime[1];
    }
    console.log('tableFormRef.value.getFormDataFun()', fromData);
    if (isCreateDialog.value) {
      const demandId = await createDemandApiFun(fromData);
      // 没有demandId就是创建需求失败
      if (demandId && fromData.attachments?.length > 0) {
        for (let index = 0; index < fromData.attachments.length; index++) {
          const form = new FormData();
          form.append('fileType', String(FILE_TYPE.DEMAND_ATTACHMENTS));
          form.append('nodeId ', demandId);
          form.append('dirId ', demandId);
          form.append('uuid ', demandId);
          form.append('fileName ', fromData.attachments[index].name);
          form.append('file ', fromData.attachments[index].raw);
          form.append('projectId ', String(fromData.projectId));
          upload(`${PREFIX}demand/uploadDemandFiles`, form);
        }
        formVisible.value = false;
      }
    } else {
      await editDemandApiFun(fromData);
    }
    loadingInterface.value = false;
    tableRef.value.tableRef.resetFun();
  }
};

const createDemandApiFun = async(fromData:any) => {
  const params = {
    'pid': fromData.nodeId,
    'demandName': fromData.demandName,
    'demandCode': fromData.demandCode,
    'demandStatus': '0',
    demandType: fromData.demandType,
    simType: fromData.simType,
    'beginTime': fromData.beginTime,
    'endTime': fromData.endTime,
    'pMemberList': fromData.pMemberList,
    eMemberList: '',
    'projectId': fromData.projectId,
    'phaseId': fromData.phaseId,
    'nodeId': fromData.nodeId,
    // extraList: [
    //   {
    //     propertyName: 'robotBrand',
    //     propertyValue: 'xxx',
    //     valueType: 'String',
    //     propertyClass: 'xxx',
    //   },
    // ],
  };
  const res:any = await addDemandApi(params);
  if (res.code === 200) {
    formVisible.value = false;
    ElMessage.success('创建成功');
    return res.data;
  } else {
    return null;
  }
};

const editDemandApiFun = async(fromData: any) => {
  console.log('fromData', fromData);
  // let addFileList = [];
  // let deleteFileList = [];
  // formData.attachments.forEach((item: any) => {
  //   if(item?.raw) {
  //     const form = new FormData();
  //     form.append('fileType', String(FILE_TYPE.DEMAND_ATTACHMENTS));
  //     form.append('nodeId ', String(demandInfo.id));
  //     form.append('fileName ', item.name);
  //     form.append('file ', item.raw);
  //     upload(`${PREFIX}data/uploadFiles`, form);
  //   }
  // })
  // oldAttachments.value.forEach((item: any) => {
  //   formData.attachments.some((item2: any) => item2.name ===)
  // })
  const res:any = await editDemandApi({ ...fromData, pMemberList: fromData.pMemberList, eMemberList: '' });
  if (res.code === 200) {
    ElMessage.success('修改成功');
    formVisible.value = false;
    if (fromData.attachments.length > 0) {
      fromData.attachments.forEach((item: any) => {
        if (item.raw) {
          const form = new FormData();
          form.append('fileType', String(FILE_TYPE.DEMAND_ATTACHMENTS));
          form.append('nodeId ', fromData.id);
          form.append('uuid ', fromData.uuid);
          form.append('fileName ', item.name);
          form.append('file ', item.raw);
          form.append('projectId ', String(fromData.projectId));
          upload(`${PREFIX}demand/uploadDemandFiles`, form);
        }
      });
    }
    if (deleteFileList.value.length > 0) {
      // todo 批量删除文件
      await dataDelFileApi({ delFileId: deleteFileList.value[0] });
    }
  }
};

const deleteFileList = ref<number[]>([]);

const changeFun = async (val: any, type:string) => {
  console.log('val', val);
  let optionRef :any;
  if (type === 'search') {
    optionRef = tableRef.value;
  } else {
    optionRef = tableFormRef.value;
  }
  // if (val.key === 'projectId' || val.key === 'phaseId') {
  //   console.log('changeFun', val);
  //   let nodeType = '';
  //   let nextKey = '';
  //   let nodeId = '';
  // val.key === 'phaseId' ||
  if (val.key === 'attachments') {
    deleteFileList.value.push(val.data.id);
  }

  if (val.key === 'projectId') {
    console.log('changeFun', val);
    let nodeType = '';
    let nextKey = '';
    let nodeId = '';
    if (val.key === 'projectId') {
      nodeType = NODE_TYPE.PHASE;
      nextKey = 'phaseId';
      nodeId = val.data.projectId;
    }
    const optionList = await getPhaseList(nodeType, nodeId);
    optionRef.setOptionsFun(nextKey, optionList);
    const formData = optionRef.getFormDataFun();
    optionRef.setFormDataFun({ ...formData, phaseId: '' });
  }
  if (val.key === 'demandType') {
    const simTypeList: any = commonStore.getDictData(val.data.demandType);
    optionRef.setOptionsFun('simType', simTypeList.A);
    const formData = optionRef.getFormDataFun();
    optionRef.setFormDataFun({ ...formData, simType: '' });
  }
};

const removeFileFun = (val: any) => {
  console.log('val', val, val.val.id);
  deleteFileList.value.push(val.val.id);
};

const getPhaseList = async (nodeType:string, projectUuid: string) => {
  let optionList = await getChildrenNodeList(nodeType, projectUuid );
  optionList = optionList.map((item: any) => {
    return {
      label: item.nodeName,
      value: item.uuid,
    };
  });
  return optionList;
};

const loadTableForm = () => {
  emits('loadTableForm');
};

// const searchChange = async (val: any) => {
//   console.log('val', val);
//     const optionList = await getPhaseList(nodeType, nodeId);
//     tableFormRef.value.setOptionsFun(nextKey, optionList);
// };
defineExpose({
  tableFormRef,
});
</script>
