<template>
  <el-form
    ref="auditForm"
    v-loading="loading"
    :model="form"
    label-width="120px"
    size="small"
    :rules="rules"
    class="audit-form"
  >
    <div class="base-dialog-body" style="min-height: 500px">
      <!-- 是否认可 -->
      <el-form-item
        :label="$t('trials:auditRecord:table:auditResult')"
        prop="PIAuditState"
      >
        <el-radio-group
          v-model="form.PIAuditState"
          @change="handlePIAuditStateChange"
        >
          <el-radio
            v-for="item of $d.PIAuditState"
            v-show="item.value > 0"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 不认可原因 -->
      <el-form-item
        v-if="form.PIAuditState === 1"
        :label="$t('trials:pendingReview:title:notAgreeReason')"
        prop="NotAgreeReason"
      >
        <el-input
          v-model="form.NotAgreeReason"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          :placeholder="$t('common:ruleMessage:specify')"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <!-- 备注 -->
      <el-form-item
        :label="$t('trials:pendingReview:title:note')"
        prop="PiAuditNote"
      >
        <el-input
          v-model="form.PIAuditNote"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          :placeholder="$t('common:ruleMessage:specify')"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <!-- 相关截图 -->
      <el-form-item :label="$t('trials:pendingReview:title:screenshots')">
        <el-upload
          action=""
          :accept="accept"
          :on-preview="handlePictureCardPreview"
          :before-upload="handleBeforeUpload"
          :http-request="uploadScreenshots"
          list-type="picture-card"
          :on-remove="handleRemove"
          :file-list="fileList"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="OSSclientConfig.basePath + file.url"
              alt=""
              crossorigin="anonymous"
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>

              <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog append-to-body :visible.sync="imgVisible" width="600px">
          <el-image :src="OSSclientConfig.basePath + imageUrl" width="100%">
            <div slot="placeholder" class="image-slot">
              {{ $t("trials:medicalFeedback:message:loading")
              }}<span class="dot">...</span>
            </div>
          </el-image>
        </el-dialog>
      </el-form-item>
      <!-- 阅片结果 -->
      <el-form-item :label="$t('trials:auditRecord:table:readingResult')">
        <el-button type="text" @click="handleView">{{
          $t("common:button:view")
        }}</el-button>
      </el-form-item>
    </div>
    <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
      <el-form-item style="text-align: right">
        <!-- 取消 -->
        <el-button size="small" type="primary" @click="handleClose">
          {{ $t("common:button:cancel") }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" @click="handleSave">
          {{
            rowData.PIAuditState
              ? $t("trials:pendingReview:button:modify")
              : $t("trials:pendingReview:button:confirm")
          }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
// import { iRSendMedicalReviewDialog, UploadMedicalReviewImage } from '@/api/trials'
import { pIAuditTask } from "@/api/reading";
export default {
  name: "FeedbackFrom",
  props: {
    rowData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      form: {
        VisitTaskId: "",
        NotAgreeReason: null,
        PIAuditNote: "",
        PIAuditImagePathList: [],
        PIAuditState: null,
      },
      rules: {
        PIAuditState: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: "blur",
            type: "number",
            min: 1,
          },
        ],
        NotAgreeReason: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
          {
            max: 500,
            message: `${this.$t("common:ruleMessage:maxLength")} 500`,
          },
        ],
        PIAuditNote: [
          {
            max: 500,
            message: `${this.$t("common:ruleMessage:maxLength")} 500`,
          },
        ],
      },
      loading: false,
      accept: ".png,.jpg,.jpeg",
      imgVisible: false,
      imageUrl: "",
      uploadDisabled: false,
      listLoading: false,
      fileList: [],
      userTypeEnumInt: zzSessionStorage.getItem("userTypeEnumInt") * 1,
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    initForm() {
      this.loading = true;
      if (Object.keys(this.rowData).length > 0) {
        for (const k in this.form) {
          if (this.rowData.hasOwnProperty(k)) {
            if (
              k === "PIAuditImagePathList" &&
              this.rowData.PIAuditImagePathList
            ) {
              this.rowData.PIAuditImagePathList.map((filePath) => {
                if (!filePath) return;
                this.fileList.push({ url: filePath });
              });
            } else {
              this.form[k] = this.rowData[k];
            }
          }
        }
      }
      this.loading = false;
    },
    // 更新qc问题配置信息
    handleSave() {
      this.$refs.auditForm.validate((valid) => {
        if (!valid) return;
        this.loading = true;
        var files = [];
        this.fileList.map((file) => {
          if (file && file.url) {
            files.push(file.url);
          }
        });
        this.form.PIAuditImagePathList = files;
        this.form.VisitTaskId = this.rowData.Id;
        pIAuditTask(this.form)
          .then((res) => {
            this.loading = false;
            if (res.IsSuccess) {
              // 关闭弹窗并刷新
              this.$emit("close");
              this.$emit("getList");
              this.$message.success(
                this.$t("common:message:savedSuccessfully")
              );
            }
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    handlePIAuditStateChange(val) {
      this.form.NotAgreeReason = "";
    },
    handleClose() {
      this.$emit("close");
    },
    handleBeforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        return true;
      } else {
        var msg = this.$t("trials:medicalFeedback:message:format");
        msg = msg.replace("xxx", this.accept);
        this.$alert(msg);
        return false;
      }
    },
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf(".");
      var suffix = fileName.substring(index + 1, fileName.length);
      if (
        this.accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) ===
        -1
      ) {
        return false;
      } else {
        return true;
      }
    },
    async uploadScreenshots(param) {
      try {
        this.loading = true;
        var file = await this.fileToBlob(param.file);
        var trialId = this.$route.query.trialId;
        const res = await this.OSSclient.put(
          `/${trialId}/PIReview/${param.file.name}`,
          file
        );
        console.log(res);
        this.fileList.push({
          name: param.file.name,
          path: res.name,
          fullPath: this.OSSclientConfig.basePath + res.name,
          url: res.name,
        });
        // this.fileList.push({
        //   name: param.file.name,
        //   url: this.$getObjectName(res.url),
        // });
        this.loading = false;
      } catch (e) {
        console.log(e);
        this.loading = false;
      }
    },
    fileToBlob(file) {
      // 创建 FileReader 对象
      const reader = new FileReader();
      return new Promise((resolve) => {
        // FileReader 添加 load 事件
        reader.addEventListener("load", (e) => {
          let blob;
          if (typeof e.target.result === "object") {
            blob = new Blob([e.target.result]);
          } else {
            blob = e.target.result;
          }
          resolve(blob);
        });
        // FileReader 以 ArrayBuffer 格式 读取 File 对象中数据
        reader.readAsArrayBuffer(file);
      });
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.imageUrl = file.url;
      this.imgVisible = true;
    },
    // 删除图片
    handleRemove(file, fileList) {
      var idx = this.fileList.findIndex((i) => i.url === file.url);
      if (idx === -1) return;
      this.fileList.splice(idx, 1);
    },
    handleView() {
      this.$emit("viewReaingResult");
    },
  },
};
</script>

<style lang="scss" scoped>
.audit-form {
  .disabled {
    >>> .el-upload--picture-card {
      display: none;
    }
  }
  >>> .el-upload-list__item {
    transition: none !important;
  }
  >>> .el-upload-list__item-thumbnail {
    /* 图片在方框内显示长边 */
    object-fit: scale-down !important;
  }
}
</style>
