<script setup lang="ts">
import { reactive, onMounted, ref, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { ProModal } from 'antdv-pro-modal';
import { Form, message, Modal } from 'ant-design-vue/es';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { MenuInfo } from 'ant-design-vue/es/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/es/table';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';
import useNeInfoStore from '@/store/modules/neinfo';
import {
  addCustom,
  delCustom,
  listCustom,
  updateCustom,
} from '@/api/perfManage/customTarget';
import { getKPITitle } from '@/api/perfManage/goldTarget';
import useDictStore from '@/store/modules/dict';
const { t, currentLocale } = useI18n();
const { getDict } = useDictStore();

/**字典数据 */
let dict: {
  /**状态 */
  sysNormalDisable: DictType[];
} = reactive({
  sysNormalDisable: [],
});

/**查询参数 */
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.neType'),
    dataIndex: 'neType',
    align: 'center',
  },
  {
    title: t('views.perfManage.customTarget.kpiId'),
    dataIndex: 'kpiId',
    align: 'center',
  },
  {
    title: t('views.perfManage.customTarget.title'),
    dataIndex: 'title',
    align: 'center',
  },
  {
    title: t('views.perfManage.customTarget.expression'),
    dataIndex: 'exprAlias',
    align: 'center',
  },
  {
    title: t('views.perfManage.customTarget.description'),
    dataIndex: 'description',
    align: 'center',
  },
  {
    title: t('views.perfManage.customTarget.status'),
    dataIndex: 'status',
    key: 'status',
    align: 'left',
    width: 100,
    customRender: ({ text }) => {
      if (text === '1') {
        return 'Active';
      }
      return 'Inactive';
    },
  },
  {
    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.customTarget.delCustomTip', {
      num: row.kpiId,
    }),
    onOk() {
      const key = 'delThreshold';
      message.loading({ content: t('common.loading'), key });
      delCustom(row).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('views.perfManage.customTarget.delCustom', {
              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;
  }
  listCustom(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      const { total, rows } = res.data;
      tablePagination.total = total;
      tableState.data = rows;

      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**详情框是否显示 */
  openByView: boolean;
  /**新增框或修改框是否显示 */
  openByEdit: boolean;
  /**标题 */
  title: string;
  /**网元类型设备对象 */
  neType: string[];
  /**网元类型性能测量集 */
  neTypPerformance: Record<string, any>[];
  /**已选择性能测量项 */
  selectedPre: string[];
  /** 元素选择*/
  elemSelect: any;
  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByView: false,
  openByEdit: false,
  title: '',
  neType: [],
  neTypPerformance: [],
  selectedPre: [],
  elemSelect: '',
  from: {
    id: undefined,
    neType: 'UDM',
    title: '',
    expression: '',
    status: '1',
    unit: '',
    description: '',
  },
  confirmLoading: false,
});

/**表单中多选的OPTION */
const modalStateFromOption = reactive({
  symbolJson: [
    { label: '(', value: '(' },
    { label: ')', value: ')' },
    { label: '+', value: '+' },
    { label: '-', value: '-' },
    { label: '*', value: '*' },
    { label: '/', value: '/' },
  ],
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    neType: [
      {
        required: true,
        message: t('views.ne.common.neTypePlease'),
      },
    ],
    expression: [
      {
        required: true,
        message:
          t('views.perfManage.customTarget.expression') +
          t('common.unableNull'),
      },
    ],
    title: [
      {
        required: true,
        message:
          t('views.perfManage.customTarget.title') + t('common.unableNull'),
      },
    ],
    unit: [
      {
        required: true,
        message:
          t('views.perfManage.customTarget.unit') + t('common.unableNull'),
      },
    ],
  })
);

