<template>
  <div class="page_personal">
    <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>
      <el-select v-model="query.project_id" placeholder="请选择" style="width:120px;margin-right:10px"
                 @change="changeProject">
        <el-option
          v-for="item in project_columns"
          :key="item.project_id"
          :label="item.project_name"
          :value="item.project_id"
        ></el-option>
      </el-select>

      <el-select
        v-model="query.item_id"
        placeholder="请选择"
        style="width:120px;margin-right:10px"
        @change="changeItem"
      >
        <el-option
          v-for="item in item_columns"
          :key="item.id"
          :label="item.item_name"
          :value="item.id"
        ></el-option>
      </el-select>

      <!--<el-select v-model="query.range_value" placeholder="请选择" style="width:120px;margin-right:20px"-->
                 <!--@change="changeRangeValue">-->
        <!--<el-option-->
          <!--v-for="item in range_value_columns"-->
          <!--:key="item"-->
          <!--:label="item"-->
          <!--:value="item"-->
        <!--&gt;</el-option>-->
      <!--</el-select>-->

      <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"
        :picker-options="pickerOptions"
        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"
        :picker-options="pickerOptions"
        style="width: 150px;"
        type="date"
        placeholder="选择日期时间"
        align="right"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
    </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">
            <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="90">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div style="padding-left:10px;flex:1">
        <div class="tableTitle" style="magrin-bottom:0;">统计图<span style="font-weight:normal">&nbsp;&nbsp;（当前患者:{{patient_name}}）</span></div>
        <div>
          <line-chart :options="options"></line-chart>
        </div>
        <div class="tableTitle">指标趋势</div>
        <div>
          <div>
            <line-chart :options="options2"></line-chart>
          </div>
        </div>
        <div></div>
      </div>
    </el-container>
  </div>
</template>


