<template>
  <BaseTable
    showExport
    ref="tableRef"
    showIndex
    :tableName="tableName"
    :params="searchParams"
    :api="apiParams"
    :searchLimitNum="searchLimitNum"
    @searchChange="changeFun($event, 'search')"
    @load="tableOnLoadFun"
    v-bind="$attrs"
    :exportApi="isDemandExportApi ? exportTaskByDemandIdApi : exportTaskApi"
    :exportFileName="exportFileName"
    :exportParams="{
      ...searchParams,
      idMap: tagIdMap,
      tagMap: getTagMapList(),
    }"
    :actionList="actionList"
    fullHeight
    @search="searchFun"
  >
    <template #leftOptions>
      <div class="btn-box" v-if="!hideSpecialSearch">
        <div
          class="filter-btn"
          :style="{ backgroundColor: item.color }"
          @click="filterTaskFun(item)"
          v-for="item in filterBtnList"
          :key="item.key"
        >
          {{ item.label }}：{{ item.count }}
          <span v-show="item.selected" class="selected"></span>
        </div>
      </div>
    </template>
    <template #shouldProgress="{ row }">
      {{ TASK_PROGRESS_STATUS.O[row.shouldProgress] }}
    </template>
    <template #actualProgress="{ row }">
      {{ TASK_PROGRESS_STATUS.O[row.actualProgress] }}
    </template>
    <template #difficult="{ row }">
      {{ DIFFICULTY_COEFFICIENT.O[row.difficult] }}
    </template>
    <template #discipline="{ row }">
      <span v-if="DISCIPLINE_TYPE.O[row.discipline]">{{ DISCIPLINE_TYPE.O[row.discipline] }}</span>
      <span v-else>{{ row.discipline }}</span>
    </template>
    <template #taskName="{ row }">
      <span class="task-name" @click="nameClickFun(row)">
        {{ row.taskName }}
      </span>
    </template>
    <template #demandName="{ row }">
      <span class="demand-name" @click="seeDemandDetailDialogFun(row.demandId)">
        {{ row.demandName }}
      </span>
    </template>
    <template #exeStatus="{ row }">
      <StatusDot
        :status="getTaskExeStyleClass(row.exeStatus)"
        :title="TASK_PROCESS_STATUS_OBJ[row.exeStatus as keyof typeof TASK_PROCESS_STATUS_OBJ]"
      />
    </template>
    <template #achieveStatus="{ row }">
      <StatusDot
        :status="getTaskAchieveStyleClass(row.achieveStatus)"
        :title="
          TASK_CALCULATE_STATUS_OBJ[row.achieveStatus as keyof typeof TASK_CALCULATE_STATUS_OBJ] ||
          '未分析'
        "
      />
    </template>
    <!-- <template #achieveStatus="{row}">
      <el-text
        :type="
          row.achieveStatus === TASK_CALCULATE_STATUS.QUALIFIED?
            'primary':
            row.achieveStatus === TASK_CALCULATE_STATUS.UNQUALIFIED?
              'danger':row.achieveStatus === TASK_CALCULATE_STATUS.NO_CALCULATE?
                'info':'info'"
      >
        {{ TASK_CALCULATE_STATUS_OBJ[row.achieveStatus as keyof typeof TASK_CALCULATE_STATUS_OBJ] || '未分析' }}
      </el-text>
    </template> -->
    <template #progress="{ row }"> {{ row.progress || 0 }}% </template>
    <template #approvalStatus="{ row }">
      <StatusDot
        class="clcik-approval"
        :status="getApproveStyleClass(row.approvalStatus || TASK_APPROVE_STATUS_ENUM.NOT_APPROVED)"
        :title="TASK_APPROVE_STATUS.O[row.approvalStatus || TASK_APPROVE_STATUS_ENUM.NOT_APPROVED]"
        @click="seeApproveDetailFun(row)"
      >
      </StatusDot>
    </template>
    <template #demandAttachments="{ row }">
      <el-link v-if="row.demandId" type="primary" @click="seeAttachments(row.demandId)"
        >查看附件</el-link
      >
    </template>
    <template #taskAttachments="{ row }">
      <el-link type="primary" @click="seeAttachments(row.demandId)">查看附件</el-link>
    </template>
    <!-- <template #demandType="{row}">
      {{ DEMAND_TYPE.O[row.demandType] }}
    </template>
    <template #simType="{row}">
      {{ disposeSimType(row.demandType,row.simType) }}
    </template> -->
    <template #project="{ row }">
      {{ disposeTagName(row, NODE_TYPE.PROJECT) }}
    </template>
    <template #phase="{ row }">
      {{ disposeTagName(row, NODE_TYPE.PHASE) }}
    </template>
    <template #pMemberList="{ row }">
      {{ disposeMemberList(row, 'pMemberList') }}
    </template>
    <template #eMemberList="{ row }">
      {{ disposeMemberList(row, 'eMemberList') }}
    </template>
    <template #expStatus="{ row }">
      <span :class="row.expStatus === 1 ? 'abnormal' : ''">
        {{ TASK_ABNORMAL.O[row.expStatus] }}
      </span>
    </template>
  </BaseTable>
  <attachments :demandId="demandInfo.id" v-model:visible="attachmentsVisible"></attachments>
  <ApprovalProcess v-model="approveDetailVisible" :flowId="approveId" />
  <DemandDetailDialog
    v-model:showDialog="demandDetailDialogVisible"
    :demandUid="demandInfo.uuid"
  ></DemandDetailDialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, type PropType } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { getChildrenNodeList } from '../../projectDetail/components/projectApi';
