<template>
  <div>
    <div class="contenttitle">
      体检 /<span class="contenttitleBold">pacs看图</span>
    </div>
    <div style="display: flex;">
      <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;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 style="width: 310px;margin-left: 2px;">
        <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 @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 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%;border: 1px solid #232748;" type="textarea" v-model="item.result"
                placeholder="请输入检查结果" :autosize="{ minRows: 8, maxRows: 8 }" />
              <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: -15px;">
          <span style="color: #232748;">检查结论：</span>
          <el-input style="width: 98%;border: 1px solid #232748;" type="textarea" v-model="pacsParams.summary"
            placeholder="请输入结论" size="small" :autosize="{ minRows: 6, maxRows: 6 }" />
        </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" size="small" class="commonbutton"
              :disabled="dataTransOpts.tableS.patient_register.completeFlag == '3'">选择描述</el-button>
            <el-button type="primary" @click="btnOkBigtext" size="small" class="commonbutton"
              :disabled="dataTransOpts.tableS.patient_register.completeFlag == '3'">保存结果</el-button>
            <el-checkbox v-model="autoNext" true-label="Y" false-label="N" size="small">自动下一条</el-checkbox>
          </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 {
      sysConfig: {}, //
      pagePriv: {
        routeUrlorPageName: 'doctorCheck', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },
      query: {
        patientName: "",
        checkRequestNo: "",
        dateType: "1",
        startDate: "",
        endDate: "",
        maxResultCount: 1000,
        skipCount: 0
      },

      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", // 多个明细检查排列方式
    };
  },

  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 && LocalConfig.doctorCheck && LocalConfig.doctorCheck.pacsType) this.pacsType = LocalConfig.doctorCheck.pacsType
    // console.log('this.pacsType', this.pacsType,)
  },

  //挂载完成
  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",
      "customerOrg"
    ]),
    lmoment(date, forMat) {
      return moment(new Date(date)).format(forMat);
    },
    tableHeight() {
      return this.window.pageHeight - 105 - 400 - 76
    },
  },
  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);
          }
        });
    },


    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;

    },

    // 浏览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++

      // console.log('pacsParams', this.pacsParams)
      let token = window.sessionStorage.getItem('token')
      this.iframeSrc = `${this.sysConfig.dcmViewers}/?mrn=${this.doctorCheck.RegisterCheckEdit.checkRequestNo}&token=${token}&pacsapi=${this.sysConfig.pacsApi}`
      // this.iframeSrc = `${this.sysConfig.dcmViewers}/viewer?StudyInstanceUIDs=1.3.12.2.1107.5.1.4.79623.30000024091203062645300000022`
      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)
      if (!this.pacsParams.summary) {
        this.$message.warning({ showClose: true, message: '请填写检查结论' })
        return
      }
      //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',
      }]

      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>
