<template>
  <div class="auth-set pg-main">
    <div class="pg-title">
      <span>授权配置</span>
    </div>
    <div class="pg-select-infos pg-total-infos">
      <Form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        :label-width="120"
      >
        <FormItem prop="loginName" label="当前信息：">
          {{ AUTH_TYPE[authInfo.authMode] }}
        </FormItem>
        <FormItem label="过期时间：">
          <span v-if="authInfo.expireTime === -1">不过期</span>
          <span v-else-if="authInfo.expireTime">
            {{ authInfo.expireTime | dateFormat }}</span
          >
          <span v-else>--</span>
        </FormItem>
        <FormItem label="授权模式：">
          <Select v-model="mode" @change="modeChange">
            <Option value="OFF_LINE" label="离线激活"></Option>
            <Option value="ON_LINE" label="在线激活"></Option>
          </Select>
        </FormItem>
        <FormItem v-if="IS_OFFLINE_MODE" prop="mobileNumber" label="导出：">
          <Button type="primary" :loading="downloading" @click="toExport">
            硬件信息
          </Button>
        </FormItem>
        <FormItem v-if="IS_OFFLINE_MODE" prop="code" label="导入授权文件：">
          <upload-button
            btn-content="选择文件"
            btn-type="primary"
            :upload-url="uploadUrl"
            :format="['lic']"
            accept=".lic"
            style="margin: 0"
            @valid-error="validError"
            @upload-success="uploadSuccess"
          >
          </upload-button>
        </FormItem>
        <FormItem v-if="!IS_OFFLINE_MODE" prop="accessKey" label="accessKey：">
          <Input
            v-model.trim="modalForm.accessKey"
            placeholder="请输入accessKey"
            clearable
          ></Input>
        </FormItem>
        <FormItem
          v-if="!IS_OFFLINE_MODE"
          prop="accessSecret"
          label="accessSecret："
        >
          <Input
            v-model.trim="modalForm.accessSecret"
            placeholder="请输入accessSecret"
            clearable
          ></Input>
        </FormItem>
        <FormItem v-if="!IS_OFFLINE_MODE">
          <Button type="primary" :loading="loading" @click="confirm"
            >保存</Button
          >
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
import { downloadByApi } from "@/libs/download";
import UploadButton from "@/components/UploadButton";
import { axios } from "@/libs/http";
import util from "@/libs/util";

const authSelect = () => axios.post("/system/auth/select");
const exportDeviceInfo = () =>
  axios.post(
    "/system/auth/export/device/info",
    {},
    {
      responseType: "blob",
    }
  );
const onlineActivation = (data) =>
  axios.post("/system/auth/online/activation", data);

export default {
  name: "auth-set",
  components: { UploadButton },
  data() {
    return {
      mode: "OFF_LINE",
      authInfo: { expireTime: -1, authMode: "NON_ACTIVATED" },
      AUTH_TYPE: {
        ON_LINE: "在线激活",
        OFF_LINE: "离线激活",
        NON_ACTIVATED: "未激活",
      },
      modalForm: {
        accessKey: "",
        accessSecret: "",
      },
      rules: {
        accessKey: [
          {
            required: true,
            message: "请输入秘钥",
            trigger: "change",
          },
          {
            message: "秘钥不能超过200个字符",
            max: 200,
            trigger: "change",
          },
        ],
        accessSecret: [
          {
            required: true,
            message: "请输入密匙",
            trigger: "change",
          },
          {
            message: "密匙不能超过200个字符",
            max: 200,
            trigger: "change",
          },
        ],
      },
      loading: false,
      downloading: false,
      // import
      uploadUrl: "/system/auth/offline/activation",
    };
  },
  computed: {
    IS_OFFLINE_MODE() {
      return this.mode === "OFF_LINE";
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      const res = await authSelect();
      this.authInfo = res.data.data || {};
      this.mode =
        this.authInfo.authMode === "NON_ACTIVATED"
          ? ""
          : this.authInfo.authMode;
      this.modalForm = util.objAssign(this.modalForm, this.authInfo);
    },
    modeChange() {
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    async confirm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;
      let datas = { ...this.modalForm };
      const res = await onlineActivation(datas).catch(() => {});
      this.loading = false;
      this.search();

      if (!res.data.data) return;
      this.$Message.success("操作成功！");
    },
    async toExport() {
      if (this.downloading) return;
      this.downloading = true;

      const res = await downloadByApi(() => {
        return exportDeviceInfo();
      }).catch((e) => {
        this.$Message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$Message.success("下载成功！");
    },
    validError(errorData) {
      this.$Message.error(errorData.message);
    },
    uploadSuccess() {
      this.search();
    },
  },
};
</script>
