<template>
  <div style="display: flex;">
    <div>
      <div v-show="checkPagePriv(pagePriv.privs, '采图')">
        <el-button type="primary" class="btnClass" @click="btnGetPic" :disabled="doctorBtnDisabled('btnGetPic')"
          size="small">采图</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '导图')">
        <el-button type="primary" class="btnClass" @click="btnExpPic" :disabled="doctorBtnDisabled('btnExpPic')"
          size="small">导图</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '裁图')">
        <el-button type="primary" class="btnClass" @click="btnCutPic" :disabled="doctorBtnDisabled('btnCutPic')"
          size="small">裁图</el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs, '保存')">
        <el-button type="primary" class="btnClass" @click="btnSavePic" :disabled="doctorBtnDisabled('btnSavePic')"
          size="small">保存</el-button>
      </div>
    </div>
    <!--  -->
    <div :style="`overflow-x: scroll;width:${Math.floor((window.pageWidth - 200 - 110 - 15 - 4))}px;`">
      <div style="display: flex;">
        <div class="demo-image__preview" v-for="(item, index) in checkPictures" :key="item.id"
          style="display: inline-block; padding: 0 0 0 2px">
          <div style="
              position: relative;
              font-size: 24px;
              margin: -6px 0 0 55px;              
              height: 30px;
              z-index: 2;
            ">
            <el-tooltip content="删除该图" placement="bottom" effect="light">
              <i class="el-icon-close" @click="btnDelImage(index)" v-show="!doctorBtnDisabled('btnDelImage')"
                style="color: red; cursor: pointer"></i>
            </el-tooltip>
          </div>
          <div style="margin-top: -25px">
            <el-image style="width: 80px; height: 80px; border-radius: 5px" :src="imageFilePlus(item.pictureFilename)"
              :preview-src-list="previewSrcList(checkPictures, item)">
            </el-image>
          </div>
          <div style="display: flex">
            <div style="margin: -6px 0 0 1px">
              <el-checkbox v-model="item.isPrintTrans" @change="btnSavePic"
                :disabled="doctorBtnDisabled('btnSavePic')"></el-checkbox>
            </div>
            <div style="font-size: 12px; margin: -2px 0 0 1px">打印</div>
            <div style="font-size: 15px; margin: -5px 0 0 2px">
              <el-tooltip content="保存后，图片将按序号从小到大排序" placement="bottom" effect="light">
                <input placeholder="排序" v-model="item.displayOrder" @onkeyup="validateInteger(e, index)"
                  style="width: 30px" :disabled="doctorBtnDisabled('btnSavePic')" />
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="图片上传" :visible.sync="dialogCheckPictureUpload" :close-on-click-modal="false" width="800px"
      @close="getCheckPictures(doctorCheck.RegisterCheckId)">
      <CheckPictureUpload :registerCheckId="doctorCheck.RegisterCheckId" :uploadSeq="uploadSeq"
        :closePicUpload="closePicUpload" />
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { Loading } from "element-ui";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv, checkPagePriv, deepCopy, arrayExistObj } from "../../utlis/proFunc";
import CheckPictureUpload from "./CheckPictureUpload.vue";

