<script setup lang="ts">
import { reactive, ref, toRaw, watch } from 'vue';
import { ProModal } from 'antdv-pro-modal';
import { message, Modal } from 'ant-design-vue/es';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { ColumnsType } from 'ant-design-vue/es/table';
import { saveAs } from 'file-saver';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';
import { exportNBState, listNBState } from '@/api/neData/nb-state';
import { Dayjs } from 'dayjs';
const { t } = useI18n();
const emit = defineEmits(['cancel', 'update:open']);
const props = defineProps({
  title: {
    type: String,
    default: '标题',
  },
  open: {
    type: Boolean,
    default: false,
  },
  /**网元ID */
  neId: {
    type: String,
    default: false,
  },
  neType: {
    type: String,
    default: false,
  },
});

/**开始结束时间 */
let queryRangePicker = ref<[Dayjs, Dayjs] | undefined>(undefined);
/**状态字典 */
const nbStateOptions = ref<DictType[]>([
  {
    value: 'ON',
    label: t('views.neData.baseStation.online'),
    tagType: 'green',
    tagClass: '',
  },
  {
    value: 'OFF',
    label: t('views.neData.baseStation.offline'),
    tagType: 'red',
    tagClass: '',
  },
]);

/**查询参数 */
let queryParams = reactive({
  /**网元 */
  neType: '',
  neId: '',
  /**排序字段 */
  sortField: 'id',
  sortOrder: 'desc',
  /**状态 */
  status: undefined as undefined | string,
  /**开始时间 */
  startTime: undefined as undefined | number,
  /**结束时间 */
  endTime: undefined as undefined | number,
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    status: undefined,
    startTime: undefined,
    endTime: undefined,
    pageNum: 1,
    pageSize: 20,
  });
  queryRangePicker.value = undefined;
  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 = ref<ColumnsType>([
  {
    title: t('common.rowId'),
    dataIndex: 'id',
    align: 'left',
    width: 80,
  },
  {
    title: t('views.neData.baseStation.name'),
    dataIndex: 'name',
    align: 'left',
    resizable: true,
    width: 120,
    minWidth: 100,
    maxWidth: 250,
    ellipsis: true,
  },
  {
    title: t('views.neData.baseStation.position'),
    dataIndex: 'position',
    align: 'left',
    resizable: true,
    width: 150,
    minWidth: 100,
    maxWidth: 400,
    ellipsis: true,
  },
  {
    title: t('views.neData.baseStation.address'),
    dataIndex: 'address',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.neData.baseStation.nbName'),
    dataIndex: 'nbName',
    align: 'left',
    resizable: true,
    width: 100,
    minWidth: 100,
    maxWidth: 200,
  },
  {
    title: t('views.neData.baseStation.state'),
    dataIndex: 'state',
    key: 'state',
    align: 'left',
    width: 80,
  },
  {
    title: t('views.neData.baseStation.time'),
    dataIndex: 'time',
    align: 'left',
    width: 150,
  },
]);

/**表格分页器参数 */
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: total }),
  onChange: (page: number, pageSize: number) => {
    tablePagination.current = page;
    tablePagination.pageSize = pageSize;
    queryParams.pageNum = page;
    queryParams.pageSize = pageSize;
    fnGetList();
  },
});

/**列表导出 */
function fnExportList() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.neData.baseStation.exportTip'),
    onOk() {
      const hide = message.loading(t('common.loading'), 0);
      const querys = toRaw(queryParams);
      exportNBState(querys)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.operateOk'),
              duration: 3,
            });
            saveAs(res.data, `nb_state_history_records_export_${Date.now()}.xlsx`);
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
        });
    },
  });
}

/**查询字典数据列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }

  // 时间范围
  if (
    Array.isArray(queryRangePicker.value) &&
    queryRangePicker.value.length > 0
  ) {
    queryParams.startTime = queryRangePicker.value[0].valueOf();
    queryParams.endTime = queryRangePicker.value[1].valueOf();
  } else {
    queryParams.startTime = undefined;
    queryParams.endTime = undefined;
  }

  listNBState(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;
  });
}

/**弹框取消按钮事件 */
function fnModalCancel() {
  emit('update:open', false);
  emit('cancel');
}

/**监听是否显示，初始数据 */
watch(
  () => props.open,
  val => {
    if (val) {
      queryParams.neType = props.neType;
      queryParams.neId = props.neId;
      // 获取列表数据
      fnGetList();
    }
  }
);
</script>

<template>
  <ProModal
    :drag="true"
    :destroyOnClose="true"
    :width="1200"
    :title="props.title"
    :open="props.open"
    :keyboard="false"
    :mask-closable="false"
    @cancel="fnModalCancel"
    :footer="null"
  >
    <!-- 表格搜索栏 -->
    <a-form :model="queryParams" name="queryParams" layout="horizontal">
      <a-row :gutter="16" style="margin-left: 0; margin-right: 0">
        <a-col :lg="6" :md="12" :xs="24">
          <a-form-item
            :label="t('views.neData.baseStation.state')"
            name="status"
          >
            <a-select
              v-model:value="queryParams.status"
              allow-clear
              :placeholder="t('common.selectPlease')"
              :options="nbStateOptions"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :lg="16" :md="12" :xs="24">
          <a-form-item
            :label="t('views.neData.baseStation.time')"
            name="queryRangePicker"
          >
            <a-range-picker
              v-model:value="queryRangePicker"
              :bordered="true"
              :allow-clear="true"
              style="width: 100%"
              :show-time="{ format: 'HH:mm:ss' }"
              format="YYYY-MM-DD HH:mm:ss"
            ></a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :lg="24" :md="24" :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-button type="dashed" @click.prevent="fnExportList()">
                <template #icon><ExportOutlined /></template>
                {{ t('common.export') }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 表格列表 -->
    <a-table
      class="table"
      row-key="id"
      :columns="tableColumns"
      :loading="tableState.loading"
      :data-source="tableState.data"
      :size="tableState.size"
      :pagination="tablePagination"
      :scroll="{ x: tableColumns.length * 120, y: 'calc(100vh - 480px)' }"
      @resizeColumn="(w:number, col:any) => (col.width = w)"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'state'">
          <DictTag
            :options="nbStateOptions"
            :value="record.state"
            value-default="OFF"
          />
        </template>
      </template>
    </a-table>
  </ProModal>
</template>

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