<script setup lang="ts">
import { reactive, onMounted, ref, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { Form, message, Modal } from 'ant-design-vue/lib';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/lib/table';
import { parseDateToStr } from '@/utils/date-utils';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';
import useUserStore from '@/store/modules/user';
import useNeInfoStore from '@/store/modules/neinfo';
import {
  addPerfTask,
  delPerfTask,
  getPerfTask,
  listPerfTask,
  updatePerfTask,
  taskStop,
  taskRun,
} from '@/api/perfManage/taskManage';
const neInfoStore = useNeInfoStore();
const { t, currentLocale } = useI18n();

const generateOptions = (start: any, end: any) => {
  const options = [];
  for (let i = start; i <= end; i++) {
    options.push({ label: i.toString(), value: i.toString() });
  }
  return options;
};

/**表格所需option */
const taskManageOption = reactive({
  granulOption: [
    { label: '15M', value: '15M' },
    { label: '30M', value: '30M' },
    { label: '60M', value: '60M' },
    { label: '24H', value: '24H' },
  ],
  timeSlotAll: [{ label: '', value: '' }],
  bigPlan: [
    { label: t('views.perfManage.taskManage.weekPlan'), value: 'Weekly' },
    { label: t('views.perfManage.taskManage.monthPlan'), value: 'Monthly' },
  ],
  smPlan: {
    Weekly: [
      { label: t('views.perfManage.taskManage.one'), value: '1' },
      { label: t('views.perfManage.taskManage.two'), value: '2' },
      { label: t('views.perfManage.taskManage.three'), value: '3' },
      { label: t('views.perfManage.taskManage.four'), value: '4' },
      { label: t('views.perfManage.taskManage.five'), value: '5' },
      { label: t('views.perfManage.taskManage.six'), value: '6' },
      { label: t('views.perfManage.taskManage.seven'), value: '7' },
    ],
    Monthly: generateOptions(1, 30),
  },
});

/**记录开始结束时间 */
let queryRangePicker = ref<[string, string]>(['', '']);

/**查询参数 */
let queryParams = reactive({
  /**网元类型 */
  neType: '',
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    neType: '',
    pageNum: 1,
    pageSize: 20,
  });
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  fnGetList();
}

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**搜索栏 */
  seached: boolean;
  /**记录数据 */
  data: object[];
  /**勾选记录 */
  selectedRowKeys: (string | number)[];
};

/**表格状态 */
let tableState: TabeStateType = reactive({
  loading: false,
  size: 'middle',
  seached: true,
  data: [],
  selectedRowKeys: [],
});

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('views.perfManage.taskManage.taskId'),
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: t('views.perfManage.taskManage.neType'),
    dataIndex: 'neType',
    align: 'center',
  },
  {
    title: t('views.perfManage.taskManage.size'),
    dataIndex: 'granulOption',
    align: 'center',
  },
  {
    title: t('views.perfManage.taskManage.taskStatus'),
    dataIndex: 'status',
    key: 'status',
    align: 'center',
  },
  {
    title: t('views.perfManage.taskManage.addUser'),
    dataIndex: 'accountId',
    align: 'center',
  },
  {
    title: t('views.perfManage.taskManage.addTime'),
    dataIndex: 'createTime',
    align: 'center',
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(opt.value);
    },
  },
  {
    title: t('common.operate'),
    key: 'id',
    align: 'center',
  },
];

/**表格分页器参数 */
let tablePagination = reactive({
  /**当前页数 */
  current: 1,
  /**每页条数 */
  pageSize: 20,
  /**默认的每页条数 */
  defaultPageSize: 20,
  /**指定每页可以显示多少条 */
  pageSizeOptions: ['10', '20', '50', '100'],
  /**只有一页时是否隐藏分页器 */
  hideOnSinglePage: false,
  /**是否可以快速跳转至某页 */
  showQuickJumper: true,
  /**是否可以改变 pageSize */
  showSizeChanger: true,
  /**数据总数 */
  total: 0,
  showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
  onChange: (page: number, pageSize: number) => {
    tablePagination.current = page;
    tablePagination.pageSize = pageSize;
    queryParams.pageNum = page;
    queryParams.pageSize = pageSize;
    fnGetList();
  },
});

