<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { Form, message, Modal } from 'ant-design-vue';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { ColumnsType } from 'ant-design-vue/es/table';
import { ProModal } from 'antdv-pro-modal';
import useNeInfoStore from '@/store/modules/neinfo';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import {
  addAMFNbState,
  delAMFNbState,
  editAMFNbState,
  listAMFNbStatelist,
} from '@/api/neData/amf';
const { t } = useI18n();
import { useRoute } from 'vue-router';
const route = useRoute();

const nbState = 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 neCascaderOptions = ref<Record<string, any>[]>([]);
/**网元数据 */
let neTypeAndId = ref<string[]>([]);
/**查询参数 */
let queryParams = reactive({
  /**网元ID */
  neId: '',
  /**IMSI */
  state: undefined,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    state: undefined,
  });
  fnGetList();
}

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

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

/**表格字段列 */
let tableColumns = ref<ColumnsType>([
  {
    title: t('common.rowId'),
    dataIndex: 'index',
    align: 'left',
    width: 80,
  },
  {
    title: t('views.neData.baseStation.name'),
    dataIndex: 'name',
    align: 'left',
    width: 150,
    ellipsis: true,
  },
  {
    title: t('views.neData.baseStation.position'),
    dataIndex: 'position',
    align: 'left',
    width: 150,
    ellipsis: true,
  },
  {
    title: t('views.neData.baseStation.address'),
    dataIndex: 'address',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.neData.baseStation.nbName'),
    dataIndex: 'nbName',
    align: 'left',
    width: 80,
  },
  {
    title: t('views.neData.baseStation.state'),
    dataIndex: 'state',
    key: 'state',
    align: 'left',
    width: 80,
  },
  {
    title: t('views.neData.baseStation.time'), 
    align: 'left',
    width: 150,
    customRender(opt) {
      const record = opt.value;
      console.log(opt)
      if (record.state === 'OFF') {
        return record.offTime || '-';
      }
      return record.onTime || '-';
    },
  },
]);

/**表格分页器参数 */
let tablePagination = {
  /**当前页数 */
  current: 1,
  /**每页条数 */
  pageSize: 20,
  /**默认的每页条数 */
  defaultPageSize: 20,
  /**指定每页可以显示多少条 */
  pageSizeOptions: ['10', '20', '50', '100'],
  /**只有一页时是否隐藏分页器 */
  hideOnSinglePage: true,
  /**是否可以快速跳转至某页 */
  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;
  },
};

/**表格多选 */
function fnTableSelectedRowKeys(keys: (string | number)[]) {
  tableState.selectedRowKeys = keys;
}

/**
 * 记录删除
 * @param index ID
 */
function fnRecordDelete(index: string) {
  const [neType, neId] = neTypeAndId.value;
  if (!neId) return;
  let msg = `Delete index as:${index}`;
  if (index === '0') {
    msg = `Remove the index checkbox:${tableState.selectedRowKeys.length}`;
  }

  Modal.confirm({
    title: t('common.tipTitle'),
    content: msg,
    onOk() {
      const reqArr = [];
      if (index === '0') {
        if (tableState.selectedRowKeys.length <= 0) {
          return;
        }
        for (const v of tableState.selectedRowKeys) {
          if (neType === 'MME') {
            // reqArr.push(delAMFNbState(neId, v));
          }
          if (neType === 'AMF') {
            reqArr.push(delAMFNbState(neId, v));
          }
        }
      } else {
        if (neType === 'MME') {
          // reqArr.push(delAMFNbState(neId, index));
        }
        if (neType === 'AMF') {
          reqArr.push(delAMFNbState(neId, index));
        }
      }
      if (reqArr.length <= 0) return;
      Promise.all(reqArr).then(res => {
        const resArr = res.filter(
          (item: any) => item.code !== RESULT_CODE_SUCCESS
        );
        if (resArr.length <= 0) {
          message.success({
            content: `${t('common.operateOk')}`,
            duration: 3,
          });
          fnGetList();
        } else {
          message.error({
            content: `${t('common.operateErr')}`,
            duration: 3,
          });
        }
      });
    },
  });
}

/**查询列表 */
function fnGetList() {
  if (tableState.loading) return;
  tableState.loading = true;
  const [neType, neId] = neTypeAndId.value;
  queryParams.neId = neId;
  let req = null;
  // if (neType === 'MME') {
  //   req = listAMFNbStatelist(toRaw(queryParams));
  // }
  if (neType === 'AMF') {
    req = listAMFNbStatelist(toRaw(queryParams));
  }
  if (req === null) {
    tableState.data = [];
    tableState.loading = false;
    return;
  }
  req.then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      tableState.data = res.data.filter((item: any) => {
        // 状态过滤
        if (queryParams.state) {
          return item.state === queryParams.state;
        }
        return true;
      });
    } else {
      tableState.data = [];
    }
    tableState.loading = false;
  });
}

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**新增框或修改框是否显示 */
  openByEdit: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByEdit: false,
  title: 'NB Config List',
  from: {
    index: undefined,
    address: '',
    name: '',
    position: '',
  },
  confirmLoading: false,
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    address: [
      { required: true, message: t('views.neData.baseStation.addressPlease') },
    ],
    name: [
      { required: true, message: t('views.neData.baseStation.namePlease') },
    ],
    position: [
      { required: true, message: t('views.neData.baseStation.positionPlease') },
    ],
  })
);

