<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { message, Form } 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';
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: [],
});

/**表格分页器参数 */
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;
}

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

/**表格分页、排序、筛选变化时触发操作, 排序方式，取值为 ascend descend */
function fnTableChange(pagination: any, filters: any, sorter: any, extra: any) {
  const { columnKey, order } = sorter;
  if (order) {
    queryParams.sortField = columnKey;
    queryParams.sortOrder = order.replace('end', '');
  } else {
    queryParams.sortOrder = 'asc';
  }
  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 : undefined;
}

/**筛选条件进行制图 */
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];
  const neType = queryParams.neType[0];
  let goldXDate: any = [];
  let goldYData: any = [];
  let hideAll: any = {};
  goldData(queryParams).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      if (res.data.length > 0) {
        tableState.data = res.data;
        tablePagination.total = res.data.length;
        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 = [];
        tablePagination.total = 0;
        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,
      });
    }
  });
}

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-button type="primary" @click.prevent="fnMakeTable(0)">
            <template #icon> <area-chart-outlined /> </template>
            {{ t('views.perfManage.goldTarget.kpiTitle') }}
          </a-button>
        </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="tablePagination"
          :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>
