<template>
  <div class="comp-content comp-tree-case-table">
    <TreeTable
      ref="TreeTableRef"
      :tableName="tableName"
      :data="treeData"
      :editMode="editMode"
      v-bind="$attrs"
    >
      <!-- 名称 -->
      <template #nodeName="{ row, icon }">
        <TreeEditItem :data="row.nodeName" :editMode="editMode" :icon="icon">
          <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>
        </TreeEditItem>
      </template>
      <template #nodeName-edit="{ row }">
        <nodeNameMixed
          v-model="row.nodeName"
          :nodeType="row.nodeType"
          :editable="true"
          size="small"
          @update:modelValue="(val) => onNodeNameChangeFun(row, val)"
          @keyup.enter="enterFun"
        />
      </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> -->
        <span v-if="row.nodeType === NODE_TYPE.WORKSPACE">
          完成率：{{ row.finishTaskNum }}/{{ row.totalTaskNum }}
        </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 #englishName="{ row, icon }">
        <TreeEditItem :data="row.englishName" :editMode="editMode" :icon="icon" />
      </template>
      <template #englishName-edit="{ row }">
        <el-input
          v-model="row.englishName"
          size="small"
          placeholder="请输入"
          :disabled="row.nodeType === NODE_TYPE.DISCIPLINE"
          @keyup.enter="enterFun"
        />
      </template>
      <!-- 编号 -->
      <template #nodeCode="{ row, icon }">
        <TreeEditItem :data="row.nodeCode" :editMode="editMode" :icon="icon" />
      </template>
      <template #nodeCode-edit="{ row }">
        <el-input
          v-model="row.nodeCode"
          size="small"
          placeholder="请输入"
          :disabled="row.nodeType === NODE_TYPE.DISCIPLINE"
          @keyup.enter="enterFun"
        />
      </template>
      <!-- 应达成进度 -->
      <template #shouldProgress="{ row }">
        {{ TASK_PROGRESS_STATUS.O[row.shouldProgress] }}
      </template>
      <!-- 实际达成进度 -->
      <template #actualProgress="{ row }">
        {{ TASK_PROGRESS_STATUS.O[row.actualProgress] }}
      </template>
      <template #pMemberIds="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType)"
          :data="row.pMemberIds"
          :editMode="editMode"
          :icon="icon"
          hideTitle
        >
          <span :title="row.hoverTitle">
            {{ disposeMemberList(row['pMemberList'], 'pMemberList') }}
          </span>
        </TreeEditItem>
      </template>
      <template #pMemberIds-edit="{ row }">
        <userSelect
          @change="(data) => changeUserFun(row, data, 'pMemberList', 'pMemberIds')"
          :multiple="true"
          v-model="row.pMemberIds"
        ></userSelect>
      </template>
      <template #eMemberIds="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType)"
          :data="row.eMemberIds"
          :editMode="editMode"
          :icon="icon"
          hideTitle
        >
          <span :title="row.hoverTitle">
            {{ disposeMemberList(row['eMemberList'], 'eMemberList') }}
          </span>
        </TreeEditItem>
      </template>
      <template #eMemberIds-edit="{ row }">
        <userSelect
          @change="(data) => changeUserFun(row, data, 'eMemberList', 'eMemberIds')"
          :multiple="true"
          v-model="row.eMemberIds"
        ></userSelect>
      </template>
      <!-- 计划开始时间 -->
      <template #beginTime="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType)"
          :data="row.beginTime"
          :editMode="editMode"
          :icon="icon"
        />
      </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
          :disabled-date="(time: Date) => disabledDate(time, row, 'beginTime')"
        />
      </template>
      <!-- 计划结束时间 -->
      <template #endTime="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType)"
          :data="row.endTime"
          :editMode="editMode"
          :icon="icon"
        />
      </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
          :disabled-date="(time: Date) => disabledDate(time, row, 'endTime')"
        />
      </template>
      <!-- 军令状时间 -->
      <template #commitmentDeadline="{ row }">
        <span v-if="row.nodeType === NODE_TYPE.WORKSPACE && row.commitmentDeadline">
          <el-icon><Calendar /></el-icon>
          {{ row.commitmentDeadline }}
        </span>
      </template>
      <!-- 达标方式 -->
      <template #method="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.method"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.highValue"
          :editMode="editMode"
          :icon="icon"
        >
        </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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.flowTemplate"
          :editMode="editMode"
          :icon="icon"
          hideTitle
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.standard"
          :editMode="editMode"
          :icon="icon"
          hideTitle
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.discipline"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.analyseTarget"
          :editMode="editMode"
          :icon="icon"
        />
      </template>
      <template #analyseTarget-edit="{ row }">
        <el-input
          v-model="row.analyseTarget"
          size="small"
          placeholder="请输入"
          @keyup.enter="enterFun"
        />
      </template>
      <!-- 准确度 -->
      <!-- <template #confidence="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.confidence"
          :editMode="editMode"
          :icon="icon"
        />
      </template>
      <template #confidence-edit="{ row }">
        <el-input-number v-model="row.confidence" size="small" placeholder="请输入" />
      </template> -->
      <!-- 难度系数 -->
      <template #difficult="{ row }">
        <dictLabel v-model="row.difficult" dictName="DIFFICULTY_COEFFICIENT" />
      </template>
      <!-- <template #difficult="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.difficult"
          :editMode="editMode"
          :icon="icon"
        />
      </template>
      <template #difficult-edit="{ row }">
        <el-input-number v-model="row.difficult" size="small" placeholder="请输入" />
      </template> -->
      <!-- 标准工时 -->
      <template #days="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.days"
          :editMode="editMode"
          :icon="icon"
        />
      </template>
      <template #days-edit="{ row }">
        <el-input-number v-model="row.days" size="small" placeholder="请输入" />
      </template>
      <!-- 指标类型 -->
      <template #performanceType="{ row, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.performanceType"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.PERFORMANCE].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.unit"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.analyseSoftware"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.imageFileId"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.bCapacity"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.department"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.section"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="[NODE_TYPE.TASK].includes(row.nodeType) || isMixedNodeType(row.nodeType)"
          :data="row.group"
          :editMode="editMode"
          :icon="icon"
        >
          <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, icon }">
        <TreeEditItem
          v-if="
            [NODE_TYPE.TASK, NODE_TYPE.PERFORMANCE].includes(row.nodeType) ||
            isMixedNodeType(row.nodeType)
          "
          :data="row.description"
          :editMode="editMode"
          :icon="icon"
        />
      </template>
      <template #description-edit="{ row }">
        <el-input
          v-model="row.description"
          size="small"
          placeholder="请输入"
          @keyup.enter="enterFun"
        />
      </template>
      <!-- 插槽 -->
      <template v-for="name in Object.keys($slots)" :key="name" #[name]="scope">
        <slot :name="name" v-bind="scope" />
      </template>
    </TreeTable>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue';
