<template>
  <div class="gl-page-content-full">
    <taskTable
      showIndex
      ref="exeTableRef"
      tableName="SIMULATION_TASK_EXECUTE_LIST"
      :params="taskParams"
      :actionList="actionList"
      @show="editTaskFun"
    >
    </taskTable>
    <Dialog
      v-model="formVisible"
      :loading="loadingInterface"
      diaTitle="编辑任务"
      :width="500"
      :height="500"
      @close="closeFun"
      show-footer
    >
      <TableForm
        ref="tableFormRef"
        tableName="SIMULATION_TASK_EXECUTE_LIST"
        showDisabled
        :hide-keys="hideKeys"
        @change="changeFun"
        @load="formLoad"
        v-model:data="editRow"
        :formAttrs="formAttrs"
      >
      </TableForm>
      <template #footer>
        <div>
          <el-button @click="closeFun">取消</el-button>
          <el-button type="primary" @click="confirmFun">确认</el-button>
        </div>
      </template>
    </Dialog>
    <TaskDetail
      v-if="showTaskDetailDialog"
      :taskId="currentTaskInfo.id"
      :currentTaskInfo="currentTaskInfo"
      @closeFn="showTaskDetailDialog = false"
      :show-task-info="false"
      :show-approval="false"
      :show-footer="false"
      :show-left-options="false"
      @updateFn="updateTaskInfoFun"
    >
    </TaskDetail>
  </div>
</template>

<script setup lang="ts">
import { updateTaskStatusApi } from '@/api/project/task';
// import BaseTable from '@/components/common/table/baseTable.vue';
import {
  disposeDisabledExeStatus,
  TASK_CALCULATE_STATUS,
  TASK_CALCULATE_STATUS_OPTIONS,
  TASK_PROCESS_STATUS,
  TASK_PROCESS_STATUS_OPTIONS,
} from '@/utils/enum/task';
import { ElMessage } from 'element-plus';
import taskTable from '../components/taskTable.vue';
import { nextTick, onMounted, ref } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import TableForm from '@/components/common/table/tableForm.vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import TaskDetail from '@/views/task/projectDetail/components/taskDetail.vue';
import { isNumber } from 'lodash-es';
import { getMemberListIds } from '@/utils/task';

const props = defineProps({
  actionList: {
    type: Array,
    default: () => [],
  },
});

const formAttrs = ref({
  progress: {
    min: 0,
    max: 100,
  },
  confidence: {
    min: 0,
    max: 1,
    precision: 2,
    step: 0.01,
  },
});

const taskParams = ref({ type: 0 });

const exeTableRef = ref();
const router = useRouter();
const loadingInterface = ref(false);

const changeTaskStatus = async (row: any, status: string) => {
  const params: {
    taskIds: any[];
    req: {
      exeStatus: string;
      finishTime?: string;
    };
  } = {
    taskIds: [row.uuid],
    req: {
      exeStatus: status,
    },
  };
  if (status === TASK_PROCESS_STATUS.COMPLETED) {
    params.req.finishTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
  }
  const res: any = await updateTaskStatusApi(params);
  if (res.code === 200) {
    ElMessage({
      message: '操作成功',
      type: 'success',
    });
    exeTableRef.value.tableRef.resetFun();
    exeTableRef.value.initTaskCount();
  }
};
const formVisible = ref(false);
const tableFormRef = ref();

const closeFun = () => {
  formVisible.value = false;
};
const editRow = ref();
const editTaskFun = (row: any) => {
  formVisible.value = true;
  editRow.value = { ...row, achieveStatus: row.achieveStatus + '' };
  getHideKeys(row.exeStatus);
  nextTick(() => {
    formLoad();
  });
};
const formLoad = () => {
  const exeStatusList = TASK_PROCESS_STATUS_OPTIONS.map((item: any) => {
    return {
      label: item.label,
      value: item.value,
      disabled: disposeDisabledExeStatus(editRow.value.exeStatus, item),
    };
  });
  const achieveStatusList = TASK_CALCULATE_STATUS_OPTIONS.map((item: any) => {
    return {
      label: item.label,
      value: item.value,
      disabled: disposeDisabledAchieveStatus(editRow.value.achieveStatus, item),
    };
  });
  tableFormRef.value.setOptionsFun('exeStatus', exeStatusList);
  tableFormRef.value.setOptionsFun('achieveStatus', achieveStatusList);
};

const disposeDisabledAchieveStatus = (status: string, option: { value: TASK_CALCULATE_STATUS }) => {
  if (status === TASK_CALCULATE_STATUS.NO_CALCULATE) {
    return false;
  }
  if (status === TASK_CALCULATE_STATUS.QUALIFIED) {
    return [TASK_CALCULATE_STATUS.NO_CALCULATE].includes(option.value);
  }
  if (status === TASK_CALCULATE_STATUS.UNQUALIFIED) {
    return [TASK_CALCULATE_STATUS.NO_CALCULATE].includes(option.value);
  }
};

