<template>
  <div>
    <el-table
      :data="doctorCheck.checkItemList"
      style="width: 100%"
      :height="
        window.pageHeight < 600
          ? Math.floor(((420 - 40 - (isCheckPicture ? 110:0)) * 3) / 5)
          : Math.floor(((window.pageHeight - 260 - 40 - (isCheckPicture ? 110:0)) * 3) / 5)
      "
      border highlight-current-row
      @row-click="rowClick" size="small"
    >
      <el-table-column prop="itemName" label="项目" width="180" />
      <el-table-column prop="result" label="结果" min-width="200">
        <template slot-scope="scope">
          <el-autocomplete
            style="width: 100%;"
            type="textarea" 
            v-model="scope.row.result"
            :fetch-suggestions="querySearch"
            placeholder="请输入结果值"
            @select="handleSelect"
            :disabled="scope.row.isCalculationItem == 'Y' ||
              doctorCheck.RegisterCheckEdit.completeFlag == '1' ||
              doctorCheck.RegisterCheckEdit.completeFlag == '2'
            "
            :autosize="{ minRows: 1, maxRows: 100 }"
            :data-ismultiline="scope.row.isMultiLine"
            @input="madeTooltips(scope.$index)"
            v-bind:class="scope.row.class"
          /> 
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="80" align="center"/>
      <el-table-column
        prop="referenceRangeValue"
        label="参考范围"
        width="80" align="center"
      />
      <el-table-column
        prop="tooltips"
        label="提示"
        width="40" align="center"
      />
    </el-table>
  </div>
</template>
<script>
// 0-无参考范围，1-数字型，2-字符型，3-性激素
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { deepCopy } from '../../utlis/proFunc'

