<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { message, Form, Modal } from 'ant-design-vue/lib';
import { ColumnsType } from 'ant-design-vue/lib/table';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import ChartLine from '@/components/ChartLine/index.vue';
import { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
import TableColumnsDnd from '@/components/TableColumnsDnd/index.vue';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useNeInfoStore from '@/store/modules/neinfo';
import useI18n from '@/hooks/useI18n';
import { getGoldTitleByNE, goldData } from '@/api/perfManage/goldTarget';
import { parseDateToStr } from '@/utils/date-utils';
import { writeSheet } from '@/utils/execl-utils';
import saveAs from 'file-saver';
const neInfoStore = useNeInfoStore();
const { t, currentLocale } = useI18n();

/**网元参数 */
let neCascaderOptions = ref<Record<string, any>[]>([]);

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

/**表格字段列排序 */
let tableColumnsDnd = ref<ColumnsType>([]);

/**表格状态类型 */
type TabeStateType = {
  /**表格列 */
  tableColumns: object[];
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**搜索栏 */
  seached: boolean;
  /**记录数据 */
  data: object[];
};

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

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

/**查询参数 */
let queryParams: any = reactive({
  /**卡片切换Flag */
  cardFlag: 0, //0-显示统计图 1-显示统计表
  /**告警设备类型 */
  neType: '',
  /**告警网元标识 */
  neId: '',
  /**颗粒度 */
  particle: '15',
  beginTime: '',
  endTime: '',
  /**排序字段 */
  sortField: 'timeGroup',
  /**排序方式 */
  sortOrder: 'desc',
});

/**表格分页、排序、筛选变化时触发操作, 排序方式，取值为 ascend descend */
function fnTableChange(pagination: any, filters: any, sorter: any, extra: any) {
  tableState.loading = true;
  const { columnKey, order } = sorter;
  if (order) {
    queryParams.sortField = columnKey;
    queryParams.sortOrder = order.replace('end', '');
  } else {
    queryParams.sortOrder = 'desc';
  }
  fnMakeTable(1);
}

/**图表显示数据 */
const chartsOption = reactive({
  /**性能指标 */
  perfChart: {},
});

/**对象信息状态类型 */
type StateType = {
  /**网元类型 */
  neType: string[];
  /**制表网元类型 */
  designNeType: string;
  /**黄金指标集 tree */
  designTreeData: any[];
  /**表单数据 */
  from: Record<string, any>;
};

/**对象信息状态 */
let state: StateType = reactive({
  neType: [],
  designNeType: '',
  designTreeData: [],
  from: {
    uploadLoading: false,
    sendLoading: false,
  },
});

/**网元类型选择对应修改 */
function fnNeChange(keys: any, _: any) {
  // 不是同类型时需要重新加载
  if (state.designNeType !== keys[0]) {
    state.designTreeData = [];
    queryParams.cardFlag = 0;
    fnGetList();
  }
}

/**查询可选命令列表 */
function fnGetList() {
  const neType = queryParams.neType[0];
  state.designNeType = neType;
  var language = currentLocale.value.split('_')[0];
  if (language === 'zh') language = 'cn';
  getGoldTitleByNE(neType).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      // 构建树结构
      const treeArr: Record<string, any>[] = [];
      for (const item of res.data) {
        const id = item['id'];
        const kpiDisplay = item[`${language}Title`];
        const kpiValue = item[`kpiId`];
        treeArr.push({
          key: kpiValue,
          title: kpiDisplay,
        });
      }
      state.designTreeData = treeArr;
    } else {
      message.warning({
        content: t('common.getInfoFail'),
        duration: 2,
      });
    }
  });
  fnDesign();
}

/**根据 key 查找对应的 title */
function findTitleByKey(key: string): string | undefined {
  const item = state.designTreeData.find(item => item.key === key);
  return item ? item.title : key;
}

/**筛选条件进行制图 */
function fnMakeTable(flag: any) {
  queryParams.cardFlag = flag;
  fnDesign();
}

