<script setup lang="ts">
import { reactive, onMounted, watch, PropType, computed } from 'vue';
import { message, Upload } from 'ant-design-vue/lib';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { UploadRequestOption } from 'ant-design-vue/lib/vc-upload/interface';
import { FileType } from 'ant-design-vue/lib/upload/interface';
import { uploadFile } from '@/api/tool/file';
import { changeNeLicense, listNeLicense } from '@/api/ne/neLicense';
const { t } = useI18n();
const emit = defineEmits(['ok', 'cancel', 'update:visible']);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  /**指定网元类型 */
  licenseList: {
    type: Array as PropType<Record<string, any>[]>,
    default: [],
  },
});

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**新增框或修改框是否显示 */
  visibleByUploadFile: boolean;
  /**标题 */
  title: string;
  /**模式 */
  mode: 'Universal' | 'AUSF-UDM-IMS';
  /**指定网元 */
  selectNe: any[];
  /**授权文件路径 */
  licensePath: string;
  /**上传文件 */
  uploadFiles: any[];
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  visibleByUploadFile: false,
  mode: 'Universal',
  selectNe: [],
  licensePath: '',
  uploadFiles: [],
  title: '授权文件',
  confirmLoading: false,
});

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
async function fnModalOk() {
  if (!modalState.licensePath) {
    message.warning('请上传授权文件', 3);
    return;
  }
  if (modalState.confirmLoading) return;
  modalState.confirmLoading = true;
  const hide = message.loading(t('common.loading'), 0);

  let reqArr: any = calcSelectNe.value.map(s => {
    s.reload = true; // 重启网元
    s.licensePath = modalState.licensePath;
    return changeNeLicense(s);
  });
  if (reqArr.length === 0) {
    message.warning('没有对应的网元对象', 3);
    hide();
    modalState.confirmLoading = false;
    return;
  }

  Promise.all(reqArr)
    .then(resArr => {
      for (const res of resArr) {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(t('common.operateOk'), 3);
        } else {
          message.success(res.msg, 3);
        }
      }
      emit('ok', resArr);
      fnModalCancel();
    })
    .finally(() => {
      hide();
      modalState.confirmLoading = false;
    });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.visibleByUploadFile = false;
  modalState.confirmLoading = false;
  modalState.mode = 'Universal';
  modalState.selectNe = [];
  modalState.licensePath = '';
  modalState.uploadFiles = [];
  emit('cancel');
  emit('update:visible', false);
}

/**表单上传前检查或转换压缩 */
function fnBeforeUploadFile(file: FileType) {
  if (modalState.confirmLoading) return false;
  const fileName = file.name;
  if (!fileName.endsWith('.ini')) {
    message.error('只支持上传文件格式 .ini', 3);
    return Upload.LIST_IGNORE;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('文件必须小于2MB', 3);
    return Upload.LIST_IGNORE;
  }
  return true;
}

/**表单上传文件 */
function fnUploadFile(up: UploadRequestOption) {
  // 发送请求
  const hide = message.loading(t('common.loading'), 0);
  modalState.confirmLoading = true;
  let formData = new FormData();
  formData.append('file', up.file);
  formData.append('subPath', 'license');
  uploadFile(formData)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success('upload success', 3);
        // 改为完成状态
        const file = modalState.uploadFiles[0];
        file.percent = 100;
        file.status = 'done';
        // 预置到表单
        const { fileName } = res.data;
        modalState.licensePath = fileName;
      } else {
        message.error(res.msg, 3);
      }
    })
    .finally(() => {
      hide();
      modalState.confirmLoading = false;
    });
}

/**监听是否显示，初始数据 */
watch(
  () => props.visible,
  val => {
    if (val) {
      // 传入授权列表
      if (props.licenseList.length === 0) {
        listNeLicense({
          neType: undefined,
          neId: '',
          version: '',
          pageNum: 1,
          pageSize: 20,
        }).then(res => {
          if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
            modalState.selectNe = res.rows;
          }
        });
      } else {
        modalState.selectNe = props.licenseList;
      }

      modalState.title = 'Upload License File';
      modalState.visibleByUploadFile = true;
    }
  }
);

/**授权模式选择 */
const calcSelectNe = computed(() => {
  if (!Array.isArray(modalState.selectNe)) return [];
  if (modalState.mode === 'AUSF-UDM-IMS') {
    return modalState.selectNe.filter(s =>
      ['AUSF', 'UDM', 'IMS'].includes(s.neType)
    );
  }

  return modalState.selectNe.filter(
    s => !['OMC', 'AUSF', 'UDM', 'IMS'].includes(s.neType)
  );
});

onMounted(() => {});
</script>

<template>
  <a-modal
    width="500px"
    :keyboard="false"
    :mask-closable="false"
    :visible="modalState.visibleByUploadFile"
    :title="modalState.title"
    :confirm-loading="modalState.confirmLoading"
    @ok="fnModalOk"
    @cancel="fnModalCancel"
  >
    <a-form
      name="modalStateFrom"
      layout="horizontal"
      :validate-on-rule-change="false"
      :validateTrigger="[]"
      :wrapper-col="{ span: 18 }"
      :label-col="{ span: 6 }"
      :labelWrap="true"
    >
      <a-form-item label="NE Type" v-if="calcSelectNe.length > 0">
        <a-tag color="default" v-for="s in calcSelectNe">
          {{ s.neType }}
        </a-tag>
      </a-form-item>
      <a-form-item label="License Mode" name="mode">
        <a-select v-model:value="modalState.mode">
          <a-select-option value="Universal">Universal</a-select-option>
          <a-select-option value="AUSF-UDM-IMS">AUSF-UDM-IMS</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="License File" name="file" :required="true">
        <a-upload
          name="file"
          v-model:file-list="modalState.uploadFiles"
          accept=".ini"
          list-type="text"
          :multiple="true"
          :max-count="1"
          :show-upload-list="{
            showPreviewIcon: false,
            showRemoveIcon: false,
            showDownloadIcon: false,
          }"
          :before-upload="fnBeforeUploadFile"
          :custom-request="fnUploadFile"
          :disabled="modalState.confirmLoading"
        >
          <a-button type="primary">
            <template #icon>
              <UploadOutlined />
            </template>
            Upload
          </a-button>
        </a-upload>
      </a-form-item>

      <a-form-item label="License File" name="file" v-if="false">
        <a-input-group compact>
          <a-upload
            name="file"
            v-model:file-list="modalState.uploadFiles"
            accept=".ini"
            list-type="text"
            :multiple="true"
            :max-count="1"
            :show-upload-list="{
              showPreviewIcon: false,
              showRemoveIcon: false,
              showDownloadIcon: false,
            }"
            :before-upload="fnBeforeUploadFile"
            :custom-request="fnUploadFile"
            :disabled="modalState.confirmLoading"
          >
            <a-button type="primary">
              <template #icon>
                <UploadOutlined />
              </template>
              Upload
            </a-button>
          </a-upload>
          <a-select v-model:value="modalState.mode" style="width: 142px">
            <a-select-option value="Other">Other</a-select-option>
            <a-select-option value="AUSF-UDM-IMS">AUSF-UDM-IMS</a-select-option>
          </a-select>
        </a-input-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style lang="less" scoped></style>
