<script setup lang="ts">
import { reactive, onMounted, toRaw, watch } from 'vue';
import { ProModal } from 'antdv-pro-modal';
import { Form, Modal, Upload, message } from 'ant-design-vue/es';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import {
  changeNeLicense,
  getNeLicense,
  getNeLicenseByTypeAndID,
} from '@/api/ne/neLicense';
import { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import { FileType } from 'ant-design-vue/es/upload/interface';
import { uploadFile } from '@/api/tool/file';
import { useClipboard } from '@vueuse/core';
import saveAs from 'file-saver';
const { copy } = useClipboard({ legacy: true });
const { t } = useI18n();
const emit = defineEmits(['ok', 'cancel', 'update:open']);
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  /**记录ID 优先级高于neId */
  editId: {
    type: Number,
    default: 0,
  },
  /**网元ID */
  neId: {
    type: String,
    default: '',
  },
  neType: {
    type: String,
    default: '',
  },
  /**是否重启服务 */
  reload: {
    type: Boolean,
    default: false,
  },
});

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**新增框或修改框是否显示 */
  openByEdit: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: {
    id: number | undefined;
    neType: string;
    neId: string;
    activationRequestCode: string;
    licensePath: string;
    remark: string;
    reload: boolean;
  };
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**上传文件 */
  uploadFiles: any[];
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByEdit: false,
  title: '授权文件',
  from: {
    id: undefined,
    neType: '',
    neId: '',
    activationRequestCode: '',
    licensePath: '',
    remark: '',
    reload: false,
  },
  confirmLoading: false,
  uploadFiles: [],
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    licensePath: [
      {
        required: true,
        message: t('views.ne.neLicense.licensePathTip'),
      },
    ],
  })
);

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  if (modalState.confirmLoading || !modalState.from.id) return;

  modalStateFrom
    .validate()
    .then(e => {
      modalState.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);
      const from = toRaw(modalState.from);
      changeNeLicense(from).then(res => {
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('common.operateOk'),
            duration: 3,
          });
          // 返回无引用信息
          emit('ok', JSON.parse(JSON.stringify(from)));
          fnModalCancel();
        } else {
          message.error({
            content: `${res.msg}`,
            duration: 3,
          });
        }
        hide();
        modalState.confirmLoading = false;
      });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.openByEdit = false;
  modalState.confirmLoading = false;
  modalStateFrom.resetFields();
  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.from.licensePath = res.data.filePath;
      } else {
        message.error(res.msg, 3);
      }
    })
    .finally(() => {
      hide();
      modalState.confirmLoading = false;
    });
}

/**复制授权申请码 */
function fnCopyCode() {
  const code = modalState.from.activationRequestCode;
  if (!code) return;
  copy(code).then(() => {
    message.success(t('common.copyOk'), 3);
  });
}

/**下载授权申请码文件 */
function fnDownCode() {
  const { activationRequestCode, neType, neId } = modalState.from;
  if (!activationRequestCode) return;
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.ne.neLicense.downCodeTop'),
    onOk() {
      const blob = new Blob([activationRequestCode], {
        type: 'text/plain',
      });
      saveAs(blob, `${neType}_${neId}_code.txt`);
    },
  });
}

/**
 * 对话框弹出显示为 ID编辑
 * @param id id
 */
function fnModalVisibleById(id: number) {
  const hide = message.loading(t('common.loading'), 0);
  getNeLicense(id)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        Object.assign(modalState.from, res.data);
        modalState.from.licensePath = '';
        modalState.from.reload = props.reload;
        modalState.title = t('views.ne.neLicense.updateTtile');
        modalState.openByEdit = true;
      } else {
        message.error(res.msg, 3);
      }
    })
    .finally(() => {
      modalState.confirmLoading = false;
      hide();
    });
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param neType 网元类型
 * @param neId 网元ID
 */
function fnModalVisibleByTypeAndId(neType: string, neId: string) {
  const hide = message.loading(t('common.loading'), 0);
  getNeLicenseByTypeAndID(neType, neId)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        Object.assign(modalState.from, res.data);
        modalState.from.licensePath = '';
        modalState.from.reload = props.reload;
        modalState.title = t('views.ne.neLicense.updateTtile');
        modalState.openByEdit = true;
      } else {
        message.error(res.msg, 3);
      }
    })
    .finally(() => {
      modalState.confirmLoading = false;
      hide();
    });
}

/**监听是否显示，初始数据 */
watch(
  () => props.open,
  val => {
    if (val) {
      if (props.editId > 0) {
        fnModalVisibleById(props.editId);
      }
      if (props.neType && props.neId) {
        fnModalVisibleByTypeAndId(props.neType, props.neId);
      }
    }
  }
);

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

<template>
  <ProModal
    :drag="true"
    :width="800"
    :destroyOnClose="true"
    :keyboard="false"
    :mask-closable="false"
    :open="modalState.openByEdit"
    :title="modalState.title"
    :confirm-loading="modalState.confirmLoading"
    @ok="fnModalOk"
    @cancel="fnModalCancel"
  >
    <a-form
      name="modalStateFrom"
      layout="horizontal"
      :wrapper-col="{ span: 18 }"
      :label-col="{ span: 6 }"
      :labelWrap="true"
    >
      <a-row>
        <a-col :lg="12" :md="12" :xs="24">
          <a-form-item
            :label-col="{ span: 12 }"
            :label="t('views.ne.common.neType')"
            name="neType"
          >
            {{ modalState.from.neType }}
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="12" :xs="24">
          <a-form-item
            :label-col="{ span: 12 }"
            :label="t('views.ne.common.neId')"
            name="neId"
          >
            {{ modalState.from.neId }}
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        :label="t('views.ne.neLicense.activationRequestCode')"
        name="activationRequestCode"
        v-bind="modalStateFrom.validateInfos.activationRequestCode"
      >
        <a-input-group compact>
          <a-input
            v-model:value="modalState.from.activationRequestCode"
            :disabled="true"
            style="width: calc(100% - 64px)"
          />
          <a-tooltip :title="t('common.copyText')" placement="topRight">
            <a-button type="default" @click="fnCopyCode()">
              <template #icon><CopyOutlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip :title="t('common.downloadText')" placement="topRight">
            <a-button type="primary" @click="fnDownCode()">
              <template #icon><DownloadOutlined /></template>
            </a-button>
          </a-tooltip>
        </a-input-group>
      </a-form-item>

      <a-form-item
        :label="t('views.ne.neLicense.licensePath')"
        name="file"
        v-bind="modalStateFrom.validateInfos.licensePath"
      >
        <a-upload
          name="file"
          v-model:file-list="modalState.uploadFiles"
          accept=".ini"
          list-type="text"
          :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-item label="NE Reload" name="reload" v-if="false">
        <a-switch v-model:checked="modalState.from.reload"> </a-switch>
      </a-form-item>

      <a-form-item :label="t('common.remark')" name="remark">
        <a-textarea
          v-model:value="modalState.from.remark"
          :maxlength="200"
          :show-count="true"
          :placeholder="t('common.inputPlease')"
        />
      </a-form-item>
    </a-form>
  </ProModal>
</template>

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