<template>
  <!-- 新增待办 -->
  <div class="gl-page-content-full">
    <demandTable
      showIndex
      ref="tableRef"
      tableName="SIMULATION_TASK_DEMAND_CREATE"
      :params="demandParams"
      :api="demandListApi"
      exportFileName="新增待办需求"
      :actionList="actionList"
      @show="showTaskDetailFun"
      :name-click="false"
    >
      <template #leftOptions>
        <el-button
          v-if="enableConfigByTenant([TENANT_ENUM.LYRIC])"
          icon="Refresh"
          type="primary"
          @click="syncDemandList"
          >同步</el-button
        >
        <el-button icon="plus" type="primary" @click="visibleDialog(true)">创建需求</el-button>
      </template>
    </demandTable>
    <Dialog
      v-model="formVisible"
      :loading="loadingInterface"
      :diaTitle="isCreateDialog ? '创建需求' : '编辑需求'"
      :width="800"
      :height="650"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_TASK_DEMAND_CREATE"
        @change="changeFun($event, 'form')"
        @load="loadTableForm"
        :colNum="2"
        :hideKeys="hideKeys.concat(formHideKeys)"
        v-model:data="editFormInfo"
      >
        <template #form-pMemberList>
          <el-select v-model="editFormInfo.pMemberList" filterable placeholder="请选择">
            <el-option
              v-for="item in deptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
        <!-- <template v-for="name in Object.keys($slots)" :key="name" #[name]="scope">
          <slot :name="name" v-bind="scope" />
        </template> -->
      </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 { batchAddFileInfoApi, dataDelFileApi, dataQueryDirApi } from '@/api/data/data';
import demandTable from '../components/demandTable.vue';
import { getMemberListIds } from '@/utils/task';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';
import { syncDemandList } from '../taskPage';
import { getChildrenNodeListApi } from '@/api/project/node';
import type { Options } from '@/types';
import { listDeptApi } from '@/api/system/departMent';
import { uploadBigFile } from '@/utils/file';
// import emitter from '@/utils/eventBus';

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

defineProps({
  hideKeys: {
    type: Array,
    default: () => [],
  },
  deptOptions: {
    type: Array<Options>,
    default: () => [],
  },
});

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

const demandParams = ref({ type: 0 });

const commonStore = CommonStore();

const showTaskDetailFun = (row: any) => {
  // showTaskDetailDialog.value = true;
  // currentTaskInfo.value = row;

  visibleDialog(false, row);
};
const actionList = ref([
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      visibleDialog(false, row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row: any) => {
      deleteDemandFun(row.uuid);
    },
  },
]);

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: '',
});

const isCreateDialog = ref(true);

const editFormInfo = ref<any>({});

const visibleDialog = async (isCreate: boolean, row?: any) => {
  formVisible.value = true;
  isCreateDialog.value = isCreate;
  loadingInterface.value = true;
  if (isCreate) {
    formHideKeys.value = ['materialNo'];
    nextTick(() => {
      tableFormRef.value.resetFun();
    });
  }
  if (!isCreateDialog.value) {
    if (row?.isMoldMaking === 'Y') {
      formHideKeys.value = [];
    } else {
      formHideKeys.value = ['materialNo'];
    }
    const res: any = await dataQueryDirApi({ uuid: row.uuid, 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,
        };
      }) || [];
    oldAttachments.value = [...row.attachments];
    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 workspaceList = [];
    if (row.workspace && row.phaseId) {
      workspaceList = await getChildrenNodeList(NODE_TYPE.WORKSPACE, row.phaseId);
      workspaceList = workspaceList.map((item: any) => {
        return {
          label: item.nodeName,
          value: item.uuid,
        };
      });
    }
    let simList: any;
    if (row.simType) {
      simList = commonStore.getDictData(row.demandType);
    }
    row.planTime = [row.beginTime, row.endTime];

    nextTick(() => {
      tableFormRef.value.setOptionsFun('phaseId', phaseList);
      tableFormRef.value.setOptionsFun('workspace', workspaceList);
      if (simList?.A) {
        tableFormRef.value.setOptionsFun('simType', simList.A);
      }
      let pMemberList = '';
      if (row.pMemberList) {
        pMemberList = getMemberListIds(row.pMemberList);
      }
      let tMemberList = '';
      if (row.tMemberList) {
        tMemberList = getMemberListIds(row.tMemberList);
      }
      let aMemberList = '';
      if (row.aMemberList) {
        aMemberList = getMemberListIds(row.aMemberList);
      }
      editFormInfo.value = {
        ...row,
        pMemberList,
        tMemberList,
        aMemberList,
      };
      // tableFormRef.value.setFormDataFun({ ...row, pMemberList, tMemberList, aMemberList });
    });
  } else {
    editFormInfo.value = {};
    // nextTick(() => {
    //   tableFormRef.value.resetFun();
    // });
  }
  emits('visibleDialog', { isCreate, row });
  loadingInterface.value = false;
};

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();
    if (fromData.planTime) {
      fromData.beginTime = fromData.planTime[0];
      fromData.endTime = fromData.planTime[1];
    }
    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('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);
        // }
      }
      const params = {
        fileList: fromData.attachments.filter((item: any) => item.raw), // 文件列表
        // dirId: demandId, // 文件目录id
        projectId: fromData.projectId, // 项目id
        callbackFlag: '/task/sponsor', // 回调标识
        uuid: demandId,
      };
      await uploadBigFile(params, batchAddFileInfoApi);
      // batchUploadFile(fromData.attachments, fromData.projectId, demandId);
      formVisible.value = false;
    } else {
      await editDemandApiFun(fromData);
    }
    loadingInterface.value = false;
    tableRef.value.tableRef.resetFun();
  }
};