/**
 * 对话框弹出显示为 新增或者修改
 * @param noticeId 网元id, 不传为新增
 */
function fnModalVisibleByEdit(edit?: string | number) {
  if (!edit) {
    modalStateFrom.resetFields(); //重置表单
    modalState.title = t('views.neData.baseStation.addRadio');
    modalState.openByEdit = true;
    // 获取最大index
    if (tableState.data.length <= 0) {
      modalState.from.index = 1;
    } else {
      const last = tableState.data[tableState.data.length - 1];
      modalState.from.index = last.index + 1;
    }
  }
  // 编辑
  if (edit === '0') {
    const row = tableState.data.find((row: any) => {
      return row.index === tableState.selectedRowKeys[0];
    });
    modalStateFrom.resetFields(); //重置表单
    Object.assign(modalState.from, row);
    modalState.title = t('views.neData.baseStation.editRadio');
    modalState.openByEdit = true;
  }
}

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  const neID = queryParams.neId;
  if (!neID) return;
  const from = JSON.parse(JSON.stringify(modalState.from));
  modalStateFrom
    .validate()
    .then(e => {
      modalState.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);
      let result: any = modalState.title.startsWith('Edit')
        ? editAMFNbState(neID, from)
        : addAMFNbState(neID, from);
      result
        .then((res: any) => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.operateOk'),
              duration: 3,
            });
            fnModalCancel();
            fnGetList();
          } else {
            message.error({
              content: t('common.operateErr'),
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

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

onMounted(() => {
  // 获取网元网元列表
  useNeInfoStore()
    .fnNelist()
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
        if (res.data.length > 0) {
          let arr: Record<string, any>[] = [];
          useNeInfoStore().neCascaderOptions.forEach(item => {
            if (['AMF', 'MME'].includes(item.value)) {
              arr.push(JSON.parse(JSON.stringify(item)));
            }
          });
          neCascaderOptions.value = arr;
          // 无查询参数neType时 默认选择AMF
          const queryNeType = (route.query.neType as string) || 'AMF';
          const item = arr.find(s => s.value === queryNeType);
          if (item && item.children) {
            const info = item.children[0];
            neTypeAndId.value = [info.neType, info.neId];
          } else {
            const info = neCascaderOptions.value[0].children[0];
            neTypeAndId.value = [info.neType, info.neId];
          }
        }
      } else {
        message.warning({
          content: t('common.noData'),
          duration: 2,
        });
      }
    })
    .finally(() => {
      // 获取列表数据
      fnGetList();
    });
});
</script>

<template>
  <div>
    <a-card
      :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-cascader
                v-model:value="neTypeAndId"
                :options="neCascaderOptions"
                :allow-clear="false"
                :placeholder="t('common.selectPlease')"
                @change="fnGetList"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="6" :xs="24">
            <a-form-item
              :label="t('views.neData.baseStation.state')"
              name="state"
            >
              <a-select
                v-model:value="queryParams.state"
                :options="nbState"
                :placeholder="t('common.selectPlease')"
              />
            </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()">
                  <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-space :size="8" align="center">
          <a-button type="primary" @click.prevent="fnModalVisibleByEdit()">
            <template #icon>
              <PlusOutlined />
            </template>
            {{ t('common.addText') }}
          </a-button>
          <a-button
            type="default"
            :disabled="tableState.selectedRowKeys.length != 1"
            :loading="modalState.confirmLoading"
            @click.prevent="fnModalVisibleByEdit('0')"
          >
            <template #icon><FormOutlined /></template>
            {{ t('common.editText') }}
          </a-button>
          <a-button
            type="default"
            danger
            :disabled="tableState.selectedRowKeys.length <= 0"
            :loading="modalState.confirmLoading"
            @click.prevent="fnRecordDelete('0')"
          >
            <template #icon><DeleteOutlined /></template>
            {{ t('common.deleteText') }}
          </a-button>
        </a-space>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="index"
        :columns="tableColumns"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ x: tableColumns.length * 120 }"
        :row-selection="{
          type: 'checkbox',
          selectedRowKeys: tableState.selectedRowKeys,
          onChange: fnTableSelectedRowKeys,
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <DictTag
              :options="nbState"
              :value="record.state"
              value-default="OFF"
            />
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增框或修改框 -->
    <ProModal
      :drag="true"
      :width="500"
      :destroyOnClose="true"
      :keyboard="false"
      :mask-closable="false"
      :open="modalState.openByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 6 }"
        :labelWrap="true"
      >
        <a-form-item
          :label="t('views.neData.baseStation.name')"
          name="name"
          v-bind="modalStateFrom.validateInfos.name"
        >
          <a-input
            v-model:value="modalState.from.name"
            allow-clear
            :maxlength="64"
          >
          </a-input>
        </a-form-item>
        <a-form-item
          :label="t('views.neData.baseStation.position')"
          name="position"
          v-bind="modalStateFrom.validateInfos.position"
        >
          <a-input
            v-model:value="modalState.from.position"
            allow-clear
            :maxlength="64"
          >
          </a-input>
        </a-form-item>
        <a-form-item
          :label="t('views.neData.baseStation.address')"
          name="address"
          v-bind="modalStateFrom.validateInfos.address"
        >
          <a-input
            v-model:value="modalState.from.address"
            allow-clear
            :maxlength="64"
          >
          </a-input>
        </a-form-item>
      </a-form>
    </ProModal>
  </div>
</template>

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