<template>
  <el-dialog v-dialogDrag :visible.sync="visible" :close-on-click-modal="false"
    :title="$t('trials:trials-list:action:activateProject')" :width="isEN ? '600px' : '500px'" append-to-body
    :before-close="handleCancel">
    <el-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')">
          <span>{{ form.HospitalName }}</span>
        </el-form-item>
        <!-- 机构编码 -->
        <el-form-item :label="$t('trials:trials-list:activate:hospitalCode')">
          <span>{{ form.HospitalCode }}</span>
        </el-form-item>
        <!-- 项目编号 -->
        <el-form-item :label="$t('trials:trials-list:table:trialId')">
          <span>{{ form.TrialCode }}</span>
        </el-form-item>
        <!-- 评估标准 -->
        <el-form-item :label="$t('trials:trials-list:activate:evaluationCriteria')">
          <span>{{
            form.CriterionTypeList.map((item) =>
              $fd("CriterionType", Number(item))
            ).join(",")
          }}</span>
        </el-form-item>
        <!-- 项目码 -->
        <el-form-item :label="$t('trials:trials-list:table:trialGuid')">
          <span>{{ form.TrialId }}</span>
        </el-form-item>
        <!-- 机器码 -->
        <el-form-item :label="$t('trials:trials-list:table:CreateUserId')">
          <span>{{ form.CreateUserId }}</span>
        </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>
        <!-- 激活码 -->
        <el-form-item :label="$t('trials:trials-list:form:activateCode')" prop="Activate">
          <el-input v-model="form.Activate" :disabled="isActivate" />
          <input type="file" id="uploadFileInp" @change="uploadFile" style="display: none" />
          <label class="copy" style="margin-left: 10px" for="uploadFileInp" v-if="!isActivate">{{
            $t("trials:activate:button:upload") }}</label>
          <span v-if="form.Activate" class="copy" @click.stop="getActivationCodeInfo" style="margin-left: 10px">{{
            $t("trials:reviewTrack:impactList:save") }}</span>
        </el-form-item>
        <div v-if="isActivate">
          <p class="title">{{ $t("trials:activate:Message") }}</p>
          <!-- 单位名称 -->
          <el-form-item :label="$t('trials:trials-list:activate:organizationName')">
            <span>{{ ActivateData.HospitalName }}</span>
          </el-form-item>
          <!-- 项目编号 -->
          <el-form-item :label="$t('trials:trials-list:table:trialId')">
            <span>{{ ActivateData.TrialCode }}</span>
          </el-form-item>
          <!-- 评估标准 -->
          <el-form-item :label="$t('trials:trials-list:activate:evaluationCriteria')">
            <span>{{
              ActivateData.CriterionTypeList.map((item) =>
                $fd("CriterionType", Number(item))
              ).join(",")
            }}</span>
          </el-form-item>
          <!-- 授权时长 -->
          <el-form-item :label="$t('trials:trials-list:activate:durationAuthorized')">
            <span>{{ ActivateData.PurchaseDuration }}</span>
          </el-form-item>
        </div>
      </div>
      <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
        <el-form-item>
          <!-- 取消 -->
          <el-button :disabled="btnLoading" size="small" type="primary" @click="handleCancel">
            {{ $t("common:button:cancel") }}
          </el-button>
          <!-- 保存 -->
          <el-button size="small" type="primary" :disabled="!isActivate" :loading="btnLoading" @click="handleSave">
            {{ $t("trials:trials-list:action:activate") }}
          </el-button>
        </el-form-item>
      </div>
    </el-form>
  </el-dialog>
</template>
<script>
import {
  activateTrial,
  getTrialAuthorizationCode,
  getTrialAuthorizationInfo,
  getActivationCodeInfo,
} from "@/api/trials.js";
import { fileDownload } from "@/utils/uploadZip.js";
export default {
  name: "activateProject",
  props: {
    data: {
      required: true,
      default: () => {
        return {};
      },
    },
    visible: {
      required: true,
      default: false,
    },
  },
  data() {
    return {
      form: {
        Authorization: null, // 授权码
        Activate: null, // 激活码
        TrialId: null,
        TrialCode: null,
        PurchaseDuration: null,
        HospitalName: null,
        CriterionTypeList: [],
        CreateUserId: null,
        HospitalCode: null,
        AuthorizationDeadLineDate: null,
      },
      ActivateData: {
        TrialId: null,
        TrialCode: null,
        PurchaseDuration: null,
        HospitalName: null,
        CriterionTypeList: [],
        CreateUserId: null,
        HospitalCode: null,
        AuthorizationDeadLineDate: null,
      },
      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.getTrialAuthorizationInfo();
  },
  destroyed() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  },
  methods: {
    handleCancel() {
      this.$emit("update:visible", false);
    },
    // 购买时长变更
    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() {
      try {
        let params = {
          TrialId: this.data.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() {
      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 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>
::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>