/**性能测量数据集选择初始  value:neType*/
function fnSelectPerformanceInit(value: any) {
  modalState.from.expression = '';
  modalState.elemSelect = '';
  modalState.neTypPerformance = [
    {
      value: 'granularity',
      label: t('views.perfManage.customTarget.granularity'),
    },
  ];
  // 当前语言
  var language = currentLocale.value.split('_')[0];
  if (language === 'zh') language = 'cn';
  // 获取表头文字
  getKPITitle(value).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      for (const item of res.data) {
        const kpiDisplay = item[`${language}Title`];
        const kpiValue = item[`kpiId`];
        modalState.neTypPerformance.push({
          value: kpiValue,
          label: kpiDisplay,
        });
      }
    } else {
      message.warning({
        content: t('common.getInfoFail'),
        duration: 2,
      });
    }
  });
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByEdit(row?: any, id?: any) {
  if (!id) {
    modalStateFrom.resetFields();
    modalState.title = t('views.perfManage.customTarget.addCustom');
    modalState.openByEdit = true;
    fnSelectPerformanceInit(modalState.from.neType);
  } else {
    fnSelectPerformanceInit(row.neType);
    modalState.from = Object.assign(modalState.from, row);
    modalState.from.expression = modalState.from.exprAlias;
    modalState.title = t('views.perfManage.customTarget.editCustom');
    modalState.openByEdit = true;
  }
}

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  modalStateFrom
    .validate()
    .then((e: any) => {
      const matches = modalState.from.expression.match(/'([^']+)'/g); // 提取单引号内容
      // 替换为对应的 value
      let result = modalState.from.expression;

      if (matches) {
        for (const match of matches) {
          const valueToReplace = match.slice(1, -1); // 去掉单引号
          const found = modalState.neTypPerformance.find(
            (item: any) => item.label === valueToReplace
          );
          if (found) {
            result = result.replace(match, `'${found.value}'`); // 替换为对应的 value
          } else {
            message.error(
              t('views.perfManage.customTarget.expressionErrorTip', {
                kpiId: valueToReplace,
              }),
              3
            );
            return;
          }
        }
      } else {
        message.error(t('views.perfManage.customTarget.expressionNoIdTip'), 3);
        return false;
      }
      //modalState.from.expression = result;
      //const from = toRaw(modalState.from);
      const from = { ...toRaw(modalState.from) };
      from.expression = result;
      //return false;
      modalState.confirmLoading = true;
      const perfTask = from.id ? updateCustom(from) : addCustom(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,
            });
            modalStateFrom.resetFields();
            fnModalCancel();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
          fnGetList();
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.openByEdit = false;
  modalState.confirmLoading = false;
  modalStateFrom.resetFields();
  modalState.neType = [];
  modalState.neTypPerformance = [];
}

/**
 * 选择性能指标,填充进当前计算公式的值
 */
function fnSelectPer(s: any, option: any) {
  modalState.from.expression += `'${option.label}'`;
}

function fnSelectSymbol(s: any) {
  modalState.from.expression += s;
}

function fnChangeUnit(value: any) {
  if (value === '%' && modalState.from.expression) {
    modalState.from.expression = `(${modalState.from.expression})*100`;
  }
}