/**表格紧凑型变更操作 */
function fnTableSize({ key }: MenuInfo) {
  tableState.size = key as SizeType;
}

/**
 * 测量任务删除
 * @param row 记录编号ID
 */
function fnRecordDelete(row: Record<string, any>) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.perfManage.taskManage.delPerfTip', { num: row.id }),
    onOk() {
      const key = 'delTraceTask';
      message.loading({ content: t('common.loading'), key });
      delPerfTask(row).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('views.perfManage.taskManage.delPerf', { num: row.id }),
            key,
            duration: 2,
          });
          fnGetList();
        } else {
          message.error({
            content: `${res.msg}`,
            key: key,
            duration: 2,
          });
        }
      });
    },
  });
}

/**查询信息列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }
  listPerfTask(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      tablePagination.total = res.total;
      tableState.data = res.rows;
      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**详情框是否显示 */
  visibleByView: boolean;
  /**新增框或修改框是否显示 */
  visibleByEdit: boolean;
  /**标题 */
  title: string;
  /**选择后清空 */
  initPeriods: [];
  /**网元类型设备对象 */
  neType: string[];
  /**网元类型性能测量集 */
  neTypPerformance: Record<string, any>[];
  /**网元类型性能测量集选择 */
  neTypPerformanceList: [];
  /**任务开始结束时间 */
  timeRangePicker: [string, string];
  /**时间段多选 */
  timeSlotAll: string[];
  /**时间段多选 */
  periodsStep: number;

  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  visibleByView: false,
  visibleByEdit: false,
  title: '',
  initPeriods: [],
  neType: [],
  neTypPerformance: [],
  neTypPerformanceList: [],
  timeRangePicker: ['', ''],
  timeSlotAll: [],
  periodsStep: 30,

  from: {
    id: '',
    neType: '',
    neId: '',
    granulOption: '',
    startTime: '',
    endTime: '',
    bigPlan: '',
    smPlan: [],
    comment: '',
    // 跟踪类型接口
    performanceArr: '',
    kpiSet: '',
    periods: [],
  },
  confirmLoading: false,
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    neId: [
      {
        required: true,
        message: t('views.ne.common.neTypePlease'),
      },
    ],
    granulOption: [
      {
        required: true,
        message: t('views.perfManage.taskManage.granulOptionPlease'),
      },
    ],
    kpiSet: [
      {
        required: true,
        message: t('views.perfManage.taskManage.performanceSelect'),
      },
    ],
  })
);

/**网元类型选择对应修改 */
function fnNeChange(_: any, item: any) {
  modalState.from.neType = item[1].neType;
  modalState.from.neId = item[1].neId;

  modalState.neTypPerformanceList = [];

  // 网元信令接口
  fnSelectPerformanceInit(item[1].neType);
}

/**开始结束时间选择对应修改 */
function fnRangePickerChange(_: any, item: any) {
  modalState.from.startTime = item[0];
  modalState.from.endTime = item[1];
}

/**时间段的选择对应的修改 */
function fnPeriodsSelect(item: any, timeString: any) {
  taskManageOption.timeSlotAll.push({
    label: timeString.join(','),
    value: item.join(','),
  });
  modalState.timeSlotAll.push(item.join(','));
  modalState.from.periods = modalState.timeSlotAll;
}
/**时间段选择后回调 */
function fnChange(open: any) {
  if (!open && queryRangePicker.value[0] && queryRangePicker.value[1]) {
    queryRangePicker.value = ['', ''];
  }
}

/**性能测量数据集对应修改 */
function fnSelectPer(s: any, option: any) {
  modalState.from.kpiSet = s.join(',');
  const groupedData = option.reduce((groups: any, item: any) => {
    const { kpiCode, ...rest } = item;
    if (!groups[kpiCode]) {
      groups[kpiCode] = [];
    }
    groups[kpiCode].push(rest);
    return groups;
  }, {});
  let kpiGroup = []; //最终上报给网元的kpi_set数据
  let kpisArr = []; //整理kpis数据所用
  //进行打包网元所需的规范数据
  for (var key in groupedData) {
    for (let i = 0; i < groupedData[key].length; i++) {
      //  console.log(i, groupedKpi[key][i].name)
      kpisArr.push(groupedData[key][i].value);
    }
    kpiGroup.push({ Code: key, KPIs: kpisArr });
    kpisArr = [];
  }
  modalState.from.kpiSet = JSON.stringify(kpiGroup);
}

