<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="btnSavePic" :disabled="doctorBtnDisabled('btnSavePic')"
          size="small">保存</el-button>
      </div>
      <el-dropdown v-show="checkPagePriv(pagePriv.privs, '导图')" :disabled="doctorBtnDisabled('btnExpPic')">
        <span class="el-dropdown-link" style="color: #222531; font-weight: 700">
          <el-button type="primary" class="btnClass" :disabled="doctorBtnDisabled('btnExpPic')">更多</el-button>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-show="checkPagePriv(pagePriv.privs, 'Dcm')" @click.native="btnBrowseDcm"
            :disabled="doctorBtnDisabled('btnBrowseDcm')">Dcm</el-dropdown-item>
          <el-dropdown-item v-show="checkPagePriv(pagePriv.privs, '裁图')" @click.native="btnCutPic"
            :disabled="doctorBtnDisabled('btnCutPic')">裁剪图片</el-dropdown-item>
          <el-dropdown-item v-show="checkPagePriv(pagePriv.privs, '清理pacs结果')" @click.native="btnClean"
            :disabled="doctorBtnDisabled('btnClean')">清理pacs结果</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <!--  -->
    <div :style="`overflow-x: scroll;width:${Math.floor((window.pageWidth - 200 - 110 - 15 - 4))}px;`"
      @contextmenu.prevent="onContextmenu" ref="DivPic">
      <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 v-if="false"  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)"
              :data-imageSeq="index" :preview-src-list="previewSrcList(checkPictures, item)">
            </el-image>
          </div>
          <div style="display: flex">
            <div style="margin: -6px 2px 0 1px">
              <el-tooltip content="是否打印" placement="bottom" effect="light">
                <el-checkbox v-model="item.isPrintTrans" @change="btnSavePic"
                  :readonly="doctorBtnDisabled('btnSavePic')"></el-checkbox>
              </el-tooltip>
            </div>
            <!--
            <div style="font-size: 12px; margin: -2px 0 0 1px">打印</div>
            -->
            <div style="font-size: 15px; margin: -5px 2px 0 2px">
              <el-tooltip content="保存后，图片将按序号从小到大排序" placement="bottom" effect="light">
                <input placeholder="排序" v-model="item.displayOrder" @onkeyup="validateInteger(e, index)"
                  style="width: 30px" :readonly="doctorBtnDisabled('btnSavePic')" />
              </el-tooltip>
            </div>
            <div v-if="false" style="margin: -6px 0 0 2px">
              <el-tooltip content="是否报告图片" placement="bottom" effect="light">
                <el-checkbox v-model="item.pictureFileType" @change="btnSavePic" true-label="1" false-label="0"
                  :disabled="doctorBtnDisabled('btnSavePic')"></el-checkbox>
              </el-tooltip>
            </div>
          </div>
        </div>
        <div>
          <table :width="`${getPicing ? 300:0}px;`"></table>
          <!--是否采图进行时，采图时自动滚到最右边-->
          <!--暴力滚动 element.scrollLeft = element.scrollWidth;-->
          <!--平滑滚动 element.scrollTo({ left: element.scrollWidth, behavior: 'smooth' });-->
        </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>

    <el-dialog title="Dcm查看" :visible.sync="dialogDcm" :close-on-click-modal="false" fullscreen @close="iframeSrc = ''">
      <div style="display: flex;">
        <div>
          <iframe :src="iframeSrc" :height="window.pageHeight - 85" :width="window.pageWidth - 260"></iframe>
        </div>
        <div style="width: 240px;margin-left: 2px;">
          <div style="margin-top: 5px;">
            <span style="color: #232748;">人员信息：</span>
            <div style="display: flex;">
              <span style="width: 80px;margin: 7px 0;">检查条码</span>
              <el-input ref="checkRequestNo" placeholder="检查条码" v-model="checkRequestNo" size="small" clearable
                @keyup.native.enter="onQueryByPacsNo(checkRequestNo)" @focus="onFocus" disabled />
            </div>
            <div style="display: flex;">
              <span style="width: 80px;margin: 7px 0;">姓名</span>
              <el-input v-model="patient_register.patientName" size="small" disabled />
            </div>
            <div style="display: flex;">
              <span style="width: 80px;margin: 7px 0;">性别</span>
              <el-input v-model="patient_register.sexName" size="small" disabled />
            </div>
            <div style="display: flex;">
              <span style="width: 80px;margin: 7px 0;">年龄</span>
              <el-input v-model="patient_register.age" size="small" disabled />
            </div>
          </div>


          <div style="margin-top: 5px;">
            <div>
              <span>检查结果：</span>
              <el-radio-group v-model="tabPosition">
                <el-radio :label="'top'">横排</el-radio>
                <el-radio :label="'left'">纵排</el-radio>
              </el-radio-group>
            </div>

            <el-tabs :tab-position="tabPosition" v-model="tabChoosed">
              <el-tab-pane v-for="(item, seq) in doctorCheck.checkItemList" :label="dispLabel(item.itemName)"
                :name="seq + ''" :key="seq">
                <el-input style="width: 100%;" type="textarea" v-model="item.result" placeholder="请输入检查结果"
                  :disabled="doctorBtnDisabled('save')"
                  :autosize="{ minRows: Math.floor((window.pageHeight - 550) / 24), maxRows: 18 }" />
                <div style="display: flex;justify-content: space-between;">
                  <div></div>
                  <div>
                    <el-tooltip :content="`给 ${item.itemName} 项目，赋默认结果`" placement="top">
                      <i class="el-icon-edit" @click="btnDefResult(seq)"
                        style="font-size: 18px;color: blue;cursor:pointer;margin-right: 10px;"></i>
                    </el-tooltip>
                    <el-tooltip :content="`清除 ${item.itemName} 项目的检查结果`" placement="top">
                      <i class="el-icon-delete" @click="btnClear(seq)"
                        style="font-size: 18px;color: red;cursor:pointer;margin-right: 10px;"></i>
                    </el-tooltip>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <div style="margin-top: 5px;">
            <span style="color: #232748;">检查结论：</span>
            <el-table row-key="id" :data="doctorCheck.checkSummaryList" size="samll" height="186" width="100%" border>
              <el-table-column width="30" align="center">
                <template slot-scope="scope">
                  <el-tag class="moveSummary" style="height:25px;padding:0 2px;cursor: move;background-color: #EEEEEE;">
                    <div style="width: 16px;">{{ scope.$index + 1 }}</div>
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="summary" label="小结">
                <template slot="header">
                  <div style="display: flex;justify-content:space-between;">
                    <div>小结</div>
                    <div></div>
                  </div>
                </template>
                <template slot-scope="scope">
                  <div style="display: flex;">
                    <el-input type="textarea" v-model="scope.row.summary" :autosize="{ minRows: 1, maxRows: 100 }"
                      placeholder="请输入小结">
                    </el-input>
                    <el-button type="danger" style="min-width:23px;padding:2px;" icon="el-icon-delete"
                      @click="delSum(scope.$index)" size="small"></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="display: flex;justify-content: space-between;margin-top: 10px;">
            <div></div>
            <div>
              <!--
          <el-button type="primary" @click="btnTest" class="commonbutton">测试</el-button>
            -->
              <el-button type="primary" @click="btnChooseBigtext" :disabled="doctorBtnDisabled('save')"
                class="commonbutton">选择描述</el-button>
              <el-button type="primary" @click="btnOkBigtext" :disabled="doctorBtnDisabled('save')"
                class="commonbutton">保存结果</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <!--Pacs结果录入模版-->
    <el-dialog :title="'Pacs结果录入模版 -- ' + doctorCheck.asbitemName" :visible.sync="dialogWin.PacsTemplate" width="880px"
      :close-on-click-modal="false">
      <PacsTemplate :refParams="pacsParams" :refFuncOther="handlePacsResult" />
    </el-dialog>

    <el-dialog title="裁图" :visible.sync="dialogWinCutPic" width="1300px" :close-on-click-modal="false">
      <PacsCutPic />
    </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 { hadoopGet, hadoopPost, hadoopPut, hadoopDel } from "../../api/hadoopApi"
