<template>
  <div class="task-performance-page" v-if="showSetting">
    <BaseTable
      tableName="TASK_RUN_PERFORMANCE"
      ref="baseTableRef"
      :export-file-name="'指标列表'"
      :export-api="exportPerformanceApi"
      showCheckbox
      hidePagination
      :data="performanceData"
      :actionList="showLeftOptions ? actionList : []"
      :export-params="excelParams"
      :full-height="fullHeight"
    >
      <template v-if="showLeftOptions" #leftOptions>
        <div class="operate-box">
          <el-button type="primary" @click="openAddPerformanceWindFun">新增</el-button>
        </div>
      </template>

      <template #completeStatus="{ row }">
        <StatusDot
          :status="getTaskAchieveStyleClass(row.completeStatus || '0')"
          :title="RESULT_ACHIEVE_STATUS.O[row.completeStatus || '0']"
        />
      </template>

      <template #unit="{ row }">
        {{ PERFORMANCE_UNIT.O[row.unit] }}
      </template>

      <template #operate="{ row }">
        <el-button type="danger" link @click="delPerformance(row)">删除</el-button>
      </template>
    </BaseTable>

    <addTaskPerformance
      v-if="performanceVisible"
      :tableName="'TASK_RUN_PERFORMANCE'"
      @cancel="performanceVisible = false"
      @submit="addPerformanceFun"
    >
    </addTaskPerformance>
    <editPerformancePage
      v-if="editPerformanceVisible"
      @cancel="editPerformanceVisible = false"
      :performance-info="currentPerformance"
      @submit="updatePerformanceFun"
    ></editPerformancePage>
  </div>
  <div class="task-performance-page" v-else>
    <div class="table-box">
      <BaseTable
        tableName="TASK_RUN_PERFORMANCE"
        ref="baseTableRef"
        :data="performanceData"
        :export-file-name="'指标列表'"
        :export-api="exportPerformanceApi"
        showCheckbox
        hidePagination
        :actionList="showLeftOptions ? actionList : []"
        :export-params="excelParams"
        :full-height="fullHeight"
        :show-setting="false"
      >
        <template v-if="showLeftOptions" #leftOptions>
          <div class="operate-box">
            <el-button type="primary" @click="ArchiveRunDataFun">归档</el-button>
            <el-button type="primary" @click="openAddPerformanceWindFun">新增</el-button>
            <el-button type="danger" @click="deleteFun">删除</el-button>
          </div>
        </template>

        <template #completeStatus="{ row }">
          <StatusDot
            :status="getTaskAchieveStyleClass(row.completeStatus || '0')"
            :title="RESULT_ACHIEVE_STATUS.O[row.completeStatus || '0']"
          />
        </template>

        <template #unit="{ row }">
          {{ PERFORMANCE_UNIT.O[row.unit] }}
        </template>

        <template #operate="{ row }">
          <el-button type="danger" link @click="delPerformance(row)">删除</el-button>
        </template>
      </BaseTable>
    </div>
    <!-- <div class="operate-box">
      <el-button type="primary" @click="ArchiveRunDataFun">归档</el-button>
      <el-button type="primary" @click="openAddPerformanceWindFun">新增</el-button>
      <el-button type="danger" @click="deleteFun">删除</el-button>
    </div> -->

    <addTaskPerformance
      v-if="performanceVisible"
      :tableName="'TASK_RUN_PERFORMANCE'"
      @cancel="performanceVisible = false"
      @submit="addPerformanceFun"
    >
    </addTaskPerformance>
    <editPerformancePage
      v-if="editPerformanceVisible"
      @cancel="editPerformanceVisible = false"
      :performance-info="currentPerformance"
      @submit="updatePerformanceFun"
    ></editPerformancePage>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { ElMessage } from 'element-plus';
import {
  getTaskPerformanceApi,
  batchAddTaskPerformanceApi,
  batchDeleteTaskPerformanceApi,
  getRunPerformanceApi,
} from '@/api/task/taskpool';
import addTaskPerformance from './addTaskPerformance.vue';
import { editPerformanceApi, exportPerformanceApi } from '@/api/task/taskPerformance';
import { getFormConfigureApi } from '@/api/system/systemData';
import editPerformancePage from './editPerformancePage.vue';
import { getTaskAchieveStyleClass } from '../common/statusDot/statusMap';
import { useDict } from '@/utils/useDict';
import StatusDot from '@/components/common/statusDot/index.vue';
import { syncKeyResultToTaskApi } from '@/api/project/run';

