<template>
  <div class="project-overview-page">
    <!-- <loadCaseTable
      ref="baseTableRef"
      readonly
      tableName="PROJECT_TASK_TREE_LIST"
      :data="treeData"
      :loading="tableLoading"
    >
    </loadCaseTable> -->

    <BaseTable
      ref="baseTableRef"
      hide-pagination
      tableName="PROJECT_TASK_TREE_LIST"
      :show-node-name="'nodeName'"
      :loading="tableLoading"
      :tree-config="{
        expandAll: true,
        rowField: 'uuid',
        childrenField: 'children',
      }"
      :action-list="actionList"
      :full-height="true"
    >
      <template #leftOptions>
        <el-form inline :model="filterParamFormData">
          <!-- <el-form-item label="项目">
            <el-select
              class="select-style200"
              v-model="filterParamFormData.projectNodeId"
              @change="changeSelectFun('project')"
              clearable
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.nodeName"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="阶段">
            <el-select
              class="select-style200"
              v-model="filterParamFormData.phaseNodeId"
              @change="changeSelectFun('phase')"
              clearable
            >
              <el-option
                v-for="item in phaseList"
                :key="item.id"
                :label="item.nodeName"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="展开">
            <el-select
              class="select-style100"
              v-model="filterParamFormData.expandType"
              @change="expandTreeFun"
            >
              <el-option
                v-for="item in expandTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="returnListFun">返回列表</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template #nodeName="{ row }">
        <div class="node-name">
          <el-icon v-if="row.nodeType === NODE_TYPE.TASK" :size="16" class="blue">
            <Document />
          </el-icon>
          <el-icon v-else-if="row.nodeType === NODE_TYPE.PERFORMANCE" :size="16" class="blue">
            <Operation />
          </el-icon>
          <el-icon v-else :size="16" class="blue">
            <Folder />
          </el-icon>
          <span class="name">{{ row.nodeName }}</span>
        </div>
      </template>

      <!-- 执行状态 -->
      <template #exeStatus="{ row }">
        <!-- <span v-if="row.nodeType === NODE_TYPE.TASK">
          <span :class="getTaskExeStyleClass(row.exeStatus)"> </span>
          {{ TASK_EXE_STATUS.O[row.exeStatus] }}
        </span> -->
        <StatusDot
          v-if="row.nodeType === NODE_TYPE.TASK"
          :status="getTaskExeStyleClass(row.exeStatus)"
          :title="TASK_EXE_STATUS.O[row.exeStatus]"
        />
      </template>
      <!-- 达成状态 -->
      <template #achieveStatus="{ row }">
        <!-- <span v-if="row.nodeType === NODE_TYPE.TASK">
          <span :class="getTaskAchieveStyleClass(row.achieveStatus)"> </span>
          {{ RESULT_ACHIEVE_STATUS.O[row.achieveStatus] }}
        </span> -->
        <StatusDot
          v-if="row.nodeType === NODE_TYPE.TASK"
          :status="getTaskAchieveStyleClass(row.achieveStatus)"
          :title="RESULT_ACHIEVE_STATUS.O[row.achieveStatus]"
        />
      </template>
      <!-- 审批状态 -->
      <template #approvalStatus="{ row }">
        <StatusDot
          v-if="
            row.nodeType === NODE_TYPE.TASK ||
            (enableConfigByTenant([TENANT_ENUM.LYRIC]) && row.nodeType === NODE_TYPE.WORKSPACE)
          "
          :status="
            getApproveStyleClass(
              Number(row.approvalStatus) || TASK_APPROVE_STATUS_ENUM.NOT_APPROVED
            )
          "
          :title="
            TASK_APPROVE_STATUS.O[row.approvalStatus || TASK_APPROVE_STATUS_ENUM.NOT_APPROVED]
          "
        >
        </StatusDot>
      </template>

      <!-- 应达成进度 -->
      <template #shouldProgress="{ row }">
        {{ TASK_PROGRESS_STATUS.O[row.shouldProgress] }}
      </template>
      <!-- 实际达成进度 -->
      <template #actualProgress="{ row }">
        {{ TASK_PROGRESS_STATUS.O[row.actualProgress] }}
      </template>
      <template #pMemberIds="{ row }">
        {{ disposeMemberList(row, 'pMemberList') }}
      </template>
      <!-- <template #pMemberIds-edit="{ row }">
        <userSelect
          @change="(data: any) => changeUserFun(row, data, 'pMemberList', 'pMemberIds')"
          :multiple="true"
          v-model="row.pMemberIds"
        ></userSelect>
      </template> -->

      <template #eMemberIds="{ row }">
        {{ disposeMemberList(row, 'eMemberList') }}
      </template>
      <!-- <template #eMemberIds-edit="{ row }">
        <userSelect
          @change="(data) => changeUserFun(row, data, 'eMemberList', 'eMemberIds')"
          :multiple="true"
          v-model="row.eMemberIds"
        ></userSelect>
      </template> -->

      <!-- 计划开始时间 -->
      <template #beginTime="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK, NODE_TYPE.PERFORMANCE].includes(row.nodeType) && row.beginTime"
          :data="row.beginTime"
          :editMode="editMode"
        />
      </template>
      <!-- <template #beginTime-edit="{ row }">
        <el-date-picker
          v-model="row.beginTime"
          type="datetime"
          placeholder="请选择"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
        />
      </template> -->
      <!-- 计划结束时间 -->
      <template #endTime="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK, NODE_TYPE.PERFORMANCE].includes(row.nodeType) && row.endTime"
          :data="row.endTime"
          :editMode="editMode"
        />
      </template>
      <!-- <template #endTime-edit="{ row }">
        <el-date-picker
          v-model="row.endTime"
          type="datetime"
          placeholder="请选择"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
        />
      </template> -->
      <!-- 达标方式 -->
      <template #method="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.method"
          :editMode="editMode"
        >
          <dictLabel v-model="row.method" dictName="COMPLIANCE_METHOD" />
        </TreeEditItem>
      </template>
      <!-- <template #method-edit="{ row }">
        <dictLabel v-model="row.method" dictName="COMPLIANCE_METHOD" :editable="true" />
      </template> -->
      <!-- 目标值 -->
      <template #highValue="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.highValue"
          :editMode="editMode"
        >
        </TreeEditItem>
      </template>
      <!-- <template #highValue-edit="{ row }">
        <el-input-number
          v-if="row.performanceType === '1'"
          v-model="row.highValue"
          size="small"
          placeholder="请输入"
        />
        <el-input
          v-else
          v-model="row.highValue"
          size="small"
          placeholder="请输入"
          @keyup.enter="enterFun"
        />
      </template> -->
      <!-- 类型 -->
      <template #nodeType="{ row }">
        <dictLabel v-model="row.nodeType" :options="allNodeTypeOptions" />
      </template>

      <!-- 任务模板 -->
      <template #flowTemplate="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.flowTemplate"
          :editMode="editMode"
        >
          <flowTemplateSelect v-model="row.flowTemplate" :editable="false" size="small" />
        </TreeEditItem>
      </template>
      <!-- <template #flowTemplate-edit="{ row }">
        <flowTemplateSelect v-model="row.flowTemplate" size="small" />
      </template> -->
      <!-- 标准规范 -->
      <template #standard="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.standard"
          :editMode="editMode"
        >
          <knowledgeSelect
            v-model="row.standard"
            v-model:modelName="row.standardName"
            :editable="false"
            size="small"
          />
        </TreeEditItem>
      </template>
      <!-- <template #standard-edit="{ row }">
        <knowledgeSelect v-model="row.standard" v-model:modelName="row.standardName" size="small" />
      </template> -->
      <!-- 学科 -->
      <template #discipline="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.discipline"
          :editMode="editMode"
        >
          <dictLabel v-model="row.discipline" dictName="DISCIPLINE_TYPE" />
        </TreeEditItem>
      </template>
      <!-- <template #discipline-edit="{ row }">
        <dictLabel v-model="row.discipline" dictName="DISCIPLINE_TYPE" :editable="true" />
      </template> -->
      <!-- 分析目标 -->
      <template #analyseTarget="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.analyseTarget"
          :editMode="editMode"
        />
      </template>
      <!-- <template #analyseTarget-edit="{ row }">
        <el-input
          v-model="row.analyseTarget"
          size="small"
          placeholder="请输入"
          @keyup.enter="enterFun"
        />
      </template> -->
      <!-- 难度系数 -->
      <template #difficult="{ row }">
        <dictLabel v-model="row.difficult" dictName="DIFFICULTY_COEFFICIENT" />
      </template>

      <!-- 标准工时 -->
      <template #days="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.days"
          :editMode="editMode"
        />
      </template>
      <!-- <template #days-edit="{ row }">
        <el-input-number v-model="row.days" size="small" placeholder="请输入" />
      </template> -->
      <!-- 指标类型 -->
      <template #performanceType="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.performanceType"
          :editMode="editMode"
        >
          <dictLabel v-model="row.performanceType" dictName="PERFORMANCE_TYPE" />
        </TreeEditItem>
      </template>
      <!-- <template #performanceType-edit="{ row }">
        <dictLabel v-model="row.performanceType" dictName="PERFORMANCE_TYPE" :editable="true" />
      </template> -->
      <!-- 指标单位 -->
      <template #unit="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.unit"
          :editMode="editMode"
        >
          <dictLabel v-model="row.unit" dictName="PERFORMANCE_UNIT" />
        </TreeEditItem>
      </template>
      <!-- <template #unit-edit="{ row }">
        <dictLabel v-model="row.unit" dictName="PERFORMANCE_UNIT" :editable="true" />
      </template> -->

      <!-- 分析软件 -->
      <template #analyseSoftware="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.analyseSoftware"
          :editMode="editMode"
        >
          <dictLabel v-model="row.analyseSoftware" dictName="ANALYSIS_SOFTWARE" />
        </TreeEditItem>
      </template>
      <!-- <template #analyseSoftware-edit="{ row }">
        <dictLabel
          v-model="row.analyseSoftware"
          dictName="ANALYSIS_SOFTWARE"
          :editable="true"
          :multiple="true"
        />
      </template> -->
      <!-- 3d图示 -->
      <template #imageFileId="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.imageFileId"
          :editMode="editMode"
        >
          <uploadImg v-model="row.imageFileId" :disabled="!editMode" viewMode="inline" />
        </TreeEditItem>
      </template>
      <!-- <template #imageFileId-edit="{ row }">
        <uploadImg v-model="row.imageFileId" viewMode="inline" />
      </template> -->
      <!-- 仿真能力 -->
      <template #bCapacity="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.bCapacity"
          :editMode="editMode"
        >
          <dictLabel v-model="row.bCapacity" dictName="SIMULATION_CAPACITY" />
        </TreeEditItem>
      </template>
      <!-- <template #bCapacity-edit="{ row }">
        <dictLabel v-model="row.bCapacity" dictName="SIMULATION_CAPACITY" :editable="true" />
      </template> -->
      <!-- 部 -->
      <template #department="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.department"
          :editMode="editMode"
        >
          <dictLabel v-model="row.department" dictName="DEPARTMENT_LIST" />
        </TreeEditItem>
      </template>
      <!-- <template #department-edit="{ row }">
        <dictLabel v-model="row.department" dictName="DEPARTMENT_LIST" :editable="true" />
      </template> -->
      <!-- 科 -->
      <template #section="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.section"
          :editMode="editMode"
        >
          <dictLabel v-model="row.section" dictName="SECTION_LIST" />
        </TreeEditItem>
      </template>
      <!-- <template #section-edit="{ row }">
        <dictLabel v-model="row.section" dictName="SECTION_LIST" :editable="true" />
      </template> -->
      <!-- 组 -->
      <template #group="{ row }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.group"
          :editMode="editMode"
        >
          <dictLabel v-model="row.group" dictName="GROUP_LIST" />
        </TreeEditItem>
      </template>
      <!-- <template #group-edit="{ row }">
        <dictLabel v-model="row.group" dictName="GROUP_LIST" :editable="true" />
      </template> -->
      <!-- 描述 -->
      <template #description="{ row }">
        <TreeEditItem
          v-if="
            [NODE_TYPE.TASK, NODE_TYPE.PERFORMANCE].includes(row.nodeType) ||
            isMixedNodeType(row.nodeType)
          "
          :data="row.description"
          :editMode="editMode"
        />
      </template>
      <!-- <template #description-edit="{ row }">
        <el-input
          v-model="row.description"
          size="small"
          placeholder="请输入"
          @keyup.enter="enterFun"
        />
      </template> -->
      <!-- 插槽 -->
    </BaseTable>

    <taskDetail
      v-if="showTaskDetailDialog"
      :taskId="currentTaskInfo.id"
      :current-task-info="currentTaskInfo"
      @closeFn="showTaskDetailDialog = false"
      :show-approval="false"
      @updateFn="updateTaskInfoFun"
    >
    </taskDetail>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