const confirmFun = async () => {
  if (await tableFormRef.value.validateFun()) {
    loadingInterface.value = true;
    const fromData: any = tableFormRef.value.getFormDataFun();
    const params: {
      taskIds: string[];
      req: {
        exeStatus: string;
        achieveStatus: string;
        progress: number;
        finishTime?: string;
        extras: any[];
      };
    } = {
      taskIds: [fromData.uuid],
      req: {
        exeStatus: fromData.exeStatus,
        achieveStatus: fromData.achieveStatus,
        progress: fromData.progress,
        extras: fromData.extras,
      },
    };
    if (fromData.exeStatus === TASK_PROCESS_STATUS.COMPLETED) {
      params.req.finishTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }
    const res: any = await updateTaskStatusApi(params);
    if (res.code === 200) {
      // row.exeStatus = status;
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
      formVisible.value = false;
      exeTableRef.value.tableRef.resetFun();
    } else {
      ElMessage({
        message: '任务数据更新失败！',
        type: 'error',
      });
    }
    loadingInterface.value = false;
  }
};

// 跳转到任务执行相关的信息
const jumpToTaskExecutionFun = (row: any) => {
  const obj = {
    ProjectType: 'self_develop',
    projectName: row.newTag1,
    projectCodeName: '',
    phaseName: row.newTag2,
    phaseCodeName: '',
    discipline: 'discipline',
    attribution: 'personal',
    taskType: 'all',
    expendType: 'all',
  };

  localStorage.setItem('CURRENT_FILTER_RUN_TASK_TREE_PARAM', JSON.stringify(obj));

  localStorage.setItem('CURRENT_TASK_RUN_INFO', JSON.stringify({ ...row, nodeType: 'task' }));

  router.push({ path: '/task/execution' });
};

const showTaskDetailDialog = ref(false);
const currentTaskInfo = ref({ id: '', uuid: '', nodeType: 'task' });

const actionList = ref<any>([
  {
    title: '启动',
    type: 'primary',
    click: (row: any) => {
      changeTaskStatus(row, TASK_PROCESS_STATUS.IN_PROGRESS);
    },
    hide: (row: any) => {
      return !(
        row.exeStatus === TASK_PROCESS_STATUS.NO_STARTED ||
        row.exeStatus === TASK_PROCESS_STATUS.PAUSED
      );
    },
  },
  {
    title: '暂停',
    type: 'warning',
    click: (row: any) => {
      changeTaskStatus(row, TASK_PROCESS_STATUS.PAUSED);
    },
    hide: (row: any) => {
      return !(row.exeStatus === TASK_PROCESS_STATUS.IN_PROGRESS);
    },
  },
  ...props.actionList,
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      editTaskFun(row);
    },
    hide: (row: any) => {
      return (
        row.exeStatus === TASK_PROCESS_STATUS.COMPLETED ||
        row.exeStatus === TASK_PROCESS_STATUS.REJECTED
      );
    },
  },
  {
    title: '完成',
    type: 'success',
    click: (row: any) => {
      changeTaskStatus(row, TASK_PROCESS_STATUS.COMPLETED);
    },
    hide: (row: any) => {
      return !(row.exeStatus === TASK_PROCESS_STATUS.IN_PROGRESS);
    },
  },
  {
    title: '详情',
    type: 'primary',
    click: (row: any) => {
      showTaskDetailDialog.value = true;
      currentTaskInfo.value = row;
    },
  },
  {
    title: '驳回',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认驳回吗？',
    click: (row: any) => {
      changeTaskStatus(row, TASK_PROCESS_STATUS.REJECTED);
    },
    hide: (row: any) => {
      return !(row.exeStatus === TASK_PROCESS_STATUS.NO_STARTED);
    },
  },
  {
    title: '跳转',
    type: 'primary',
    click: (row: any) => {
      jumpToTaskExecutionFun(row);
    },
  },
]);

const hideKeys = ref();

const changeFun = (val: any) => {
  editRow.value = tableFormRef.value.getFormDataFun();
  if (val.key === 'exeStatus') {
    getHideKeys(val.val);
  }
};

const getHideKeys = (key: string) => {
  if (key === TASK_PROCESS_STATUS.REJECTED || key === TASK_PROCESS_STATUS.PAUSED) {
    hideKeys.value = [];
  } else {
    hideKeys.value = ['reason'];
  }
};

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

  if (flag === 'info') {
    if (data.exeStatus === TASK_PROCESS_STATUS.COMPLETED && !isNumber(data.difficult)) {
      ElMessage({
        message: '关闭任务时需要填写难度系数！',
        type: 'warning',
      });
      return false;
    }

    const params: any = {
      taskIds: [data.uuid],
      req: {
        ...data,
        exeStatus: data.exeStatus,
        achieveStatus: data.achieveStatus,
        process: data.progress,
        pMemberList: getMemberListIds(data.pMemberList),
        nodeName: data.taskName,
      },
    };
    if (data.exeStatus === TASK_PROCESS_STATUS.COMPLETED) {
      params.req.finishTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    }
    const res: any = await updateTaskStatusApi(params);

    if (res.code === 200) {
      // row.exeStatus = status;
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '任务数据更新失败！',
        type: 'error',
      });
    }
  }

  showTaskDetailDialog.value = false;
  exeTableRef.value.tableRef.resetFun();
};

onMounted(() => {});
</script>