import { NODE_TYPE } from '@/utils/enum/node';
import { CommonStore } from '@/stores/common';
import attachments from '@/views/task/simulationTask/components/attachments.vue';
import { disposeMemberList } from '../../projectDetail/components/project';
// import { useDict } from '@/utils/useDict';
// import { disposeSimType } from '@/utils/task';
import {
  TASK_PROCESS_STATUS_OBJ,
  TASK_CALCULATE_STATUS_OBJ,
  TASK_PROCESS_STATUS,
  TASK_APPROVE_STATUS_ENUM,
} from '@/utils/enum/task';
import { disposeTagName, formatQueryTaskListApi, setTaskSearchOptions } from '../taskPage';
import { getIdMap } from '../../projectDetail/components/project';
import { exportTaskApi, exportTaskByDemandIdApi, getTaskCountApi } from '@/api/project/task';
import { getTagMapList } from '@/utils/task';
import StatusDot from '@/components/common/statusDot/index.vue';
import {
  getTaskExeStyleClass,
  getTaskAchieveStyleClass,
  getApproveStyleClass,
} from '@/components/common/statusDot/statusMap';
import { FLOW_APPROVE_STATUS_ENUM } from '@/utils/enum/flow';
import ApprovalProcess from '@/components/common/approvalProcess/index.vue';
import DemandDetailDialog from './demandDetailDialog.vue';
import { useDict } from '@/utils/useDict';
import { ElMessage } from 'element-plus';

const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
  tableName: {
    type: String,
    default: '',
  },
  api: {
    type: Function as PropType<(params: any) => Promise<any>>,
    default: () => {},
  },
  exportFileName: {
    type: String,
    default: '任务列表',
  },
  actionList: {
    type: Array,
    default: () => [],
  },
  hideSpecialSearch: {
    type: Boolean,
    default: false,
  },
  searchLimitNum: {
    type: Number,
    default: 3,
  },
  isDemandExportApi: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['show']);

const {
  TASK_APPROVE_STATUS,
  TASK_PROGRESS_STATUS,
  TASK_ABNORMAL,
  DISCIPLINE_TYPE,
  DIFFICULTY_COEFFICIENT,
} = useDict(
  'TASK_APPROVE_STATUS',
  'TASK_PROGRESS_STATUS',
  'TASK_ABNORMAL',
  'DISCIPLINE_TYPE',
  'DIFFICULTY_COEFFICIENT'
);

const commonStore = CommonStore();
const approveDetailVisible = ref(false);
const approveId = ref('');