import { getTaskTreeListApi } from '@/api/project/project';
import BaseTable from '@/components/common/table/baseTable.vue';
import { NODE_TYPE, nodeTypeList } from '@/utils/enum/node';
import { useDict } from '@/utils/useDict';
import StatusDot from '@/components/common/statusDot/index.vue';
import {
  getApproveStyleClass,
  getTaskAchieveStyleClass,
  getTaskExeStyleClass,
} from '@/components/common/statusDot/statusMap';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';
import { TASK_APPROVE_STATUS_ENUM } from '@/utils/enum/task';
import { disposeMemberList } from '@/views/task/projectDetail/components/project';
import { getTagMapList } from '@/utils/task';
import TreeEditItem from '@/components/common/table/treeEditItem.vue';
import { isMixedNodeType } from '@/utils/node';
import { poolCategoryTypeOptions } from '@/utils/project';
import dictLabel from '@/components/common/treeCaseTable/dictLabel.vue';
import uploadImg from '@/components/common/table/uploadImg.vue';
import taskDetail from '@/views/task/projectDetail/components/taskDetail.vue';
import { modifyNodeTaskPerformanceApi } from '@/api/project/node';

const props = defineProps({
  projectUuid: {
    type: Array,
    default: () => [],
  },
});
const emits = defineEmits(['close']);
const baseTableRef = ref();
const tableLoading = ref(false);
const editMode = ref(false);
const filterParamFormData = reactive<any>({
  projectNodeId: [],
  phaseNodeId: '',
  expandType: 'all',
});
const { TASK_EXE_STATUS, RESULT_ACHIEVE_STATUS, TASK_APPROVE_STATUS, TASK_PROGRESS_STATUS } =
  useDict(
    'RESULT_ACHIEVE_STATUS',
    'TASK_EXE_STATUS',
    'TASK_APPROVE_STATUS',
    'TASK_PROGRESS_STATUS'
  );
