<script setup lang="ts">
import { reactive, onMounted, toRaw, watch } from 'vue';
import { Form, Modal, Upload, message } from 'ant-design-vue/lib';
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/lib/vc-upload/interface';
import { FileType } from 'ant-design-vue/lib/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:visible']);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  /**记录ID 优先级高于neId */
  editId: {
    type: String,
    default: '',
  },
  /**网元ID */
  neId: {
    type: String,
    default: '',
  },
  neType: {
    type: String,
    default: '',
  },
});

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

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  visibleByEdit: false,
  title: '授权文件',
  from: {
    id: '',
    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.visibleByEdit = false;
  modalState.confirmLoading = false;
  modalStateFrom.resetFields();
  modalState.uploadFiles = [];
  emit('cancel');
  emit('update:visible', 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) {
        message.success('upload success', 3);
        // 改为完成状态
        const file = modalState.uploadFiles[0];
        file.percent = 100;
        file.status = 'done';
        // 预置到表单
        const { fileName } = res.data;
        modalState.from.licensePath = fileName;
      } 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: string) {
  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.title = t('views.ne.neLicense.updateTtile');
        modalState.visibleByEdit = 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.title = t('views.ne.neLicense.updateTtile');
        modalState.visibleByEdit = true;
      } else {
        message.error(res.msg, 3);
      }
    })
    .finally(() => {
      modalState.confirmLoading = false;
      hide();
    });
}

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

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

<template>
  <a-modal
    width="800px"
    :keyboard="false"
    :mask-closable="false"
    :visible="modalState.visibleByEdit"
    :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 :gutter="16">
        <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>
            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('views.ne.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>
  </a-modal>
</template>

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