/**网元参数 */
let neCascaderOptions = ref<Record<string, any>[]>([]);
onMounted(() => {
  Promise.allSettled([
    // 获取网元网元列表
    getDict('sys_normal_disable'),
    useNeInfoStore().fnNelist(),
  ])
    .then(resArr => {
      if (resArr[0].status === 'fulfilled') {
        dict.sysNormalDisable = resArr[0].value;
      }

      if (
        resArr[1].status === 'fulfilled' &&
        Array.isArray(resArr[1].value.data)
      ) {
        if (resArr[1].value.data.length > 0) {
          // 过滤不可用的网元
          neCascaderOptions.value =
            useNeInfoStore().getNeCascaderOptions.filter((item: any) => {
              return !['OMC', 'NSSF', 'NEF', 'NRF', 'LMF', 'N3IWF'].includes(
                item.value
              );
            });
          if (neCascaderOptions.value.length === 0) {
            message.warning({
              content: t('common.noData'),
              duration: 2,
            });
            return;
          }
        }
      }
    })
    .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="neCascaderOptions"
                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.editText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByEdit(record, record.id)"
                >
                  <template #icon><FormOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.deleteText') }}</template>
                <a-button type="link" @click.prevent="fnRecordDelete(record)">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>

          <template v-if="column.key === 'status'">
            <DictTag
              :options="[
                {
                  label: t('views.perfManage.customTarget.active'),
                  value: '1',
                  tagType: 'success',
                },
                {
                  label: t('views.perfManage.customTarget.inactive'),
                  value: '0',
                  tagType: 'error',
                },
              ]"
              :value="record.status"
            />
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增框或修改框 -->
    <ProModal
      :drag="true"
      :width="800"
      :destroyOnClose="true"
      :keyboard="false"
      :mask-closable="false"
      v-model:open="modalState.openByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 6 }"
        :label-wrap="true"
      >
        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.ne.common.neType')"
              name="neType"
              v-bind="modalStateFrom.validateInfos.neType"
            >
              <a-select
                v-model:value="modalState.from.neType"
                :options="neCascaderOptions"
                @change="fnSelectPerformanceInit"
                :allow-clear="false"
                :placeholder="t('views.ne.common.neTypePlease')"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.customTarget.status')"
              name="status"
            >
              <a-select
                v-model:value="modalState.from.status"
                default-value="0"
                :options="[
                  {
                    label: t('views.perfManage.customTarget.active'),
                    value: '1',
                  },
                  {
                    label: t('views.perfManage.customTarget.inactive'),
                    value: '0',
                  },
                ]"
                :placeholder="t('common.selectPlease')"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :lg="24" :md="24" :xs="24">
            <a-form-item
              :label="t('views.perfManage.customTarget.title')"
              name="title"
              :label-col="{ span: 3 }"
              v-bind="modalStateFrom.validateInfos.title"
            >
              <a-input
                v-model:value="modalState.from.title"
                :maxlength="255"
                allow-clear
              >
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">{{
          t('views.perfManage.customTarget.expressionModal')
        }}</a-divider>
        <a-form-item
          :label="t('views.perfManage.customTarget.expression')"
          name="expression"
          :label-col="{ span: 3 }"
          v-bind="modalStateFrom.validateInfos.expression"
        >
          <a-input
            v-model:value="modalState.from.expression"
            :disabled="modalState.from.id"
            :maxlength="1024"
            autocomplete="off"
            allow-clear
          >
          </a-input>
        </a-form-item>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              name="elemSelect"
              :label="t('views.perfManage.customTarget.element')"
            >
              <a-select
                v-model:value="modalState.elemSelect"
                placeholder="Please select"
                :options="modalState.neTypPerformance"
                @select="fnSelectPer"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              name="symbol"
              :label="t('views.perfManage.customTarget.symbol')"
            >
              <a-select
                placeholder="Please select"
                :options="modalStateFromOption.symbolJson"
                @select="fnSelectSymbol"
              ></a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.customTarget.unit')"
              name="expression"
              v-bind="modalStateFrom.validateInfos.unit"
              :help="t('views.perfManage.customTarget.TourDes4')"
            >
              <a-auto-complete
                v-model:value="modalState.from.unit"
                @change="fnChangeUnit"
                :options="[
                  {
                    label: 'Mbps',
                    value: 'Mbps',
                  },
                  {
                    label: '%',
                    value: '%',
                  },
                ]"
              >
              </a-auto-complete>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider></a-divider>

        <a-form-item
          :label="t('views.perfManage.customTarget.description')"
          name="description"
          :label-col="{ span: 3 }"
        >
          <a-textarea
            v-model:value="modalState.from.description"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            :maxlength="250"
            :show-count="true"
          />
        </a-form-item>
      </a-form>
    </ProModal>
  </PageContainer>
</template>

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