const searchParams = computed(() => {
  if (filterTaskParams.exeStatus.length > 0) {
    return { ...props.params, ...filterTaskParams, sortOrder: 1 };
  } else {
    return { ...props.params, todayTmrTasks: filterTaskParams.todayTmrTasks, sortOrder: 1 };
  }
});

const apiParams = computed(() => {
  if (props.hideSpecialSearch) {
    return props.api;
  } else {
    return formatQueryTaskListApi;
  }
});

const filterBtnList = ref([
  { label: '总数', count: 0, value: 'total', selected: false, key: 'total', color: '#1890FF' }, // 中性灰
  {
    label: '今明任务',
    count: 0,
    value: 'todayTmrTasks',
    selected: false,
    key: 'todayTmrTasks',
    color: '#FF9900',
  }, // 蓝色
  {
    label: '进行中',
    count: 0,
    value: TASK_PROCESS_STATUS.IN_PROGRESS,
    selected: false,
    key: 'inProgress',
    color: '#0066FF',
  }, // 橙色
  {
    label: '已逾期',
    count: 0,
    value: TASK_PROCESS_STATUS.POSTPONED,
    selected: false,
    key: 'postponed',
    color: '#FF0000',
  }, // 红色
  {
    label: '未开始',
    count: 0,
    value: TASK_PROCESS_STATUS.NO_STARTED,
    selected: false,
    key: 'noStarted',
    color: '#999999',
  }, // 浅灰
  {
    label: '已完成',
    count: 0,
    value: TASK_PROCESS_STATUS.COMPLETED,
    selected: false,
    key: 'completed',
    color: '#33FF00',
  }, // 绿色
  {
    label: '已关闭',
    count: 0,
    value: TASK_PROCESS_STATUS.CLOSED,
    selected: false,
    key: 'closed',
    color: '#339900',
  }, // 靛蓝色
  {
    label: '已暂停',
    count: 0,
    value: TASK_PROCESS_STATUS.PAUSED,
    selected: false,
    key: 'paused',
    color: '#DDDD09',
  }, // 淡灰
  {
    label: '已驳回',
    count: 0,
    value: TASK_PROCESS_STATUS.REJECTED,
    selected: false,
    key: 'rejected',
    color: '#F4652C',
  }, // 粉色
]);

const attachmentsVisible = ref(false);

const tableRef = ref();

const tableFormRef = ref();

const demandInfo = reactive({
  id: '',
  uuid: '',
});

const projectUuid = ref(null);
const phaseUuid = ref(null);

// const tagIdMap = ref<any[]>(getIdMap(projectUuid.value, phaseUuid.value));

const tagIdMap = computed(() => {
  const idMap = getIdMap(projectUuid.value, phaseUuid.value);
  return idMap;
});

const searchFun = () => {
  // tagIdMap.value = getIdMap(projectUuid.value, phaseUuid.value);
};

const changeFun = async (val: any, type: string) => {
  let optionRef: any;
  if (type === 'search') {
    optionRef = tableRef.value;
  } else {
    optionRef = tableFormRef.value;
  }
  if (val.key === 'project') {
    let nodeType = '';
    let nextKey = '';
    let nodeId = '';
    // if (val.key === 'project') {
    nodeType = NODE_TYPE.PHASE;
    nextKey = 'phase';
    nodeId = val.data.project;
    projectUuid.value = val.data.project;
    // }
    if (val.data.project) {
      const optionList = await getPhaseList(nodeType, nodeId);
      optionRef.setOptionsFun(nextKey, optionList);
    } else {
      optionRef.setOptionsFun(nextKey, []);
      optionRef?.setSearchParamsFun({
        ...optionRef?.getSearchParamsFun(),
        [nextKey]: '',
      });
      phaseUuid.value = null;
    }
  }

  if (val.key === 'phase') {
    phaseUuid.value = val.data.phase;
  }
  if (val.key === 'demandType') {
    const simTypeList: any = commonStore.getDictData(val.data.demandType);
    optionRef.setOptionsFun('simType', simTypeList.A);
  }
};
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 seeAttachments = (demandId: string) => {
  attachmentsVisible.value = true;
  demandInfo.id = demandId;
};