const tagMap = ref([
  {
    key: 'project',
    value: 'tag1',
  },
  {
    key: 'phase',
    value: 'tag2',
  },
  {
    key: 'machine',
    value: 'tag4',
  },
  {
    key: 'workspace',
    value: 'tag5',
  },
  {
    key: 'discipline',
    value: 'tag6',
  },
]);

const treeData = ref<any>([]);
const getTaskTreeListFun = async () => {
  tableLoading.value = true;
  try {
    const param = {
      projectNodeId: filterParamFormData.projectNodeId || [],
      // phaseNodeId: filterParamFormData.phaseNodeId || '',
      tagMap: tagMap.value,
    };

    const res: any = await getTaskTreeListApi(param);
    if (res && res.code === 200) {
      const data = res.data;
      treeData.value = data;

      formatDataFun(treeData.value, 0);
      nextTick(() => {
        baseTableRef.value.setDataFun(treeData.value);
      });
      tableLoading.value = false;
    }
  } catch {}
};

// 格式化输入的数据信息
const formatDataFun = (list: any, parentId: any) => {
  for (let i = 0; i < list.length; i++) {
    list[i].parentNodeId = parentId;
    if (list[i]?.children?.length) {
      formatDataFun(list[i]?.children, list[i].uuid);
    }
  }
};