// const batchUploadFile = async (files: any[], projectUuid: string, uuid: string) => {
//   const sourceFiles = [];
//   for (let index = 0; index < files.length; index++) {
//     sourceFiles.push({
//       fileName: files[index].name,
//       size: files[index].size,
//       fileType: await fileUploadAllocationTypeFun(files[index].name),
//     });
//   }
//   if (sourceFiles.length > 0) {
//     const params = {
//       sourceFiles,
//       uploadTaskId: new Date().getTime(),
//       projectId: projectUuid,
//       uuid: uuid,
//       type: 0,
//       remarks: '',
//     };
//     batchAddFileInfoApi(params).then((res: any) => {
//       if (res.code === 200) {
//         res.data.forEach((item: any, index: number) => {
//           emitter.emit('ADD_UPLOAD_FILE', {
//             file: files[index]?.raw,
//             data: {
//               ...item,
//               isApprove: 0,
//               taskType: 5,
//               callbackFlag: '/task/sponsor',
//             },
//           });
//         });
//       }
//     });
//   }
// };

const createDemandApiFun = async (fromData: any) => {
  const params = {
    pid: fromData.nodeId,
    // 'demandName': fromData.demandName,
    // 'demandCode': fromData.demandCode,
    // 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,
    ...fromData,

    demandStatus: '0',
  };
  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) => {
  // 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) {
      const files = fromData.attachments.filter((item: any) => item.raw);
      const params = {
        fileList: files, // 文件列表
        // dirId: fromData.uuid, // 文件目录id
        projectId: fromData.projectId, // 项目id
        callbackFlag: '/task/sponsor', // 回调标识
        // isApprove: 0, // 0不需要审批 1需要审批 默认0
        // type: 0,
        uuid: fromData.uuid,
      };
      await uploadBigFile(params, batchAddFileInfoApi);

      // batchUploadFile(
      //   fromData.attachments.filter((item: any) => item.raw),
      //   fromData.projectId,
      //   fromData.uuid
      // );
      // 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);
      //   }
      // });
    }
    oldAttachments.value.forEach((item: any) => {
      if (
        !fromData.attachments.some((item2: any) => {
          if (item2.name === item.name) {
            return true;
          }
        })
      ) {
        dataDelFileApi({ delFileId: item.id });
      }
    });
  }
};

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

const oldAttachments = ref<any[]>([]);

const formHideKeys = ref<any[]>(['materialNo']);

