<template>
  <div class="pageContent">
    <el-empty description="未查到信息" v-if="resultFlag"></el-empty>
    <div v-else>
      <div class="content-head">
        <el-tabs v-model="active_Name" type="card" @tab-click="handleClick" style="width: 90%">
          <el-tab-pane :label="item.optionName+formatDate(item.applydate)"
                       :name="item" v-for=" (item,index) in tableData"
          >
            <el-tooltip slot="label" effect="dark"
                        :content="item.optionName+formatDate(item.applydate)"
                        placement="bottom-start"
            >
                    <span class="tmp"
                    > {{ item.optionName + formatDate(item.applydate) }}</span>
            </el-tooltip>
            {{ item.optionName + ' 申请时间:' + formatDate(item.applydate) }}
          </el-tab-pane>
        </el-tabs>
        <!--     <div class="content-head-title">血常规</div>-->
        <div class="content-head-right">
<!--          <div class="content-head-btn">-->
<!--            <i class="el-icon-download"/>-->
<!--            <div>下载</div>-->
<!--          </div>-->
          <div class="content-head-btn" @click="showPdf">
            <svg-icon icon-class="pdf"/>
            <div>查看PDF</div>
          </div>
        </div>
      </div>
      <el-table
        v-loading="loding"
        :data="tableList"
        :header-cell-style="{background:'#edf4fb'}"
        style="width: 100%"
      >
        <el-table-column prop="detailsItemName" label="项目名称" min-width="150" show-overflow-tooltip/>
        <el-table-column prop="checkReportResult" label="检测结果"/>
        <el-table-column prop="adviceType" label="偏">
          <template slot-scope="scope">
            <div style="font-size: 20px">
              <i v-if="scope.row.resultLogoExplin==='↓' " class="el-icon-bottom textGreen"></i>
              <i v-if="scope.row.resultLogoExplin==='↑'" class="el-icon-top textRed"></i>
            </div>

            <!--          <div :class="[scope.row.resultLogoExplin === '' ? '' : 'detail_text2' , scope.row.resultLogoExplin === '↑' ? 'detail_text2-2' : '' , scope.row.resultLogoExplin === '↓' ? 'detail_text2-1' : '']">-->
            <!--            {{ resultHandeler(scope.row.resultLogoExplin) }}-->
            <!--          </div>-->
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位">
          <template slot-scope="scope">
            <div :class="filterColor(scope.row.unit)">
              {{ scope.row.unit }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="referenceChinese" label="参考区间"/>
        <el-table-column prop="spec" label="近期趋势">
          <template slot-scope="scope">
            <i class="el-icon-data-line icon-trend" @click="handleOpen(scope.row)"></i>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="card-page"
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="pageFunction"
      />
      <el-dialog
        title="检验结果"
        :visible.sync="open"
        width="1100px"
        append-to-body
      >
        <div class="dialog-content">
          <div class="dialog-left">
            <div class="dialog-head">
              <div class="dialog-head-left">
                <div class="head-text">结果值</div>
                <div>
                  <span>项目名称：</span>
                  <span class="dialog-val">{{ lineTable.checkKindName }}</span>
                </div>
              </div>
              <div>
                <span class="dialog-label">参考范围：</span>
                <span class="dialog-val">{{ lineTable.referenceChinese }}</span>
              </div>
            </div>
            <div class="dialog-chart" ref="lineChart"></div>
          </div>
          <div class="dialog-right">
            <div class="right-text">说明</div>
            <div class="right-item">
              <div class="item-icon bgBlue"></div>
              <div>正常值</div>
            </div>
            <div class="right-item">
              <div class="item-icon bgGreen"></div>
              <div>低于正常值</div>
            </div>
            <div class="right-item">
              <div class="item-icon bgRed"></div>
              <div>高于正常值</div>
            </div>
            <div class="right-date">检查日期</div>
          </div>
          <div  style="height:400px;overflow-y:auto">
            <el-checkbox-group v-model="checkedItem" size="small"
                               style="display: flex;flex-direction:column;justify-content: flex-start "
                               @change="handleCheckedChange">
              <el-checkbox :label="item" border class="checkboxItem" v-for="item in lineData" style="
              display:block;
              margin-top: 10px;
              margin-left: 10px;
              height: 40px ;
              width: 80%;"
              >
                <div>{{formatDate(item.checkDate)}}</div>
                <div>{{ item.deptName }}</div>
              </el-checkbox>

            </el-checkbox-group>


          </div>
        </div>

        <!--        <div class="cycle-child">-->
        <!--          <div-->
        <!--            class="child-item"-->
        <!--            v-for="child in lineTable"-->
        <!--            :key="child.patientId"-->

        <!--          >-->
        <!--            <div class="child-date">-->
        <!--              <div class="child-day">{{ formatDay(child.applyDate) }}</div>-->
        <!--              <div class="child-year">{{ formatYear(child.applyDate) }}</div>-->
        <!--            </div>-->
        <!--            <div class="child-text">-->
        <!--              <div class="active" >{{ child.deptName }}</div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </div>-->
      </el-dialog>
      <el-dialog
        title="查看报告"
        :visible.sync="openPdf"
        width="1000px"
        class="dialogClass"
        append-to-body
      >
        <iframe :src="src" id="mobsf" scrolling="no" frameborder="0" style="height: 85vh;width: 100%;" ></iframe>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { handlerRequestNoAuth } from '@/api/patient360'
import moment from 'moment'
import echarts from 'echarts'

export default {
  name: 'bloodRoutine',
  data() {
    return {
      tableData: [],
      total: 20,
      queryParams: {
        page: 1,
        pageSize: 20
      },
      active_Name: 0,
      tableList: [],
      loding: false,
      resultFlag: false,
      open: false,
      lineTable: {
        checkKindName: '',
        referenceChinese: ''
      },
      lineData: [],
      active: 1,
      checkedItem: [],
      zbEnd : '0',
      zbStart:'0',
      openPdf:false,
      src:""
    }
  },
  mounted() {
    this.initMethodMethod()

  },
  props: {
    msg: {
      type: Object
    }
  },
  methods: {
    filterColor(flag) {
      let _flag
      switch (flag) {
        case 1:
          _flag = 'textGreen'
          break
        case 2:
          _flag = 'textRed'
          break
      }
      return _flag
    },
    async initMethodMethod() {
      this.loding = true
      console.log(this.msg)

      let param = {}
      let data = {}
      if (this.msg.clinicClass === '2') {
        param = {
          orgCode: this.msg.orgCode,
          registeredId: this.msg.patientId
        }
        param = JSON.stringify(param)
        data = {
          apiId: '141',
          param: param
        }
      } else {
        param = {
          orgCode: this.msg.orgCode,
          jzlsh: this.msg.jzlsh
        }
        param = JSON.stringify(param)
        data = {
          apiId: '444',
          param: param
        }
      }

      const res = await handlerRequestNoAuth(data)
      if (res.code != 200 || res.data.length === 0) {
        this.loding = false
        this.resultFlag = true
        return
      }
      let map = new Map()
      res.data.forEach((item, index) => {
        if (item.reportSn && !map.has(item.reportSn)) {
          //没有这个key,新建一个list把键值对保存到map中
          let obj = {
            list: [item],
            orderNo: item.orderNo,
            patientId: item.patientId,
            applySn: item.applySn,
            checkKindName: item.checkKindName
            // url: this.joinUrl(item.orderNo, item.patientId, item.applySn)
          }
          map.set(item.reportSn, obj)
        } else {
          //如果map对象中存在这个对象的key,则直接向它的value（value是list类型）add item
          if (item.reportSn) {
            map.get(item.reportSn).list.push(item)
          }
        }
      })
      let list = []

      map.forEach(function(value, key, map) {
        list.push({
          keyName: key,
          valueName: value,
          optionName: value.checkKindName,
          applydate: value.list[0].applydate,
          hide: false
        })
      })
      console.log('list', list)
      let order = {}
      for (var i = 0; i < list.length - 1; i++) {
        console.log('list', list[i].applydate)
        for (var j = 0; j < list.length - 1 - i; j++) {
          if (Date.parse(list[j].applydate) < Date.parse(list[j + 1].applydate)) {
            order = list[j]
            list[j] = list[j + 1]
            list[j + 1] = order
          }

        }
      }
      this.tableData = list
      // this.tableData.push(list[0])
      this.active_Name = list[0]

      this.handleClick()
      console.log('map', map)
      this.loding = false
    },
    handleClick(row) {
      console.log(this.active_Name)
      // this.tableList = this.active_Name.valueName.list
      this.pageFunction()
    },
    classHandeler(value) {
      if (value === '↓') {
        return 'detail_text2-1'
      } else if (value === '↑') {
        return 'detail_text2-2'
      } else {
        return 'detail_text2'
      }
    },
    resultHandeler(value) {
      if (value === '-') {
        return ''
      }
      return value
    },
    formatDate(time) {
      return moment(time).format('YYYY/MM/DD ')
    },
    formatDate2(time) {
      return moment(time).format('YYYY/MM/DD HH:mm:ss')
    },
    pageFunction() {
      this.total = this.active_Name.valueName.list.length
      this.tableList = this.active_Name.valueName.list.slice(
        (this.queryParams.page - 1) * this.queryParams.pageSize,
        this.queryParams.page * this.queryParams.pageSize
      )
      console.log('page', this.total, this.queryParams.pageSize, this.tableList)

    },
    async handleOpen(i) {
      this.open = true

      console.log('row', i, this.msg)
      this.lineTable.checkKindName = i.detailsItemName
      this.lineTable.referenceChinese = i.referenceChinese
      console.log('lineTable', this.lineTable)
      let param = {
        orgCode: this.msg.orgCode,
        registeredId: this.msg.patientIds,
        detailsItemCodes: i.detailsItemCode
      }
      param = JSON.stringify(param)
      let data = {
        apiId: '436',
        param: param
      }
      const res = await handlerRequestNoAuth(data)
      this.lineData = res.data
      this.checkedItem = this.lineData
      let date = []
      let itemdata = []
      // for (let j = 0; j < res.data.length; j++) {
      //   date.push(this.formatDate(res.data[j].checkDate))
      //   itemdata.push(res.data[j].checkReportResult)
      // }

      if (i.referenceChinese) {
        this.zbStart = i.referenceChinese.substring(0, i.referenceChinese.indexOf('-'))
        this.zbEnd = i.referenceChinese.substring(i.referenceChinese.indexOf('-') + 1, i.referenceChinese.length)
      }
      console.log(res, date, itemdata,this.zbStart,this.zbEnd)
      this.$nextTick(() => {
        // this.getChart(date, itemdata, zbEnd, zbStart)
        this.handleCheckedChange()
      })
    },
    getChart(date, itemdata) {
      console.log('date', date,this.zbStart,this.zbEnd)
       let zbS =  this.zbStart
         let zbE = this.zbEnd
      const myCharts = echarts.init(this.$refs.lineChart)
      const option = {
        grid: {
          left: 30,
          right: 10,
          bottom: 50
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: [{
          type: 'category',
          data: date,
          axisLabel: {
            fontSize: 11
          },
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          }
        }],
        yAxis: [{
          type: 'value',
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLine: {
            show: false
          },
          nameTextStyle: {
            color: '#999'
          },
          splitArea: {
            show: false
          }
        }],
        series: [{
          name: '值',
          type: 'line',
          data: itemdata,
          lineStyle: {
            normal: {
              width: 4,
              color: {
                type: 'linear',
                colorStops: [{
                  offset: 0,
                  color: '#0ff' // 0% 处的颜色
                }, {
                  offset: 1,
                  color: '#0A69F3' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              },
              shadowColor: 'rgba(10,150,234, 0.3)',
              shadowBlur: 6,
              shadowOffsetY: 10
            }
          },
          itemStyle: {
            normal: {
              borderWidth: 5,
              borderColor: '#00e1ff',
              color: function(params) {
                const val = params.value

                console.log('val', val,zbS,zbE)
                // console.log('zb', parseFloat(this.zbStart))
                if (parseFloat(val) < parseFloat(zbS)) {
                  return '#28b276'
                } else if (parseFloat(val) > parseFloat(zbE)) {
                  return '#FA1919'
                } else {
                  return '#0A69F3'
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: function(p) {
                  return p.value > 0 ? (p.value) : ''
                }
              }
            }
          },
          smooth: true
        }]
      }
      console.log(option)
      myCharts.setOption(option, true)
    },
    formatYear(time) {
      return moment(time).format('YYYY')
    },
    formatDay(time) {
      return moment(time).format('MM-DD')
    },
    handleCheckedChange(){
      console.log("checkedItem",this.checkedItem)
      let dataItem = []
      let dateItem = []
      for (let i = 0; i <this.checkedItem.length-1; i++) {

        for (let j = 0; j < this.checkedItem.length-1 -i; j++) {

          if (Date.parse(this.checkedItem[j].checkDate) > Date.parse(this.checkedItem[j+1].checkDate)){
            let da = this.checkedItem[j+1]
            this.checkedItem[j+1] = this.checkedItem[j]
            this.checkedItem[j]  =da
          }
        }
      }
      for (let i = 0; i < this.checkedItem.length; i++) {
        dataItem.push(this.checkedItem[i].checkReportResult)
        dateItem.push(this.formatDate(this.checkedItem[i].checkDate))
      }

      console.log("che",dataItem,dateItem)
      this.getChart(dateItem,dataItem)
    },
    async showPdf(){
      console.log("active_Name",this.active_Name)
      let param = {
        key:"056cdb2251816934c09f1123b3c2dd65",
        readerId:"360",
        userCode:this.formatDate(new Date()) ,
        reportCode:this.active_Name.keyName
      }
      param = JSON.stringify(param)
      let data = {
        apiId : '430',
        param:param,
        charsetValue:"clob"
      }
      const  res =  await handlerRequestNoAuth(data)
      this.src =res.data[0].data.data.data['DE01.00.018.08']
      console.log(this.src)
      this.openPdf = true
    }
  }
}
</script>

<style scoped lang="scss">
.textGreen {
  color: #28b276;
}

.textRed {
  color: red;
}

.icon-trend {
  color: #0A69F3;
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
}

.detail_text2 {
  //flex: 25%;
  //text-align: center;
}

.detail_text2-1 {
  //flex: 25%;
  //text-align: center;
  color: #3bbc72;
}

.detail_text2-2 {
  //flex: 25%;
  //text-align: center;
  color: red;
}

.tmp {
  white-space: nowrap; /*强制单行显示*/
  text-overflow: ellipsis; /*超出部分省略号表示*/
  overflow: hidden; /*超出部分隐藏*/
  //width: 100px;/*设置显示的最大宽度*/
  display: inline-flex;
}

.dialog-content {
  display: flex;
  padding: 10px;

  .dialog-left {
    width: 720px;
    flex: 0 0 auto;


    .dialog-head {
      display: flex;
      justify-content: space-between;
      font-size: 13px;
      color: #666666;

      .dialog-head-left {
        display: flex;

        .head-text {
          margin-right: 30px;
        }

        .dialog-val {
          color: #333333;
        }
      }
    }

    .dialog-chart {
      width: 100%;
      height: 460px;
    }
  }
}

.dialog-right {
  flex: 1 1 auto;
  padding-top: 210px;
  padding-left: 10px;
  font-size: 13px;

  .right-text {
    color: #333333;
    margin-bottom: 10px;
  }

  .right-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    color: #999999;

    .item-icon {
      width: 10px;
      height: 10px;
      border-radius: 200px;
      margin-right: 10px;
    }

    .bgBlue {
      background: #0A69F3;
    }

    .bgRed {
      background: red;
    }

    .bgGreen {
      background: #28b276;
    }
  }

  .right-date {
    margin-top: 105px;
    color: #666666;
  }

  .active {
    border: 1px solid #c8eddd;
    color: #28b276;
    background: #e6fcf2;
    position: relative;
  }

  .checkboxItem {
    margin-top: 10px;
    height: 40px;
    width: 100%;
  }
}
.dialogClass {
  .el-dialog {
    .el-dialog__body {
      //border-top: 1px solid #dcdfe6;
      //border-bottom: 1px solid #dcdfe6;
      max-height: 500px !important;
      min-height: 100px;
      overflow-y: hidden;
    }
  }
}

</style>
