<template>
  <div class="comp-content">
    <Dialog
      :loading="loadingInterface"
      v-model="dialogVisible"
      diaTitle="项目信息"
      :width="500"
      :height="600"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="NODE_LIST_LEVEL1"
        :formAttrs="formAttrs"
        @load="loadFun"
        @change="formChangeFun"
        v-model:data="editRowInfo"
      >
        <template #form-epProjectSelect="{ attrs: slotAttrs }">
          <EpProjectSelect
            v-model="epProjectId"
            :disabled="slotAttrs?.disabled"
            @select="epProjectSelectFun"
          />
        </template>
      </TableForm>

      <template #footer>
        <div>
          <el-button @click="closeFun">取消</el-button>
          <el-button type="primary" :loading="loadingInterface" @click="addOrEditProject"
            >完成</el-button
          >
        </div>
      </template>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { addNodeApi, editNodeApi, getNodeDetailApi } from '@/api/project/node';
import Dialog from '@/components/common/dialog/index.vue';
import { getTagKeyMap, NODE_TYPE } from '@/utils/enum/node';
import { ElMessage } from 'element-plus';
import { computed, reactive, ref, watch } from 'vue';
import { getProjectExeStatus } from '@/views/task/projectDetail/components/project';
import { getTagMapList } from '@/utils/task';
import TableForm from '@/components/common/table/tableForm.vue';
import { PROJECT_EXE_STATUS_CODE } from '@/utils/enum/project';
import { getMemberListIds } from '@/utils/task';
import dayjs from 'dayjs';
import EpProjectSelect from './epProjectSelect.vue';

const props = defineProps<{
  modelValue: boolean;
  nodeLevel1List: Array<any>;
  projectId?: any;
}>();

const tableFormRef = ref();

const loadingInterface = ref(false);
const epProjectId = ref<number | null>(null);
const formAttrs = computed(() => {
  return {
    projectSource: { disabled: !!props.projectId },
    epProjectSelect: { disabled: projectInfo.projectSource !== 'EP' || !!props.projectId },
    nodeName: { disabled: projectInfo.projectSource === 'EP' },
    nodeCode: { disabled: projectInfo.projectSource === 'EP' },
    projectId: { disabled: projectInfo.projectSource === 'EP' },
  };
});

const dialogVisible = computed(() => {
  return props.modelValue;
});
const emits = defineEmits([
  'update:modelValue',
  'update:currentProjectBaseInfo',
  'nextPageFun',
  'completeFun',
]);
// const projectForm = reactive<any>({
//   nodeName: '',
//   nodeCode: '',
//   nodeSubType: '',
//   memberList: [],
//   beginTime: '',
//   endTime: '',
//   description: '',
// });

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

const addOrEditProject = async () => {
  if (await tableFormRef.value.validateFun()) {
    loadingInterface.value = true;
    const projectForm = tableFormRef.value.getFormDataFun();

    let result;
    if (projectForm.planTime) {
      projectForm.beginTime = projectForm.planTime[0];
      projectForm.endTime = projectForm.planTime[1];
    }

    if (!props?.projectId) {
      result = await createProject(projectForm);
    } else {
      result = await editNode(projectForm);
      emits('update:currentProjectBaseInfo', { ...tableFormRef.value.getFormDataFun() });
    }
    loadingInterface.value = false;
    emits('completeFun', 'projectBasePage');

    if (result?.code === 200) {
      closeFun();
    }
  }
};

const createProject = async (projectForm: any) => {
  // const memberList = projectForm.memberList.map((item: any) => {
  //   return JSON.parse(item);
  // });
  // if (projectForm.memberList) {
  //   projectForm.memberList = projectForm.memberList.map((item: any) => {
  //     return {
  //       name: item.nickname,
  //       identity: item.id,
  //     };
  //   });
  // }
  const tagKeyMap = getTagKeyMap();
  const res: any = await addNodeApi({
    addNodeList: [
      {
        ...projectForm,
        pid: '',
        nodeType: NODE_TYPE.PROJECT,
        [tagKeyMap.get(NODE_TYPE.PROJECT)]: null,
      },
    ],
    tagMap: getTagMapList(),
  });
  if (res && res.code === 200) {
    emits('update:currentProjectBaseInfo', {
      ...projectForm,
      nodeType: NODE_TYPE.PROJECT,
      id: res.data[0].uuid,
      uuid: res.data[0].uuid,
    });
    ElMessage.success('创建项目成功');
  }
  return res;
};

