<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <el-button type="primary" @click="$router.back(-1)">返回</el-button>
    </div>
    <div class="app-container">

      <div class="cell clearfix">
        <label class="title">
          <span class="name">病人搜索</span> :
        </label>
        <div >

          <el-form :inline="true">
            <el-form-item label>
              <el-autocomplete
                class="checkSearch"
                style="margin-top: 20px;"
                popper-class="my-autocomplete"
                v-model="search_value"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="false"
                placeholder="请输入病人名字"
                @select="handleSelect"
              >
                <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>
        </div>

      </div>

      <div class="cell clearfix">
        <label class="title">
          <span class="name">日期</span> :
        </label>
        <div class="time">
          <ul class>
            <li
              :class="item.state == stateType ? 'active' : ''"
              @click="selectStateType(item.state)"
              v-for="item in month"
              :key="item.value"
            >{{ item.label }}
            </li>
          </ul>
        </div>
        <el-date-picker
          v-if="stateType == 5"
          v-model="query.start_time"
          prefix-icon="el-icon-date"
          @change="changeTime"
          :editable="false"
          style="width: 196px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        ></el-date-picker>
        <span v-if="stateType == 5"
              class>-</span>
        <el-date-picker
          v-if="stateType == 5"
          v-model="query.end_time"
          prefix-icon="el-icon-date"
          @change="changeEndTime"
          :editable="false"
          style="width: 196px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </div>
      <el-container>
        <div style="width:150px">
          <div class="tableTitle">患者列表</div>
          <div class="tableTitle">当前患者: {{patient_name}}</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="80">
              <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="80">
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
          </el-table>

        </div>
        <div style="padding-left:10px;flex:1">
          <div class="tableTitle">统计图</div>
          <div>
            <!--<line-chart :options="options2"></line-chart>-->
            <line-chart v-if="this.$route.query.range_type == 1" :options="options"></line-chart>
            <line-chart v-if="this.$route.query.range_type == 2" :options="options2"></line-chart>



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