import CheckPictureUpload from "./CheckPictureUpload.vue";
import PacsTemplate from "./PacsTemplate.vue";
import PacsCutPic from "./PacsCutPic.vue";

export default {
  components: {
    CheckPictureUpload, PacsTemplate, PacsCutPic
  },
  props: ["doctorBtnDisabled", "save","patient_register","refParams"],
  data() {
    return {
      sysConfig: {}, //
      pagePriv: {
        routeUrlorPageName: 'doctorCheck', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },

      checkRequestNo: '',
      dialogDcm: false,
      iframeSrc: '',
      pacsParams: {
        from: 'dcm',
        refresh: -1,
        row: {},
        index: 0,
        result: '',
        summary: ''
      },
      tabPosition: 'top',
      tabChoosed: "0",

      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, //第几次点图片上传，每点一次清空前次所选图片
      // 裁图
      dialogWinCutPic: false,
      cutPicParam: {},
      pictureFileType: '1',
      getPicing:false,  //是否采图中
    };
  },

  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() {
    // 监听来自 Electron 的调用    
    if (this.$peisAPI) {
      try {
        //热键--采集图像
        this.$peisAPI.onEventFromPictureHotKeyMain((data) => {
          this.acceptHotKeyData('add', data)
        });

        //热键--采集图像设为打印
        this.$peisAPI.onEventFromPictureAndPrintHotKeyMain((data) => {
          this.acceptHotKeyData('addPrint', data)
        });

        //热键--设为打印
        this.$peisAPI.onEventFromPicturePrintHotKeyMain(() => {
          this.acceptHotKeyData('print')
        });

        //热键--取消打印
        this.$peisAPI.onEventFromPictureCancelPrintHotKeyMain(() => {
          this.acceptHotKeyData('unPrint')
        });

        //删除图像
        this.$peisAPI.onEventFromPictureDeleteHotKeyMain(() => {
          this.acceptHotKeyData('delete')
        });
      } catch (error) {
        console.error(error)
      }

    }

    if (this.refParams.registerCheckId) {
      this.getCheckPictures(this.refParams.registerCheckId);
    }
  },

  computed: {
    ...mapState([
      "window",
      "dict",
      "dialogWin",
      "dataTransOpts",
      "doctorCheck"
    ]),
    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"
      // }      
      hadoopGet('pacsApi', `/api/app/registercheckpicture/getregistercheckpictureinregistercheckid?RegisterCheckId=${registerCheckId}`)
        // 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
            });

            // 标记采图中，让滚动条滑到最右边……
            if(this.getPicing) this.setGetPicing()
          }
        });
    },

    // 生成 图片预览列表
    previewSrcList(oriList, curImag) {
      let srcList = []
      let image = curImag.pictureFilename.indexOf('http') > -1
        ? curImag.pictureFilename
        : (this.sysConfig.pacsApi || this.sysConfig.apiurl) + curImag.pictureFilename;
      srcList.push(image + `?r=${Math.random()}`)
      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 + `?r=${Math.random()}`)
          srcList.push(image)
        }
        for (let index = 0; index < lfind; index++) {
          let e = oriList[index];
          image = this.imageFilePlus(e.pictureFilename + `?r=${Math.random()}`)
          srcList.push(image)
        }
      }
      return srcList
    },

    //删除小结
    delSum(index) {
      this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        this.doctorCheck.checkSummaryList.splice(index, 1);
      }).catch(err => {
        if (err == "cancel") {
          // this.$message.info("已取消删除");
          console.log('已取消删除')
        }
      });
    },

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

    // 标记采图中，让滚动条滑到最右边……
    setGetPicing(){      
      let obj = this.$refs['DivPic']
      console.log('obj',obj)
      this.$nextTick(() => {
        //obj.scrollTo({ left: obj.scrollWidth, behavior: 'smooth' })
        obj.scrollLeft = obj.scrollWidth
      })
    },

    // 采图
    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.patient_register.patientName,
        sexName: this.patient_register.sexName,
        age: (this.patient_register.age || '') + '',
        asbitemName: this.doctorCheck.checkRequestNo || 'temp'
      }
      // 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) {
            // 标记采图中，让滚动条滑到最右边……
            this.getPicing = true
            this.setGetPicing()
            
            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('\\');
              let pointIndex = fileName.lastIndexOf('.');
              if (dotIndex > -1) fileName = fileName.substring(dotIndex + 1, pointIndex || fileName.length);

              let body = {
                registerCheckId: this.refParams.registerCheckId,
                pictureBaseStrs: [{
                  fileName,
                  localPathName: item.FilePath,
                  pictureBaseStr: baseHead + item.Image,
                  isPrint: 'N'
                }],
                pictureFileType: '0' //采图暂定图0，上传暂定报告1 this.pictureFileType
              }
              try {
                //await postapi('/api/app/RegisterCheckPicture/InstrumentMapping', body)
                await hadoopPost('pacsApi', '/api/app/RegisterCheckPicture/InstrumentMapping', body)
              } catch (error) {
                console.log('btnGetPic err', error)
              }
            }
            this.getCheckPictures(this.refParams.registerCheckId)
          } else {
            console.log('this.$peisAPI.imageAcquisition', lres.message)
          }
        }).catch(err => {
          this.$message.error(err)
        }).finally(() => {
          loading.close()
        });

    },

    // 接收热键采图
    // windows.peisAPI.receive("acceptHotKeyData",() => {
    //   this.$message.success({showClose:true,message:'调用热键成功'})
    // }),
    acceptHotKeyData(oprType, data) {
      // 
      console.log('接收壳端热键采图参数 acceptHotKeyData', oprType, data)
      //this.$message.success({ showClose: true, message: '调用热键成功' })
      if (!this.refParams.registerCheckId) {
        console.log("没有选中检查项目")
        return
      }

      // 标记采图中，让滚动条滑到最右边……
      this.getPicing = true
      this.setGetPicing()

      // 设置图片打印或不打印
      if (oprType == 'print' || oprType == 'unPrint') {
        let count = this.checkPictures.length
        if (count == 0) return
        // 最后采图的记录
        let picRd = this.checkPictures[count - 1]
        if (!picRd.id) return

        if (oprType == 'print') {
          picRd.isPrintTrans = true
          picRd.isPrint = 'Y'
        } else {
          picRd.isPrintTrans = false
          picRd.isPrint = 'N'
        }
        let body = [{
          registerCheckId: picRd.registerCheckId,
          pictureFilename: picRd.pictureFilename,
          pictureFileType: picRd.pictureFileType,
          registerCheckPictureId: picRd.id,
          isPrintTrans: picRd.isPrintTrans,
          isPrint: picRd.isPrint
        }]

        postapi("/api/app/registercheckpicture/UpdateRegisterCheckPictureStatusMany", body)
          .then((res) => {
            if (res.code < 0) {
              console.log('热键更新图片打印标识失败：', res.message)
            } else {
              this.getCheckPictures(this.refParams.registerCheckId)
            }
          })
          .catch(err => {
            console.log('热键更新图片打印标识失败：', err)
          });

      } else if (oprType == 'delete') {
        let count = this.checkPictures.length
        if (count == 0) return
        // 最后采图的记录
        let picRd = this.checkPictures[count - 1]
        if (!picRd.id) return

        postapi(`/api/app/registercheckpicture/deleteregistercheckpicturemany`, [picRd.id])
          .then(res => {
            if (res.code > -1) {
              this.checkPictures.splice(count - 1, 1)
              this.getCheckPictures(this.refParams.registerCheckId)
            } else {
              console.log("热键删除图片打印标识失败：", res.message)
            }
          })
          .catch(err => {
            console.log("热键删除图片打印标识失败：", err)
          })

      } else {
        try {
          let item = data.data[0]
          let baseHead = 'data:image/jpeg;base64,'
          switch (item.ImageFormat) {
            case 'png':
            case 'bmp':
              baseHead = `data:image/${item.ImageFormat};base64,`
              break;
            default:
              break;
          }
          let isPrintTrans = false
          if (oprType == 'addPrint') {
            item.isPrint = 'Y'
            isPrintTrans = true
          } else {
            item.isPrint = 'N'
          }
          // item.isPrintTrans 是否打印

          this.checkPictures.push({ pictureFilename: baseHead + item.Image, isPrintTrans })

          let fileName = item.FilePath
          let dotIndex = fileName.lastIndexOf('\\');
          let pointIndex = fileName.lastIndexOf('.');
          if (dotIndex > -1) fileName = Date.now() + fileName.substring(dotIndex + 1, pointIndex || fileName.length);

          let body = {
            registerCheckId: this.refParams.registerCheckId,
            pictureBaseStrs: [{
              fileName,
              localPathName: item.FilePath,
              pictureBaseStr: baseHead + item.Image,
              isPrint: item.isPrint
            }],
            pictureFileType: '0' //采图暂定图0，上传暂定报告1 this.pictureFileType
          }

          hadoopPost('pacsApi', '/api/app/RegisterCheckPicture/InstrumentMapping', body)
            .then(() => {
              this.getCheckPictures(this.refParams.registerCheckId)
            })
            .catch(err => {
              console.log('热键采图失败', err)
            })

        } catch (error) {
          console.log('热键采图失败', error)
        }
      }
    },


    // 显示tab标签名称，过长处理
    dispLabel(itemName) {
      return itemName.length > 5 ? (itemName.substring(0, 4) + "…") : itemName
    },

    // 清除结果
    btnClear(seq) {
      if (this.doctorBtnDisabled('save')) {
        this.$message.warning({ showClose: true, message: "已保存，不可操作！" })
        return
      }
      this.doctorCheck.checkItemList[seq].result = ''
    },

    // 默认结果
    btnDefResult(seq) {
      if (this.doctorBtnDisabled('save')) {
        this.$message.warning({ showClose: true, message: "已保存，不可操作！" })
        return
      }
      this.doctorCheck.checkItemList[seq].result = this.doctorCheck.checkItemList[seq].defaultResult
    },

    // 浏览Dcm文件
    btnBrowseDcm() {
      this.checkRequestNo = this.doctorCheck.checkRequestNo
      this.pacsParams.result = this.doctorCheck.checkItemList[0].result
      let summary = ''
      this.doctorCheck.checkSummaryList.forEach(e => {
        summary += e.summary
      });
      this.pacsParams.summary = summary
      this.pacsParams.row = deepCopy(this.doctorCheck.checkItemList[0])
      this.pacsParams.index = 0
      this.pacsParams.refresh++

      // console.log('pacsParams', this.pacsParams)
      let token = window.sessionStorage.getItem('token')
      this.iframeSrc = `${this.sysConfig.dcmViewers}/?mrn=${this.doctorCheck.checkRequestNo}&token=${token}&pacsapi=${this.sysConfig.pacsApiHttps}`
      // this.iframeSrc = `${this.sysConfig.dcmViewers}/viewer?StudyInstanceUIDs=1.3.12.2.1107.5.1.4.79623.30000024091203062645300000022`
      this.tabPosition = this.doctorCheck.checkItemList.length > 2 ? 'left' : 'top'
      this.tabChoosed = "0"
      this.dialogDcm = true

    },

    // 选择描述与结论
    btnChooseBigtext() {
      // console.log('this.pacsParams', this.pacsParams)
      this.pacsParams.index = parseInt(this.tabChoosed)
      this.pacsParams.refresh++
      this.dialogWin.PacsTemplate = true
    },

    // 确定描述与结论
    btnOkBigtext() {
      console.log('this.pacsParams', this.pacsParams)
      // this.doctorCheck.checkItemList[0].result = this.pacsParams.result
      /*
      this.doctorCheck.checkSummaryList = [{
        id: Math.random(),
        registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
        summary: this.pacsParams.summary,
        summaryFlag: 'N',
      }]
      */
      if (this.doctorCheck.checkSummaryList.length == 0) {
        this.$message.warning({ showClose: true, message: "请填写检查结论" })
        return
      }
      this.save()

      this.dialogDcm = false
    },

    // 处理 pacs 结果录入的情况
    handlePacsResult(row, index, pacsResult) {
      Object.assign(this.pacsParams, pacsResult)
    },

    // 浏览Dcm文件
    btnBrowseDcmBak() {
      if (!this.doctorCheck.RegisterCheckId) {
        this.$message.warning({ showClose: true, message: "未选中组合项目！" });
        return;
      }

      // 创建一个新的 <a> 元素
      let a = document.createElement('a');

      // 设置 href 属性为要跳转的 URL
      a.href = `${this.sysConfig.dcmViewers}/?mrn=24071610696`;

      //（可选）设置 target 属性，比如在新窗口打开
      a.target = '_blank';

      //（可选）防止浏览器将链接添加到历史记录
      a.rel = 'noopener noreferrer';

      // 将新创建的 <a> 元素添加到 DOM 中
      // 注意：这一步是可选的，如果你只想模拟点击而不想在页面上显示 <a> 元素，可以省略这一步
      // document.body.appendChild(a);

      // 模拟点击 <a> 元素
      a.click();

      //（可选）移除刚才添加到 DOM 中的 <a> 元素
      // 如果你选择了将 <a> 元素添加到 DOM 中，现在可以移除它
      // document.body.removeChild(a);
    },

    btnBrowseDcmBak2() {
      let userName = "peis", key = "peis@123"
      // let encodedAuthstring = btoa(this.stringToAscIIBytes(`${userName}:${key}`));
      let encodedAuthstring = this.toBase64FromUtf8(`${userName}:${key}`);
      console.log('encodedAuthstring', encodedAuthstring)
      const url = 'http://192.168.4.161:8042/ohif/viewer?url=../studies/dcdc7b20-fe11f38d-f5357ad7-139cd2cd-c0bd3701/ohif-dicom-json';
      const Authorization = 'Basic ' + encodedAuthstring;

      fetch(url, {
        headers: {
          'Authorization': Authorization
        }
      })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
    },

    toBase64FromUtf8(str) {
      // 使用 TextEncoder 将字符串转换为UTF-8字节序列
      const encoder = new TextEncoder();
      const bytes = encoder.encode(str);

      // 将字节序列转换为二进制字符串
      let binaryString = '';
      for (let byte of bytes) {
        binaryString += String.fromCharCode(byte);
      }

      // 使用 btoa 将二进制字符串转换为Base64
      return btoa(binaryString);
    },

    //导图（上传图片）
    btnExpPic() {
      if (!this.doctorCheck.RegisterCheckId) {
        this.$message.warning({ showClose: true, message: "未选中组合项目！" });
        return;
      }
      this.uploadSeq++;
      this.dialogCheckPictureUpload = true;
    },
    btnClean() {
      if (!this.doctorCheck.RegisterCheckId) {
        this.$message.warning({ showClose: true, message: "未选中组合项目！" });
        return;
      }
      postapi("/api/app/PacsBusiness/DeletePacsCheckDicomDataByRegisterCheckId", {
        registerCheckId: this.doctorCheck.RegisterCheckId
      })
        .then((res) => {
          if (res.code > -1) {

          }
        });
    },

    // 裁图/修图/
    btnCutPicBak() {

      // 跨域了
      this.dialogWinCutPic = true
      this.$refs.imgCutterModal.handleOpen({
        name: "1.png",
        src: "http://192.168.2.74:9529/PacsCheckPictureImg/pacs/2024/8/29//3a141f59-cf4c-5e34-966d-aec0a0eea94c//2408010001_0005.jpg.jpg",
      });

    },

    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 = {
        asbitemName: this.doctorCheck.asbitemName,
        images: this.checkPictures,
        token,
      };
      this.$peisAPI.imageCut(JSON.stringify(toOutShell))
        .then(res => {
          let lres = JSON.parse(res)
          if (lres.code > -1) {
            this.getCheckPictures(this.refParams.registerCheckId);
          } 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,
          pictureFileType: e.pictureFileType
        };
        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.delImageBatch(body)
    },

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

    // 右击剪切图片
    rCutPic(start, count) {
      this.dataTransOpts.doctorCutPics = this.checkPictures.splice(start, count)
    },

    // 右击粘贴图片
    rCopyPic(imageSeq) {
      let body = {
        registerCheckPictureIds: [],
        registerCheckId: this.refParams.registerCheckId
      }
      this.dataTransOpts.doctorCutPics.forEach(e => {
        body.registerCheckPictureIds.push(e.id)
        e.registerCheckId = this.refParams.registerCheckId
      });

      postapi('/api/app/RegisterCheckPicture/BatchUpdateRegisterCheckIdByRegisterCheckPictureId', body)
        .then(res => {
          if (res.code > -1) {
            this.$message.success({ showClose: true, message: '操作成功！' })
            if (imageSeq == -1) {
              this.checkPictures = deepCopy(this.dataTransOpts.doctorCutPics)
            } else {
              this.checkPictures.splice(imageSeq, 0, deepCopy(this.dataTransOpts.doctorCutPics))
            }
            this.dataTransOpts.doctorCutPics = []  //清除剪切的缓存
          }
        })

    },

    // 右击菜单
    onContextmenu(event) {
      if (this.doctorBtnDisabled('btnSavePic')) {
        return false
      }
      //console.log('event',event.target,event.target.getAttribute('data-imageSeq'))
      let imageSeqStr = '-1'
      try {
        imageSeqStr = event.target.getAttribute('data-imageSeq').toString()
      } catch (error) {

      }
      //console.log('imageSeqStr',imageSeqStr)
      let imageSeq = Number(imageSeqStr)
      //console.log('imageSeq',imageSeq)
      //菜单项
      let items = [];
      let picNum = this.checkPictures.length
      if (imageSeq >= 0 && picNum > 1) {
        items.push({
          label: "剪切当前图片",
          onClick: () => {
            this.rCutPic(imageSeq, 1)
          },
        })
        if (imageSeq == 0) {
          items.push({
            label: "剪切当前图片后面的图片",
            onClick: () => {
              this.rCutPic(imageSeq + 1, picNum - 1 - imageSeq)
            },
          })
        } else if (imageSeq == picNum - 1) {
          items.push({
            label: "剪切当前图片前面的图片",
            onClick: () => {
              this.rCutPic(0, imageSeq)
            },
          })
        } else {
          items.push({
            label: "剪切当前图片后面的图片",
            onClick: () => {
              this.rCutPic(imageSeq + 1, picNum - 1 - imageSeq)
            },
          })
          items.push({
            label: "剪切当前图片前面的图片",
            onClick: () => {
              this.rCutPic(0, imageSeq)
            },
          })
        }
      }
      if (picNum > 0) {
        items.push({
          label: "剪切所有图片",
          onClick: () => {
            this.rCutPic(0, this.checkPictures.length)
          },
        })
      }

      if (this.dataTransOpts.doctorCutPics.length > 0) {
        items.splice(0, 0, {
          label: "粘贴图片",
          onClick: () => {
            this.rCopyPic(imageSeq)
          },
        })
        if (items.length > 1) {
          items.splice(1, 0, {
            label: "----------------"
          })
        }
      }

      // 删除图片
      if (picNum > 0) {
        items.push({
          label: "----------------"
        })
        if (imageSeq >= 0) {
          items.push({
            label: "删除当前图片",
            onClick: () => {
              this.delImageBatch([this.checkPictures[imageSeq].id])
            },
          })
        }
        items.push({
          label: "删除所有图片",
          onClick: () => {
            let body = []
            this.checkPictures.forEach(e => {
              body.push(e.id)
            });
            this.delImageBatch(body)
          },
        })
      }

      // items.push({
      //   label: "一级菜单",
      //   children: [
      //     { label: "修改姓名", onClick: () => { this.fnUpBaseInfo(row, 'patientName'); } }
      //   ],
      //   onClick: () => { //菜单事件 }
      // })

      // 显示明细历次结果


      this.$contextmenu({
        items,
        event,
        x: event.clientX,
        y: event.clientY,
        customClass: "custom-class",
        zIndex: 3,
        minWidth: 80,
      });

      return false;

    },

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

    // 通过检查条码查询相关数据
    onQueryByPacsNo(checkRequestNo) {
      this.checkRequestNo = checkRequestNo
      this.$refs['checkRequestNo'].select()
      postapi('/api/app/PacsBusiness/GetPatientRegisterWithCheckResultByCheckRequestNo', { checkRequestNo })
        .then(res => {
          if (res.code > -1) {
            // 人员信息
            this.patient_register = res.data.patientRegisterDetail

            // 组合项目
            this.doctorCheck.RegisterCheckList = [res.data.registerCheckDetail]

            // 组合项目明细
            this.doctorCheck.checkItemList = res.data.registerCheckItemDetails

            // 小结与建议
            this.doctorCheck.checkSummaryList = res.data.registerCheckSummaryDetails
            this.doctorCheck.checkSuggestionList = res.data.registerCheckSuggestionDetails

            // 上次结果
            this.doctorCheck.preResult = res.data.lastTimeAsbitemResultDetail

            // 检查情况
            this.doctorCheck.RegisterCheckEdit = res.data.registerCheckDetail

            // 图片
            this.checkPictures = res.data.registerCheckPictureDetails
            this.checkPictures.forEach(e => {
              e.isPrintTrans = e.isPrint == "Y" ? true : false
            });

            this.iframeSrc = ''
            this.btnBrowseDcm()
          }
        })

    },

    onFocus(event) {
      this.$refs['checkRequestNo'].select()
    }
  },

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

  },
};
</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>
