<script setup lang="ts">
import { Modal, TableColumnsType, message } from 'ant-design-vue/lib';
import { defineAsyncComponent, onMounted, reactive, ref, toRaw } from 'vue';
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';
const { t } = useI18n();
const { getDict } = useDictStore();

const UploadMoreFile = defineAsyncComponent(
  () => import('../../../ne/neSoftware/components/UploadMoreFile.vue')
);

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

/**表格字段列 */
let tableColumns = ref<TableColumnsType>([
  {
    title: 'neType',
    dataIndex: 'neType',
    align: 'left',
    width: 100,
  },
  {
    title: 'neId',
    dataIndex: 'neId',
    align: 'left',
    width: 100,
  },
  {
    title: 'version',
    dataIndex: 'version',
    align: 'left',
    width: 100,
    resizable: true,
    minWidth: 100,
    maxWidth: 200,
  },
  {
    title: 'New Version',
    dataIndex: 'newVersion',
    align: 'left',
    width: 100,
    resizable: true,
    minWidth: 100,
    maxWidth: 200,
  },
  {
    title: 'status',
    dataIndex: 'status',
    key: 'status',
    align: 'left',
    width: 100,
  },
]);

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

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

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

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

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

/**版本安装 */
function fnRecordInstall() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: `check install version?`,
    onOk() {
      if (state.confirmLoading) return;
      state.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);
      // 操作升级的网元数据
      const selectRows = state.data.filter(item =>
        state.selectedRowKeys.includes(item.id)
      );
      for (const row of selectRows) {
        if (
          row.neType.toUpperCase() === 'OMC' ||
          row.newVersion === '-' ||
          row.newVersion === ''
        ) {
          state.operateDataUpgrade.push({
            neType: row.neType,
            neId: row.neId,
            status: 'fail',
          });
          continue;
        }
        let preinput = {};
        if (row.neType.toUpperCase() === 'IMS') {
          preinput = { pisCSCF: 'y' };
        }
        state.operateDataUpgrade.push({
          neType: row.neType,
          neId: row.neId,
          action: 'install',
          preinput: preinput,
        });
      }

      // 发请求信息
      state.visibleByUpgrade = true;
      Promise.allSettled(
        state.operateDataUpgrade
          .filter(s => s.status !== 'fail')
          .map(s => operateNeVersion(s))
      )
        .then(resArr => {
          console.log(resArr);
          resArr.forEach((s, i) => {
            if (s.status === 'rejected') {
              message.error(s.reason, 3);
            } else {
              const res = s.value;
              if (res.code === RESULT_CODE_SUCCESS) {
                state.operateDataUpgrade[i].status = 'done';
                state.operateDataUpgrade[i].log = res.data;
              } else {
                state.operateDataUpgrade[i].status = 'fail';
                state.operateDataUpgrade[i].log = res.msg;
              }
            }
          });
        })
        .finally(() => {
          hide();
          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.data = res.rows.filter(s => s.neType !== 'OMC');
    }
    state.loading = false;
  });
}

/**返回上一步 */
function fnStepPrev() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: '确认要放弃当前变更返回上一步吗？',
    onOk() {
      fnToStepName('NeInfoConfigPara5G');
    },
  });
}

/**下一步操作 */
function fnStepNext(stepName: 'NeInfoSoftwareLicense') {
  if (stepName === 'NeInfoSoftwareLicense') {
    Modal.confirm({
      title: t('common.tipTitle'),
      content: '确认要下一步进行网元授权吗？',
      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>

    <!-- 新增多文件上传框 -->
    <UploadMoreFile
      v-model:visible="state.visibleByMoreFile"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    ></UploadMoreFile>

    <!-- 勾选版本升级 -->
    <a-modal
      width="800px"
      :keyboard="false"
      :mask-closable="false"
      :visible="state.visibleByUpgrade"
      title="Upgrade Version"
      :confirm-loading="state.confirmLoading"
      :closable="false"
      :cancelButtonProps="{ disabled: state.visibleByUpgrade }"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <p v-for="o in state.operateDataUpgrade">
        {{ o.neType }} - {{ o.neId }} - {{ o.status }}
        <!-- <TerminalText id="installLog" :rows="12" :value="o.log"></TerminalText> -->
      </p>
    </a-modal>

    <div class="ne-oper">
      <a-space direction="horizontal" :size="18">
        <a-button @click="fnStepPrev()"> 上一步 </a-button>

        <a-button
          type="primary"
          @click.prevent="
            () => (state.visibleByMoreFile = !state.visibleByMoreFile)
          "
        >
          <template #icon><PlusOutlined /></template>
          Upload More Software
        </a-button>

        <a-button
          type="default"
          danger
          :disabled="state.selectedRowKeys.length <= 0"
          :loading="state.confirmLoading"
          @click.prevent="fnRecordInstall()"
        >
          <template #icon><ThunderboltOutlined /></template>
          Check Install
        </a-button>

        <a-button type="dashed" @click="fnStepNext('NeInfoSoftwareLicense')">
          下一步
        </a-button>
      </a-space>
    </div>
  </div>
</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>
