<template>
  <div style="display: flex;width:100%;">
    <div style="width:180;">
      <!-- :row-class-name="tableRowClassName" -->
      <el-table :data="RegisterCheckList" width="180" :height="divHeight" border highlight-current-row
        @row-click="rowClick" ref="registerCheckList" >
        <el-table-column prop="asbitemName" label="组合项目" width="180">  
          <template slot="header">              
            <div style="width: 180px;background-color: #f4f8ff;">组合项目</div>                
          </template>      
          
        </el-table-column>
      </el-table>
    </div>
    <div :style="`padding-left:10px;width:${(window.pageWidth - 180 - 110 - 25)}px;`">
      <!--
      <el-table :data="tableData" :height="divHeight" border highlight-current-row>
        <el-table-column prop="itemName" label="项目" width="150" />
        <el-table-column prop="unitName" label="单位" width="80" align="center" />
        <el-table-column prop="referenceRangeValue" label="参考范围" width="80" align="center" />
        <el-table-column v-for="(item, index) of tableCols" :label="item.substring(0,10)" :prop="item" :key="index" min-width="150"
          align="center">
          <template slot-scope="scope">
            <div>{{ scope.row[item] }}</div>
          </template>
        </el-table-column>
      </el-table>
      -->
      <table width="100%" style="font-size:14px;border-collapse:collapse;" border="1" cellspacing="0"
        bordercolor="#909399">
        <colgroup>
          <col width="150">
          <col width="50">
          <col width="80">
          <col width="120" v-for="(item, index) of tableCols" :key="index">
        </colgroup>
        <thead>
          <tr height="30">
            <td class="tdCellClass">项目</td>
            <td class="tdCellClass">单位</td>
            <td class="tdCellClass">参考范围</td>
            <td class="tdCellClass" v-for="(item, index) of tableCols" :key="index">{{ item.substring(0, 10) }}</td>
          </tr>
        </thead>
        <tbody v-for="(item, index) of tableData" :key="index">
          <tr height="30">
            <td class="tdCellClass" style="text-align: left;">{{ item.itemName }}</td>
            <td class="tdCellClass">{{ item.unitName }}</td>
            <td class="tdCellClass">{{ item.referenceRangeValue }}</td>
            <td v-for="(item2, index2) of tableCols" :key="index2"
              :style="`padding: 0 5px;text-align:left;color: ${item.itemName == '小结' ? '#000000': getColorStr(item[item2 + '_color'])};`" v-html="item[item2]"></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayExistObj, getColorStr } from '@/utlis/proFunc';
