<template>
  <div>
    <div class="contenttitle">
      体检 /<span class="contenttitleBold">pacs看图</span>
    </div>
    <div style="display: flex;">
      <div v-if="LocalConfig.doctorCheck.isHaveExternal == 'N'">
        <div v-if="pacsType == 'image'" class="image__preview"
          :style="`overflow-y: auto;width: ${window.pageWidth - 330}px;height: ${window.pageHeight - 105}px;`">
          <div v-for="item in checkPictures" :key="item.id" style="margin-bottom: 5px;">
            <el-image :src="imageFilePlus(item.pictureFilename)" :preview-src-list="previewSrcList(checkPictures, item)"
              :style="`overflow-y: auto;max-width: ${window.pageWidth - 330}px;height: auto;`"></el-image>
            <div style="display: flex;justify-content: space-between;margin-top: -26px;">
              <div></div>
              <div style="display: flex;width: 60px;">
                <div>
                  <el-checkbox v-model="item.isPrint" true-label="Y" false-label="N" @change="btnSavePic"></el-checkbox>
                </div>
                <div style="font-size: 14px;font-weight: 700;color: #FF0000;  margin: 2px 0 0 2px;z-index: 2;">打印</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <iframe :src="iframeSrc" :height="window.pageHeight - 105" :width="window.pageWidth - 330"></iframe>
        </div>
      </div>

      <div :style="`display:${LocalConfig.doctorCheck.isHaveExternal == 'Y' ? 'flex' : 'block'};`">
        <!-- 查询条件 -->
        <div
          :style="`display: block;${LocalConfig.doctorCheck.isHaveExternal == 'Y' ? ('width: ' + leftWidth + 'px;') : ('margin-left: 2px;width: ' + rightWidth + 'px;')}`">       
          <div style="display: flex;">
            <el-select v-model="query.dateType" placeholder="请选择" style="width: 80px" size="small">
              <el-option label="检查日期" value="0" />
              <el-option label="上传日期" value="1" />
            </el-select>

            <el-date-picker v-model="query.startDate" type="date" placeholder="起始日期" size="small" style="width:90px;"
              value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
            <span class="spanClass">至</span>
            <el-date-picker v-model="query.endDate" type="date" placeholder="截止日期" size="small" style="width:90px;"
              value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
            <el-button icon="el-icon-search" @click="btnQuery" type="primary"
              style="font-size: 20px;height:32px;min-width:30px; padding: 5px;z-index: 2;" size="small"></el-button>
          </div>
          <div style="font-size: 14px;">
            <span>体检单位：</span>
            <el-select v-model="query.customerOrgIds" placeholder="请选择体检单位" :filter-method="filterMethod" default-first-option
              clearable filterable style="margin-left: 10px;width:225px;max-height: 32px;" size="small" multiple collapse-tags>
              <el-option v-for="item in customerOrg" :key="item.id" :label="item.displayName" :value="item.id">
                {{ item.displayName }}
              </el-option>
            </el-select>
          </div>
          <div @contextmenu.prevent="onContextmenu">
            <el-table :data="pacsList" style="width: 100%;" border highlight-current-row @row-click="rowClick"
              :height="tableHeight" :row-style="{ height: '28px' }" ref="pacsList" @cell-contextmenu="onCellRightClick">
              <el-table-column prop="patientName" label="姓名" min-width="80" align="center" />
              <el-table-column prop="checkRequestNo" label="检查条码" min-width="120" align="center" />
              <el-table-column prop="asbitemName" label="检查项目" show-overflow-tooltip min-width="200" />
              <el-table-column prop="pacsCheckDate" label="检查日期" min-width="90" align="center">
                <template slot-scope="scope">
                  {{ moment(scope.row.pacsCheckDate).format("yyyy-MM-DD") }}
                </template>
              </el-table-column>
              <el-table-column prop="pacsUploadDate" label="上传日期" min-width="90" align="center">
                <template slot-scope="scope">
                  {{ moment(scope.row.pacsUploadDate).format("yyyy-MM-DD") }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 检查结果 -->
        <div :style="`display: block;margin-left: 2px;width:${rightWidth}px;`">
          <div v-if="false" 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="dataTransOpts.tableS.patient_register.patientName" size="small" disabled />
            </div>
            <div style="display: flex;">
              <span style="width: 80px;margin: 7px 0;">性别</span>
              <el-input v-model="dataTransOpts.tableS.patient_register.sexName" size="small" disabled />
            </div>
            <div style="display: flex;">
              <span style="width: 80px;margin: 7px 0;">年龄</span>
              <el-input v-model="dataTransOpts.tableS.patient_register.age" size="small" disabled />
            </div>
          </div>

          <div>
            <div style="margin-top: 5px;">
              <span style="color: #232748;">检查结果：</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: 98%;font-family: 'Microsoft YaHei';font-size: ${LocalConfig.doctorCheck.pacsDescFontSize}px;`" type="textarea"
                    v-model="item.result" placeholder="请输入检查结果"
                    :autosize="{ minRows: LocalConfig.doctorCheck.pacsDescLines, maxRows: LocalConfig.doctorCheck.pacsDescLines }" />
                <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-input v-if="doctorCheck.checkItemList.length == 0" :style="`margin-bottom: 20px;width: 99%;font-family: 'Microsoft YaHei';font-size: ${LocalConfig.doctorCheck.pacsDescFontSize}px;`" type="textarea"
                    placeholder="请输入检查结果"
                    :autosize="{ minRows: LocalConfig.doctorCheck.pacsDescLines, maxRows: LocalConfig.doctorCheck.pacsDescLines }" />
            </el-tabs>
          </div>
          <div style="margin-top: -15px;">
            <span style="color: #232748;">检查结论：</span>
            <el-table row-key="id" :data="doctorCheck.checkSummaryList" size="samll" :height="resultHeight" 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;font-family: 'Microsoft YaHei';">
                    <el-input type="textarea" v-model="scope.row.summary" :autosize="{ minRows: 1, maxRows: 100 }"
                      placeholder="请输入小结" :style="`font-size: ${LocalConfig.doctorCheck.pacsDescFontSize}px;`">
                    </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>
              <el-checkbox v-model="autoNext" true-label="Y" false-label="N" size="small">自动下一条</el-checkbox>
            </div>
            <div>
              <!--
            <el-button type="primary" @click="btnTest" class="commonbutton">测试</el-button>
              -->
              <el-button type="primary" @click="btnChooseBigtext" style="width: 90px;" size="small" class="commonbutton"
                :disabled="dataTransOpts.tableS.patient_register.completeFlag == '3'">选择描述</el-button>
              <el-button type="primary" @click="btnOkBigtext" style="width: 90px;" size="small" class="commonbutton"
                :disabled="dataTransOpts.tableS.patient_register.completeFlag == '3'">保存结果</el-button>

            </div>
          </div>

        </div>
      </div>
    </div>

    <!--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>
  </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";

export default {
  components: {
    CheckPictureUpload, PacsTemplate
  },
  data() {
    return { 
      rightWidth: 430, // 右侧宽度     
      sysConfig: {}, //
      pagePriv: {
        routeUrlorPageName: 'doctorCheck', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },
      query: {
        patientName: "",
        checkRequestNo: "",
        dateType: "1",
        startDate: "",
        endDate: "",
        maxResultCount: 1000,
        skipCount: 0,
        customerOrgIds:[]
      },

      rClickRow: null, //右击的行
      rClickColumn: null, //右击的列（预留）

      autoNext: 'Y', // 保存后自动下一条
      doctorCheckEdit: {},
      pacsList: [],
      curPacs: {},
      checkRequestNo: '',
      dialogDcm: false,
      iframeSrc: '',
      pacsParams: {
        from: 'dcm',
        refresh: -1,
        row: {},
        index: 0,
        result: '',
        summary: ''
      },
      pacsType: 'dcm', // image/dcm
      checkPictures: [],

      tabChoosed: "0",
      tabPosition: "top", // 多个明细检查排列方式
      customerOrg:[], // 单位

      LocalConfig: {
        doctorCheck: { // 医生诊台
          scheduledAet: '',  //scheduledAet   
          // deviceId: '', // 设备ID      
          pacsDescLines: '5',
          pacsDescLineH: '18',
          isHaveExternal: 'N',
          pacsDescFontSize: 14, //描述控件的字体大小
        }
      },
      pacs_interface_barcode_type:'0', //pacs系统条码类型：0:检查条码，1:人员条码
    };
  },

  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'))
    let LocalConfig = JSON.parse(window.localStorage.getItem("LocalConfig") || null)
   
    if (LocalConfig?.doctorCheck?.pacsType) this.pacsType = LocalConfig.doctorCheck.pacsType
    if (LocalConfig?.doctorCheck?.deviceId) {
      this.pacsReq.deviceId = LocalConfig.doctorCheck.deviceId
      this.query.deviceId = LocalConfig.doctorCheck.deviceId
    }
    if (LocalConfig?.doctorCheck?.scheduledAet) this.pacsReq.scheduledAet = LocalConfig.doctorCheck.scheduledAet
    if (LocalConfig?.doctorCheck?.pacsDescLines) this.LocalConfig.doctorCheck.pacsDescLines = LocalConfig.doctorCheck.pacsDescLines
    if (LocalConfig?.doctorCheck?.pacsDescLineH) this.LocalConfig.doctorCheck.pacsDescLineH = LocalConfig.doctorCheck.pacsDescLineH
    if (LocalConfig?.doctorCheck?.isHaveExternal) this.LocalConfig.doctorCheck.isHaveExternal = LocalConfig.doctorCheck.isHaveExternal
    if (LocalConfig?.doctorCheck?.pacsDescFontSize) this.LocalConfig.doctorCheck.pacsDescFontSize = LocalConfig.doctorCheck.pacsDescFontSize


    // console.log('this.pacsType', this.pacsType,)
    //获取单位列表
    getapi("/api/app/customer-org/parent-all").then((res) => {
      if (res.code != -1) {
        this.customerOrgAll = res.data;
        let lfind = arrayExistObj(this.customerOrgAll, "id", this.dict.personOrgId);
        if (lfind > -1) this.customerOrgAll.splice(lfind, 1);
        this.customerOrg = deepCopy(this.customerOrgAll);
      }
    });

    // 获取系统参数(pacs系统条码类型：0:检查条码，1:人员条码)
    postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId:'pacs_interface_barcode_type' })
      .then(res => {
        if(res.code > -1){
          this.pacs_interface_barcode_type = res.data||"0"
        }
      })   

  },

  //挂载完成
  mounted() {
    let today = moment(new Date()).format("yyyy-MM-DD")
    this.query.startDate = today
    this.query.endDate = today
    this.doctorCheck.checkItemList = []
    this.result = ''
    this.summary = ''
  },

  computed: {
    ...mapState([
      "pickerOptions",
      "window",
      "dict",
      "dialogWin",
      "dataTransOpts",
      "doctorCheck",
      "patientRegister"      
    ]),
    lmoment(date, forMat) {
      return moment(new Date(date)).format(forMat);
    },
    
    // 左侧宽度
    leftWidth() {
      return this.window.pageWidth - this.rightWidth - 20
    },

    // 左侧宽度
    resultHeight() {
      return this.LocalConfig.doctorCheck.isHaveExternal == 'N' ? 120 : 300
    },

    //表格高度
    tableHeight() {
      let h = Number(this.LocalConfig.doctorCheck.pacsDescLineH)
      let n = Number(this.LocalConfig.doctorCheck.pacsDescLines)
      let th = this.window.pageHeight - this.resultHeight - 270 - 76 - (n * h) - 34
      if (this.LocalConfig.doctorCheck.isHaveExternal == 'Y') th = this.window.pageHeight - 85 - 76
      return th
    },

  },
  methods: {
    checkPagePriv, moment,

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

    // 清除结果
    btnClear(seq) {
      this.doctorCheck.checkItemList[seq].result = ''
    },

    // 默认结果
    btnDefResult(seq) {
      this.doctorCheck.checkItemList[seq].result = this.doctorCheck.checkItemList[seq].defaultResult
    },

    // 生成 图片预览列表
    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)
      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.pacsApi || this.sysConfig.apiurl) + fileName
      }
    },

    btnSavePic() {


      let body = [];
      // [
      //   {
      //     "registerCheckPictureId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",  // 新增无需传此值
      //     "registerCheckId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //     "pictureFilename": "string",
      //     "isPrint": "string",
      //     "displayOrder": 0
      //   }
      // ]

      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,
          isPrint: e.isPrint
        };
        if (e.id) item.registerCheckPictureId = e.id;
        body.push(item);
      });

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

    filterMethod(keyWords) {
      if (keyWords) {
        this.customerOrg = [];
        this.customerOrgAll.forEach((item) => {
          if (
            item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) > -1 ||
            item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > -1
            // || item.shortName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
          ) {
            this.customerOrg.push(item);
          }
        });
      } else {
        this.customerOrg = deepCopy(this.customerOrgAll);
      }
    },

    btnQuery() {
      let body = Object.assign({}, this.query)
      if (!body.checkRequestNo) delete body.checkRequestNo
      if (!body.patientName) delete body.patientName
      if (!body.startDate || !body.endDate) {
        this.$message.warning({ showClose: true, message: '请选择日期' })
        return
      }

      // 0:普通检查; 1:检验; 2:特检; 3:放射
      if (this.pacsType == 'image') {
        body.checkTypeFlag = '2'
      } else {
        body.checkTypeFlag = '3'
      }

      postapi('/api/app/PacsBusiness/GetPatientRegisterPacsCheck', body)
        .then(res => {
          if (res.code > -1) {
            res.data.items.forEach((e, i) => {
              e.seq = i // 增加序号
            });
            this.pacsList = res.data.items
          }
        })
    },

    rowClick(row) {
      this.curPacs = row
      this.onQueryByPacsNo(row.checkRequestNo)
    },

    //右击菜单
    onCellRightClick(row, column) {
      this.rClickRow = { ...row }; //右击的行记录
      this.rClickColumn = { ...column }; //右击的列（预留）
      // console.log(row, column.property);
    },
    onContextmenu(event) {
      //// console.log('onContextmenu',event);
      if (!this.rClickRow) return false;
      let row = { ...this.rClickRow };
      let items = [] //菜单项

      items.push({
        label: "清除pacs影像数据",
        onClick: () => {
          postapi("/api/app/PacsBusiness/DeletePacsCheckDicomDataByRegisterCheckId", {
            registerCheckId: row.registerCheckId
          })
            .then((res) => {
              if (res.code < 0) {
                this.$message.error({ showClose: true, message: res.message })
              }
            });
        },
      })

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

      this.rClickRow = null;
      return false;

    },

    //删除小结
    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('已取消删除')
        }
      });
    },

    // 浏览Dcm文件
    btnBrowseDcm() {

      // console.log('this.doctorCheck', this.doctorCheck.RegisterCheckEdit)
      this.checkRequestNo = this.doctorCheck.RegisterCheckEdit.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++

      let barcodeNo = this.doctorCheck.RegisterCheckEdit.checkRequestNo
      if(this.pacs_interface_barcode_type == '1'){
        barcodeNo = this.dataTransOpts.tableS.patient_register.patientRegisterNo
      }      

      // console.log('pacsParams', this.pacsParams)
      let token = window.sessionStorage.getItem('token')
      let url = `${this.sysConfig.dcmViewers}/?mrn=${barcodeNo}&token=${token}&pacsapi=${this.sysConfig.pacsApiHttps}`
      // this.iframeSrc = `${this.sysConfig.dcmViewers}/viewer?StudyInstanceUIDs=1.3.12.2.1107.5.1.4.79623.30000024091203062645300000022`
      this.dialogDcm = true
      // 有分屏且安装有壳
      if (this.$peisAPI && this.LocalConfig.doctorCheck.isHaveExternal == 'Y') {
        let  inParams = ''
        try {
          inParams = JSON.stringify({ url })
        } catch (error) {
          this.$message.error({ showClose: true, message: '壳参数 JSON.stringify({ url }) 分析失败：' + error })
          console.log('壳参数 JSON.stringify({ url }) 分析失败：',error)
          return
        }        
        
        this.$peisAPI.openExternal(inParams)
          .then(res => {
            if (res.code < 0) {
              this.$message.error({ showClose: true, message: '壳打开分屏失败：' + res.message })
              console.log( '壳打开分屏失败：',res.message)
              this.iframeSrc = url
            }
          })
          .catch(err => {
            this.$message.error({ showClose: true, message: '壳打开分屏失败：' + err })
            console.log( '壳打开分屏失败：',err)
            this.iframeSrc = url
          })
          .finally(() => console.log('this.$peisAPI.openExternal over'))

      } else {
        this.iframeSrc = url
      }

    },

    // 选择描述与结论
    btnChooseBigtext() {
      // console.log('this.pacsParams', this.pacsParams)
      if(this.doctorCheck.asbitemName){
        this.pacsParams.index = parseInt(this.tabChoosed)
        this.pacsParams.refresh++
        this.dialogWin.PacsTemplate = true
      }else{
        this.$message.warning({showClose:true,message:"没有可操作的数据！"})
      }
      
    },

    // 确定描述与结论
    btnOkBigtext() {
      // console.log('this.pacsParams', this.pacsParams)
      /*
      if (!this.pacsParams.summary) {
        this.$message.warning({ showClose: true, message: '请填写检查结论' })
        return
      }
      
      this.doctorCheck.checkSummaryList = [{
        id: Math.random(),
        registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
        summary: this.pacsParams.summary,
        summaryFlag: 'N',
      }]
      */
      if(!this.doctorCheck.asbitemName){
        this.$message.warning({showClose:true,message:"没有可操作的数据！"})
        return
      }
      if (this.doctorCheck.checkSummaryList.length < 1) {
        this.$message.warning({ showClose: true, message: '请填写检查结论' })
        return
      }

      this.save()
        .then(() => {
          if (this.autoNext == 'Y') {
            let lfind = arrayExistObj(this.pacsList, 'seq', this.curPacs.seq)
            if (lfind > -1 && this.pacsList.length - 1 > lfind) {
              this.rowClick(this.pacsList[lfind + 1])
              this.$refs['pacsList'].setCurrentRow(this.pacsList[lfind + 1]);
            }
          }
        })
        .catch(err => {
          console.log(err)
          this.$message.error({ showClose: true, message: err })
        })

    },

    //保存数据
    save() {
      return new Promise((resolve, reject) => {
        let checkDate = this.doctorCheck.RegisterCheckEdit.checkDate || new Date();
        checkDate = moment(new Date(checkDate)).format('yyyy-MM-DD HH:mm:ss'); //yyyy-MM-DD HH:mm:ss
        let checkDoctorId = this.doctorCheck.RegisterCheckEdit.checkDoctorId || null;
        let registerCheckId = this.doctorCheck.RegisterCheckEdit.id
        // 明细
        let registerCheckItems = []
        this.doctorCheck.checkItemList.forEach(e => {
          registerCheckItems.push({
            itemId: e.itemId,
            result: e.result,
            checkDoctorName: checkDoctorId,
            checkDate,
          })
        });
        // 小结
        let summarys = []
        this.doctorCheck.checkSummaryList.forEach(item => {
          summarys.push({
            summary: item.summary,
            summaryFlag: item.summaryFlag,
          })
        });
        // 建议
        let suggestions = []
        this.doctorCheck.checkSuggestionList.forEach(item => {
          suggestions.push({
            suggestion: item.suggestion
          })
        });

        let body = {
          registerCheckId,
          checkDoctorId,
          checkDate,
          registerCheckItems,
          summarys,
          suggestions
        }
        if (summarys.length == 0) reject('请填写结论！')

        postapi('/api/app/registercheck/UpdateCheckResult', body)
          .then(res => {
            if (res.code > -1) {
              this.doctorCheck.RegisterCheckEdit.completeFlag = '1';
              //更新组合项目列表记录状态
              let lfind = arrayExistObj(this.doctorCheck.RegisterCheckList, 'id', body.registerCheckId)
              if (lfind > -1) this.doctorCheck.RegisterCheckList[lfind].completeFlag = '1'

              resolve(res)
            } else {
              reject(res.message)
            }
          })
          .catch(err => reject(err))
      })
    },


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


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

            // 检查信息
            this.doctorCheck.RegisterCheckEdit = res.data.registerCheckDetail

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

            // 组合项目明细
            this.doctorCheck.checkItemList = res.data.registerCheckItemDetails
            if (this.doctorCheck.checkItemList.length > 0) {
              this.tabChoosed = "0"
            }
            if (this.doctorCheck.checkItemList.length > 3) {
              this.tabPosition = 'left'
            } else {
              this.tabPosition = 'top'
            }

            // 小结与建议
            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()
          }
        })

    },

  },

  //监听事件
  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;
}

.spanClass {
  font-size: 14px;
  padding: 6px 2px 0 0;
}

.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>