export default {
  components: {
    CheckPictureUpload,
  },
  props: ["doctorBtnDisabled"],
  data() {
    return {
      sysConfig: {}, //
      pagePriv: {
        routeUrlorPageName: 'doctorCheck', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },
      checkPictures: [
        // {
        //   id: "1",
        //   registerCheckId: "registerCheckId",
        //   isPrint: "Y",
        //   isPrintTrans: true,
        //   pictureFilename:
        //     "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
        // },
        // {
        //   id: "2",
        //   registerCheckId: "registerCheckId",
        //   isPrint: "Y",
        //   isPrintTrans: true,
        //   pictureFilename:
        //     "https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg",
        // },
      ],
      //图片上传
      dialogCheckPictureUpload: false,
      uploadSeq: 0, //第几次点图片上传，每点一次清空前次所选图片
    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))
    this.sysConfig = JSON.parse(window.sessionStorage.getItem('sysConfig'))
    console.log('this.sysConfig checkPictures', this.sysConfig)
  },

  //挂载完成
  mounted() {
    this.getCheckPictures(this.dataTransOpts.tableS.register_check.id);
  },

  computed: {
    ...mapState([
      "window",
      "dict",
      "dataTransOpts",
      "doctorCheck",
      "patientRegister",
      "customerOrg",
    ]),
    lmoment(date, forMat) {
      return moment(new Date(date)).format(forMat);
    },
  },
  methods: {
    checkPagePriv,
    // 根据checkId获取图片列表信息
    getCheckPictures(registerCheckId) {
      this.checkPictures = [];
      if (!registerCheckId) {
        return;
      }
      // {
      //   "registerCheckId": "3a0f6a3c-88a5-d5f7-d59b-ef3b3807490b",
      //   "pictureFilename": "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
      //   "isPrint": "N",
      //   "displayOrder": 1,
      //   "creatorName": "admin",
      //   "lastModifierName": "admin",
      //   "lastModificationTime": "2023-12-15T15:24:08",
      //   "lastModifierId": "3a0c4180-107c-0c89-b25b-0bd34666dcec",
      //   "creationTime": "2023-12-15T15:24:06",
      //   "creatorId": "3a0c4180-107c-0c89-b25b-0bd34666dcec",
      //   "id": "3a0f6a3c-88a5-d5f7-d59b-ef3b38074901"
      // }
      getapi(
        `/api/app/registercheckpicture/getregistercheckpictureinregistercheckid?RegisterCheckId=${registerCheckId}`
      ).then((res) => {
        if (res.code > -1) {
          this.checkPictures = res.data
          this.checkPictures.forEach(e => {
            e.isPrintTrans = e.isPrint == "Y" ? true : false
          });
        }
      });
    },

    // 生成 图片预览列表
    previewSrcList(oriList, curImag) {
      let srcList = []
      let image = curImag.pictureFilename.indexOf('http') > -1
        ? curImag.pictureFilename
        : this.sysConfig.apiurl + curImag.pictureFilename;
      srcList.push(image)
      let lfind = arrayExistObj(oriList, 'id', curImag.id)
      if (lfind > -1) {
        for (let i = lfind + 1; i < oriList.length; i++) {
          let e = oriList[i];
          image = this.imageFilePlus(e.pictureFilename)
          srcList.push(image)
        }
        for (let index = 0; index < lfind; index++) {
          let e = oriList[index];
          image = this.imageFilePlus(e.pictureFilename)
          srcList.push(image)
        }
      }
      return srcList
    },

    // 图片文件补全路径
    imageFilePlus(fileName) {
      if (fileName.indexOf('base64') > -1 || fileName.indexOf('http') > -1) {
        return fileName
      } else {
        return this.sysConfig.apiurl + fileName
      }
    },

    // 采图
    btnGetPic() {
      if (!this.doctorCheck.RegisterCheckId) {
        this.$message.warning({ showClose: true, message: "未选中组合项目！" });
        return;
      }
      if (!this.$peisAPI) {
        this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
        return
      }

      let toOutShell = {
        barCode: this.doctorCheck.checkRequestNo,
        patientName: this.dataTransOpts.tableS.patient_register.patientName,
        sexName: this.dataTransOpts.tableS.patient_register.sexName,
        age: (this.dataTransOpts.tableS.patient_register.age || '') + '',
        asbitemName: this.doctorCheck.asbitemName
      }
      // console.log('this.$peisAPI.imageAcquisition', JSON.stringify(toOutShell))

      let loading = Loading.service({
        lock: true,
        text: "正在加载中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0)",
        customClass: "boxStyle"
      });

      this.$peisAPI.imageAcquisition(JSON.stringify(toOutShell))
        .then(async (res) => {
          let lres = JSON.parse(res)
          // console.log('this.$peisAPI.imageAcquisition',lres)
          if (lres.code > -1) {
            for (let i = 0; i < lres.data.length; i++) {
              let item = lres.data[i];

              // FilePath:
              // Image
              // ImageFormat

              let baseHead = 'data:image/jpeg;base64,'
              switch (item.ImageFormat) {
                case 'png':
                case 'bmp':
                  baseHead = `data:image/${item.ImageFormat};base64,`
                  break;
                default:
                  break;
              }
              this.checkPictures.push({ pictureFilename: baseHead + item.Image })
              let fileName = item.FilePath
              let dotIndex = fileName.lastIndexOf('\\');
              if (dotIndex > -1) fileName = fileName.substring(dotIndex, fileName.length);

              let body = {
                registerCheckId: this.dataTransOpts.tableS.register_check.id,
                pictureBaseStrs: [{
                  fileName,
                  localPathName: item.FilePath,
                  pictureBaseStr: baseHead + item.Image
                }]
              }
              try {
                await postapi('/api/app/RegisterCheckPicture/InstrumentMapping', body)
              } catch (error) {
                console.log('btnGetPic err',error)
              }
            }
            this.getCheckPictures(this.dataTransOpts.tableS.register_check.id)
          }
        }).catch(err => {
          this.$message.error(err)
        }).finally(() => {
          loading.close()
        });

    },

    //导图（上传图片）
    btnExpPic() {
      if (!this.doctorCheck.RegisterCheckId) {
        this.$message.warning({ showClose: true, message: "未选中组合项目！" });
        return;
      }
      this.uploadSeq++;
      this.dialogCheckPictureUpload = true;
    },

    // 裁图/修图/ dicom 查看图
    btnCutPic() {
      if (this.checkPictures.length == 0) {
        this.$message.warning({ showClose: true, message: "暂无可裁图片！" });
        return;
      }
      
      if (!this.$peisAPI) {
        this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
        return
      }
      let token = window.sessionStorage.getItem("token");
      let toOutShell = {
        images:this.checkPictures,
        token,        
      };
      this.$peisAPI.imageCut(JSON.stringify(toOutShell))
      .then(res => {
        let lres = JSON.parse(res)
        if (lres.code > -1) {
          this.getCheckPictures(this.dataTransOpts.tableS.register_check.id);
        }else{
          console.log('裁图失败',lres.message)
        }
      })
      .catch(err => {
        console.log('裁图失败',err)
      })

    },

    //关闭上传图片窗口
    closePicUpload() {
      this.dialogCheckPictureUpload = false;
    },

    btnSavePic() {
      if (!this.doctorCheck.RegisterCheckId) {
        this.$message.warning({ showClose: true, message: "未选中组合项目！" });
        return;
      }

      let body = [];
      // [
      //   {
      //     "registerCheckPictureId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",  // 新增无需传此值
      //     "registerCheckId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //     "pictureFilename": "string",
      //     "isPrint": "string",
      //     "displayOrder": 0
      //   }
      // ]
      if (this.checkPictures.length == 0) {
        this.$message.warning({ showClose: true, message: "没有可保存的图片数据！" });
        return;
      }

      let checkPictures = deepCopy(this.checkPictures);
      checkPictures.sort((a, b) => {
        let seq1 = 0;
        let seq2 = 0;
        try {
          seq1 = parseInt(a.displayOrder);
        } catch (error) {
          seq1 = 0;
        }
        try {
          seq2 = parseInt(b.displayOrder);
        } catch (error) {
          seq2 = 0;
        }
        return seq1 - seq2;
      });

      checkPictures.forEach((e) => {
        let item = {
          registerCheckId: e.registerCheckId,
          pictureFilename: e.pictureFilename,
        };
        if (e.id) item.registerCheckPictureId = e.id;
        if (e.isPrintTrans) {
          item.isPrint = "Y";
        } else {
          item.isPrint = "N";
        }
        body.push(item);
      });

      postapi("/api/app/registercheckpicture/UpdateRegisterCheckPictureStatusMany", body)
        .then((res) => {
          if (res.code > -1) {
            this.getCheckPictures(checkPictures[0].registerCheckId);
          }
        });
    },

    // 删除图片
    btnDelImage(index) {
      let body = [this.checkPictures[index].id];
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      })
        .then(() => {
          return postapi(`/api/app/registercheckpicture/deleteregistercheckpicturemany`, body);
        })
        .then((res) => {
          if (res && res.code > -1) {
            this.checkPictures.splice(index, 1);
          }
        })
        .catch((err) => {
          if (err == "cancel") {
            this.$message.info({ showClose: true, message: "已取消" });
          }
        });
    },

    validateInteger(e, index) {
      var regex = /^[0-9]*$/;
      console.log(e, index);
      if (!regex.test(e.value)) {
        // 如果输入不满足整数条件，则清除输入框内容
        e.value = "";
      }
    },
  },

  //监听事件
  watch: {
    //检查项目未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.register_check_item.M": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 检查图片 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.dataTransOpts.tableS.register_check.id}`);
        if (newVal != oldVal) this.getCheckPictures(this.dataTransOpts.tableS.register_check.id);
      }
    },

  },
};
</script>
<style scoped>
.query {
  margin-left: 10px;
  margin-right: 2px;
  padding: 1px 1px;
}

.btnClass {
  margin: 2px 2px 0;
  height: 26px;
  min-width: 40px;
  padding: 5px 5px;
  /*原始 默认值 10px 10px */
}

/* 强制出现滚动条 */
::-webkit-scrollbar {
  height: 0.5rem;
}

::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 0.25rem;
}
</style>