export default {
  components: {},
  props:["isCheckPicture","registerCheckId"],
  data() {
    return {
      resultStatus:[], //结果状态提示数据
      tipsNormal:{
        displayName: "正常",
        dataInputPrompt: "正常",
        reportPrompt: "正常",
        reportBackgroundColor: 16777215,
        reportFontColor: 0,
        dataInputBackgroundColor: 16777215,
        dataInputFontColor: 0,
      }, //正常提示
      tipsError:{}, //错误提示
      tipsNegative:{}, //阴性提示
      tipsLowPositive:{}, //弱阳性提示
      tipsPositive:{}, //阳性提示      
      tipsLow:{}, //偏低提示
      tipsHigh:{}, //偏高提示
      tipsSuperLow:{}, //超低提示
      tipsSuperHigh:{}, //超高提示      

      restaurants: [], //结果模版
      currentRow: -1, //当前操作的行
    };
  },

  created() {},

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

  computed: {
    ...mapState(["window","dataTransOpts", "dict", "doctorCheck"]),
  },

  methods: {

    dictInit(){
      //获取结果状态提示数据
      getapi('/api/app/result-status').then(res =>{
        if(res.code != -1){
          this.resultStatus = res.data.items
          this.resultStatus.forEach(e => {
            if(e.displayName.indexOf("正常") > -1){
              this.colorTrans(e,'tipsNormal')
            }else if(e.displayName.indexOf("错误") > -1){
              this.colorTrans(e,'tipsError')
            }else if(e.displayName.indexOf("阴性") > -1){
              this.colorTrans(e,'tipsNegative')
            }else if(e.displayName.indexOf("弱阳性") > -1){
              this.colorTrans(e,'tipsLowPositive')
            }else if(e.displayName.indexOf("阳性") > -1){
              this.colorTrans(e,'tipsPositive')
            }else if(e.displayName.indexOf("偏低") > -1){
              this.colorTrans(e,'tipsLow')
            }else if(e.displayName.indexOf("偏高") > -1){
              this.colorTrans(e,'tipsHigh')
            }else if(e.displayName.indexOf("危急值下限") > -1){
              this.colorTrans(e,'tipsSuperLow')
            }else if(e.displayName.indexOf("危急值上限") > -1){
              this.colorTrans(e,'tipsSuperHigh')
            }
          });
        }
      })
    },

    // 颜色转换
    // displayName: "错误",
    // dataInputPrompt: "×",
    // reportPrompt: "×",
    // reportBackgroundColor: 2427166,
    // reportFontColor: 1070166,
    // dataInputBackgroundColor: 321313,
    // dataInputFontColor: 12991019,
    colorTrans(dataColor,frontColor){
      let tempColor = '000000' + Number(dataColor.dataInputBackgroundColor).toString(16)
      let backgroundColor = '#' + tempColor.substring(tempColor.length - 6)
      tempColor = '000000' + Number(dataColor.dataInputFontColor).toString(16)
      let color = '#' + tempColor.substring(tempColor.length - 6)
      this[frontColor] = Object.assign(
        {},
        dataColor,
        {backgroundColor,color}
      )
      console.log(`this.${frontColor}`,this[frontColor])
    },

    // "referenceRangeValue": "15-55",
    // "referenceRangeTypeFlag": "1",
    // "criticalRangeValue": null,
    // "result"
    madeTooltips(index){
      // let ts = confirm('提示')      
      let checkItem = this.doctorCheck.checkItemList[index]
      let tooltips = 'tipsNormal'
      checkItem.class = tooltips
      let referenceRangeTypeFlag = checkItem.referenceRangeTypeFlag||'0' //参考范围类别0-无参考范围，1-数字型，2-字符型，3-性激素
      // console.log('madeTooltips',index,referenceRangeTypeFlag)
      switch (referenceRangeTypeFlag) {
        case '3':  // 1 是数字型，3 是性激素期
        case '1':
          // console.log('1、3')
          if(checkItem.result && checkItem.referenceRangeValue){
            let tempResult = checkItem.result.replaceAll('<','').replaceAll('>','').replaceAll('=','').replaceAll('≤','').replaceAll('≥','').replaceAll(' ','')
            // console.log('tempResult',isNaN(tempResult),tempResult)
            if(isNaN(tempResult)) break;            
            let result = Number(tempResult)
            let criticalRangeValue = checkItem.criticalRangeValue
            let valueArr = checkItem.referenceRangeValue.split('-')
            if(valueArr.length == 1) valueArr.unshift(0)
            // console.log('valueArr',checkItem.referenceRangeValue,valueArr)
            if(criticalRangeValue){
              let criticalArr = criticalRangeValue.split('-')
              if(criticalArr.length == 1) criticalArr.unshift(0)

              // console.log('criticalArr',checkItem.criticalRangeValue,criticalArr)

              if(result < Number(criticalArr[0])){
                tooltips = 'tipsSuperLow'
              }else if(result > Number(criticalArr[1])){
                tooltips = 'tipsSuperHigh'
              }else if(result < Number(valueArr[0])){
                tooltips = 'tipsLow'
              }else if(result > Number(valueArr[1])){
                tooltips = 'tipsHigh'
              }
            }else{
              if(result < Number(valueArr[0])){
                tooltips = 'tipsLow'
              }else if(result > Number(valueArr[1])){
                tooltips = 'tipsHigh'
              }
            }
          }
          break;
        case '2':
          if(checkItem.result){
            if(checkItem.result.indexOf('阴性') > -1 || checkItem.result.indexOf('-') > -1){
              tooltips = 'tipsNegative'
            }else if(checkItem.result.indexOf('弱阳性') > -1 || checkItem.result.indexOf('±') > -1){
              tooltips = 'tipsLowPositive'
            }else if(checkItem.result.indexOf('阳性') > -1 || checkItem.result.indexOf('+') > -1){
              tooltips = 'tipsPositive'
            }
          }          
          break;        
        default:
          break;
      }

      // 判断后重新赋值
      checkItem.class = tooltips
      checkItem.tooltips = this[tooltips].dataInputPrompt

      // console.log('checkItem',checkItem)
      // console.log(`this.${tooltips}`,this[tooltips])
    },

    //选择项目
    rowClick(row) {
      this.doctorCheck.checkItem = row;
      this.restaurants = row.itemResultTemplates;
    },

    //检查组合项目下所包含的明细项目
    checkItemList(RegisterCheckId) {
      // this.doctorCheck.checkItem = null
      if(!RegisterCheckId){
        this.doctorCheck.checkItemList = []
        return
      }
      console.log(
        `/api/app/registercheckitem/getlistinregistercheckid?RegisterCheckId=${RegisterCheckId}`
      );
      getapi(
        `/api/app/registercheckitem/getlistinregistercheckid?RegisterCheckId=${RegisterCheckId}`
      )
        .then((res) => {
          // console.log("checkItemList", res.data);
          if (res.code == 1) {
            this.doctorCheck.checkItemList = res.data;
            this.doctorCheck.checkItemList.forEach((e,i) => {
              this.madeTooltips(i)
            });
            this.enterToTab();
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `操作失败，原因：${err}` });
        });
    },

    querySearch(queryString, cb) {
      var restaurants = deepCopy(this.restaurants); //[{ value: '阴性' },{ value: '阳性' }]
      restaurants.forEach((item) => {
        return (item.value = item.result);
      });
      // console.log("restaurants", restaurants);
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },

    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant["value"]
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      console.log('item',item);
    },

    //回车替代tab键
    enterToTab() {
      // console.log('enterToTab');
      this.$nextTick(() => {
        let inputs = document.querySelectorAll(["textarea","input"]); //用数组可以读取多个标签的元素  //.inline-input
        
        // 为每个输入框添加键盘事件监听器
        inputs.forEach((input,i) => {
          // console.log('input',input);
          input.addEventListener('keydown', (event) => {
            
            // 如果按下的是回车键
            // console.log('data-ismultiline',input.getAttribute('data-ismultiline'));

            if (event.keyCode === 13 && input.getAttribute('data-ismultiline') == '0') {
              // 阻止回车键的默认行为（换行）
              event.preventDefault();
              // 获取当前输入框的下一个兄弟元素
              // let nextInput = input.nextElementSibling();
              // console.log('nextInput',nextInput,this);
              // // 如果存在下一个兄弟元素，将焦点移到下一个输入框
              // if (nextInput) {
              //   nextInput.focus();
              // }
              // console.log('inputs[i+1]',inputs[i+1]);              
              // console.log('disabled',inputs[i+1].getAttribute('disabled'));
              // console.log('class',inputs[i+1].getAttribute('class'));
              for(let j=i+1; j<inputs.length;j++){
                if(inputs[j].getAttribute('disabled') != "disabled" ){
                  inputs[j].focus();
                  break;
                }
              }              
            }
          });
        });
      });
    }, 

  },

  //监听事件
  watch: {
    //检查项目切换
    // "doctorCheck.RegisterCheckId":{
    //   immediate:true,
    //   handler(newVal, oldVal) {
    //     console.log(
    //       "watch doctorCheck.RegisterCheckId newVal：",
    //       newVal,
    //       " oldVal：",
    //       oldVal
    //     );        
    //     this.checkItemList(newVal);
    //   }  
    // },

    //检查项目未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.register_check_item":{
      immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch dataTransOpts.refresh.register_check_item newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.registerCheckId}`);       
        this.checkItemList(this.registerCheckId);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../assets/css/global.css";

::v-deep .el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  padding: 0;
}

::v-deep .el-textarea__inner {
  min-height: 23px;
  height: 23px;
  line-height: 1.25;
  padding: 2px 15px 2px 2px;
}

/*正常*/ 
::v-deep .tipsNormal .el-textarea__inner {
  background-color: v-bind("tipsNormal.backgroundColor") !important; 
  color: v-bind("tipsNormal.color") !important;
}
/*错误*/ 
::v-deep .tipsError .el-textarea__inner {
  background-color: v-bind("tipsError.backgroundColor") !important; 
  color: v-bind("tipsError.color") !important;
}

/*阴性  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsNegative .el-textarea__inner {
  background-color: v-bind("tipsNegative.backgroundColor") !important; 
  color: v-bind("tipsNegative.color") !important;
}

/*弱阳性  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsLowPositive .el-textarea__inner {
  background-color: v-bind("tipsLowPositive.backgroundColor") !important; 
  color: v-bind("tipsLowPositive.color") !important;
}

/*阳性  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsPositive .el-textarea__inner {
  background-color: v-bind("tipsPositive.backgroundColor") !important; 
  color: v-bind("tipsPositive.color") !important;
}

/*偏低  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsLow .el-textarea__inner {
  background-color: v-bind("tipsLow.backgroundColor") !important; 
  color: v-bind("tipsLow.color") !important;
}

/*偏高  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsHigh .el-textarea__inner {
  background-color: v-bind("tipsHigh.backgroundColor") !important; 
  color: v-bind("tipsHigh.color") !important;
}

/*超低  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsSuperLow .el-textarea__inner {
  background-color: v-bind("tipsSuperLow.backgroundColor") !important; 
  color: v-bind("tipsSuperLow.color") !important;
}

/*偏高  v-bind("(window.pageHeight > 600 ? (window.pageHeight - 250) : 350) + 'px'") */
::v-deep .tipsSuperHigh .el-textarea__inner {
  background-color: v-bind("tipsSuperHigh.backgroundColor") !important; 
  color: v-bind("tipsSuperHigh.color") !important;
}
 

</style>


