<template>
  <div class="comp-content">
    <Dialog
      :loading="loadingInterface"
      v-model="dialogVisible"
      diaTitle="项目信息"
      :width="500"
      :height="500"
      @close="closeFun"
      show-footer
    >
      <!-- <el-form :model="projectForm" label-width="100px">
        <el-form-item label="项目名称">
          <el-input v-model="projectForm.nodeName" />
        </el-form-item>
        <el-form-item label="项目代号">
          <el-input v-model="projectForm.nodeCode" />
        </el-form-item>
        <el-form-item label="项目类型">
          <el-select v-model="projectForm.nodeSubType" placeholder="请选择项目类型">
            <el-option
              v-for="user in PROJECT_TYPE.A"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目经理">
          <el-select multiple value-key="identity" v-model="projectForm.memberList" placeholder="请选择项目经理">
            <el-option
              v-for="user in userOptions"
              :key="user.identity"
              :label="user.name"
              :value="user"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间">
          <el-date-picker
            v-model="projectForm.beginTime"
            type="datetime"
            placeholder="选择日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="计划结束时间">
          <el-date-picker
            v-model="projectForm.endTime"
            type="datetime"
            placeholder="选择日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item type="textarea" label="项目描述">
          <el-input v-model="projectForm.description" />
        </el-form-item>
      </el-form> -->
      <TableForm @load="loadFun" ref="tableFormRef" tableName="NODE_LIST_LEVEL1" />
      <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';

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

const tableFormRef = ref();

const loadingInterface = ref(false);

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 addOrEditProject = async () => {
  console.log('tableFormRef.value', tableFormRef.value);
  if (await tableFormRef.value.validateFun()) {
    loadingInterface.value = true;
    console.log('projectForm', tableFormRef.value.getFormDataFun());
    const projectForm = tableFormRef.value.getFormDataFun();

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

    if (!props?.projectId) {
      await createProject(projectForm);
    } else {
      // console.log('编辑项目', projectForm);
      await editNode(projectForm);
      emits('update:currentProjectBaseInfo', { ...tableFormRef.value.getFormDataFun() });
    }
    loadingInterface.value = false;
    emits('completeFun', 'projectBasePage');

    closeFun();
  }
};

const createProject = async(projectForm:any) => {
  // console.log('projectForm', projectForm);
  // 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('创建项目成功');
  } else {
    ElMessage.error(res.msg || '创建项目失败');
  }
};

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,
  //     };
  //   });
  // }
  const res:any = await editNodeApi({ editNodeList: [{ ...projectForm }] });
  if (res && res.code === 200) {
    ElMessage.success('编辑项目成功');
  } else {
    ElMessage.error(res.msg || '编辑项目失败');
  }
};

const closeFun = () => {
  console.log('关闭弹窗');
  emits('update:modelValue', false);
};

// const nextPageFun = () => {
//   if (hasSameValue()) return;
//   emits('update:currentProjectBaseInfo', { ...tableFormRef.value.getFormDataFun(), nodeType: NODE_TYPE.PROJECT });
//   emits('nextPageFun', 'basePage');
// };

// const setEditForm = (val: any) => {
//   console.log('val', val, tableFormRef.value);
//   nextTick(() => {
//     const memberStr = getMemberListIds(val?.memberList);
//     tableFormRef.value.setFormDataFun({ ...val, memberList: memberStr });
//   });
// };

const setOptionsFun = (key: string, options: any[]) => {
  console.log('key options', key, options);
  tableFormRef.value.setOptionsFun(key, options);
};
const loadFun = async() => {
  await getNodeDetailFun();
  initTableForm();
};

const initTableForm = () => {
  console.log('tableFormRef.value', tableFormRef.value);
  if (tableFormRef.value) {
    let statusList = [];
    if (!props?.projectId) {
      statusList = [{ label: '未开始', value: PROJECT_EXE_STATUS_CODE.NOT_STARTED }];
      tableFormRef.value.resetFun();
      // 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);
  }
};

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

const getNodeDetailFun = async() => {
  if (tableFormRef.value) {
    if (!props?.projectId ) {
      for (const key in projectInfo) {
        projectInfo[key] = '';
      }
      tableFormRef.value.setFormDataFun({ 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];
        }
        console.log('123', { ...projectInfo, planTime: [projectInfo.beginTime, projectInfo.endTime], memberList: getMemberListIds(projectInfo.memberList) });
        tableFormRef.value.setFormDataFun({ ...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>
