<script setup lang="ts">
import { Modal, TableColumnsType, message } from 'ant-design-vue/es';
import { defineAsyncComponent, h, onMounted, reactive, ref } from 'vue';
import { fnToStepName, stepState } from '../hooks/useStep';
import useI18n from '@/hooks/useI18n';
import useDictStore from '@/store/modules/dict';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import {
  codeNeLicense,
  listNeLicense,
  stateNeLicense,
} from '@/api/ne/neLicense';
import saveAs from 'file-saver';
const { t } = useI18n();
const { getDict } = useDictStore();
const UploadLicenseFile = defineAsyncComponent(
  () => import('../../../ne/neLicense/components/UploadLicenseFile.vue')
);

/**字典数据-状态 */
let dictStatus = ref<DictType[]>([]);

/**表格字段列 */
let tableColumns = ref<TableColumnsType>([
  {
    title: t('views.ne.common.neType'),
    dataIndex: 'neType',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.common.neId'),
    dataIndex: 'neId',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.neLicense.status'),
    dataIndex: 'status',
    key: 'status',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.common.serialNum'),
    dataIndex: 'serialNum',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.common.expiryDate'),
    dataIndex: 'expiryDate',
    align: 'left',
    width: 100,
  },
]);

/**对象信息信息状态类型 */
type StateType = {
  /**加载等待 */
  loading: boolean;
  /**记录数据 */
  data: any[];
  /**勾选记录 */
  selectedRowKeys: (string | number)[];
  /**授权文件上传 */
  openByLicenseFile: boolean;
  /**授权文件上传勾选指定到网元授权列表 */
  neLicenseList: any[];
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对象信息状态 */
let state: StateType = reactive({
  loading: false,
  data: [],
  selectedRowKeys: [],
  openByLicenseFile: false,
  neLicenseList: [],
  confirmLoading: false,
});

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

/**对话框弹出确认执行函数*/
function fnModalOk() {
  fnGetList();
}

/**对话框弹出关闭执行函数*/
function fnModalCancel() {
  state.openByLicenseFile = false;
}

/**对话框弹出打开执行函数 */
function fnModalOpen() {
  if (state.selectedRowKeys.length > 0) {
    // 勾选的网元数据的网元类型
    let neTypeArr = state.data.filter(item =>
      state.selectedRowKeys.includes(item.id)
    );
    state.neLicenseList = neTypeArr;
  } else {
    state.neLicenseList = [];
  }

  state.openByLicenseFile = !state.openByLicenseFile;
}

/**勾选刷新网元状态 */
function fnRecordState() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.stepLicenseReloadTip'),
    async onOk() {
      if (state.confirmLoading) return;
      state.confirmLoading = true;
      // 勾选的网元数据
      const selectRows = state.data.filter(item =>
        state.selectedRowKeys.includes(item.id)
      );

      for (const row of selectRows) {
        if (row.neType.toUpperCase() === 'OMC') {
          continue;
        }
        const res = await stateNeLicense(row.neType, row.neId);
        if (res.code === RESULT_CODE_SUCCESS && res.data) {
          row.status = '1';
          row.serialNum = res.data.sn;
          row.expiryDate = res.data.expire;
        } else {
          row.status = '0';
        }
      }

      message.success(t('common.operateOk'), 3);
      state.confirmLoading = false;
      state.selectedRowKeys = [];
    },
  });
}

/**勾选下载网元授权code */
function fnRecordCode() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.stepLicenseDownCodeTip'),
    onOk: async () => {
      if (state.confirmLoading) return;
      state.confirmLoading = true;
      // 勾选的网元数据
      const selectRows = state.data.filter(item =>
        state.selectedRowKeys.includes(item.id)
      );

      const codeArr: string[] = [];
      for (const row of selectRows) {
        if (row.neType.toUpperCase() === 'OMC') {
          continue;
        }
        const res = await codeNeLicense(row.neType, row.neId);
        if (res.code === RESULT_CODE_SUCCESS) {
          const activationRequestCode = res.data;
          row.activationRequestCode = activationRequestCode;
          codeArr.push(`[${row.neType} ${row.neId}]: ${activationRequestCode}`);
        }
      }

      if (codeArr.length > 0) {
        const blob = new Blob([codeArr.join('\r\n')], {
          type: 'text/plain',
        });
        saveAs(blob, `Activation_Request_Code_${new Date().getTime()}.txt`);
      }

      state.confirmLoading = false;
      state.selectedRowKeys = [];
    },
  });
}

