<script setup lang="ts">
import { Modal, message } from 'ant-design-vue/es';
import { defineAsyncComponent, onMounted, reactive, toRaw } from 'vue';
import { fnToStepName, stepState } from '../hooks/useStep';
import useI18n from '@/hooks/useI18n';
import { operateNeVersion } from '@/api/ne/neVersion';
import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
} from '@/constants/result-constants';
import { listNeSoftware, newNeVersion } from '@/api/ne/neSoftware';
import { parseDateToStr } from '@/utils/date-utils';
import { ColumnsType } from 'ant-design-vue/es/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: t('views.ne.common.neType'),
    dataIndex: 'neType',
    align: 'left',
    width: 100,
  },
  {
    title: t('views.ne.neSoftware.version'),
    dataIndex: 'version',
    align: 'left',
    width: 150,
  },
  {
    title: t('views.ne.neSoftware.name'),
    dataIndex: 'name',
    key: 'name',
    align: 'left',
    width: 300,
  },
  {
    title: t('common.description'),
    dataIndex: 'description',
    key: 'description',
    align: 'left',
    ellipsis: true,
  },
  {
    title: t('common.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: undefined });
}

/**查询列表, 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) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      const { total, rows } = res.data;
      tablePagination.total = total;
      tableState.data = rows;
    }
    tableState.loading = false;
  });
}

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

/**对象信息状态 */
let state: StateType = reactive({
  stepNext: false,
  optionType: 'option',
  openByFile: false,
  depType: [],
  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 fnModalOpen() {
  state.openByFile = !state.openByFile;
}

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

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

/**版本安装 */
function fnRecordInstall() {
  const from = toRaw(state.from);
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.ne.neQuickSetup.installConfirmTip', {
      name: 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', updateMFetc: 'No', updateMFshare: 'No' };
      }
      const res = await operateNeVersion({
        neType: from.neType,
        neId: from.neId,
        action: 'install',
        preinput: preinput,
      });
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success(t('common.operateOk'), 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: t('views.ne.neQuickSetup.stepPrevTip'),
    onOk() {
      fnToStepName('NeInfoConfig');
    },
  });
}

/**下一步操作 */
function fnStepNext() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.ne.neQuickSetup.installStepNext'),
    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: 4 }"
      :wrapper-col="{ span: 16 }"
      :label-wrap="true"
    >
      <a-form-item
        :label="t('views.ne.neQuickSetup.installSource')"
        name="optionType"
      >
        <a-radio-group
          v-model:value="state.optionType"
          button-style="solid"
          :disabled="state.confirmLoading"
          @change="fnOptionTypeChange"
        >
          <a-radio-button value="option">
            {{ t('views.ne.neQuickSetup.installSourceOption') }}
          </a-radio-button>
          <a-radio-button value="upload">
            {{ t('views.ne.neQuickSetup.installSourceUpload') }}
          </a-radio-button>
        </a-radio-group>
      </a-form-item>

      <!-- 选择已上传 -->
      <template v-if="state.optionType === 'option'">
        <a-form-item
          :label="t('views.ne.neQuickSetup.installSelect')"
          name="option"
        >
          <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="t('views.ne.neQuickSetup.installUpload')"
          name="upload"
          :help="state.from.name"
        >
          <a-button type="primary" @click.prevent="fnModalOpen()">
            <template #icon><UploadOutlined /></template>
            {{ t('views.ne.neSoftware.upload') }}
          </a-button>
        </a-form-item>
      </template>
    </a-form>

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

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

        <a-button
          type="primary"
          ghost
          :disabled="!state.from.version"
          :loading="state.confirmLoading"
          @click.prevent="fnRecordInstall()"
        >
          <template #icon><ThunderboltOutlined /></template>
          {{ t('views.ne.neQuickSetup.installText') }}
        </a-button>

        <a-button
          type="primary"
          @click="fnStepNext()"
          :disabled="!state.stepNext"
        >
          {{ t('views.ne.neQuickSetup.stepNext') }}
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
.ne {
  min-height: 400px;
  display: flex;
  flex-direction: column;

  & .ant-form {
    flex: 1;
  }

  &-oper {
    text-align: end;
  }
}
</style>