const allNodeTypeOptions = computed(() => {
  const options: any = poolCategoryTypeOptions.value;
  return nodeTypeList.concat(options);
});

const actionList = ref([
  {
    title: '详情',
    type: 'primary',
    click: (row: any) => {
      openTaskDetailDialogFun(row);
    },
    hide: (row: any) => {
      return row.nodeType !== NODE_TYPE.TASK;
    },
  },
]);

const showTaskDetailDialog = ref(false);

// 测试打开任务详情窗口
const currentTaskInfo = ref<any>({});
const openTaskDetailDialogFun = (row?: any) => {
  if (row) {
    currentTaskInfo.value = row;
  }
  currentTaskInfo.value.achieveStatus = currentTaskInfo.value.achieveStatus + '';
  showTaskDetailDialog.value = true;
};

const updateTaskInfoFun = async (info: any) => {
  const { flag, data }: any = info;

  if (flag === 'info') {
    const res: any = await modifyNodeTaskPerformanceApi({
      addNodeList: [],
      editNodeList: [data],
      deleteNodeList: [],
      ownRootNodeUuid: data.tag1,
      tagMap: getTagMapList(),
    });

    if (res && res.code === 200) {
      await getTaskTreeListFun();
    }
  }

  showTaskDetailDialog.value = false;
};

