<template>
  <div class="main-contain">
    <div class="app-container">
      <div class="page_process">
        <new-nav activeName="process"></new-nav>
        <div class="cell clearfix">
          <el-form :inline="true">
            <el-form-item label>
              <el-autocomplete
                class="checkSearch"
                popper-class="my-autocomplete"
                v-model="search_value"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="false"
                placeholder="请输入病人名字"
                @select="handleSelect"
                style="width:160px;"
              >
                <i class="el-icon-search el-input__icon" slot="suffix"></i>
                <template slot-scope="{ item }">
                  <div class="name">{{ item.name }}</div>
                </template>
              </el-autocomplete>

            </el-form-item>
          </el-form>

          <label class="title">
            <span class="name">日期查询</span> :
          </label>
          <el-date-picker
            v-model="query.start_time"
            prefix-icon="el-icon-date"
            @change="changeTime"
            :editable="false"
            style="width: 150px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
          <span class>-</span>
          <el-date-picker
            v-model="query.end_time"
            prefix-icon="el-icon-date"
            @change="changeEndTime"
            :editable="false"
            style="width: 150px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>

          <el-button size="small" icon="el-icon-printer" @click="printAction" type="primary">打印
          </el-button>
          <el-button size="small" icon="el-icon-printer" @click="exportAction" type="primary">导出

          </el-button>
        </div>

        <el-container>
          <div style="width:160px">

            <div class="tableTitle">患者列表</div>


            <el-table ref="table" :data="patientsData" border style="width: 100%;" height="500"
                      :row-style="{ color: '#303133' }"
                      :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                      highlight-current-row
                      @current-change="handleChange">
              <el-table-column prop="dialysis_no" label="透析号" width="70" align="center">
                <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" width="90" align="center">
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
            </el-table>
          </div>
          <div style="padding-left:10px;flex:1;width:0;">
            <div class="tableTitle">指标趋势<span style="font-weight:normal">&nbsp;&nbsp;（当前患者: {{patient_name}}）</span></div>
            <div>
              <line-chart :options="chart"></line-chart>
              <!--              <line-chart :options="bar" v-if="query.statistics_type == 9 || query.statistics_type == 10"></line-chart>-->
              <!--              <line-chart></line-chart>-->

            </div>
            <div class="tableTitle">统计表</div>
            <div>
              <el-table ref="table" :data="tableData" v-loading="loading" border :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
                <el-table-column label="姓名" align="center">
                  <template slot-scope="scope">
                    {{scope.row.name}}
                  </template>
                </el-table-column>

                <el-table-column width="100" label="检查日期" align="center">
                  <template slot-scope="scope">
                    {{getTime(scope.row.inspect_date)}}

                  </template>
                </el-table-column>

                <el-table-column width="100" label="URR(%)" align="center">
                  <template slot-scope="scope">
                    {{parseFloat(scope.row.value).toFixed(1)}}
                  </template>
                </el-table-column>
              </el-table>


            </div>
          </div>
        </el-container>
      </div>
    </div>
  </div>
</template>


<script>
import echarts from 'echarts'
import {  uParseTime } from '@/utils/tools'
import { getCurrentOrgPatients } from '@/api/common/common'
import {
  GetDefaultPatient,
} from '@/api/common/statistics'
import { PostSearch } from '@/api/patient'
import { getDataConfig } from '@/utils/data'
import { GetPersonQCStatistisData } from '../../../api/qcd'
import LineChart from '../../qcd/components/LineChart.vue'

