<template>
  <div>
    <div style="display: flex;" @contextmenu="onContextmenu">
      <div :style="`width:${sumWidth}px;`" @dblclick="blClick">
        <el-table id="tableSummary" row-key="id" :data="doctorCheck.checkSummaryList" size="samll" :height="sumHeight"
          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';" ref="divSummary">
                <el-input type="textarea" v-model="scope.row.summary" :autosize="{ minRows: 1, maxRows: 100 }"
                  placeholder="请输入小结" :style="`font-size: ${pacsDescFontSize}px;`">
                </el-input>
                <el-button type="danger" style="min-width:23px;padding:2px;" icon="el-icon-delete"
                  @click="delSum(scope.$index)" :disabled="doctorBtnDisabled('delSum')" size="small"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        :style="`display: flex;position: absolute; top:${window.pageHeight - sumHeight - 226}px;right:${sumWidth + 8}px;z-index: 1;`">
        <div v-show="checkPagePriv(pagePriv.privs, '生成小结')">
          <el-button type="primary" class="btnClass" @click="btnMakeDiagnosis"
            :disabled="doctorBtnDisabled('btnMakeDiagnosis')">生成小结</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '新增小结')">
          <el-button type="primary" class="btnClass" @click="addSummary"
            :disabled="doctorBtnDisabled('addSummary')">新增小结</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '保存结果')">
          <el-button type="primary" class="btnClass" @click="save"
            :disabled="doctorBtnDisabled('save')">保存结果</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '审核')">
          <el-button type="primary" class="btnClass" style="min-width: 40px;" @click="audit"
            :disabled="doctorBtnDisabled('audit')">审核</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '排队')">
          <el-button type="primary" class="btnClass" style="min-width: 40px;" @click="fnQueue"
            :disabled="doctorBtnDisabled('fnQueue')">排队</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '危急值')">
          <el-button type="primary" class="btnClass"
            :style="[{ minWidth: '40px' }, { backgroundColor: (this.doctorCheck.RegisterCheckEdit.isCriticalValue == 'Y' ? 'red' : '') }]"
            @click="btnCritical" :disabled="doctorBtnDisabled('btnCritical')">危急值</el-button>
        </div>
      </div>
      <el-tabs v-model="activeName" tab-position="top" :style="`margin-left:2px;width:${sumWidth}px;`">
        <el-tab-pane label="上次结果" name="preResult">
          <div :style="`width:100%;height:${sumHeight - 32}px;overflow-y: auto;`">
            <table width="100%" style="font-size:14px;border-collapse:collapse;" border="1" cellspacing="0"
              bordercolor="#909399">
              <colgroup>
                <col width="150">
                <col min-width="120">
                <col width="80">
                <col width="50">
              </colgroup>
              <thead>
                <tr height="30">
                  <td class="tdCellClass">项目</td>
                  <!--有日期时，特意居左，不然人员列表将日期挡住了-->
                  <td class="tdCellClass" :style="`text-align: ${doctorCheck.preResult.checkDate ? 'left':'center'};`">{{ doctorCheck.preResult.checkDate || '结果' }}</td>
                  <td class="tdCellClass">参考范围</td>
                  <td class="tdCellClass">单位</td>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) of doctorCheck.preResult.registerCheckItems || []" :key="index" height="30">
                  <td class="tdCellClass" style="text-align: left;">{{ item.itemName }}</td>
                  <td
                    :style="`padding: 0 5px;text-align:left;color: ${item.itemName == '小结' ? '#000000' : getColorStr(item.reportFontColor)};`"
                    v-html="item.resultValue"></td>
                  <td class="tdCellClass">{{ item.referenceRangeValue }}</td>
                  <td class="tdCellClass">{{ item.unitName }}</td>
                </tr>
                <tr height="30">
                  <td class="tdCellClass" style="text-align: left;">小结</td>
                  <td class="tdCellClass" style="text-align: left;" colspan="3">
                    <p v-for="(item, index) of doctorCheck.preResult.summarys || []" :key="index">
                      {{ item.summary }}
                    </p>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="建议" name="suggestion" v-if="doctor_check_disp_suggestion == 'Y'">
          <div>
            <div :style="`display: flex;position: absolute;top:5px;right:5px;z-index: 1;`">
              <div v-show="checkPagePriv(pagePriv.privs, '新增建议')">
                <el-button type="primary" class="btnClass" @click="addSuggestion"
                  :disabled="doctorBtnDisabled('addSuggestion')">新增建议</el-button>
              </div>
            </div>
            <div>
              <el-table id="tableSuggestion" row-key="id" :data="doctorCheck.checkSuggestionList" size="samll"
                :height="sumHeight - 32" width="100%" border>
                <el-table-column width="30" align="center">
                  <template slot-scope="scope">
                    <el-tag class="moveSuggestion"
                      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="suggestion" 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.suggestion" :autosize="{ minRows: 1, maxRows: 100 }"
                        :disabled="doctorBtnDisabled('delSug')" placeholder="请输入建议">
                      </el-input>
                      <el-button type="danger" style="min-width:23px;padding:2px;" icon="el-icon-delete"
                        @click="delSug(scope.$index)" :disabled="doctorBtnDisabled('delSug')" size="small"></el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div>
      <!-- 分诊排队 -->
      <el-dialog title="分诊排队" :visible.sync="dialogWin.queue3" width="800px" :append-to-body="true"
        :close-on-click-modal="false">
        <Queue3 :refParams="queueParams" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv, checkPagePriv, deepCopy, getColorStr, arrayExistObj } from "../../utlis/proFunc";
