<script setup lang="ts">
import { Modal, TableColumnsType, message } from 'ant-design-vue/lib';
import { defineAsyncComponent, onMounted, reactive, ref, toRaw } from 'vue';
import { fnToStepName, stepState } from '../hooks/useStep';
import useI18n from '@/hooks/useI18n';
import { listNeVersion, operateNeVersion } from '@/api/ne/neVersion';
import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
} from '@/constants/result-constants';
import {
  addNeSoftware,
  listNeSoftware,
  newNeVersion,
} from '@/api/ne/neSoftware';
import { parseDateToStr } from '@/utils/date-utils';
import { ColumnsType } from 'ant-design-vue/lib/table';
const { t } = useI18n();
const EditModal = defineAsyncComponent(
  () => import('../../../ne/neSoftware/components/EditModal.vue')
);

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('common.rowId'),
    dataIndex: 'id',
    align: 'left',
    width: 50,
  },
  {
    title: 'neType',
    dataIndex: 'neType',
    align: 'left',
    width: 100,
  },
  {
    title: 'name',
    dataIndex: 'name',
    key: 'name',
    align: 'left',
    width: 300,
  },
  {
    title: 'version',
    dataIndex: 'version',
    align: 'left',
    width: 100,
  },
  {
    title: 'description',
    dataIndex: 'description',
    key: 'description',
    align: 'left',
    ellipsis: true,
  },
  {
    title: 'createTime',
    dataIndex: 'createTime',
    align: 'left',
    width: 150,
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(+opt.value);
    },
  },
];

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

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

/**表格状态 */
let tableState: TabeStateType = reactive({
  queryParams: {
    neType: '',
    pageNum: 1,
    pageSize: 10,
  },
  loading: false,
  data: [],
  selectedRowKeys: [],
});

/**表格多选 */
function fnTableSelectedRowKeys(
  keys: (string | number)[],
  selectedRows: any[]
) {
  tableState.selectedRowKeys = keys;
  // 选择的表单数据填充
  Object.assign(state.from, selectedRows[0], { id: '' });
}

/**查询列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    tableState.queryParams.pageNum = pageNum;
  }
  listNeSoftware(toRaw(tableState.queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      tablePagination.total = res.total;
      // 遍历处理资源情况数值
      tableState.data = res.rows;
    }
    tableState.loading = false;
  });
}

/**对象信息信息状态类型 */
type StateType = {
  /**是否可以下一步 */
  stepNext: boolean;
  /**文件操作类型 上传 or 选择 */
  optionType: 'upload' | 'option';
  /**文件上传 */
  visibleByFile: boolean;
  /**软件包信息数据 */
  from: {
    neType: string; // 版本需要
    neId: string; // 版本需要
    name: string; // 软件需要
    path: string;
    version: string; // 软件需要
    description: string;
  };
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对象信息状态 */
let state: StateType = reactive({
  stepNext: false,
  optionType: 'option',
  visibleByFile: false,
  from: {
    id: undefined,
    neType: '',
    neId: '',
    name: '',
    path: '',
    version: '',
    description: '',
  },
  confirmLoading: false,
});

/**
 * 表单修改文件操作类型
 */
function fnOptionTypeChange() {
  state.from.name = '';
  state.from.version = '';
  tableState.selectedRowKeys = [];
  if (state.optionType === 'option') {
    fnGetList(1);
  }
}

/**对话框弹出确认执行函数*/
function fnModalOk(e: any) {
  Object.assign(state.from, e, { id: '' });
}

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

/**版本安装 */
function fnRecordInstall() {
  const from = toRaw(state.from);
  Modal.confirm({
    title: t('common.tipTitle'),
    content: `install software package [${from.name}] ?`,
    onOk: async () => {
      if (state.confirmLoading) return;
      state.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);

      // 选择的软件需要更新版本
      if (state.optionType === 'option') {
        const res = await newNeVersion(from);
        if (res.code === RESULT_CODE_ERROR) {
          message.error(`软件信息错误 ${res.msg}`, 3);
          hide();
          state.confirmLoading = false;
          return;
        }
      }

      // 进行安装
      let preinput = {};
      if (from.neType.toUpperCase() === 'IMS') {
        preinput = { pisCSCF: 'y' };
      }
      const res = await operateNeVersion({
        neType: from.neType,
        neId: from.neId,
        action: 'install',
        preinput: preinput,
      });
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success(`安装成功 ${res.msg}`, 3);
        state.stepNext = true;
      } else {
        message.error(`安装失败 ${res.msg}`, 3);
      }

      // 非选择的重置
      state.optionType = 'option';
      fnOptionTypeChange();
      hide();
      state.confirmLoading = false;
    },
  });
}

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

/**下一步操作 */
function fnStepNext() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: '确认要下一步进行网元授权吗？',
    onOk() {
      fnToStepName('NeInfoSoftwareLicense');
    },
  });
}

onMounted(() => {
  const { neType, neId } = stepState.neInfo;
  if (neId) {
    tableState.queryParams.neType = neType;
    state.from.neType = neType;
    state.from.neId = neId;
    fnGetList(1);
  }
});
</script>

<template>
  <div class="ne">
    <a-form
      name="installStateFrom"
      layout="horizontal"
      :label-col="{ span: 3 }"
      :wrapper-col="{ span: 8 }"
      :label-wrap="true"
    >
      <a-form-item label="软件来源" name="optionType">
        <a-radio-group
          v-model:value="state.optionType"
          button-style="solid"
          :disabled="state.confirmLoading"
          @change="fnOptionTypeChange"
        >
          <a-radio-button value="option">已上传</a-radio-button>
          <a-radio-button value="upload">新上传</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <!-- 选择已上传 -->
      <template v-if="state.optionType === 'option'">
        <a-form-item label="选择记录" name="option" :wrapper-col="{ span: 24 }">
          <a-table
            class="table"
            row-key="id"
            :columns="tableColumns"
            :loading="tableState.loading"
            :data-source="tableState.data"
            :pagination="tablePagination"
            size="small"
            :scroll="{ x: tableColumns.length * 100, y: '400px' }"
            :row-selection="{
              type: 'radio',
              columnWidth: '48px',
              selectedRowKeys: tableState.selectedRowKeys,
              onChange: fnTableSelectedRowKeys,
            }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'name'">
                <a-tooltip placement="topLeft">
                  <template #title>{{ record.path }}</template>
                  <div style="cursor: pointer">{{ record.name }}</div>
                </a-tooltip>
              </template>
              <template v-if="column.key === 'description'">
                <a-tooltip placement="topLeft">
                  <template #title>{{ record.description }}</template>
                  <div style="cursor: pointer">{{ record.description }}</div>
                </a-tooltip>
              </template>
            </template>
          </a-table>
        </a-form-item>
      </template>

      <!-- 重新上传 -->
      <template v-if="state.optionType === 'upload'">
        <a-form-item label="上传文件" name="upload" :help="state.from.name">
          <a-button
            type="primary"
            @click.prevent="() => (state.visibleByFile = !state.visibleByFile)"
          >
            <template #icon><PlusOutlined /></template>
            {{ t('common.addText') }}
          </a-button>
        </a-form-item>
      </template>
    </a-form>

    <!-- 文件上传框 -->
    <EditModal
      v-model:visible="state.visibleByFile"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    ></EditModal>

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

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

        <a-button
          type="dashed"
          @click="fnStepNext()"
          :disabled="!state.stepNext"
        >
          下一步
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
.ne {
  padding-top: 12px;

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