const tableOnLoadFun = () => {
  setTaskSearchOptions(tableRef.value);
};

const filterTaskParams = reactive({
  exeStatus: '',
  todayTmrTasks: '',
});
const filterTaskFun = (filterItem: any) => {
  if (filterItem.value === 'total') {
    return;
  }
  tableRef.value?.setSearchParamsFun({});
  if (filterItem.selected) {
    if (filterItem.key !== 'total' && filterItem.key !== 'todayTmrTasks') {
      const exeStatusList = filterTaskParams.exeStatus.split(',');
      const newExeList = exeStatusList.filter((item) => item !== filterItem.value);
      filterTaskParams.exeStatus = newExeList.join(',');
    } else if (filterItem.key === 'todayTmrTasks') {
      filterTaskParams.todayTmrTasks = '';
    }
  } else {
    if (filterItem.key !== 'total' && filterItem.key !== 'todayTmrTasks') {
      const exeStatusList = filterTaskParams.exeStatus.split(',');
      exeStatusList.push(filterItem.value);
      filterTaskParams.exeStatus = exeStatusList.join(',');
    } else if (filterItem.key === 'todayTmrTasks') {
      filterTaskParams.todayTmrTasks = filterItem.value;
    }
  }
  filterItem.selected = !filterItem.selected;
};

// const searchChange = async (val: any) => {
//     const optionList = await getPhaseList(nodeType, nodeId);
//     tableFormRef.value.setOptionsFun(nextKey, optionList);
// };
// defineExpose(tableRef);

const initTaskCount = async () => {
  const res: any = await getTaskCountApi({ type: props.params.type, idMap: tagIdMap.value });
  if (res.code === 200) {
    for (let index = 0; index < filterBtnList.value.length; index++) {
      if (res.data[filterBtnList.value[index].key]) {
        filterBtnList.value[index].count = res.data[filterBtnList.value[index].key];
      }
    }
  }
};

const seeApproveDetailFun = (row: any) => {
  if (row.cidFlowId) {
    if (row.approvalStatus !== FLOW_APPROVE_STATUS_ENUM.NOT_APPROVED && row.approvalStatus) {
      approveDetailVisible.value = true;
      approveId.value = row.cidFlowId;
    }
  } else {
    ElMessage.warning('暂无审批信息');
  }
};

const demandDetailDialogVisible = ref(false);

const seeDemandDetailDialogFun = (demandUid: string) => {
  demandInfo.uuid = demandUid;
  demandDetailDialogVisible.value = true;
};

const nameClickFun = (row: any) => {
  emits('show', row);
};

defineExpose({
  tableRef,
  initTaskCount,
});
onMounted(() => {
  if (!props.hideSpecialSearch) {
    initTaskCount();
  }
});
</script>

<style lang="scss" scoped>
.btn-box {
  display: flex;
  .filter-btn {
    margin-right: var(--margin-small);
    padding: var(--padding-tiny) var(--padding-small);
    border-radius: var(--border-radius-normal);
    cursor: pointer;
    position: relative;
    padding-right: var(--padding-large);
    // width: 110px;
    font-size: 14px;
  }
  .selected {
    position: absolute;
    bottom: 6px;
    right: 2px;
    width: 14px;
    height: 7px;
    border: 2px solid #fff;
    border-top: none;
    border-right: none;
    transform: rotate(-45deg);
  }

  // .selected::before {
  //     content: '';
  //     position: absolute;
  //     bottom: 2px;
  //     right: 2px;
  //     width: 10px;
  //     height: 5px;
  //     border: 1px solid #2ecc71;
  //     border-top: none;
  //     border-right: none;
  //     transform: rotate(-45deg);
  // }
}
.demand-name {
  color: var(--el-color-primary);
  cursor: pointer;
}

.task-name {
  color: var(--el-color-primary);
  cursor: pointer;
}

.clcik-approval {
  cursor: pointer;
}
.abnormal {
  color: var(--el-color-danger);
}
</style>