const changeFun = async (val: any, type: string) => {
  const formData = tableFormRef.value.getFormDataFun();
  // editFormInfo.value = { ...formData };
  if (val.key === 'projectId') {
    let nodeType = '';
    let nextKey = '';
    let nodeId = '';
    if (val.key === 'projectId') {
      nodeType = NODE_TYPE.PHASE;
      nextKey = 'phaseId';
      nodeId = val.data.projectId;
      let pMemberId = '';
      for (let index = 0; index < val.val.extras.length; index++) {
        if (val.val.extras[index]?.propertyName === 'projectUndertaker') {
          const deptList = await listDeptApi({ current: 1, size: 999 });
          const dept = deptList.data.data.find((item: any) => {
            return item.deptName === val.val.extras[index].propertyValue;
          });
          if (dept) {
            pMemberId = dept.userId;
          }
        }
      }
      formData.pMemberList = pMemberId;
    }
    if (nodeId) {
      const optionList = await getPhaseList(nodeType, nodeId);
      tableFormRef.value.setOptionsFun(nextKey, optionList);
      if (nextKey === 'phaseId' && optionList.length > 0) {
        formData.phaseId = optionList[0].value;
        const workspaceInfo = await getWorkSpaceList(formData.phaseId);
        formData.workspace = workspaceInfo.value;
        formData.workspaceName = workspaceInfo.label;
        formData.extras = setWorkSpaceValue(
          formData.extras,
          formData.workspace,
          formData.workspaceName
        );
      }
      if (optionList.length === 0) {
        formData.phaseId = '';
      }
    } else {
      tableFormRef.value.setOptionsFun(nextKey, []);
      formData.phaseId = '';
      formData.workspace = '';
      formData.workspaceName = '';
      formData.extras = setWorkSpaceValue(formData.extras, '', '');
    }
    // const formData = tableFormRef.value.getFormDataFun();
    // tableFormRef.value.setFormDataFun({ ...formData, phaseId: '' });
    editFormInfo.value = { ...formData };
  }

  if (val.key === 'phaseId') {
    if (formData.phaseId) {
      const workspaceInfo = await getWorkSpaceList(formData.phaseId);
      formData.workspace = workspaceInfo.value;
      formData.workspaceName = workspaceInfo.label;
      formData.extras = setWorkSpaceValue(
        formData.extras,
        formData.workspace,
        formData.workspaceName
      );
    } else {
      formData.workspace = '';
      formData.workspaceName = '';
      formData.extras = setWorkSpaceValue(
        formData.extras,
        formData.workspace,
        formData.workspaceName
      );
    }
    editFormInfo.value = { ...formData };
  }
  if (val.key === 'workspace') {
    if (formData.workspace) {
      formData.workspace = val.val.value;
      formData.workspaceName = val.val.label;
      formData.extras = setWorkSpaceValue(
        formData.extras,
        formData.workspace,
        formData.workspaceName
      );
    } else {
      formData.workspace = '';
      formData.workspaceName = '';
      formData.extras = setWorkSpaceValue(
        formData.extras,
        formData.workspace,
        formData.workspaceName
      );
    }
    editFormInfo.value = { ...formData };
  }
  if (val.key === 'isMoldMaking') {
    if (val.val?.value === 'Y') {
      formHideKeys.value = [];
    } else {
      formHideKeys.value = ['materialNo'];
    }
  }
  emits('changeForm', { val, type });
};

const setWorkSpaceValue = (extras: any, workspace: string, workspaceName: string) => {
  return extras.map((item: any) => {
    if (item.propertyName === NODE_TYPE.WORKSPACE) {
      item.propertyValue = workspace;
    }
    if (item.propertyName === NODE_TYPE.WORKSPACE + 'Name') {
      item.propertyValue = workspaceName;
    }
    return {
      ...item,
    };
  });
};

const getWorkSpaceList = async (phaseId: string) => {
  const res: any = await getChildrenNodeListApi({
    current: 1,
    size: 999,
    nodeId: phaseId,
    nodeType: NODE_TYPE.WORKSPACE,
  });
  if (res.code === 200) {
    if (res.data.length === 0) {
      ElMessage.warning('该阶段下没有工位，请先做仿真策划！');
    } else {
      const optionList = res.data.map((item: { nodeName: string; uuid: string }) => {
        return {
          label: item.nodeName,
          value: item.uuid,
        };
      });
      tableFormRef.value.setOptionsFun(NODE_TYPE.WORKSPACE, optionList);
      if (optionList.length > 0) {
        return optionList[0];
      }
    }
  }
  return {
    label: '',
    value: '',
  };
};

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) => {
//     const optionList = await getPhaseList(nodeType, nodeId);
//     tableFormRef.value.setOptionsFun(nextKey, optionList);
// };
defineExpose({
  tableFormRef,
  editFormInfo,
});
</script>