/**筛选条件进行制图 */
function fnDesign() {
  //当前界面是表格界面
  const columnsArr = state.designTreeData.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      align: 'center',
    };
  });
  tableState.tableColumns = columnsArr;
  tableState.tableColumns.unshift({
    title: t('views.perfManage.perfData.neName'),
    dataIndex: 'neName',
    align: 'center',
  });
  tableState.tableColumns.push({
    title: t('views.perfManage.goldTarget.time'),
    dataIndex: 'timeGroup',
    align: 'center',
    fixed: 'right',
    key: 'timeGroup',
    sorter: true,
  });
  if (!queryRangePicker.value) {
    queryRangePicker.value = ['', ''];
  }
  queryParams.beginTime = queryRangePicker.value[0];
  queryParams.endTime = queryRangePicker.value[1];
  let goldXDate: any = [];
  let goldYData: any = [];
  let hideAll: any = {};
  goldData(queryParams)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        if (res.data.length > 0) {
          console.log(res.data);
          tableState.data = res.data;
          goldXDate = res.data.map((item: any) => item.timeGroup);
          goldYData = Object.keys(res.data[0])
            .filter(key => !['timeGroup', 'neName', 'startIndex'].includes(key))
            .map(key => {
              const title: any = findTitleByKey(key);
              hideAll[title] = false;
              return {
                name: title,
                data: res.data.map((item: any) => parseInt(item[key])),
              };
            });
        } else {
          tableState.data = [];
          state.designTreeData.forEach((item: any) => {
            goldYData.push({ name: item.title, data: [] });
          });
          message.warning({
            content: t('views.perfManage.goldTarget.nullTip'),
            duration: 2,
          });
        }

        // 图标参数
        const option = {
          xDatas: goldXDate,
          yDatas: goldYData,
          tooltip: {
            trigger: 'axis',
            formatter: function (datas: any) {
              let res = datas[0].name + '<br/>';
              for (const item of datas) {
                res += `${item.marker} ${item.seriesName}:${item.data}<br/>`;
              }
              return res;
            },
          },
          legend: {
            //  orient: 'vertical',
            //  left: 'left',
            type: 'scroll',
            orient: 'vertical', // vertical
            right: 20,
            //itemWidth: 20,
            itemGap: 25,
            textStyle: {
              color: '#646A73',
            },
            icon: 'circle',
            selected: hideAll,
          },
          grid: {
            left: '10%',
            right: '30%',
            bottom: '20%',
          },
          yAxis: [
            { type: 'value', splitNumber: 4, axisLabel: { fontSize: 10 } },
          ],
        };
        chartsOption.perfChart = option;

        //处理表格数据
      } else {
        message.warning({
          content: t('common.getInfoFail'),
          duration: 2,
        });
      }
    })
    .finally(() => {
      tableState.loading = false;
    });
}

/**
 * 导出全部
 */
function fnExportAll() {
  Modal.confirm({
    title: 'Tip',
    content: t('views.perfManage.goldTarget.exportSure'),
    onOk() {
      const key = 'exportAlarm';
      message.loading({ content: t('common.loading'), key });
      let sortArr: any = [];
      tableColumnsDnd.value.forEach((item: any) => {
        if (item.dataIndex) sortArr.push(item.title);
      });

      // 排序字段
      const sortData = {
        header: sortArr,
      };
      if (!queryRangePicker.value) {
        queryRangePicker.value = ['', ''];
      }
      queryParams.beginTime = queryRangePicker.value[0];
      queryParams.endTime = queryRangePicker.value[1];
      goldData(queryParams).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('common.msgSuccess', { msg: t('common.export') }),
            key,
            duration: 3,
          });
          let realArr: any = [];
          res.data.map((item: any) => {
            const chineseData: any = {};
            for (const key in item) {
              const title: any = findTitleByKey(key);
              if (['timeGroup', 'neName', 'startIndex'].includes(title)) {
                switch (title) {
                  case 'timeGroup':
                    chineseData[t('views.perfManage.goldTarget.time')] =
                      item[key];
                    break;
                  case 'neName':
                    chineseData[t('views.perfManage.perfData.neName')] =
                      item[key];
                    break;
                  case 'startIndex':
                    break;
                }
              } else chineseData[title] = item[key];
            }
            realArr.push(chineseData);
          });

          writeSheet(realArr, 'gold', sortData).then(fileBlob =>
            saveAs(fileBlob, `gold_${Date.now()}.xlsx`)
          );
        } else {
          message.error({
            content: `${res.msg}`,
            key,
            duration: 3,
          });
        }
      });
    },
  });
}

