<template>
  <!-- 新增待办 -->
  <div class="gl-page-content-full">
    <demandTable
      showIndex
      ref="tableRef"
      tableName="SIMULATION_TASK_DEMAND_CREATE"
      :params="demandParams"
      :api="demandListApi"
      :searchAttrs="{
        projectId: {
          auth: false,
        },
      }"
      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"
          v-permission="'demand_add_demand'"
          @click="visibleDialog(true)"
          >创建需求</el-button
        >
      </template>
    </demandTable>
    <Dialog
      v-model="formVisible"
      :loading="loadingInterface"
      :diaTitle="isCreateDialog ? '创建需求' : '编辑需求'"
      width="60%"
      :height="700"
      @close="closeFun"
      show-footer
    >
      <div class="tabs">
        <el-tabs @tab-change="changeSimulationType" v-model="simulationType" type="card">
          <el-tab-pane
            v-for="item in simulationTypeList"
            :label="item.label + '待办'"
            :name="item.value"
            :key="item.value"
          />
        </el-tabs>
      </div>
      <PlanningInformation :data="simulationType"></PlanningInformation>
      <!-- <div class="message-info">
        <div v-if="simulationType === SIMULATION_TYPE.FINITE_ELEMENT" class="message-item">
          1、有限元仿真登记提醒： 若不清楚本待办需求如何填写，请看<span class="down-file"
            >《填写指导书》</span
          >。
        </div>
      </div> -->
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_TASK_DEMAND_CREATE"
        :formAttrs="{
          projectId: {
            auth: false,
          },
        }"
        :colNum="2"
        :hideKeys="hideKeys.concat(formHideKeys)"
        v-model:data="editFormInfo"
        @change="changeFun($event, 'form')"
        @load="loadTableForm"
      >
        <template #form-pMemberList>
          <el-select v-model="editFormInfo.pMemberList" filterable placeholder="请选择">
            <el-option
              v-for="item in deptOptions"
              :key="item.value + item.label"
              :label="item.label + '(' + item.userName + ')'"
              :value="item.value + '-' + item.label"
            />
          </el-select>
        </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 {
  addDemandNoPermissionApi,
  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 { listDeptApi } from '@/api/system/departMent';
import { uploadBigFile } from '@/utils/file';
import { getDemandHideKeys } from '@/tenants/lyric/views/task/lyricTask';
import PlanningInformation from '@/tenants/lyric/views/task/components/planningInformation.vue';
// 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<any>,
    default: () => [],
  },
});

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

// enum SIMULATION_TYPE {
//   /** 有限元仿真待办 */
//   FINITE_ELEMENT = 'finiteElement',
//   /** 机器人仿真待办 */
//   ROBOT = 'robot',
//   /** 动画仿真待办 */
//   DYNAMIC = 'dynamic',
//   /** 外观设计待办 */
//   INDUSTRIAL_DESIGN = 'industrialDesign',
// }

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 = () => {
  tableFormRef.value.resetFun();
  formVisible.value = false;
  attachmentsVisible.value = false;
  // 清空删除的文件
  deleteFileList.value = [];
  tableFormRef.value?.resetFun();
};

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) {
  //   nextTick(() => {
  //     tableFormRef.value.resetFun();
  //   });
  // }
  nextTick(() => {
    changeSimulationType(simulationType.value);
  });
  if (!isCreateDialog.value) {
    simulationType.value = row.demandType;
    // 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,
          parentId: item.parentId,
        };
      });
    }
    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 files = fromData.attachments.filter((item: any) => item.raw);
      if (files.length > 0) {
        const params = {
          fileList: files, // 文件列表
          // 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 getPMemberId = () => {
  const pMemberIdArr = editFormInfo.value.pMemberList.split('-');
  let pMemberId = '';
  if (pMemberIdArr.length > 0) {
    pMemberId = pMemberIdArr[0];
  }
  return pMemberId;
};

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,
    pMemberList: getPMemberId(),

    demandStatus: '0',

    machineId: fromData.machineId,
    workspaceId: fromData.workspace,

    // 待办所属类型
    demandType: simulationType.value,

    // 是否走利元亨创建需求直接创建任务逻辑
    isLyric: enableConfigByTenant([TENANT_ENUM.LYRIC]),
  };
  // console.log('params', params, editFormInfo.value);
  // return;
  const res: any = await addDemandNoPermissionApi(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: getPMemberId(),
    eMemberList: '',
    machineId: fromData.machineId,
    workspaceId: fromData.workspace,
  });
  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[]>([]);

