<template>
  <BaseTable
    showExport
    ref="tableRef"
    showIndex
    :tableName="tableName"
    :params="{...params,idMap:tagIdMap,...filterTaskParams,sortOrder:1}"
    :actionsWidth="actionsWidth"
    :api="api"
    :searchLimitNum="3"
    @searchChange="changeFun($event,'search')"
    @load="tableOnLoadFun"
    v-bind="$attrs"
    :exportApi="exportTaskApi"
    :exportFileName="exportFileName"
    :exportParams="{...params,idMap:tagIdMap,...filterTaskParams,sortOrder:1,tagMap: getTagMapList()}"
    :exportDict="{
      achieveStatus: 'RESULT_ACHIEVE_STATUS',
      exeStatus:'TASK_EXE_STATUS'
    }"
  >
    <template #leftOptions>
      <div class="btn-box">
        <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 #tableActions="{row}">
      <slot name="tableActions" :row="row"></slot>
    </template>
    <template #taskName="{ row }">
      <span>
        {{ row.taskName }}
      </span>
    </template>
    <template #exeStatus="{row}">
      <span
        :class="
          row.exeStatus === TASK_PROCESS_STATUS.COMPLETED?
            'dot dot-success':
            row.exeStatus === TASK_PROCESS_STATUS.IN_PROGRESS?
              'dot dot-in-precess':
              row.exeStatus === TASK_PROCESS_STATUS.NO_STARTED?
                'dot dot-default':
                row.exeStatus === TASK_PROCESS_STATUS.PAUSED?
                  'dot dot-approving':'dot dot-default'"
      >
      </span>
      {{ TASK_PROCESS_STATUS_OBJ[row.exeStatus as keyof typeof TASK_PROCESS_STATUS_OBJ] }}
    </template>
    <template
      #achieveStatus="
        {row}"
    >
      <span
        :class="
          row.achieveStatus === TASK_CALCULATE_STATUS.QUALIFIED?
            'dot dot-qualified':
            row.achieveStatus === TASK_CALCULATE_STATUS.UNQUALIFIED?
              'dot dot-unqualified':row.achieveStatus === TASK_CALCULATE_STATUS.NO_CALCULATE?
                'dot dot-no-calculate':'dot dot-no-calculate'"
      >
      </span>
      {{ 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 }">
      {{ row.approvalStatus || '未审批' }}
    </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>
  </BaseTable>
  <attachments :demandId="demandInfo.id" v-model:visible="attachmentsVisible" ></attachments>
</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_CALCULATE_STATUS } from '@/utils/enum/task';
import { disposeTagName, setTaskSearchOptions } from '../taskPage';
import { getIdMap } from '../../projectDetail/components/project';
import { exportTaskApi, getTaskCountApi } from '@/api/project/task';
import { getTagMapList } from '@/utils/task';

const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
  tableName: {
    type: String,
    default: '',
  },
  api: {
    type: Function as PropType<(params: any) => Promise<any>>,
    default: () => {},
  },
  actionsWidth: {
    type: Number,
    default: 95,
  },
  exportFileName: {
    type: String,
    default: '任务列表',
  },
});

const commonStore = CommonStore();

// const { DEMAND_TYPE } = useDict('DEMAND_TYPE');

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 = computed(() => {
  const idMap = getIdMap(projectUuid.value, phaseUuid.value);
  return idMap;
});

// SIMULATION_TASK_DEMAND_CREATE
// const headData = ref<any[]>([
//   { title: '任务名称', key: 'demandName', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '任务状态', key: 'taskStatus', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '风险状态', key: 'achievement', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '任务进度', key: 'progress', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '审批状态', key: 'approvalStatus', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '仿真负责人', key: 'simLeader', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '项目', key: 'projectId', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '阶段', key: 'phaseId', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '学科', key: 'nodeId', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '计划开始时间', key: 'beginTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '计划结束时间', key: 'endTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
//   { title: '实际结束时间', key: 'actualEndTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
// ]);

const changeFun = async (val: any, type:string) => {
  console.log('val', val);
  let optionRef :any;
  if (type === 'search') {
    optionRef = tableRef.value;
  } else {
    optionRef = tableFormRef.value;
  }
  if (val.key === 'project') {
    console.log('changeFun', val);
    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;
    // }
    const optionList = await getPhaseList(nodeType, nodeId);
    optionRef.setOptionsFun(nextKey, optionList);
  }

  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;
  console.log('demandId', demandId);
  demandInfo.id = demandId;
};

const tableOnLoadFun = () => {
  console.log('tableOnLoadFun', tableRef.value);
  setTaskSearchOptions(tableRef.value);
};

const filterTaskParams = reactive({
  exeStatus: '',
  todayTmrTasks: '',
});
const filterTaskFun = (filterItem: any) => {
  if (filterItem.value === 'total') {
    return ;
  }
  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;
  console.log('filterTaskParams', filterTaskParams);
  console.log('filterItem', filterItem);
};

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

const initTaskCount = async () => {
  console.log('{ type: 2, idMap: tagIdMap }', { type: 2, idMap: tagIdMap });
  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];
      }
    }
  }
};

defineExpose({
  tableRef,
});
onMounted(() => {
  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);
  // }
}
</style>