onMounted(() => {
  // 获取网元网元列表
  neInfoStore.fnNelist().then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      if (res.data.length > 0) {
        // 过滤不可用的网元
        neCascaderOptions.value = neInfoStore.getNeCascaderOptions.filter(
          (item: any) => {
            return !['OMC'].includes(item.value);
          }
        );
        if (neCascaderOptions.value.length === 0) {
          message.warning({
            content: t('common.noData'),
            duration: 2,
          });
          return;
        }
        // 默认选择AMF
        const item = neCascaderOptions.value.find(s => s.value === 'UPF');
        if (item && item.children) {
          const info = item.children[0];
          queryParams.neType = [info.neType, info.neId];
        } else {
          const info = neCascaderOptions.value[0].children[0];
          queryParams.neType = [info.neType, info.neId];
        }
        const initTime: Date = new Date();
        const startTime: Date = new Date(initTime);
        startTime.setHours(0, 0, 0, 0); // 设置为今天的0点
        const endTime: Date = new Date(initTime);
        endTime.setHours(23, 59, 59, 59); // 设置为今天的12点

        queryRangePicker.value = [
          parseDateToStr(startTime),
          parseDateToStr(endTime),
        ];
        fnGetList();
      }
    } else {
      message.warning({
        content: t('common.noData'),
        duration: 2,
      });
    }
  });
});
</script>

<template>
  <PageContainer>
    <a-card
      v-show="tableState.seached"
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParamsFrom" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item
              name="neType"
              :label="t('views.traceManage.task.neType')"
            >
              <a-cascader
                v-model:value="queryParams.neType"
                :options="neCascaderOptions"
                @change="fnNeChange"
                :allow-clear="false"
                :placeholder="t('common.selectPlease')"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="10" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.goldTarget.timeFrame')"
              name="eventTime"
            >
              <a-range-picker
                v-model:value="queryRangePicker"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                :allow-clear="false"
                show-time
              />
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="12" :xs="24">
            <a-form-item
              :label="t('views.perfManage.goldTarget.particle')"
              name="particle"
            >
              <a-select
                v-model:value="queryParams.particle"
                :placeholder="t('common.selectPlease')"
                :options="[
                  { label: '5M', value: '5' },
                  { label: '15M', value: '15' },
                  { label: '30M', value: '30' },
                  { label: '60M', value: '60' },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="2" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnDesign()">
                  <template #icon><SearchOutlined /></template>
                  {{ t('common.search') }}
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <template v-if="queryParams.cardFlag">
      <a-card :bordered="false" :body-style="{ padding: '0px' }">
        <!-- 插槽-卡片左侧侧 -->
        <template #title>
          <a-space :size="8" align="center">
            <a-button type="primary" @click.prevent="fnMakeTable(0)">
              <template #icon> <area-chart-outlined /> </template>
              {{ t('views.perfManage.goldTarget.kpiTitle') }}
            </a-button>
            <a-button type="primary" @click.prevent="fnExportAll()">
              <template #icon> <export-outlined /> </template>
              {{ t('views.faultManage.activeAlarm.exportAll') }}
            </a-button>
          </a-space>
        </template>

        <!-- 插槽-卡片右侧 -->
        <template #extra>
          <a-space :size="8" align="center">
            <a-tooltip>
              <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>
              <template #title>{{ t('common.reloadText') }}</template>
              <a-button type="text" @click.prevent="fnGetList()">
                <template #icon><ReloadOutlined /></template>
              </a-button>
            </a-tooltip>
            <TableColumnsDnd
              :columns="tableState.tableColumns"
              v-model:columns-dnd="tableColumnsDnd"
            ></TableColumnsDnd>
            <a-tooltip>
              <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="tableColumnsDnd"
          :loading="tableState.loading"
          :data-source="tableState.data"
          :size="tableState.size"
          :pagination="false"
          :scroll="{ x: tableColumnsDnd.length * 200, y: 450 }"
          @resizeColumn="(w:number, col:any) => (col.width = w)"
          :show-expand-column="false"
          @change="fnTableChange"
        >
        </a-table>
      </a-card>
    </template>

    <a-card :bordered="false" :body-style="{ marginBottom: '24px' }" v-else>
      <!-- 插槽-卡片左侧侧 -->
      <template #title>{{
        t('views.perfManage.goldTarget.kpiTitle')
      }}</template>
      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-button type="default" size="small" @click.prevent="fnMakeTable(1)">
            <template #icon> <bars-outlined /> </template>
            {{ t('views.perfManage.goldTarget.allData') }}
          </a-button>
        </a-space>
      </template>
      <div class="chart">
        <ChartLine
          :option="chartsOption.perfChart"
          :dataZoom="false"
          height="400px"
        ></ChartLine>
      </div>
    </a-card>
  </PageContainer>
</template>

<style lang="less" scoped>
.chart {
  width: 100%;
  height: 400px;
}
</style>
