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

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**新增框或修改框是否显示 */
  openByUploadFile: boolean;
  /**标题 */
  title: string;
  /**授权文件路径 */
  licensePath: string;
  /**上传文件 */
  uploadFiles: any[];
  /**确定按钮 loading */
  confirmLoading: boolean;
};

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

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
async function fnModalOk() {
  if (!modalState.licensePath) {
    message.warning(t('views.ne.neLicense.licensePathTip'), 3);
    return;
  }
  if (modalState.confirmLoading) return;
  modalState.confirmLoading = true;

  const notificationKey = 'NE_LICENSE_MORE';
  notification.info({
    key: notificationKey,
    message: modalState.title,
    description: t('common.loading'),
    duration: 0,
  });

  if (props.licenseList.length === 0) {
    notification.close(notificationKey);
    modalState.confirmLoading = false;
    return;
  }

  const hasFailNeType: string[] = [];
  for (const item of props.licenseList) {
    try {
      const res = await changeNeLicense({
        neType: item.neType,
        neId: item.neId,
        licensePath: modalState.licensePath,
        reload: true, // 重启网元
      });
      if (res.code !== RESULT_CODE_SUCCESS) {
        hasFailNeType.push(item.neType);
      }
    } catch (error) {
      console.error(error);
    }
  }

  // 存在错误网元提示
  if (hasFailNeType.length > 0) {
    notification.warning({
      message: modalState.title,
      description: h('div', {}, [
        h('p', t('views.ne.neLicense.uploadChangeFail')),
        h('div', { style: { color: '#f5222d' } }, hasFailNeType.join('、')),
      ]),
      duration: 4.5,
    });
  } else {
    notification.success({
      message: modalState.title,
      description: t('views.ne.neLicense.uploadChangeOk'),
      duration: 4.5,
    });
  }

  // 结束
  emit('ok', hasFailNeType);
  fnModalCancel();
  notification.close(notificationKey);
  modalState.confirmLoading = false;
}

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

/**表单上传前检查或转换压缩 */
function fnBeforeUploadFile(file: FileType) {
  if (modalState.confirmLoading) return false;
  if (!file.name.endsWith('.ini')) {
    const msg = `${t('components.UploadModal.onlyAllow')} .ini`;
    message.error(msg, 3);
    return Upload.LIST_IGNORE;
  }
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isLt3M) {
    const msg = `${t('components.UploadModal.allowFilter')} 3MB`;
    message.error(msg, 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) {
        // 改为完成状态
        const file = modalState.uploadFiles[0];
        file.percent = 100;
        file.status = 'done';
        // 预置到表单
        modalState.licensePath = res.data.filePath;
      } else {
        message.error(res.msg, 3);
      }
    })
    .finally(() => {
      hide();
      modalState.confirmLoading = false;
    });
}

/**监听是否显示，初始数据 */
watch(
  () => props.open,
  val => {
    if (val) {
      modalState.title = t('views.ne.neLicense.updateTtile');
      modalState.openByUploadFile = true;
    }
  }
);

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

<template>
  <ProModal
    :drag="true"
    :destroyOnClose="true"
    :keyboard="false"
    :mask-closable="false"
    :open="modalState.openByUploadFile"
    :title="modalState.title"
    :confirm-loading="modalState.confirmLoading"
    :cancel-button-props="{ disabled: modalState.confirmLoading }"
    :closable="false"
    @ok="fnModalOk"
    @cancel="fnModalCancel"
  >
    <a-form
      name="modalStateFrom"
      layout="horizontal"
      :wrapper-col="{ span: 18 }"
      :label-col="{ span: 6 }"
      :labelWrap="true"
    >
      <a-form-item :label="t('views.ne.common.neType')">
        <a-tag color="processing" v-for="s in props.licenseList">
          {{ s.neType }}
        </a-tag>
      </a-form-item>

      <a-form-item
        :label="t('views.ne.neLicense.licensePath')"
        name="file"
        :required="true"
        :validate-on-rule-change="false"
        :validateTrigger="[]"
      >
        <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>
            {{ t('views.ne.neLicense.upload') }}
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </ProModal>
</template>

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