const props = defineProps({
  taskId: {
    type: String,
    default: '',
  },
  runInfo: {
    type: Object,
    default: () => {},
  },
  taskInfo: {
    type: Object,
    default: () => {},
  },
  showSaveButton: {
    type: Boolean,
    default: false,
  },
  paramType: {
    type: String,
    default: 'task',
  },
  fullHeight: {
    type: Boolean,
    default: false,
  },
  showLeftOptions: {
    type: Boolean,
    default: true,
  },
  showSetting: {
    type: Boolean,
    default: true,
  },
});

const baseTableRef = ref();
const performanceVisible = ref(false);
const editPerformanceVisible = ref(false);
const performanceData = ref<any>([]);
const getTaskPerformanceDataFun = async () => {
  const res: any =
    props.paramType === 'task'
      ? await getTaskPerformanceApi({ taskId: props.taskInfo?.uuid })
      : await getRunPerformanceApi({ runId: props.runInfo?.uuid });
  if (res && res.code === 200) {
    performanceData.value = res.data.map((item: any) => {
      const completeStatus = getPerformanceSTatus(item) || 0;
      return {
        ...item,
        completeStatus,
      };
    });
  }
};

const { RESULT_ACHIEVE_STATUS, PERFORMANCE_UNIT } = useDict(
  'RESULT_ACHIEVE_STATUS',
  'PERFORMANCE_UNIT'
);

const openAddPerformanceWindFun = () => {
  performanceVisible.value = true;
};

const addPerformanceFun = async (data: any) => {
  data.flag = 'add';
  // const { fullData } = baseTableRef.value.tableRef.getTableData();

  // const existPerformance =
  //   fullData.find((item: any) => {
  //     return item.nodeName === data.nodeName;
  //   }) || null;

  // if (existPerformance) {
  //   ElMessage.warning('已存在该指标，无法新增！');
  // } else {
  //   baseTableRef.value.tableRef.insertAt(data, -1);
  // }

  const list = [data];

  performanceVisible.value = false;
  await batchAddTaskPerformanceFun(list);
};

const deletePerformanceList = ref<any>([]);
const delPerformance = (row: any) => {
  baseTableRef.value.tableRef.remove(row);
  if (row.flag != 'add') {
    deletePerformanceList.value.push(row);
    batchDeleteTaskPerformanceFun([row.id]);
  }
};

const batchAddTaskPerformanceFun = async (list: any) => {
  // const list = baseTableRef.value.tableRef.getInsertRecords();

  const performanceList: any = [];

  for (let i = 0; i < list.length; i++) {
    const obj: any = {
      uuid: '',
      nodeId: '',
      performanceName: list[i].performanceName,
      nodeName: list[i].nodeName,
      englishName: list[i].englishName,
      nodeCode: list[i].nodeCode,
      poolName: list[i].poolName,
      performanceType: list[i].performanceType,
      unit: list[i].unit,
      targetValue: list[i].targetValue,
      resultValue: list[i].resultValue,
      lowValue: list[i].lowValue,
      highValue: list[i].highValue,
      method: list[i].method,
      description: list[i].description,
      taskName: list[i].taskName,
      standard: list[i].standard,
      tenantId: list[i].tenantId,
      createTime: list[i].createTime,
      pid: 0,
    };

    if (props.paramType === 'task') {
      obj.taskId = props.taskInfo?.uuid;
    }

    if (props.paramType === 'run') {
      obj.runId = props.runInfo.uuid;
      obj.taskId = props.runInfo.taskId;
    }

    performanceList.push(obj);
  }

  if (!list.length) {
    return;
  }

  const param: any = {
    performanceList: performanceList,
  };

  if (props.paramType === 'task') {
    param.taskId = props.taskInfo?.uuid;
  }

  if (props.paramType === 'run') {
    param.taskId = props.runInfo.taskId;
    param.runId = props.runInfo.uuid;
  }
  const res: any = await batchAddTaskPerformanceApi(param);
  if (res && res.code === 200) {
    ElMessage.success('新增成功！');
    await getTaskPerformanceDataFun();
  } else {
  }
};