import TreeTable from '@/components/common/table/treeTable.vue';
import { Folder, Document, Operation } from '@element-plus/icons-vue';
import TreeEditItem from '@/components/common/table/treeEditItem.vue';
import { NODE_TYPE, nodeTypeList } from '@/utils/enum/node';
import { isMixedNodeType } from '@/utils/node';
import { cloneDeep } from 'lodash-es';
import dictLabel from './dictLabel.vue';
import nodeNameMixed from './nodeNameMixed.vue';
import { poolCategoryTypeOptions } from '@/utils/project';
import flowTemplateSelect from './flowTemplateSelect.vue';
import knowledgeSelect from './knowledgeSelect.vue';
import uploadImg from '@/components/common/table/uploadImg.vue';
import { useTaskStore } from '@/stores/taskPool';
import userSelect from '../userSelect/index.vue';
import { disposeMemberList } from '@/views/task/projectDetail/components/project';
import { getMemberListIds } from '@/utils/task';
import { useDict } from '@/utils/useDict';
import StatusDot from '@/components/common/statusDot/index.vue';
import {
  getTaskExeStyleClass,
  getTaskAchieveStyleClass,
  getApproveStyleClass,
} from '../statusDot/statusMap';
import { initProjectDicts } from '@/utils/project';
import { TASK_APPROVE_STATUS_ENUM } from '@/utils/enum/task';
import { enableConfigByTenant, TENANT_ENUM } from '@/tenants/tenant';

const TreeTableRef = ref<any>();

interface Props {
  tableName: string;
  data: any;
  editMode?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  tableName: '',
  data: [],
  editMode: false,
});

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 treeData = ref<any>([]);
const taskStore = useTaskStore();

const treeDataFormatFun = (data: any, build: any, pId: any) => {
  data.forEach((item: any) => {
    item.parentId = pId;
    const children = cloneDeep(item.children);
    item.children = [];
    build.push(item);
    if (children && children.length > 0) {
      treeDataFormatFun(children, build, item.fakeId);
    }
  });
  return build;
};

const changeUserFun = (row: any, data: any, listKey: string, idKey: string) => {
  row[listKey] = data;
  row[idKey] = getMemberListIds(data);
};

watch(
  () => props.data,
  (val: any) => {
    treeData.value = treeDataFormatFun(val, [], '0');
  },
  { immediate: true }
);

const getCheckboxRecordsFun = (isFull: boolean) => {
  return TreeTableRef.value?.getCheckboxRecordsFun(isFull);
};

const removeFun = (data: any) => {
  return TreeTableRef.value?.removeFun(data);
};

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

const enterFun = () => {
  TreeTableRef.value?.cancelEditFun();
};

const onNodeNameChangeFun = (row: any, val: string) => {
  if (row.nodeType === NODE_TYPE.DISCIPLINE) {
    row.nodeCode = val;
    row.englishName = val;
  }
};

const disabledDate = (time: Date, row: any, flag: string) => {
  if (flag === 'beginTime') {
    if (row.endTime) {
      return time.getTime() > new Date(row.endTime).getTime();
    } else {
      return false;
    }
  } else {
    if (row.beginTime) {
      return time.getTime() < new Date(row.beginTime).getTime();
    } else {
      return false;
    }
  }
};

onMounted(() => {
  initProjectDicts();
  taskStore.fetchTemplates();
});

defineExpose({
  getCheckboxRecordsFun,
  removeFun,
  TreeTableRef,
});
</script>

<style lang="scss" scoped>
.comp-tree-case-table {
  width: 100%;
  height: 100%;
  .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;
    }
  }
}
</style>
