<template>
  <el-form class="authorize_form" ref="activateProjectForm" :model="form" :rules="rules" size="small"
    :label-width="isEN ? '200px' : '120px'">
    <div class="base-dialog-body">
      <p class="title">{{ $t("trials:activate:ApplyMessage") }}</p>
      <!-- 单位名称 -->
      <el-form-item :label="$t('trials:trials-list:activate:organizationName')">
        <el-input v-model="form.HospitalName" />
      </el-form-item>
      <!-- 机构编码 -->
      <el-form-item :label="$t('trials:trials-list:activate:hospitalCode')">
        <el-input v-model="form.HospitalCode" />
      </el-form-item>
      <!-- 项目编号 -->
      <el-form-item :label="$t('trials:trials-list:table:trialId')">
        <el-input v-model="form.TrialCode" />
      </el-form-item>
      <!-- 评估标准 -->
      <el-form-item :label="$t('trials:trials-list:activate:evaluationCriteria')">
        <el-select v-model="form.CriterionTypeList" multiple clearable>
          <el-option v-for="item of criterionTypeList" :key="item.Id" :label="item.CriterionName"
            :value="item.CriterionType" :title="item.Description" />
        </el-select>
      </el-form-item>
      <!-- 项目码 -->
      <el-form-item :label="$t('trials:trials-list:table:trialGuid')">
        <el-input v-model="form.TrialId" />
      </el-form-item>
      <!-- 机器码 -->
      <el-form-item :label="$t('trials:trials-list:table:CreateUserId')">
        <el-input v-model="form.CreateUserId" />
      </el-form-item>
      <!-- 购买时长 -->
      <el-form-item :label="$t('trials:trials-list:activate:purchaseDuration')">
        <el-input-number v-model="form.PurchaseDuration" @change="handleChange" :min="0" :max="100"
          step-strictly></el-input-number>
      </el-form-item>
      <!-- 授权码 -->
      <el-form-item :label="$t('trials:trials-list:form:authorizationCode')">
        <p v-if="form.Authorization" class="AuthorizationBox">
          <span class="Authorization" :title="form.Authorization">{{
            form.Authorization
          }}</span>
          <span class="copy" @click.stop="copy">{{
            $t("trials:trials-list:action:copy")
          }}</span>
          <span class="copy" style="margin-left: 10px" @click.stop="getCode">{{ $t("trials:reading:button:download")
          }}</span>
        </p>
      </el-form-item>
    
    </div>
  </el-form>
</template>
<script>
import {
  activateTrial,
  getTrialAuthorizationCode,
  getTrialAuthorizationInfo,
  getActivationCodeInfo,
  getSystemConfirmedCreiterionList
} from "@/api/trials.js";
import { fileDownload } from "@/utils/uploadZip.js";
export default {
  name: "authorize",
  data() {
    return {
      form: {
        Authorization: null, // 授权码
        Activate: null, // 激活码
        TrialId: null,
        TrialCode: null,
        PurchaseDuration: null,
        HospitalName: null,
        CriterionTypeList: [],
        CreateUserId: null,
        HospitalCode: null,
        AuthorizationDeadLineDate: null,
      },
      criterionTypeList: [],
      btnLoading: false,
      rules: {
        Activate: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
        ],
      },
      isActivate: false,
      timer: null,
    };
  },
  computed: {
    isEN() {
      return this.$i18n.locale !== 'zh'
    }
  },
  created() {
    this.getSystemConfirmedCreiterionList();
    // this.getTrialAuthorizationInfo();
  },
  destroyed() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  },
  methods: {
    // 购买时长变更
    async handleChange() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
      this.timer = setTimeout(() => {
        this.getTrialAuthorizationCode();
        clearTimeout(this.timer);
        this.timer = null;
      }, 500);
    },
    // 获取授权信息
    async getTrialAuthorizationInfo() {
      if (!this.form.TrialId) return
      try {
        let params = {
          TrialId: this.form.TrialId,
        };
        let res = await getTrialAuthorizationInfo(params);
        if (res.IsSuccess) {
          Object.keys(this.form).forEach((key) => {
            this.form[key] = res.Result[key];
          });
          this.getTrialAuthorizationCode();
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 获取授权码
    async getTrialAuthorizationCode() {
      if (!this.form.TrialId) return
      let params = {
        TrialId: this.form.TrialId,
        TrialCode: this.form.TrialCode,
        PurchaseDuration: this.form.PurchaseDuration,
        HospitalName: this.form.HospitalName,
        CriterionTypeList: this.form.CriterionTypeList,
        CreateUserId: this.form.CreateUserId,
        HospitalCode: this.form.HospitalCode,
      };
      try {
        let res = await getTrialAuthorizationCode(params);
        if (res.IsSuccess) {
          this.form.Authorization = res.Result;
          return true;
        }
        return false;
      } catch (err) {
        console.log(err);
        return false;
      }
    },
    // 获取阅片标准
    async getSystemConfirmedCreiterionList() {
      try {
        let res = await getSystemConfirmedCreiterionList();
        if (res.IsSuccess) {
          this.criterionTypeList = res.Result;
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 激活
    async handleSave() {
      if (!this.isActivate) return;
      try {
        let validate = this.$refs.activateProjectForm.validate();
        if (!validate) return;
        let params = {
          TrialId: this.data.TrialId,
          ActivationCode: this.form.Activate,
        };
        this.btnLoading = true;
        let res = await activateTrial(params);
        this.btnLoading = false;
        if (res.IsSuccess) {
          this.$message.success(
            this.$t("trials:trials-list:action:activateSuccessfully")
          );
          this.$emit("getList");
          this.handleCancel();
        }
      } catch (err) {
        this.btnLoading = false;
        console.log(err);
      }
    },
    // 复制
    copy() {
      this.$copyText(this.form.Authorization)
        .then((res) => {
          // 复制成功
          this.$message.success(
            this.$t("trials:researchRecord:message:copySuccessfully")
          );
        })
        .catch(() => {
          // 复制失败
          this.$alert(this.$t("trials:researchRecord:message:copyFailed"));
        });
    },
    // 下载
    async getCode() {
      fileDownload(
        this.form.Authorization,
        this.form.TrialCode + "_Request_Code.req"
      );
    },
    // 上传并读取文件
    uploadFile(file) {
      let input = file.target;
      const reader = new FileReader();
      reader.readAsText(input.files[0], "utf8"); // input.files[0]为第一个文件
      reader.onload = () => {
        this.form.Activate = reader.result; // reader.result为获取结果
        input.value = null;
      };
    },
    // 获取激活码信息
    async getActivationCodeInfo() {
      try {
        let params = {
          ActivationCode: this.form.Activate,
        };
        let res = await getActivationCodeInfo(params);
        if (res.IsSuccess) {
          if (res.IsSuccess) {
            Object.keys(this.ActivateData).forEach((key) => {
              this.ActivateData[key] = res.Result[key];
            });
          }
          this.isActivate = true;
        }
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.authorize_form {
  width: 60%;
  padding: 20px;
}
::v-deep .el-dialog__body {
  padding-bottom: 10px;
  padding-top: 0;
}

.Authorization {
  width: 70%;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-form-item__content {
  .el-input {
    width: 60%;
  }
}

.copy {
  cursor: pointer;
  color: #409eff;
}

.AuthorizationBox {
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

::v-deep .el-form-item__label {
  font-weight: bold;
}
</style>