const batchDeleteTaskPerformanceFun = async (ids: any) => {
  // const ids = deletePerformanceList.value.map((item: any) => {
  //   return item.id;
  // });

  if (!ids.length) {
    return;
  }
  const res: any = await batchDeleteTaskPerformanceApi(ids);
  if (res && res.code === 200) {
    ElMessage.success('删除成功！');
    baseTableRef.value.resetFun();
  } else {
  }
};

const saveFun = async () => {};

const excelHeaders = ref<any>({});
const excelParams = ref<any>({});
const getFormConfigureFun = async () => {
  const res: any = await getFormConfigureApi({
    formName: 'PERFORMANCE_POOL',
  });

  if (res && res.code === 200) {
    const cloumn: any = JSON.parse(res.data.formConfig) || [];
    excelHeaders.value = cloumn.map((item: any) => {
      return {
        key: item.key,
        title: item.title,
      };
    });

    if (props.paramType === 'run') {
      excelParams.value = {
        runId: props.runInfo.uuid,
      };
    } else {
      excelParams.value = {
        taskId: props.taskInfo.uuid,
      };
    }
  }
};

const getPerformanceSTatus = (row: any) => {
  let status: any = 0;
  // 当指标值，达标方式，目标值有一个不存在时，返回状态未分析
  if (!row?.method || !row?.highValue || !row?.targetValue) {
    return status;
  }

  if (row?.method && row?.resultValue && row?.targetValue) {
    const highValue = Number(row?.targetValue);
    const targetValue = Number(row?.resultValue);
    const lowValue = Number(row?.lowValue);

    // 小于等于
    if (row.method === '≤') {
      if (targetValue <= highValue) {
        status = 2;
      } else {
        status = 1;
      }
    }

    // 小于
    if (row.method === '<') {
      if (targetValue < highValue) {
        status = 2;
      } else {
        status = 1;
      }
    }
    // 大于
    if (row.method === '>') {
      if (targetValue > highValue) {
        status = 2;
      } else {
        status = 1;
      }
    }
    // 大于等于
    if (row.method === '≥') {
      if (targetValue >= highValue) {
        status = 2;
      } else {
        status = 1;
      }
    }
    // 包含
    if (row.method === '[]') {
      if (targetValue <= highValue && targetValue >= lowValue) {
        status = 2;
      } else {
        status = 1;
      }
    }
  }

  return status;
};

const deleteFun = async () => {
  const checkData: any = baseTableRef.value.tableRef.getCheckboxRecords();
  if (checkData.length) {
    for (let i = 0; i < checkData.length; i++) {
      delPerformance(checkData[i]);
    }
  } else {
    ElMessage.warning('请选择数值结果后删除');
  }
};

defineExpose({
  saveFun,
  baseTableRef,
});

const actionList = ref([
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      editPerformanceFun(row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row: any) => {
      delPerformance(row);
    },
  },
]);

const currentPerformance = ref<any>({});
const editPerformanceFun = (row: any) => {
  currentPerformance.value = row;
  editPerformanceVisible.value = true;
};

const updatePerformanceFun = async (data: any) => {
  editPerformanceVisible.value = false;
  const res: any = await editPerformanceApi(data);
  if (res && res.code === 200) {
    ElMessage.success('操作成功');
    await getTaskPerformanceDataFun();
  }
};

// 归档
const ArchiveRunDataFun = async () => {
  const param = {
    runId: props.runInfo.uuid,
  };
  try {
    const res: any = await syncKeyResultToTaskApi(param);
    if (res && res.code === 200) {
      ElMessage.success('归档成功');
    } else {
      ElMessage.warning('归档未成功');
    }
  } catch (error) {
    console.error(error);
  }
};

onMounted(async () => {
  await getTaskPerformanceDataFun();

  await getFormConfigureFun();
});
</script>

<style lang="scss" scoped>
.task-performance-page {
  width: 100%;
  height: 100%;

  .table-box {
    width: 100%;
    // height: calc(100% - 50px);
    height: 100%;
  }

  .operate-box {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .mr12 {
    margin-right: 12px;
  }
}
</style>