const expandTypeList = ref([
  {
    label: '全部',
    value: 'all',
  },
  {
    label: '项目',
    value: NODE_TYPE.PROJECT,
  },
  {
    label: '阶段',
    value: NODE_TYPE.PHASE,
  },
  {
    label: '工位',
    value: NODE_TYPE.WORKSPACE,
  },
  {
    label: '任务',
    value: NODE_TYPE.TASK,
  },
]);

// 展开的节点的uuid
const expandRowKeys = ref<any>([]);

const expandTreeFun = async () => {
  // if (
  //   filterParamFormData.expandType === 'all' ||
  //   filterParamFormData.expandType === NODE_TYPE.TASK
  // ) {
  //   baseTableRef.value.tableRef.setAllTreeExpand(true);
  // }else if(filterParamFormData.expandType === )

  expandRowKeys.value = [];
  await baseTableRef.value.tableRef.setAllTreeExpand(false);

  if (filterParamFormData.expandType === 'all') {
    await baseTableRef.value.tableRef.setAllTreeExpand(true);
  } else {
    getexpandKeysFun(treeData.value, filterParamFormData.expandType);
    await baseTableRef.value.tableRef.setTreeExpand(expandRowKeys.value, true);
  }

  // switch (filterParamFormData.expandType) {
  //   case NODE_TYPE.TASK:
  //     await baseTableRef.value.tableRef.setAllTreeExpand(true);
  //     break;
  //   case NODE_TYPE.PROJECT:
  //     getexpandKeysFun(treeData.value, NODE_TYPE.PROJECT);
  //     await baseTableRef.value.tableRef.setTreeExpand(expandRowKeys.value, true);
  //     // await baseTableRef.value.tableRef.setAllTreeExpand(false);
  //     break;
  //   case NODE_TYPE.PHASE:
  //     // baseTableRef.value.tableRef.setAllTreeExpand(false);
  //     getexpandKeysFun(treeData.value, NODE_TYPE.PHASE);
  //     await baseTableRef.value.tableRef.setTreeExpand(expandRowKeys.value, true);
  //     break;
  //   case NODE_TYPE.WORKSPACE:
  //     // baseTableRef.value.tableRef.setAllTreeExpand(false);
  //     getexpandKeysFun(treeData.value, NODE_TYPE.WORKSPACE);
  //     await baseTableRef.value.tableRef.setTreeExpand(expandRowKeys.value, true);
  //     break;
  //   default:
  //     break;
  // }
};

// 获取展开节点的uuid
const getexpandKeysFun = (list: any, nodeType: any) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].nodeType === nodeType) {
      expandRowKeys.value.push(list[i]);
    } else {
      if (list[i]?.children?.length) {
        expandRowKeys.value.push(list[i]);
        getexpandKeysFun(list[i]?.children, nodeType);
      }
    }
  }
};

const returnListFun = () => {
  emits('close');
};

onMounted(async () => {
  // await queryProjectListFun();
  // await getNodeDetailFun();
  if (props.projectUuid) {
    filterParamFormData.projectNodeId = props.projectUuid;
  }
  await getTaskTreeListFun();
});
</script>

<style lang="scss" scoped>
.project-overview-page {
  width: 100%;
  height: 100%;
  background-color: #fff;
  padding: 10px;

  .node-name {
    display: flex;
    align-items: center;
    .blue {
      color: var(--el-color-primary);
    }
    .name {
      padding-left: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .el-form {
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }

  .select-style200 {
    width: 200px;
  }

  .select-style100 {
    width: 100px;
  }
}
</style>
