<template>
  <div class="gl-page-content-full">
    <taskTable
      showIndex
      ref="exeTableRef"
      tableName="SIMULATION_TASK_SEND_LIST"
      :params="taskParams"
      exportFileName="我分发的任务列表"
      :action-list="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_SEND_LIST"
        showDisabled
        @load="formLoad"
        v-model:data="editFormInfo"
        @change="changeFun"
        :formAttrs="formAttrs"
      >
      </TableForm>
      <template #footer>
        <div>
          <el-button @click="closeFun">取消</el-button>
          <el-button v-loading="loadingInterface" type="primary" @click="confirmFun"
            >确认</el-button
          >
        </div>
      </template>
    </Dialog>

    <taskDetail
      v-if="showTaskDetailDialog"
      :taskId="currentTaskInfo.id"
      :currentTaskInfo="currentTaskInfo"
      @closeFn="showTaskDetailDialog = false"
      :showFooter="true"
      @update-fn="updateTaskFun"
    >
    </taskDetail>
  </div>
</template>

<script setup lang="ts">
import { deleteTaskApi, 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 { getMemberListIds } from '@/utils/task';
import { isNumber } from 'lodash-es';
import taskDetail from '@/views/task/projectDetail/components/taskDetail.vue';

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

const exeTableRef = ref();

const loadingInterface = ref(false);

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

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

const closeFun = () => {
  formVisible.value = false;
};

const actionList = ref([
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      editTaskFun(row);
    },
  },

  ...props.actionList,
  {
    title: '详情',
    type: 'primary',
    click: (row: any) => {
      showTaskDetailFun(row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row: any) => {
      deleteTaskFun(row.uuid);
    },
  },
]);

const editRow = ref();
const editTaskFun = (row: any) => {
  formVisible.value = true;
  editRow.value = row;
  nextTick(() => {
    formLoad();
  });
  setFormData(editRow.value);
};

const showTaskDetailDialog = ref(false);

const currentTaskInfo = ref({ id: '', uuid: '' });
const showTaskDetailFun = (row: any) => {
  showTaskDetailDialog.value = true;
  currentTaskInfo.value = row;
};

const editFormInfo = ref({});

const changeFun = async () => {
  const formData = tableFormRef.value.getFormDataFun();
  editFormInfo.value = formData;
};

const setFormData = (row: any) => {
  if (tableFormRef.value) {
    // tableFormRef.value.setFormDataFun({
    //   ...row,
    //   achieveStatus: row.achieveStatus + '',
    //   eMemberList: getMemberListIds(row.eMemberList),
    // });
    editFormInfo.value = {
      ...row,
      achieveStatus: row.achieveStatus + '',
      eMemberList: getMemberListIds(row.eMemberList),
    };
  }
};

const deleteTaskFun = async (uuid: string) => {
  const res: any = await deleteTaskApi({ taskIdList: [uuid] });
  if (res.code === 200) {
    ElMessage({
      message: '删除成功！',
      type: 'success',
    });
    exeTableRef.value.tableRef.resetFun();
  } else {
    ElMessage({
      message: res.msg,
      type: 'error',
    });
  }
};
const formLoad = () => {
  // nextTick(() => {
  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);
  setFormData(editRow.value);
  // });
};

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()) {
    const fromData: any = tableFormRef.value.getFormDataFun();
    if (fromData.exeStatus === TASK_PROCESS_STATUS.COMPLETED && !isNumber(fromData.difficult)) {
      ElMessage({
        message: '关闭任务时需要填写难度系数！',
        type: 'warning',
      });
      return false;
    }
    loadingInterface.value = true;
    const params: any = {
      taskIds: [fromData.uuid],
      req: {
        ...fromData,
        exeStatus: fromData.exeStatus,
        achieveStatus: fromData.achieveStatus,
        process: fromData.progress,
        pMemberList: getMemberListIds(fromData.pMemberList),
        nodeName: fromData.taskName,
        beginTime: fromData.planTime ? fromData.planTime[0] : '',
        endTime: fromData.planTime ? fromData.planTime[1] : '',
      },
    };
    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 updateTaskFun = async (info: any) => {
  const { data }: any = info;
  if (data.exeStatus === TASK_PROCESS_STATUS.COMPLETED && !isNumber(data.difficult)) {
    ElMessage({
      message: '关闭任务时需要填写难度系数！',
      type: 'warning',
    });
    return false;
  }
  loadingInterface.value = true;
  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',
    });
    formVisible.value = false;
    exeTableRef.value.tableRef.resetFun();
  } else {
    ElMessage({
      message: '任务数据更新失败！',
      type: 'error',
    });
  }

  showTaskDetailDialog.value = false;
};
onMounted(() => {});
</script>