const currentProjectUndertaker = ref('');

const simulationTypeList = ref(commonStore.getDictData('SIMULATION_TYPE').A);
const simulationType = ref(simulationTypeList.value[0].value);

const changeSimulationType = (val: string) => {
  let simTypeList = [];
  simTypeList = commonStore.getDictData(val).A;
  tableFormRef.value.setOptionsFun('simType', simTypeList);
  formHideKeys.value = getDemandHideKeys(val);
};

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;
      currentProjectUndertaker.value = '';
      for (let index = 0; index < val.val.extras.length; index++) {
        if (val.val.extras[index]?.propertyName === 'projectUndertaker') {
          currentProjectUndertaker.value = val.val.extras[index].propertyValue;
        }
      }
      if (formData.simType) {
        await disposeDeptMember();
        // formData.pMemberList = await disposeDeptMember();
      }
    }
    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.machineId = '';
        if (formData.phaseId !== workspaceInfo.parentId) {
          formData.machineId = workspaceInfo.parentId;
        }
        formData.workspaceName = workspaceInfo.label;
        formData.extras = setWorkSpaceValue(
          formData.extras,
          formData.workspace,
          formData.workspaceName
        );
      }
      if (optionList.length === 0) {
        formData.phaseId = '';
        // 清空工位数据
        formData.extras = setWorkSpaceValue(formData.extras, '', '');
        tableFormRef.value.setOptionsFun(NODE_TYPE.WORKSPACE, []);
      }
    } 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.machineId = '';
      if (formData.phaseId !== workspaceInfo.parentId) {
        formData.machineId = workspaceInfo.parentId;
      }
      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.machineId = '';
      if (formData.phaseId !== val.val.parentId) {
        formData.machineId = val.val.parentId;
      }
      formData.workspace = val.val.value;
      formData.workspaceName = val.val.label;
      formData.extras = setWorkSpaceValue(
        formData.extras,
        formData.workspace,
        formData.workspaceName
      );
    } else {
      formData.machineId = '';
      formData.workspace = '';
      formData.workspaceName = '';
      formData.extras = setWorkSpaceValue(
        formData.extras,
        formData.workspace,
        formData.workspaceName
      );
    }
    editFormInfo.value = { ...formData };
  }
  if (val.key === 'simType') {
    if (formData.projectId) {
      await disposeDeptMember();
      // formData.pMemberList = await disposeDeptMember();
    }
  }

  // if (val.key === 'isMoldMaking') {
  //   if (val.val?.value === 'Y') {
  //     formHideKeys.value = [];
  //   } else {
  //     formHideKeys.value = ['materialNo'];
  //   }
  // }
  emits('changeForm', { val, type });
};

const deptList = ref<any[]>([]);
const disposeDeptMember = async () => {
  let pMemberId = '';
  editFormInfo.value.pMemberList = '';
  if (deptList.value.length === 0) {
    const res = await listDeptApi({ current: 1, size: 999 });
    deptList.value = res.data.data;
  }
  const matchingDeptList = deptList.value.filter((item: any) => {
    return item.deptName.indexOf(currentProjectUndertaker.value) !== -1;
  });
  if (matchingDeptList.length > 0) {
    if (matchingDeptList.length === 1) {
      pMemberId = matchingDeptList[0].userId;
      editFormInfo.value.pMemberList =
        matchingDeptList[0].userId + '-' + matchingDeptList[0].deptName;
    } else {
      const machDept = matchingDeptList.find((item: any) => {
        return item.deptName.indexOf(editFormInfo.value.simType) !== -1;
      });
      if (machDept) {
        pMemberId = machDept.userId;
        editFormInfo.value.pMemberList = machDept.userId + '-' + machDept.deptName;
      }
    }
  }
  return pMemberId;
};

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('该阶段下没有工位，请先做仿真策划！');
      // 清空工位数据
      tableFormRef.value.setOptionsFun(NODE_TYPE.WORKSPACE, []);
    } else {
      const optionList = res.data.map((item: any) => {
        return {
          label: item.nodeName,
          value: item.uuid,
          parentId: item.parentId,
        };
      });
      tableFormRef.value.setOptionsFun(NODE_TYPE.WORKSPACE, optionList);
      if (optionList.length > 0) {
        return optionList[0];
      }
    }
  }
  return {
    label: '',
    value: '',
    parentId: '',
  };
};

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>