const editNode = async (projectForm: any) => {
  // const memberList = projectForm.memberList.map((item: any) => {
  //   return JSON.parse(item);
  // });
  // if (projectForm.memberList) {
  //   projectForm.memberList = projectForm.memberList.map((item: any) => {
  //     return {
  //       name: item.nickname,
  //       identity: item.id,
  //     };
  //   });
  // }
  if (projectForm.exeStatus === PROJECT_EXE_STATUS_CODE.COMPLETED) {
    projectForm.finishTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
  }
  const res: any = await editNodeApi({ editNodeList: [{ ...projectForm }] });
  if (res && res.code === 200) {
    ElMessage.success('编辑项目成功');
  }
  return res;
};

const closeFun = () => {
  loadingInterface.value = false;
  emits('update:modelValue', false);
};

const setOptionsFun = (key: string, options: any[]) => {
  tableFormRef.value.setOptionsFun(key, options);
};

const formChangeFun = (val: any) => {
  if (val.key === 'projectSource') {
    projectInfo.projectSource = val.data.projectSource;
  }
};

const epProjectSelectFun = (row: any) => {
  if (tableFormRef.value) {
    editRowInfo.value = {
      ...tableFormRef.value.getFormDataFun(),
      nodeCode: row.projectNum,
      nodeName: row.projectName,
      projectId: row.id,
      // EP的项目主体字段 放到拓展字段
      projectUndertaker: row.projectUndertaker,
    };

    // EP的项目主体字段 放到拓展字段
    editRowInfo.value.extras = editRowInfo.value.extras.map((item: any) => {
      if (item.propertyName === 'projectUndertaker') {
        item.propertyValue = editRowInfo.value.projectUndertaker;
      }
      return {
        ...item,
      };
    });
    // tableFormRef.value.setFormDataFun({
    //   ...tableFormRef.value.getFormDataFun(),
    //   nodeCode: row.projectNum,
    //   nodeName: row.projectName,
    //   projectId: row.id,
    // });
  }
};
const loadFun = async () => {
  await getNodeDetailFun();
  initTableForm();
};

const initTableForm = () => {
  if (tableFormRef.value) {
    let statusList = [];
    if (!props?.projectId) {
      statusList = [{ label: '未开始', value: PROJECT_EXE_STATUS_CODE.NOT_STARTED }];
      // tableFormRef.value.resetFun();
      editRowInfo.value = {};
      // setEditForm({ exeStatus: PROJECT_EXE_STATUS_CODE.NOT_STARTED });
    } else {
      // setEditForm({ ...props.currentRow });
      statusList = getProjectExeStatus(projectInfo.exeStatus as PROJECT_EXE_STATUS_CODE);
    }
    tableFormRef.value.setOptionsFun('exeStatus', statusList);
    if (statusList.length > 0 && editRowInfo.value.exeStatus === undefined) {
      editRowInfo.value.exeStatus = statusList[0].value;
    }
  }
};

const projectInfo = reactive<any>({});

const resetState = () => {
  epProjectId.value = null;
  Object.keys(projectInfo).forEach((key) => delete projectInfo[key]);
};

const getNodeDetailFun = async () => {
  if (tableFormRef.value) {
    if (!props?.projectId) {
      resetState();
      // tableFormRef.value.setFormDataFun({ exeStatus: PROJECT_EXE_STATUS_CODE.NOT_STARTED });
      editRowInfo.value = { exeStatus: PROJECT_EXE_STATUS_CODE.NOT_STARTED };
    } else {
      const res: any = await getNodeDetailApi({ projectNodeId: props.projectId });
      if (res.code === 200) {
        for (const key in res.data) {
          projectInfo[key] = res.data[key];
        }
        // tableFormRef.value.setFormDataFun({
        //   ...projectInfo,
        //   planTime: [projectInfo.beginTime, projectInfo.endTime],
        //   memberList: getMemberListIds(projectInfo.memberList),
        // });
        editRowInfo.value = {
          ...projectInfo,
          planTime: [projectInfo.beginTime, projectInfo.endTime],
          memberList: getMemberListIds(projectInfo.memberList),
        };
      }
    }
  }
};

watch(
  () => props.modelValue,
  async (val: any) => {
    if (val) {
      await getNodeDetailFun();
      initTableForm();
    }
  },
  {
    immediate: true,
  }
);
// onMounted(() => {
//   setOptions('onMounted');
// });

defineExpose({
  // projectForm,
  createProject,
  setOptionsFun,
});
</script>