<script>
  import echarts from 'echarts'
  import LineChart from '../../components/LineChart'
  import {
    GetInspectionIndexChart,
    GetInspectionIndexInit,
    GetInspectionIndexTable,
    GetPatientInspectionIndexBarChart,
    GetPatientInspectionIndexChart,
    GetRangeValue,
    GetDefalutPatient
  } from '@/api/common/statistics'
  import { uParseTime } from '@/utils/tools'
  import { getCurrentOrgPatients } from '@/api/common/common'

  import { PostSearch } from '@/api/patient'

  export default {
    components: {
      LineChart
    },
    data() {
      return {
        percent:[],

        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:'',
        item_name: '',
        search_value: '',
        query: {
          patient_id: '',
          start_time: '',
          end_time: '',
          limit: 20,
          page: 1,
          project_id: '',
          item_id: '',
          range_type: '',
          range_value: ''
        },
        project_columns: [],
        item_columns: [],
        range_value_columns: [],

        all_inspection_reference: [],
        patientsData: [],
        value: '请选项',
        tableData: [],
        options: {
          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)'
                }
              }
            }
          ]
        },
        options2: {
          title: {
            text: 'ECharts 入门示例'
          },
          tooltip: {},
          legend: {
            data: ['次数'],
            left: 0
          },
          xAxis: {
            data: [],
            axisLine: {
              lineStyle: {
                color: '#FF0000',
                width: 8 //这里是为了突出显示加上的
              }
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                var ret = '' //拼接加\n返回的类目项
                var maxLength = 8 //每项显示文字个数
                var valLength = value.length //X轴类目项的文字个数
                var rowN = Math.ceil(valLength / maxLength) //类目项需要换行的行数
                if (rowN > 1) {
                  //如果类目项的文字大于3,
                  for (var i = 0; i < rowN; i++) {
                    var temp = '' //每次截取的字符串
                    var start = i * maxLength //开始截取的位置
                    var end = start + maxLength //结束截取的位置
                    //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
                    temp = value.substring(start, end) + '\n'
                    ret += temp //凭借最终的字符串
                  }
                  return ret
                } else {
                  return value
                }
              }
            }
          },
          yAxis: {
            axisLabel: {
              formatter: '{value} %'
            },
            show: false,
            axisLine: {
              lineStyle: {
                color: '#00FF00',
                width: 8 //这里是为了突出显示加上的
              }
            }
          },
          series: [
            {
              name: '',
              type: 'line',
              data: [],
              barWidth: 30,
              label: {
                normal: {
                  show: true,
                  position: 'top',
                  formatter: '{c}'
                }
              },
              //配置样式
              itemStyle: {
                //通常情况下：

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

                      ["#FFD7C0", "#FF9994"],
                      ["#D7C3FD", "#B3A8F7"],
                    ];

                    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 // 锁定区域禁止缩放
            }
          ]
        }

      }
    },
    methods: {
      handleChange(val){
        this.query.patient_id = val.id
        this.query.page = 1
        this.patient_name = val.name
        this.GetPatientInspectionIndexBarChart(this.query)
        this.GetPatientInspectionIndexChart(this.query)
      },
      handleSelect(val) {
        this.query.patient_id = val.id
        this.query.page = 1
        this.patient_name = val.name
        this.GetPatientInspectionIndexBarChart(this.query)
        this.GetPatientInspectionIndexChart(this.query)

        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([])
          }
        })
      },

      getCurrentOrgPatients() {
        getCurrentOrgPatients().then(response => {
          if (response.data.state == 1) {
            var patients = response.data.data.patients
            this.patientsData = patients

            GetDefalutPatient()
              .then(rs => {
                var resp = rs.data
                if (resp.state == 1) {
                  this.query.patient_id =resp.data.patient.id
                  this.patient_name  = resp.data.patient.name

                  for (let i = 0; i< this.patientsData.length; i++){
                    if(this.patientsData[i].id == resp.data.patient.id){
                      this.$refs.table.setCurrentRow(this.patientsData[i])
                    }
                  }


                  this.GetInspectionIndexInit()
                } else {

                }
              })
              .catch(error => {

              })

          }
        })
      },
      changeProject(val) {
        this.query.page = 1
        let item_inspection_reference = []
        for (let i = 0; i < this.all_inspection_reference.length; i++) {
          if (this.all_inspection_reference[i].project_id == val) {
            item_inspection_reference.push(this.all_inspection_reference[i])
          }
        }
        this.item_columns = item_inspection_reference
        var projectInfo = this.getPojectInfo(this.item_columns[0].project_id, this.item_columns[0].id)
        this.query.project_id = projectInfo.project_id
        this.query.item_id = projectInfo.id
        this.item_name = projectInfo.item_name
        this.query.range_type = projectInfo.range_type
        this.GetRangeValue(projectInfo.range_type, projectInfo.project_id, projectInfo.id)

      }, changeItem(val) {
        this.query.page = 1
        this.query.item_id = val
        var projectInfo = this.getPojectInfo(this.query.project_id, val)
        this.item_name = projectInfo.item_name
        this.GetRangeValue(projectInfo.range_type, projectInfo.project_id, projectInfo.id)

      }, changeRangeValue(val) {
        this.query.range_value = val
        this.query.page = 1
        // this.GetInspectionIndexTable(this.query)



      }, GetInspectionIndexInit() {
        GetInspectionIndexInit()
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              let project = []
              let item = []
              this.all_inspection_reference = resp.data.references

              for (let i = 0; i < this.all_inspection_reference.length; i++) {
                project.push(this.all_inspection_reference[i])
              }
              var obj = {}
              //去重复
              project = project.reduce((cur, next) => {
                obj[next.project_id] ? '' : (obj[next.project_id] = true && cur.push(next))
                return cur
              }, [])

              this.project_columns = project

              for (let i = 0; i < this.all_inspection_reference.length; i++) {
                if (this.all_inspection_reference[i].project_id == this.project_columns[0].project_id) {
                  item.push(this.all_inspection_reference[i])
                }
              }
              this.item_columns = item
              this.item_name = item[0].item_name

              var projectInfo = this.getPojectInfo(this.project_columns[0].project_id, this.item_columns[0].id)
              this.query.project_id = projectInfo.project_id
              this.query.item_id = projectInfo.id
              this.query.range_type = projectInfo.range_type
              this.GetRangeValue(projectInfo.range_type, projectInfo.project_id, projectInfo.id)
            } else {
              this.$message.error(resp.msg)

            }
          })
          .catch(error => {

          })

      },
      getPojectInfo(project_id, item_id) {
        for (let i = 0; i < this.all_inspection_reference.length; i++) {
          if (this.all_inspection_reference[i].project_id == project_id && this.all_inspection_reference[i].id == item_id) {
            return this.all_inspection_reference[i]
          }
        }
        return null
      }, changeTime(val) {
        var time = this.getTimestamp(val) - this.getTimestamp(this.query.end_time)
        if (time > 0) {
          this.$message.error('结束时间不能小于开始时间')
        } else {
          // this.getDialysisList()
          this.query.page = 1
          this.GetInspectionIndexChart(this.query)
          this.GetInspectionIndexTable(this.query)

        }

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

        }
      }, GetRangeValue(range_type, project_id, id) {
        let params = {
          range_type: range_type,
          project_id: project_id,
          item_id: id
        }
        GetRangeValue(params)
          .then(rs => {
              var resp = rs.data
              if (resp.state == 1) {
                if (range_type == 1) {
                  this.range_value_columns = []
                  this.range_value_columns.push('全部')
                  this.range_value_columns.push('小于' + resp.data.range_vaule[0])
                  this.range_value_columns.push(resp.data.range_vaule[0] + '~' + resp.data.range_vaule[1])
                  this.range_value_columns.push('大于' + resp.data.range_vaule[1])
                  this.query.range_value = '全部'

                } else {
                  this.range_value_columns = []
                  this.range_value_columns.push('全部')
                  for (let i = 0; i < resp.data.range_vaule.length; i++) {
                    this.range_value_columns.push(resp.data.range_vaule[i])
                  }
                  this.query.range_value = '全部'
                }

                this.GetPatientInspectionIndexBarChart(this.query)
                this.GetPatientInspectionIndexChart(this.query)

              } else {
                this.$message.error(resp.msg)

              }
            }
          )
          .catch(error => {

          })
      },
      GetPatientInspectionIndexBarChart(params) {
        this.options.xAxis.data = []
        this.options.series[0].data = []
        GetPatientInspectionIndexBarChart(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              for (let i = 0; i < resp.data.data.length; i++) {
                this.options.xAxis.data.push(resp.data.data[i].name)
                this.options.series[0].data.push(resp.data.data[i].total)
                this.percent.push(resp.data.data[i].ratio)

              }

            } else {
              this.$toast({
                message: resp.msg
              })
            }
          })
          .catch(error => {

          })

      },
      GetPatientInspectionIndexChart(params) {
        this.options2.xAxis.data = []
        this.options2.series[0].data = []
        GetPatientInspectionIndexChart(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              for (let i = 0; i < resp.data.data.length; i++) {
                this.options2.xAxis.data.push(resp.data.data[i].date)
                this.options2.series[0].data.push(resp.data.data[i].value)
              }
              this.getArrLength(this.options2.xAxis.data)

            } else {

            }
          })
          .catch(error => {

          })

      },   getTimestamp(time) {
        // 把时间日期转成时间戳
        return new Date(time).getTime() / 1000;
      },
      getArrLength(result){
        if(result.length > 10){
          var dataZoom_end = (10/result.length)*100;
          this.options2.dataZoom[0].end = dataZoom_end
        }else{
          var dataZoom_end = 100;
          this.options2.dataZoom[0].end = dataZoom_end
        }
      }

    }, created() {
      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.end_time = year + '-' + month + '-' + day
      this.query.start_time = year + '-' + last_month + '-' + day


      this.getCurrentOrgPatients()

    }
  }
</script>


<style lang="scss" scoped>
  .tableTitle {
    font-size: 16px;
    color: #000;
    font-weight: bold;
    margin-bottom: 10px;
  }
</style>
<style lang="scss">
  .page_personal {

  .cell {
    text-align: center;
  }

  .el-button--medium {
    padding: 10px 8px;
  }

  .el-form-item {
    margin-bottom: 0;
  }

  }
</style>