export default {
  components: {},
  props: ["patientId", "tabChoosed","refParams"],
  data() {
    return {
      RegisterCheckList: [],
      tableData: [],   //显示数据
      tableRows: [],   //动态行
      tableCols: [],   //动态列
    };
  },

  created() { },

  //挂载完成
  mounted() {
    this.registerCheckList(this.patientId)
  },

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

    divHeight() {
      let tableHeight = 465
      switch (this.refParams.place) {
        case 'summary': //总检处
          tableHeight = (this.window.pageHeight < 600 ? 600 : this.window.pageHeight) - 195
          break;      
        default:
          break;
      }
      return tableHeight
    },
  },

  methods: {
    getColorStr,
    //组合项目颜色标识
    tableRowClassName({ row, rowIndex }) {
      //console.log('tableRowClassName',rowIndex,row)
      if (row.completeFlag === '0') {
        return 'warning'; //未检
      } else if (row.completeFlag === '2') {
        return 'info'; //弃检
      }
      return '';
    },

    //获取检查组合项目
    registerCheckList(patientId) {
      this.RegisterCheckList = []
      if (!patientId) return
      // console.log(`/api/app/sumsummaryreport/gethorizontalcomparisonasbitemlist?PatientId=${patientId}`)
      postapi('/api/app/SumSummaryReport/GetHorizontalComparisonAsbitems', { patientId })
        .then((res) => {
          console.log("获取横向对比 SumItems", res.data);
          if (res.code != -1) {
            this.RegisterCheckList = res.data;
            // if (this.RegisterCheckList && this.RegisterCheckList.length > 0){
            //   this.rowClick(this.RegisterCheckList[0])
            //   this.$refs['registerCheckList'].setCurrentRow(this.RegisterCheckList[0])
            // }
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });

    },

    rowClick(row) {
      //console.log('row',row) //asbitemId
      this.SumItems(this.patientId, row.asbitemId)
    },



    //获取结果明细 3a0c6589-9989-4d7f-ba54-61e5b0138220
    // "itemName": "乙肝表面抗原(HBsAg)",
    // "unitName": "次/分",
    // "referenceRangeValue": "",
    // "checkDate": "2023-07-14",
    // "resultValue": "阴性"
    SumItems(patientId, asbitemId) {
      // console.log(`/api/app/sumsummaryreport/gethorizontalcomparisonlist?PatientId=${patientId}&AsbitemId=${asbitemId}`)
      postapi('/api/app/SumSummaryReport/GetHorizontalComparisons', { patientId, asbitemId })
        .then((res) => {
          console.log("获取横向对比 SumItems", res.data);
          if (res.code != -1) {
            this.crossTable(res.data);
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },

    //交叉报表    
    crossTable(tableData) {
      // [
      //   {
      //     "regsterCheckId": "00000000-0000-0000-0000-000000000000",
      //     "checkDate": "2018-06-08T00:00:00",
      //      "summarys": [
      //           {
      //               "summary": "体重指数:23.89 诊断为：正常"
      //           }
      //       ],
      //       "registerCheckItems": [
      //           {
      //               "itemName": "身高",
      //               "unitName": "",
      //               "referenceRangeValue": "",
      //               "resultValue": "176",
      //               "reportFontColor": 0
      //           }

      this.tableData = []   //显示数据
      this.tableCols = []   //动态列

      // console.log('tableData', tableData)
      // this.tableCols.push('itemName')
      // this.tableCols.push('unitName')
      // this.tableCols.push('referenceRangeValue')
      let summary = { itemName: '小结', unitName: '', referenceRangeValue: '' }
      tableData.forEach((e, i) => {

        let lsummary = ''
        e.summarys.forEach((s, i) => {
          let splitStr = '<br>'
          if (i == 0) splitStr = ''
          lsummary += splitStr + (s.summary || '')
        });
        summary[e.checkDate] = lsummary

        // 获取列数
        if (this.tableCols.indexOf(e.checkDate) == - 1) this.tableCols.push(e.checkDate)

        // 获取行及数据
        let row = {}
        e.registerCheckItems.forEach(r => {
          let lfind = arrayExistObj(this.tableData, 'itemName', r.itemName)
          if (lfind > -1) {
            this.tableData[lfind][e.checkDate] = r.resultValue
            this.tableData[lfind][e.checkDate + '_color'] = r.reportFontColor
          } else {
            row = {
              itemName: r.itemName,
              unitName: r.unitName,
              referenceRangeValue: r.referenceRangeValue
            }
            row[e.checkDate] = r.resultValue
            row[e.checkDate + '_color'] = r.reportFontColor
            this.tableData.push(row)
          }
        })

      });
      this.tableData.push(summary)
    },


  },

  //监听事件
  watch: {
    // 虚拟表 触发强制刷新 （sumDoctor.M 合并包含：综述、建议、对比、历史等，不包含总检诊断）
    "dataTransOpts.refresh.sumDoctor.M": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch 总检--横向对比 newVal: ${newVal}, oldVal: ${oldVal} patientId: ${this.patientId} tabChoosed: ${this.tabChoosed}`);
        if (newVal != oldVal){
          if(this.refParams.place == 'doctor'){
            this.registerCheckList(this.patientId)
          }else{
            if(this.tabChoosed == '5') this.registerCheckList(this.patientId)
          }
        } 
      }
    },
  },
};
</script>
<style scoped>
@import '../../assets/css/global_table.css';

.tdCellClass {
  padding: 0 5px;
  text-align: center;
}
::v-deep .el-table tr {
    background-color: #f4f8ff;
}
</style>
  