<script>

  const moment = require('moment')
  import echarts from 'echarts'
  import LineChart from '../../qcd/components/LineChart'
  import { uParseTime } from '@/utils/tools'
  import BreadCrumb from '@/xt_pages/components/bread-crumb'
  import { getCurrentOrgPatients } from '@/api/common/common'
  import {
    GetDefalutPatient,
    GetInspectionIndexChart,
    GetInspectionIndexInit,
    GetInspectionIndexTable,
    GetPatientInspectionIndexBarChart,
    GetPatientInspectionIndexChart,
    GetRangeValue
  } from '@/api/common/statistics'
  import { PostSearch } from '@/api/patient'

  export default {
    name: 'dialysisTotal',
    components: {
      LineChart,
      BreadCrumb
    },
    data() {
      return {
        custom_chart_data_color: [],
        patient_name: '',
        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']
                    ]

                    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)'
                }
              }
            }
          ]
        },
        options: {
          title: {
            text: "ECharts 入门示例"
          },
          tooltip: {},
          legend: {
            data: [""],
            left: 0
          },
          xAxis: {
            data: [],
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                var ret = ""; //拼接加\n返回的类目项
                var maxLength = 4; //每项显示文字个数
                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
          },
          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"]
                    ];

                    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: '#5B98FF' //改变折线颜色
                  },
                  barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
                },

                //鼠标悬停时：
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)"
                }
              }
            },
            {
              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"]
                    ];

                    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: '#f56c6c' //改变折线颜色
                  },
                  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 //锁定区域禁止缩放
            }
          ],
        },
        query: {
          patient_id: this.$route.query.patient_id,
          start_time: '',
          end_time: '',
          limit: 20,
          page: 1,
          project_id: this.$route.query.project_id,
          item_id: this.$route.query.item_id,
          range_type: this.$route.query.range_type,
          range_value: ''
        },
        patientsData: [],

        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

          }
        },
        crumbs: [
          { path: false, name: '质控管理' },
          { path: false, name: '基本信息统计' }
        ],
        listQuery: {
          start_time: '',
          end_time: '',
          page: 1,
          limit: 10
        },
        stateType: 1,
        month: [
          { value: 1, label: '近一个月', state: 1 },
          { value: 2, label: '近三个月', state: 2 },
          { value: 3, label: '近半年', state: 3 },
          { value: 4, label: '近一年', state: 4 },
          { value: 5, label: '自定义', state: 5 }
        ],
        search_value: ''
      }
    },
    methods: {
      handleSelect(val) {
        this.query.patient_id = val.id
        this.patient_name = val.name
        // 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([])
          }
        })
      },
      selectStateType(val) {
        this.stateType = val
        switch (val) {
          case 1: //本月

            this.query.start_time = moment().subtract('month', 1).format('YYYY-MM-DD')
            // 本月的结束时间
            this.query.end_time = moment(new Date()).format('YYYY-MM-DD')
            this.query.patient_id = this.$route.query.patient_id
            this.query.project_id = this.$route.query.project_id
            this.query.item_id = this.$route.query.item_id
            this.query.range_type = this.$route.query.range_type
            this.GetPatientInspectionIndexChart(this.query)

            break
          case 2: //近3个月
            const startDate = moment().subtract('month', 3).format('YYYY-MM-DD')
            this.query.start_time = startDate
            const endDate = moment(new Date()).format('YYYY-MM-DD')
            this.query.patient_id = this.$route.query.patient_id
            this.query.project_id = this.$route.query.project_id
            this.query.item_id = this.$route.query.item_id
            this.query.range_type = this.$route.query.range_type

            this.GetPatientInspectionIndexChart(this.query)

            break
          case 3: //近半年
            this.query.start_time = moment().subtract('month', 6).format('YYYY-MM-DD')
            this.query.end_time = moment(new Date()).format('YYYY-MM-DD')
            this.query.patient_id = this.$route.query.patient_id
            this.query.project_id = this.$route.query.project_id
            this.query.item_id = this.$route.query.item_id
            this.query.range_type = this.$route.query.range_type

            this.GetPatientInspectionIndexChart(this.query)
            break
          case 4: //近一年
            this.query.start_time = moment().subtract('month', 12).format('YYYY-MM-DD')
            this.query.end_time = moment(new Date()).format('YYYY-MM-DD')
            this.query.patient_id = this.$route.query.patient_id
            this.query.project_id = this.$route.query.project_id
            this.query.item_id = this.$route.query.item_id
            this.query.range_type = this.$route.query.range_type
            this.GetPatientInspectionIndexChart(this.query)
            break
          case 5: //自定义
            this.query.start_time = moment().subtract('month', 1).format('YYYY-MM-DD')
            // 本月的结束时间
            this.query.end_time = moment(new Date()).format('YYYY-MM-DD')
            this.query.patient_id = this.$route.query.patient_id
            this.query.project_id = this.$route.query.project_id
            this.query.item_id = this.$route.query.item_id
            this.query.range_type = this.$route.query.range_type
            this.GetPatientInspectionIndexChart(this.query)
            break
        }

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

            for (let i = 0; i < this.patientsData.length; i++) {
              if (this.patientsData[i].id == this.query.patient_id) {
                this.patient_name = this.patientsData[i].name
                this.$refs.table.setCurrentRow(this.patientsData[i])
              }
            }

          }
        })
      }, handleChange(val) {
        this.query.patient_id = val.id
        this.query.page = 1
        this.patient_name = val.name
        this.GetPatientInspectionIndexChart(this.query)
      }, changeTime(val) {
        var time = this.getTimestamp(val) - this.getTimestamp(this.query.end_time)
        if (time > 0) {
          this.$message.error('结束时间不能小于开始时间')
        } else {
          console.log(this.query)
          this.GetPatientInspectionIndexChart(this.query)
        }
      },
      changeEndTime(val) {
        var time =
          this.getTimestamp(val) - this.getTimestamp(this.query.start_time)
        if (time < 0) {
          this.$message.error('结束时间不能小于开始时间')
        } else {
          console.log(this.query)
          this.GetPatientInspectionIndexChart(this.query)

        }
      },
      GetPatientInspectionIndexChart(params) {
        this.options.xAxis.data = []
        this.options.series[0].data = []

        this.options2.xAxis.data = []
        this.options2.series[0].data = []
        GetPatientInspectionIndexChart(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {

              let tempData = []
              let otherData = []

              for (let i = 0; i < resp.data.data.length; i++) {
                if (this.$route.query.range_type == 1) {
                  this.options.xAxis.data.push(resp.data.data[i].date)
                  this.options.series[0].data.push(resp.data.data[i].value)
                }else{
                  this.options2.series[0].data.push("1")
                  this.options2.xAxis.data.push(resp.data.data[i].date)
                  tempData.push(resp.data.data[i].value)
                  otherData.push(resp.data.data[i].value)
                }
              }

              console.log(this.options.series[0].data)

              //获取无法确定选项的颜色
              if (this.query.range_type == 2) {
                //去重复
                let obj = {}
                tempData = tempData.reduce((cur, next) => {
                  obj[next] ? '' : (obj[next] = true && cur.push(next))
                  return cur
                }, [])

                //随机获取颜色值
                let newObj = {}
                for (let i = 0; i < tempData.length; i++) {
                  newObj[tempData[i]] = this.getColor()
                }

                //匹配对应的颜色值
                for (let i = 0; i < otherData.length; i++) {
                  for (let key in newObj) {
                    if (otherData[i] === key) {
                      this.custom_chart_data_color.push(newObj[key])
                    }
                  }
                }
              }

            } else {
            }
          })
          .catch(error => {

          })

      }, getTimestamp(time) {
        // 把时间日期转成时间戳
        return new Date(time).getTime() / 1000
      }

    },
    created() {

      this.getCurrentOrgPatients()
      this.query.start_time = moment().subtract('month', 1).format('YYYY-MM-DD')
      this.query.end_time = moment(new Date()).format('YYYY-MM-DD')
      this.query.patient_id = this.$route.query.patient_id
      this.query.project_id = this.$route.query.project_id
      this.query.item_id = this.$route.query.item_id
      this.query.range_type = this.$route.query.range_type
      this.GetPatientInspectionIndexChart(this.query)
    }
  }
