<script setup lang="ts">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ProModal } from 'antdv-pro-modal';
import { Modal, TableColumnsType } from 'ant-design-vue/es';
import { fnToStepName } from '../hooks/useStep';
import useI18n from '@/hooks/useI18n';
import useDictStore from '@/store/modules/dict';
import { listNeVersion, operateNeVersion } from '@/api/ne/neVersion';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { NE_TYPE_LIST } from '@/constants/ne-constants';
const { t } = useI18n();
const { getDict } = useDictStore();

const UploadMoreFile = defineAsyncComponent(
  () => import('../../../ne/neSoftware/components/UploadMoreFile.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.neVersion.version'),
    dataIndex: 'version',
    align: 'left',
    width: 100,
    resizable: true,
    minWidth: 100,
    maxWidth: 200,
  },
  {
    title: t('views.ne.neVersion.newVersion'),
    dataIndex: 'newVersion',
    align: 'left',
    width: 100,
    resizable: true,
    minWidth: 100,
    maxWidth: 200,
  },
  {
    title: t('views.ne.neVersion.status'),
    dataIndex: 'status',
    key: 'status',
    align: 'left',
    width: 100,
  },
]);

/**对象信息信息状态类型 */
type StateType = {
  /**加载等待 */
  loading: boolean;
  /**记录数据 */
  data: any[];
  /**勾选记录 */
  selectedRowKeys: (string | number)[];
  /**勾选单行记录 */
  selectedRowOne: any;
  /**多文件上传 */
  openByMoreFile: boolean;
  /**勾选安装弹窗 */
  openByInstall: boolean;
  /**操作数据进行版本升级 */
  operateDataUpgrade: any[];
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对象信息状态 */
let state: StateType = reactive({
  loading: false,
  data: [],
  selectedRowKeys: [],
  selectedRowOne: { neType: '' },
  openByMoreFile: false,
  openByInstall: false,
  operateDataUpgrade: [],
  confirmLoading: false,
});

/**表格多选 */
function fnTableSelectedRowKeys(
  keys: (string | number)[],
  selectedRows: any[]
) {
  state.selectedRowKeys = keys;
  // 勾选单个上传
  if (selectedRows.length === 1) {
    state.selectedRowOne = selectedRows[0];
  } else {
    state.selectedRowOne = { neType: '' };
  }
}

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

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

/**版本安装弹出确认是否安装 */
function fnRecordInstallConfirm() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.stepInstallTip'),
    onOk() {
      fnRecordInstall();
    },
  });
}

/**版本安装进行 */
async function fnRecordInstall() {
  if (state.confirmLoading) return;
  state.confirmLoading = true;
  state.openByInstall = true;
  // 操作升级的网元数据
  const selectRows = state.data.filter(item =>
    state.selectedRowKeys.includes(item.id)
  );
  //通过sort进行冒泡排序
  selectRows.sort((a: any, b: any) => {
    const typeA = NE_TYPE_LIST.indexOf(a.neType);
    const typeB = NE_TYPE_LIST.indexOf(b.neType);
    if (typeA === -1) return 1; // 如果不在特定顺序中，排到后面
    if (typeB === -1) return -1; // 如果不在特定顺序中，排到后面
    return typeA - typeB;
  });

  for (const row of selectRows) {
    if (row.newVersion === '-' || row.newVersion === '') {
      state.operateDataUpgrade.push({
        neType: row.neType,
        neId: row.neId,
        status: 'fail',
        log: t('views.system.quickStart.stepInstallNotNewVer'),
      });
      continue;
    }
    // 开始安装
    let preinput = {};
    if (row.neType.toUpperCase() === 'IMS') {
      preinput = { pisCSCF: 'y', updateMFetc: 'No', updateMFshare: 'No' };
    }
    const installData = {
      neType: row.neType,
      neId: row.neId,
      action: 'install',
      preinput: preinput,
    };

    try {
      const res = await operateNeVersion(installData);
      const operateData = {
        neType: row.neType,
        neId: row.neId,
        status: 'fail',
        log: t('common.operateErr'),
      };
      if (res.code === RESULT_CODE_SUCCESS) {
        operateData.status = 'done';
        operateData.log = t('views.system.quickStart.stepInstallDone');
      } else {
        operateData.status = 'fail';
        operateData.log = t('views.system.quickStart.stepInstallFail');
      }
      state.operateDataUpgrade.unshift(operateData);
    } catch (error) {
      console.error(error);
    }
  }

  // 结束
  state.confirmLoading = false;
}

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

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

/**下一步操作 */
function fnStepNext(stepName: 'NeInfoSoftwareLicense') {
  if (stepName === 'NeInfoSoftwareLicense') {
    Modal.confirm({
      title: t('common.tipTitle'),
      content: t('views.system.quickStart.stepInstallStepNext'),
      onOk() {
        fnToStepName('NeInfoSoftwareLicense');
      },
    });
  }
}

onMounted(() => {
  // 初始字典数据
  getDict('ne_version_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>

    <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="() => (state.openByMoreFile = !state.openByMoreFile)"
        >
          <template #icon><UploadOutlined /></template>
          {{ t('views.ne.neSoftware.upload') }}
          {{ state.selectedRowOne.neType }}
        </a-button>

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

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

  <!-- 新增多文件上传框 -->
  <UploadMoreFile
    v-model:open="state.openByMoreFile"
    :ne-type="state.selectedRowOne.neType"
    @ok="fnModalOk"
    @cancel="fnModalCancel"
  ></UploadMoreFile>

  <!-- 勾选网元版本进行安装框 -->
  <ProModal
    :drag="true"
    :destroyOnClose="true"
    :body-style="{ height: '520px', overflowY: 'scroll' }"
    :keyboard="false"
    :mask-closable="false"
    :open="state.openByInstall"
    :title="t('views.system.quickStart.stepInstallModal')"
    :closable="false"
    @ok="fnModalOk"
    @cancel="fnModalCancel"
  >
    <template #footer>
      <a-button
        key="submit"
        type="primary"
        :disabled="state.confirmLoading"
        @click="fnModalOk"
      >
        {{ t('common.close') }}
      </a-button>
    </template>

    <p>
      <a-alert
        v-if="state.confirmLoading"
        :message="t('common.loading')"
        type="info"
        show-icon
      >
        <template #icon>
          <LoadingOutlined />
        </template>
      </a-alert>
    </p>

    <p v-for="o in state.operateDataUpgrade" :key="o.neId">
      <a-alert
        :message="`${o.neType}-${o.neId}`"
        :description="o.log"
        :type="o.status === 'done' ? 'success' : 'error'"
        show-icon
      >
        <template #icon>
          <CheckCircleOutlined v-if="o.status === 'done'" />
          <InfoCircleOutlined v-else />
        </template>
      </a-alert>
    </p>
  </ProModal>
</template>

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

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