/**性能测量数据集选择初始 */
function fnSelectPerformanceInit(neType: string) {
  //console.logg(currentLocale.value); //当前语言
  const performance = neInfoStore.perMeasurementList.filter(
    i => i.neType === neType
  );
  //进行分组选择
  const groupedData = performance.reduce((groups: any, item: any) => {
    const { kpiCode, ...rest } = item;
    if (!groups[kpiCode]) {
      groups[kpiCode] = [];
    }
    groups[kpiCode].push(rest);
    return groups;
  }, {});

  //渲染出性能测量集的选择项
  modalState.neTypPerformance = Object.keys(groupedData).map(kpiCode => {
    return {
      label: kpiCode,
      options: groupedData[kpiCode].map((item: any) => {
        return {
          value: item.kpiId,
          label:
            currentLocale.value === 'zh_CN'
              ? JSON.parse(item.titleJson).cn
              : JSON.parse(item.titleJson).en,
          kpiCode: kpiCode,
        };
      }),
    };
  });
}

/**
 * 对话框弹出显示为 详情框
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByVive(id: string) {
  if (modalState.confirmLoading) return;
  const hide = message.loading(t('common.loading'), 0);
  modalState.confirmLoading = true;
  getPerfTask(id).then(res => {
    modalState.confirmLoading = false;
    hide();
    if (res.code === RESULT_CODE_SUCCESS) {
      if (res.data.kpiSet.includes('[') && res.data.neIds.includes('[')) {
        modalState.neType = [res.data.neType, JSON.parse(res.data.neIds)[0]];
        modalState.neTypPerformanceList = JSON.parse(res.data.kpiSet).reduce(
          (acc: any, item: any) => acc.concat(item.KPIs),
          []
        );
      }

      if (res.data.periods.includes('[') && res.data.periods.length > 4) {
        const jsonArray = JSON.parse(res.data.periods);
        modalState.initPeriods = jsonArray.map(
          (item: any) => `${item.Start} - ${item.End}`
        );
      }

      if (res.data.schedule.includes('[') && res.data.schedule.length > 4) {
        modalState.from.bigPlan = JSON.parse(res.data.schedule)[0].Type;
        modalState.from.smPlan = JSON.parse(res.data.schedule)[0].Days;
      }

      modalState.timeRangePicker = [res.data.startTime, res.data.endTime];
      modalState.from = Object.assign(modalState.from, res.data);
      modalState.title = t('views.perfManage.taskManage.viewTask');
      modalState.visibleByView = true;
    } else {
      message.error(t('views.perfManage.taskManage.errorTaskInfo'), 3);
    }
  });
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByEdit(id?: string) {
  if (!id) {
    modalStateFrom.resetFields();
    modalState.title = t('views.perfManage.taskManage.addTask');
    modalState.visibleByEdit = true;
  } else {
    if (modalState.confirmLoading) return;
    const hide = message.loading(t('common.loading'), 0);
    modalState.confirmLoading = true;
    getPerfTask(id).then(res => {
      modalState.confirmLoading = false;
      hide();
      if (res.code === RESULT_CODE_SUCCESS && res.data) {
        modalState.periodsStep = parseInt(
          res.data.granulOption.substring(0, 2)
        );

        if (res.data.kpiSet.includes('[')) {
          modalState.neTypPerformanceList = JSON.parse(res.data.kpiSet).reduce(
            (acc: any, item: any) => acc.concat(item.KPIs),
            []
          );
        }

        if (res.data.schedule.includes('[') && res.data.schedule.length > 4) {
          modalState.from.bigPlan = JSON.parse(res.data.schedule)[0].Type;
          modalState.from.smPlan = JSON.parse(res.data.schedule)[0].Days;
        }

        modalState.neType = [res.data.neType, JSON.parse(res.data.neIds)[0]];
        fnSelectPerformanceInit(res.data.neType); //初始性能测量数据
        modalState.from.neId = JSON.parse(res.data.neIds)[0];
        modalState.timeRangePicker = [res.data.startTime, res.data.endTime];
        modalState.from = Object.assign(modalState.from, res.data);

        if (res.data.periods.includes('[') && res.data.periods.length > 4) {
          const jsonArray = JSON.parse(res.data.periods);
          modalState.initPeriods = jsonArray.map(
            (item: any) => `${item.Start},${item.End}`
          );
          if (modalState.initPeriods.length) {
            modalState.timeSlotAll = [];
            taskManageOption.timeSlotAll = [];
            const updatedTimeRanges = modalState.initPeriods.map(
              (timeRange: any) => {
                const [startTime, endTime] = timeRange.split(',');
                const updatedStartTime = startTime.slice(0, -3);
                const updatedEndTime = endTime.slice(0, -3);
                taskManageOption.timeSlotAll.push({
                  label: `${updatedStartTime},${updatedEndTime}`,
                  value: timeRange,
                });
                return `${updatedStartTime},${updatedEndTime}`;
              }
            );

            modalState.timeSlotAll.push(...modalState.initPeriods);
            modalState.initPeriods = [];
            modalState.from.periods = modalState.timeSlotAll;
          }
        } else {
          modalState.from.periods = [];
        }
        modalState.title = t('views.perfManage.taskManage.editTask');
        modalState.visibleByEdit = true;
      } else {
        message.error(t('views.perfManage.taskManage.errorTaskInfo'), 3);
      }
    });
  }
}

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  modalStateFrom
    .validate()
    .then(e => {
      const from = toRaw(modalState.from);
      from.accountId = useUserStore().userName;
      modalState.confirmLoading = true;
      const perfTask = from.id ? updatePerfTask(from) : addPerfTask(from);
      const hide = message.loading(t('common.loading'), 0);
      perfTask
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', { msg: modalState.title }),
              duration: 3,
            });
            modalState.visibleByEdit = false;
            modalStateFrom.resetFields();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
          fnModalCancel();
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
          fnGetList();
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**
 * 为时间段设置步长
 */