</script>

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

  .infoBox {
    display: flex;
    flex-wrap: wrap;

  .infoOne {
    margin-right: 30px;
    margin-top: 30px;

  .titleBox {
    display: flex;
    align-items: center;
  }

  .point {
    display: inline-block;
    width: 7px;
    height: 7px;
    background: linear-gradient(
      90deg,
      rgba(169, 224, 243, 1),
      rgba(159, 189, 252, 1)
    );
    border-radius: 50%;
  }

  .point1 {
    width: 7px;
    height: 7px;
    background: linear-gradient(
      90deg,
      rgba(255, 215, 192, 1),
      rgba(255, 153, 148, 1)
    );
    border-radius: 50%;
  }

  .point2 {
    width: 7px;
    height: 7px;
    background: linear-gradient(
      90deg,
      rgba(215, 195, 253, 1),
      rgba(179, 168, 247, 1)
    );
    border-radius: 50%;
  }

  .infoTitle {
    font-size: 16px;
    font-weight: bold;
    margin-left: 5px;
    color: #000;
  }

  .borderBox {
    width: 340px;
    min-height: 140px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(229, 229, 229, 1);
    border-radius: 10px;
    padding: 0 14px 20px;
    margin-top: 10px;

  p {
    font-size: 14px;
    color: #000;
    margin: 10px 0 3px;
  }

  }
  .borderBox1 {
    width: 340px;
    min-height: 140px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(229, 229, 229, 1);
    border-radius: 10px;
    padding: 0 14px 20px;
    margin-top: 10px;

  p {
    font-size: 14px;
    color: #000;
    margin: 10px 0 3px;
  }

  }
  .borderBox2 {
    width: 340px;
    min-height: 140px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(229, 229, 229, 1);
    border-radius: 10px;
    padding: 0 14px 20px;
    margin-top: 10px;

  p {
    font-size: 14px;
    color: #000;
    margin: 10px 0 3px;
  }

  }
  }
  }
</style>

<style lang="scss">
  .infoBox {

  .infoOne {

  .borderBox {

  .el-progress-bar__inner {
    background: linear-gradient(
      90deg,
      rgba(169, 224, 243, 1),
      rgba(159, 189, 252, 1)
    );
  }

  .el-progress-bar {
    margin-right: -59px;
    padding-right: 60px;
  }

  }
  .borderBox1 {

  .el-progress-bar__inner {
    background: linear-gradient(
      90deg,
      rgba(255, 215, 192, 1),
      rgba(255, 153, 148, 1)
    );
  }

  .el-progress-bar {
    margin-right: -59px;
    padding-right: 60px;
  }

  }
  .borderBox2 {

  .el-progress-bar__inner {
    background: linear-gradient(
      90deg,
      rgba(215, 195, 253, 1),
      rgba(179, 168, 247, 1)
    );
  }

  .el-progress-bar {
    margin-right: -59px;
    padding-right: 60px;
  }

  }
  }
  }
</style>