/**获取列表 */
function fnGetList() {
  state.loading = true;
  listNeLicense({
    neType: undefined,
    neId: '',
    version: '',
    pageNum: 1,
    pageSize: 20,
  }).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      // 取消勾选
      if (state.selectedRowKeys.length > 0) {
        state.selectedRowKeys = [];
      }
      state.data = res.data.rows.filter((s: any) => s.neType !== 'OMC');
    }
    state.loading = false;
  });
}

/**返回上一步 */
function fnStepPrev() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.stepLicenseStepPrev'),
    onOk() {
      fnToStepName('NeInfoSoftwareInstall');
    },
  });
}

/**下一步操作 */
function fnStepNext(stepName: 'Done') {
  if (stepName === 'Done') {
    Modal.confirm({
      title: t('common.tipTitle'),
      content: h('div', {}, [
        h('p', t('views.system.quickStart.stepLicenseStepNext')),
        h(
          'div',
          { style: { color: '#f5222d' } },
          t('views.system.quickStart.stepLicenseStepNext2')
        ),
      ]),
      onOk() {
        stepState.setupNE = true;
        fnToStepName('Done');
      },
    });
  }
}

onMounted(() => {
  // 初始字典数据
  getDict('ne_license_status')
    .then(res => {
      dictStatus.value = res;
    })
    .finally(() => {
      fnGetList();
    });
});
</script>

<template>
  <div class="ne">
    <!-- 表格列表 -->
    <a-table
      class="table"
      row-key="id"
      :columns="tableColumns"
      :loading="state.loading"
      :data-source="state.data"
      size="middle"
      :pagination="false"
      @resizeColumn="(w:number, col:any) => (col.width = w)"
      :scroll="{ y: '60vh' }"
      :row-selection="{
        type: 'checkbox',
        columnWidth: '48px',
        selectedRowKeys: state.selectedRowKeys,
        onChange: fnTableSelectedRowKeys,
      }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <DictTag :options="dictStatus" :value="record.status" />
        </template>
      </template>
    </a-table>

    <!-- 授权文件上传框 -->
    <UploadLicenseFile
      v-model:open="state.openByLicenseFile"
      :licenseList="state.neLicenseList"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    ></UploadLicenseFile>

    <div class="ne-oper">
      <a-space direction="horizontal" :size="18">
        <a-button @click="fnStepPrev()">
          {{ t('views.system.quickStart.stepPrev') }}
        </a-button>

        <a-button
          type="dashed"
          :disabled="state.selectedRowKeys.length < 1"
          @click.prevent="fnModalOpen"
        >
          <template #icon><UploadOutlined /></template>
          {{ t('views.ne.neLicense.uploadFile') }}
        </a-button>

        <a-button
          type="primary"
          ghost
          :disabled="state.selectedRowKeys.length <= 0"
          :loading="state.confirmLoading"
          @click.prevent="fnRecordState()"
        >
          <template #icon><SecurityScanOutlined /></template>
          {{ t('views.system.quickStart.stepLicenseReload') }}
        </a-button>

        <a-button
          type="primary"
          ghost
          :disabled="state.selectedRowKeys.length <= 0"
          :loading="state.confirmLoading"
          @click.prevent="fnRecordCode()"
        >
          <template #icon><DownloadOutlined /></template>
          {{ t('views.system.quickStart.stepLicenseDownCode') }}
        </a-button>

        <a-button type="primary" @click="fnStepNext('Done')">
          {{ t('views.system.quickStart.stepLicenseEnd') }}
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
.ne {
  padding-top: 12px;
  // height: 78vh;
  overflow-x: hidden;
  overflow-y: auto;

  &-oper {
    padding-top: 24px;
    text-align: end;
  }
}
</style>