function updateStep(str: any) {
  modalState.from.periods = [];
  modalState.periodsStep = parseInt(str.substring(0, 2));
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.visibleByView = false;
  modalState.visibleByEdit = false;
  modalState.confirmLoading = false;
  modalStateFrom.resetFields();
  modalState.timeRangePicker = ['', ''];
  modalState.neTypPerformanceList = [];
  modalState.initPeriods = [];
  modalState.neType = [];
  modalState.timeSlotAll = [];
}

/**
 * 激活任务
 * @param row 网元编号ID
 */
function fnRecordRun(row: Record<string, any>) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.perfManage.taskManage.letupSure', { id: row.id }),
    onOk() {
      const key = 'taskRun';
      message.loading({ content: t('common.loading'), key });
      taskRun(row).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('common.msgSuccess', {
              msg: t('views.configManage.softwareManage.runBtn'),
            }),
            key,
            duration: 2,
          });
          fnGetList();
        } else {
          message.error({
            content: `${res.msg}`,
            key: key,
            duration: 2,
          });
        }
      });
    },
  });
}

/**
 * 挂起任务
 * @param row 网元编号ID
 */
function fnRecordStop(row: Record<string, any>) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.perfManage.taskManage.stopSure', { id: row.id }),
    onOk() {
      const key = 'taskStop';
      message.loading({ content: t('common.loading'), key });
      taskStop(row).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('common.msgSuccess', {
              msg: t('views.perfManage.taskManage.stopTask'),
            }),
            key,
            duration: 2,
          });
          fnGetList();
        } else {
          message.error({
            content: `${res.msg}`,
            key: key,
            duration: 2,
          });
        }
      });
    },
  });
}

/**
 * 记录多项选择
 */
function fnTaskModalVisible(type: string | number, row: Record<string, any>) {
  if (type === 'run') {
    if (row.status === 'Active') {
      var key = 'Active';
      message.error({
        content: t('views.perfManage.taskManage.letUpWarning'),
        key: key,
        duration: 2,
      });
      return false;
    }
    fnRecordRun(row);
  }

  if (type === 'stop') {
    if (row.status === 'Inactive') {
      var key = 'stop';
      message.error({
        content: t('views.perfManage.taskManage.stopWarning'),
        key: key,
        duration: 2,
      });
      return false;
    }
    fnRecordStop(row);
  }
}