export default {
  components: {
    LineChart
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          let threeMonths = new Date(new Date().setFullYear(new Date().getFullYear() - 1)).getTime() - 24 * 3600 * 1000
          return time.getTime() > Date.now() || time.getTime() < threeMonths

        }
      },
      patient_name:'',
      percent:[],
      patientsData: [],
      tableData: [],
      loading: false,
      search_value: '',
      total: 0,
      query: {
        patient_id: '',
        statistics_type: 1,
        start_time: '',
        end_time: '',
        type:3,
        limit: 10,
        page: 1
      },
      crumbs: [
        { path: false, name: '科室质控' },
        { path: false, name: '指标评估统计' },
        { path: false, name: '透析过程指标统计' }
      ],
      tableData1: [],
      chart: {
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        legend: {
          data: [],
          left: 0
        },
        xAxis: {
          data: []
        },
        yAxis: {
          axisLabel: {
            formatter: '{value} %'
          },
          show: false
        },
        series: [
          {
            name: '',
            type: 'line',
            data: [],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: 'top',
                formatter: (params) => {
                  if(this.percent.length > 0){
                    let str = ''
                    str = params.data + '('+ this.percent[params.dataIndex] +'%)'
                    return str
                  }else{
                    let str = ''
                    str = params.data
                    return str
                  }
                }
              }
            },
            //配置样式
            itemStyle: {
              //通常情况下：

              //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
              normal: {
                color: function(params) {
                  //我这边就两个柱子，大体就两个柱子颜色渐变，所以数组只有两个值，多个颜色就多个值
                  var colorList = [
                    ['#A9E0F3', '#9FBDFC'],

                    ['#FFD7C0', '#FF9994']
                  ]

                  var index = params.dataIndex
                  if (params.dataIndex >= colorList.length) {
                    index = params.dataIndex % colorList.length
                  }

                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: colorList[index][0] },
                    // { offset: 0.5, color: colorList[index][1] },
                    { offset: 1, color: colorList[index][1] }
                  ])
                },
                lineStyle:{
                  color:'#409eff' //改变折线颜色
                },
                barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
              },

              //鼠标悬停时：
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ],
        dataZoom: [
          {
            // Y轴固定,让内容滚动
            type: 'slider',
            show: false,
            xAxisIndex: [0],
            start: 1,
            end: 20, // 设置X轴刻度之间的间隔(根据数据量来调整)
            zoomLock: true // 锁定区域禁止缩放(鼠标滚动会缩放,所以禁止)
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 1,
            end: 20,
            zoomLock: true // 锁定区域禁止缩放
          }
        ]
      },
      bar: {
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        legend: {
          data: [],
          left: 0
        },
        xAxis: {
          data: []
        },
        yAxis: {
          axisLabel: {
            formatter: '{value} %'
          },
          show: false
        },
        series: [
          {
            name: '',
            type: 'bar',
            data: [],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: 'top',
                formatter: (params) => {
                  if(this.percent.length > 0){
                    let str = ''
                    str = params.data + '('+ this.percent[params.dataIndex] +'%)'
                    return str
                  }else{
                    let str = ''
                    str = params.data
                    return str
                  }
                }
              }
            },
            //配置样式
            itemStyle: {
              //通常情况下：

              //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
              normal: {
                color: function(params) {
                  //我这边就两个柱子，大体就两个柱子颜色渐变，所以数组只有两个值，多个颜色就多个值
                  var colorList = [
                    ['#A9E0F3', '#9FBDFC'],
                    ['#FFD7C0', '#FF9994']
                  ]

                  var index = params.dataIndex
                  if (params.dataIndex >= colorList.length) {
                    index = params.dataIndex % colorList.length
                  }

                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: colorList[index][0] },
                    // { offset: 0.5, color: colorList[index][1] },
                    { offset: 1, color: colorList[index][1] }
                  ])
                },
                barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
              },

              //鼠标悬停时：
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

    }
  },
  methods: {
    printAction(){
      this.$router.push({
        path: "/Dialysisanalysis/qualitycontrol/print?patient_id=" + this.query.patient_id+"&project_id="+this.query.project_id+"&item_id="+this.query.item_id+"&start_time="+this.query.start_time+"&end_time="+this.query.end_time
      });

    },exportAction(){
      let list = []
      for (let i = 0; i < this.tableData.length; i++) {
        let order = this.tableData[i]
        let name = order.name
        let value = order.value
        let inspect_date = order.inspect_date

        let obj = {
          '姓名': name,
          '数值': value,
          '日期': inspect_date,
        }
        list.push(obj)
      }
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['姓名', '数值', '日期']
        const filterVal = ['姓名', '数值', '日期']
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel1({
          header: tHeader,
          data,
          filename: '明细',
          ref: this.$refs['table'].$el
        })
      })
    },
    changeProject(val) {
      this.query.statistics_type = val
      this.query.page = 1
      this.GetPersonQCStatistisData(this.query)
      this.GetInspectionCheckIndexTableData(this.query)

    },
    handleChange(val) {
      this.query.patient_id = val.id
      this.query.page = 1
      this.patient_name = val.name
      this.GetPersonQCStatistisData(this.query)
      this.GetInspectionCheckIndexTableData(this.query)
    },
    handleSizeChange(limit) {
      this.query.limit = limit
      this.GetInspectionCheckIndexTableData(this.query)

    },
    handleCurrentChange(page) {
      this.query.page = page
      this.GetPersonQCStatistisData(this.query)
    },formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeTime(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.query.end_time)
      if (time > 0) {
        this.$message.error('结束时间不能小于开始时间')
        this.query.start_time = ''
      } else {
        // this.getDialysisList()
        this.query.page = 1
        this.GetPersonQCStatistisData(this.query)
        this.GetInspectionCheckIndexTableData(this.query)

      }

    },
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.query.start_time)
      if (time < 0) {
        this.$message.error('结束时间不能小于开始时间')
        this.query.end_time = ''
      } else {
        this.query.page = 1
        this.GetPersonQCStatistisData(this.query)
        this.GetInspectionCheckIndexTableData(this.query)

      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000
    },
    QueryOperaById: function(val) {
      let vascular_access_desc_name = ''
      let vascular_access_desc = getDataConfig(
        'hemodialysis',
        'vascular_access_desc'
      )
      for (let i = 0; i < vascular_access_desc.length; i++) {
        if (vascular_access_desc[i].id == val) {
          vascular_access_desc_name = vascular_access_desc[i].name
        }
      }

      return vascular_access_desc_name
    },
    GetAnticoagulantById: function(val) {
      let anticoagulan_name = ''
      var anticoagulantsConfitTwo = this.$store.getters.anticoagulants_confit
      let anticoagulant = anticoagulantsConfitTwo
      for (let keys in anticoagulant) {
        if (anticoagulant[keys].id == val) {
          anticoagulan_name = anticoagulant[keys].name
        }
      }
      return anticoagulan_name
    },
    getModeName(mode_id) {
      return this.$store.getters.treatment_mode[mode_id] != undefined ? this.$store.getters.treatment_mode[mode_id].name : ''
    },  getTime(val) {
      if(val == "" || val == undefined){
        return ""
      }else {
        return uParseTime(val, '{y}-{m}-{d}')
      }
    },
    GetInspectionCheckIndexTableData(params) {
      this.loading = true
      GetPersonQCStatistisData(params)
        .then(rs => {
          var resp = rs.data
          console.log("resp=====",resp)
          if (resp.state == 1) {
            this.loading = false
            this.tableData = []
            for (let i = 0; i < resp.data.inspections.length; i++) {
              let obj = {
                name:resp.data.patient.name,
                value:parseFloat(resp.data.inspections[i].inspect_value).toFixed(1),
                inspect_date:resp.data.inspections[i].inspect_date
              }
              this.tableData.push(obj)
            }
            this.total = resp.data.total

          } else {
            this.loading = false
          }
        })
        .catch(error => {

        })
    },
    GetPersonQCStatistisData(params) {
      this.chart.xAxis.data = []
      this.chart.series[0].data = []
      this.bar.xAxis.data = []
      this.bar.series[0].data = []
      this.percent = []
      GetPersonQCStatistisData(params)
        .then(rs => {
          var resp = rs.data
          if (resp.state == 1) {
            console.log(resp.data.inspections)
            for (let i = 0; i < resp.data.inspections.length; i++) {
              this.chart.xAxis.data.push(this.getTime(resp.data.inspections[i].inspect_date))
              this.chart.series[0].data.push(resp.data.inspections[i].inspect_value)
            }
            console.log(this.chart.xAxis.data)
            console.log( this.chart.series[0].data)

            this.getArrLength(this.chart.xAxis.data,1)
          } else {

          }
        })
        .catch(error => {
        })
    },
    handleSelect(val) {
      this.query.patient_id = val.id
      this.query.page = 1
      this.patient_name = val.name
      for (let i = 0;i < this.patientsData.length; i++){
        if (this.patientsData[i].id == val.id){
          this.$refs.table.setCurrentRow(this.patientsData[i])
        }
      }


    },
    querySearchAsync(keyword, cb) {
      let key = ''
      if (keyword != undefined) {
        key = keyword
      }
      let searchArray = []
      PostSearch(key).then(response => {
        if (response.data.state == 1) {
          searchArray = response.data.data.patient
          cb(searchArray)
        } else {
          cb([])
        }
      })
    },
    chooseWay(way) {
      this.wayType = way
    }, getCurrentOrgPatients() {
      getCurrentOrgPatients().then(response => {
        if (response.data.state == 1) {
          var patients = response.data.data.patients
          this.patientsData = patients
          this.GetDefaultPatient()
        }
      })
    }, GetDefaultPatient() {
      GetDefaultPatient().then(response => {
        if (response.data.state == 1) {
          var patient = response.data.data.patient
          for (let i = 0;i < this.patientsData.length; i++){
            if (this.patientsData[i].id == patient.id){
              this.patient_name = this.patientsData[i].name
              this.$refs.table.setCurrentRow(this.patientsData[i])
            }
          }
          this.query.patient_id = patient.id
          this.GetPersonQCStatistisData(this.query)

        }
      })

    },
    getArrLength(result,type){
      if(type == 1){
        if(result.length > 10){
          var dataZoom_end = (10/result.length)*100;
          this.chart.dataZoom[0].end = dataZoom_end
        }else{
          var dataZoom_end = 100;
          this.chart.dataZoom[0].end = dataZoom_end
        }
      }else if(type == 2){
        if(result.length > 10){
          var dataZoom_end = (10/result.length)*100;
          this.bar.dataZoom[0].end = dataZoom_end
        }else{
          var dataZoom_end = 100;
          this.bar.dataZoom[0].end = dataZoom_end
        }
      }

    }
  }, mounted() {
    var date = new Date()
    var year = date.getFullYear() //获取完整的年份(4位)
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : date.getMonth() + 1 //获取当前月份(0-11,0代表1月)
    var day = date.getDate() < 10 ? '0' + date.getDate().toString() : date.getDate() //获取当前日(1-31)
    var last_month = date.getMonth() < 10 ? '0' + date.getMonth().toString() : date.getMonth() //获取当前月份(0-11,0代表1月)
    this.query.patient_id = 0
    this.query.end_time = year + '-' + month + '-' + day
    this.query.start_time = year + '-' + last_month + '-' + day
    this.query.project_id = 1
    this.query.item_id = 166
    this.getCurrentOrgPatients()

    // this.GetPersonQCStatistisData()


  }
}
</script>

<style lang="scss" scoped>
.tableTitle {
  font-size: 16px;
  color: #000;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
<style lang="scss">
.page_process {
.el-tabs{
  margin-bottom:0 !important;
}
.el-button--medium {
  padding: 10px 8px;
}

.el-form-item {
  margin-bottom: 0;
}
::-webkit-scrollbar{
  height: 15px !important;
}

}
</style>