import Queue3 from "../../components/queue/Queue.vue";

export default {
  components: {
    Queue3
  },
  props: ["refParams", "isCheckPicture", "optGrant", "addSummary", "btnMakeDiagnosis", "save", "audit", "unAudit", "btnLineUp", "doctorBtnDisabled","patient_register"],
  data() {
    return {
      queueParams: {
        patientRegisterId:'',
        patientName:'',
        queueTimes:0, //刷新用
      },
      pagePriv: {
        routeUrlorPageName: 'doctorCheck', //当前页面归属路由或归属页面权限名称
        privs: [], // 页面权限        
      },
      activeName: 'preResult',
      doctor_check_disp_suggestion: 'N', // 医生诊台 默认不显示建议
      pacsDescFontSize: 14, //结论内容的字体大小

    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))

    let LocalConfig = JSON.parse(window.localStorage.getItem("LocalConfig") || null)
    if (LocalConfig?.doctorCheck?.pacsDescFontSize) this.pacsDescFontSize = LocalConfig.doctorCheck.pacsDescFontSize

    postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: 'doctor_check_disp_suggestion' })
      .then(res => {
        if (res.code > -1) {
          this.doctor_check_disp_suggestion = (res.data.toUpperCase()) || "N"
        }
      })
  },

  //挂载完成
  mounted() {

    // 监听来自 Electron 的调用 右击事件    
    if (this.$peisAPI) {
      try {
        this.$peisAPI.onContextMenuAction((data) => {
          this.onContextMenuDIY(data)
        });
      } catch (error) {
        console.error(error)
      }
    }

    this.rowDrop();

    if (this.doctor_check_disp_suggestion == 'Y') this.rowDropSuggestion()

  },

  computed: {
    ...mapState(['window', 'dataTransOpts', 'dict', 'doctorCheck', 'dialogWin']),

    //小结宽度
    sumWidth() {
      return Math.floor((this.window.pageWidth - 200 - 110 - 15 - 4) / 2);
    },

    //小结高度
    sumHeight() {
      let fixHeight = this.window.pageHeight < 600 ? 600 : this.window.pageHeight
      return Math.floor((fixHeight - 120 - (this.isCheckPicture ? 110 : 0)) * 2 / 5);
    }

  },

  methods: {
    checkPagePriv, getColorStr,
    //获取小结
    checkSummaryList(registerCheckId) {
      this.doctorCheck.checkSummaryList = [];
      if (!registerCheckId) return;
      // console.log(`/api/app/registerchecksummary/getregisterchecksummarylist?RegisterCheckId=${RegisterCheckId}`)
      let defaultResult = "未见明细异常"
      let lfind = arrayExistObj(this.doctorCheck.RegisterCheckList, 'id', registerCheckId)
      if (lfind > -1) {
        defaultResult = this.doctorCheck.RegisterCheckList[lfind].defaultResult || defaultResult
      }

      getapi(`/api/app/registerchecksummary/getregisterchecksummarylist?RegisterCheckId=${registerCheckId}`)
        .then((res) => {
          console.log("checkSummaryList", res.data);
          if (res.code > -1) {
            this.doctorCheck.checkSummaryList = res.data;
            if (this.doctorCheck.checkSummaryList.length == 0) {
              this.doctorCheck.checkSummaryList.push({
                id: Math.random(),
                registerCheckId,
                summary: defaultResult,
                summaryFlag: 'N'
              })
            }
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },

    //获取建议
    checkSuggestionList(RegisterCheckId) {
      if (!RegisterCheckId) {
        this.doctorCheck.checkSuggestionList = [];
        return;
      }
      // console.log(`/api/app/registerchecksuggestion/getregisterchecksuggestionlist?RegisterCheckId=${RegisterCheckId}`)
      getapi(`/api/app/registerchecksuggestion/getregisterchecksuggestionlist?RegisterCheckId=${RegisterCheckId}`)
        .then((res) => {
          console.log("checkSuggestionList", res.data);
          if (res.code != -1) {
            this.doctorCheck.checkSuggestionList = res.data;
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },

    //获取历次结果
    getPreResult(RegisterCheckId) {
      if (!RegisterCheckId) {
        this.doctorCheck.preResult = {};
        return;
      }
      // console.log(`/api/app/registerchecksuggestion/getregisterchecksuggestionlist?RegisterCheckId=${RegisterCheckId}`)
      postapi('/api/app/SumSummaryReport/GetLastTimeAsbitemResult', { registerCheckId: RegisterCheckId })
        .then((res) => {
          console.log("getPreResult", res.data);
          if (res.code > -1) {
            this.doctorCheck.preResult = res.data || {};
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },


    //拖拽
    rowDrop() {
      this.$nextTick(() => {
        const el = document.querySelector("#tableSummary tbody");
        console.log('el0', el)
        const that = this;
        Sortable.create(el, {
          handle: ".moveSummary",
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          // 开始拖拽的时候
          onStart: (evt) => {
            if (this.doctorCheck.RegisterCheckEdit.completeFlag != '0') {
              this.$alert("项目已检或弃检，不可执行此操作！", { showClose: false })
              return false
            }
          },
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isshow = false;
            const currRow = that.doctorCheck.checkSummaryList.splice(oldIndex, 1)[0];
            that.doctorCheck.checkSummaryList.splice(newIndex, 0, currRow);
            console.log('el', el)
          },
        });
      });
    },

    //拖拽
    rowDropSuggestion() {
      this.$nextTick(() => {
        const el = document.querySelector("#tableSuggestion tbody");
        //console.log('tbody',tbody)
        const that = this;
        Sortable.create(el, {
          handle: ".moveSuggestion",
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          // 开始拖拽的时候
          onStart: (evt) => {
            if (this.doctorCheck.RegisterCheckEdit.completeFlag != '0') {
              this.$alert("项目已检或弃检，不可执行此操作！", { showClose: false })
              return false
            }
          },
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isshow = false;
            const currRow = that.doctorCheck.checkSuggestionList.splice(oldIndex, 1)[0];
            that.doctorCheck.checkSuggestionList.splice(newIndex, 0, currRow);
          },
        });
      });
    },

    // 分诊排队
    fnQueue() {
      if (!this.patient_register.id) {
        this.$message.warning({ showClose: true, message: '未获取到人员信息' })
        return
      }      
      this.queueParams.patientRegisterId = this.patient_register.id
      this.queueParams.patientName = this.patient_register.patientName
      this.queueParams.queueTimes++   
      this.dialogWin.queue3 = true   
    },

    // 危急值
    btnCritical() {
      this.dialogWin.FollowCriticalCheck = true
      this.doctorCheck.combinationCriticalValue = true
    },

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

    addSuggestion() {
      this.doctorCheck.checkSuggestionList.push({
        id: Math.random(),
        registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
        suggestion: '',
      })
    },


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

    // 双击生成小结
    blClick() {
      //this.$message.warning({showClose:true,message:'双击'})    
      if (this.doctorBtnDisabled('btnMakeDiagnosis')) {
        return
      }
      this.btnMakeDiagnosis()
    },

    // 右击菜单
    onContextmenu(event) {
      if (!this.$peisAPI) {
        return
      }


      let menus = [
        // { type: 'separator' },
        // { label: '测试菜单', itemId: '测试菜单', enabled: true },
        // {
        //   label: '更多操作',
        //   submenu: [
        //     { label: '子菜单', itemId: '子菜单', enabled: true }
        //   ]
        // }
      ]

      this.$peisAPI.showContextMenu(menus)
        .then(res => {
          console.log('res', res)
        })
        .catch(err => {
          console.log('err', err)
        })
        .finally(() => {
          console.log('finally')
        })

    },

    // 自定义右击事件
    onContextMenuDIY(data) {
      //this.$message({showClose:true,message:data})
    }
  },

  //监听事件
  watch: {
    //检查项目切换
    // "doctorCheck.RegisterCheckId"(newVal, oldVal) {
    //   console.log("watch doctorCheck.RegisterCheckId newVal：", newVal, " oldVal：", oldVal);      
    //   this.checkSummaryList(newVal)
    //   this.checkSuggestionList(newVal)      
    // },
    //检查项目未切换换时 也可以强制刷新数据
    // "dataTransOpts.refresh.register_check.S": {
    "refParams.brushItemList": {
      immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 小结 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.refParams.registerCheckId}`);
        if (newVal != oldVal) {
          this.checkSummaryList(this.refParams.registerCheckId)
          this.checkSuggestionList(this.refParams.registerCheckId)
          this.getPreResult(this.refParams.registerCheckId)
        }
      }
    },

  },
};
</script>
<style scoped>
@import '../../assets/css/global_table.css';

.tdCellClass {
  padding: 0 5px;
  text-align: center;
}

.btnClass {
  margin-left: 2px;
  height: 22px;
  padding: 2px 2px;
  /*原始 默认值 500 */
}

::v-deep .el-textarea__inner {
  min-height: 23px;
  height: 23px;
  line-height: 1.25;
  padding: 1px 15px 1px 2px;
}
</style>