onMounted(() => {
  // 初始字典数据

  Promise.allSettled([
    // 获取网元网元列表
    neInfoStore.fnNelist(),
    // 获取性能测量集列表
    neInfoStore.fnNeTaskPerformance(),
  ]).finally(() => {
    // 获取列表数据
    fnGetList();
  });
});
</script>

<template>
  <PageContainer>
    <a-card
      v-show="tableState.seached"
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item
              :label="t('views.ne.common.neType')"
              name="neType "
            >
              <a-auto-complete
                v-model:value="queryParams.neType"
                :options="neInfoStore.getNeSelectOtions"
                allow-clear
                :placeholder="t('views.ne.common.neTypePlease')"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnGetList(1)">
                  <template #icon><SearchOutlined /></template>
                  {{ t('common.search') }}
                </a-button>
                <a-button type="default" @click.prevent="fnQueryReset">
                  <template #icon><ClearOutlined /></template>
                  {{ t('common.reset') }}
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-button type="primary" @click.prevent="fnModalVisibleByEdit()">
          <template #icon><PlusOutlined /></template>
          {{ t('common.addText') }}
        </a-button>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip placement="topRight">
            <template #title>{{ t('common.searchBarText') }}</template>
            <a-switch
              v-model:checked="tableState.seached"
              :checked-children="t('common.switch.show')"
              :un-checked-children="t('common.switch.hide')"
              size="small"
            />
          </a-tooltip>
          <a-tooltip placement="topRight">
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip placement="topRight">
            <template #title>{{ t('common.sizeText') }}</template>
            <a-dropdown trigger="click" placement="bottomRight">
              <a-button type="text">
                <template #icon><ColumnHeightOutlined /></template>
              </a-button>
              <template #overlay>
                <a-menu
                  :selected-keys="[tableState.size as string]"
                  @click="fnTableSize"
                >
                  <a-menu-item key="default">{{
                    t('common.size.default')
                  }}</a-menu-item>
                  <a-menu-item key="middle">{{
                    t('common.size.middle')
                  }}</a-menu-item>
                  <a-menu-item key="small">{{
                    t('common.size.small')
                  }}</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="id"
        :columns="tableColumns"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ x: true }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <a-space :size="8" align="center">
              <a-tooltip>
                <template #title>{{ t('common.viewText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByVive(record.id)"
                >
                  <template #icon><ProfileOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.editText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByEdit(record.id)"
                  :disabled="record.status !== 'Inactive'"
                >
                  <template #icon><FormOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.deleteText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnRecordDelete(record)"
                  :disabled="record.status !== 'Inactive'"
                >
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.moreText') }}</template>
                <a-dropdown placement="bottomRight" trigger="click">
                  <a-button type="link">
                    <template #icon><EllipsisOutlined /> </template>
                  </a-button>
                  <template #overlay>
                    <a-menu
                      @click="({ key }:any) => fnTaskModalVisible(key, record)"
                    >
                      <a-menu-item key="run">
                        <ThunderboltOutlined />
                        {{ t('views.configManage.softwareManage.runBtn') }}
                      </a-menu-item>
                      <a-menu-item key="stop">
                        <UndoOutlined />
                        {{ t('views.perfManage.taskManage.stopTask') }}
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情框 -->
    <ProModal
      :drag="true"
      :width="800"
      :visible="modalState.visibleByView"
      :title="modalState.title"
      @cancel="fnModalCancel"
    >
      <a-form layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.ne.common.neType')"
              name="neType"
            >
              <a-cascader
                :value="modalState.neType"
                :options="neInfoStore.getNeCascaderOptions"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.traceManage.task.rangePicker')"
          name="endTime"
        >
          <a-range-picker
            disabled
            :value="modalState.timeRangePicker"
            allow-clear
            bordered
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></a-range-picker>
        </a-form-item>

        <a-form-item
          :label="t('views.perfManage.taskManage.performanceList')"
          name="performanceArr"
        >
          {{ modalState.neTypPerformanceList }}
        </a-form-item>

        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              name="granulOption"
              :label="t('views.perfManage.taskManage.granulOption')"
            >
              <a-select
                v-model:value="modalState.from.granulOption"
                :options="taskManageOption.granulOption"
                disabled
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.perfManage.taskManage.period')"
          name="performanceArr"
        >
          {{ modalState.initPeriods }}
        </a-form-item>

        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.taskManage.plan')"
              name="bigPlan"
            >
              <a-select
                v-model:value="modalState.from.bigPlan"
                :options="taskManageOption.bigPlan"
                disabled
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item name="smPlan">
              <a-select
                v-model:value="modalState.from.smPlan"
                mode="multiple"
                :options="taskManageOption.smPlan[modalState.from.bigPlan as 'Weekly' | 'Monthly']"
                disabled
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.traceManage.task.comment')"
          name="comment"
        >
          {{ modalState.from.comment }}
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="cancel" @click="fnModalCancel">{{
          t('common.close')
        }}</a-button>
      </template>
    </ProModal>

    <!-- 新增框或修改框 -->
    <ProModal
      :drag="true"
      :width="800"
      :destroyOnClose="true"
      :keyboard="false"
      :mask-closable="false"
      :visible="modalState.visibleByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <a-form name="modalStateFrom" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.ne.common.neType')"
              name="neType"
              v-bind="modalStateFrom.validateInfos.neId"
            >
              <a-cascader
                v-model:value="modalState.neType"
                :options="neInfoStore.getNeCascaderOptions"
                @change="fnNeChange"
                :allow-clear="false"
                :placeholder="t('views.ne.common.neTypePlease')"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.perfManage.taskManage.performanceList')"
          name="performanceArr"
          v-show="modalState.neType.length !== 0"
          v-bind="modalStateFrom.validateInfos.kpiSet"
        >
          <a-select
            mode="multiple"
            placeholder="Please select"
            v-model:value="modalState.neTypPerformanceList"
            :options="modalState.neTypPerformance"
            @change="fnSelectPer"
          >
          </a-select>
        </a-form-item>

        <a-form-item
          :label="t('views.traceManage.task.rangePicker')"
          name="endTime"
          v-bind="modalStateFrom.validateInfos.endTime"
        >
          <a-range-picker
            v-model:value="modalState.timeRangePicker"
            @change="fnRangePickerChange"
            allow-clear
            bordered
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="[
              t('views.traceManage.task.startTime'),
              t('views.traceManage.task.endTime'),
            ]"
            style="width: 100%"
          ></a-range-picker>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.taskManage.granulOption')"
              name="granulOption"
              v-bind="modalStateFrom.validateInfos.granulOption"
            >
              <a-select
                v-model:value="modalState.from.granulOption"
                :options="taskManageOption.granulOption"
                @change="updateStep"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.perfManage.taskManage.period')"
          name="period"
          v-if="
            modalState.from.granulOption &&
            modalState.from.granulOption !== '24H'
          "
        >
          <a-select
            mode="multiple"
            placeholder="Please select"
            v-model:value="modalState.from.periods"
            :options="taskManageOption.timeSlotAll"
            :open="false"
          >
          </a-select>
          <a-time-range-picker
            format="HH:mm"
            value-format="HH:MM:00"
            v-model:value="queryRangePicker"
            @change="fnPeriodsSelect"
            @open-change="fnChange"
            :minute-step="modalState.periodsStep"
          />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.taskManage.plan')"
              name="bigPlan"
            >
              <a-select
                v-model:value="modalState.from.bigPlan"
                :options="taskManageOption.bigPlan"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item name="smPlan" v-show="modalState.from.bigPlan">
              <a-select
                v-model:value="modalState.from.smPlan"
                mode="multiple"
                :options="taskManageOption.smPlan[modalState.from.bigPlan as 'Weekly' | 'Monthly']"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.traceManage.task.remark')"
          name="comment"
        >
          <a-textarea
            v-model:value="modalState.from.comment"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            :maxlength="250"
            :show-count="true"
            :placeholder="t('views.traceManage.task.remarkPlease')"
          />
        </a-form-item>
      </a-form>
    </ProModal>
  </PageContainer>
</template>

<style lang="less" scoped>
.table :deep(.ant-pagination) {
  padding: 0 24px;
}
</style>
