<template>
  <div class="page_office">
    <div class="cell clearfix">
      <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:10px"
                 @change="changeRangeValue">
        <el-option
          v-for="item in range_value_columns"
          :key="item"
          :label="item"
          :value="item"
        ></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>
    <div class="tableTitle">统计图</div>
    <div>
      <line-chart :options="options"></line-chart>
    </div>
    <div class="tableTitle">统计表</div>
    <div>
      <el-table :data="tableData" style="width: 100%" 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.patient.name}}
          </template>
        </el-table-column>

        <el-table-column  label="检查日期" align="center">
          <template slot-scope="scope">
            <!--{{getTime(scope.row.inspect_date)}}-->
            {{scope.row.inspect_date | parseTime('{y}-{m}-{d}') }}

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


        <el-table-column :label="item_name" align="center">
          <template slot-scope="scope">
            <span v-html="getValue(scope.row)"></span>

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

        <el-table-column label="趋势" align="center">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="jumpDetail(scope.row)"
              type="text"
              size="small"
              style="font-size:14px;"
            >详情
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        background
        style="margin-top:20px;"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>


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

  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

          }
        },
        range_type:'',
        total:0,
        item_name: '',
        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: [],

        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"],
                    ["#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]}
                    ])
                  },
                  barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
                },

                //鼠标悬停时：
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
      }
    },
    methods: {
      getValue(row) {
        if (this.query.range_type == 1 ) {
          if(row.inspect_value != "") {
            let min_range_value = this.range_value_columns[2]
            let arr = min_range_value.split("~")
            if (parseFloat(row.inspect_value) > arr[1]) {
              return row.inspect_value + "<span style='color:#F56C6C;margin-left:5px;'>↑</span>"
            } else if (parseFloat(row.inspect_value) < arr[0]) {
              return row.inspect_value + "<span style='color:#5B98FF;margin-left:5px;'>↓</span>"
            } else {
              return row.inspect_value
            }
          }else{
            return row.inspect_value
          }

        } else if (this.query.range_type == 2) {
          return row.inspect_value
        }
      },
      getTimestamp(time) {
        // 把时间日期转成时间戳
        return new Date(time).getTime() / 1000;
      },
      jumpDetail(row){
        // this.$router.push("/qcd/indicatorControlAnalysis/bloodPressureDetails?id="+patient_id)
        this.$router.push("/qcd/inspection/detail?project_id="+row.project_id+"&item_id="+row.item_id+"&range_type="+this.query.range_type+"&patient_id="+row.patient.id)
      },
      handleSizeChange(limit) {
        this.query.limit = limit
        this.GetInspectionIndexTable(this.query)

      },
      handleCurrentChange(page) {
        this.query.page = page
        this.GetInspectionIndexTable(this.query)

      },
      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)
        console.log("projectInfo",projectInfo)
        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)
        console.log(projectInfo)
        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
               console.log("====",this.all_inspection_reference)
              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])
                }
              }
             console.log("item",item)
              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)

        }
      },
      handleClick(row) {
        console.log(row)
        this.$router.push({ path: '/qcd/analysisDetails' })
      },
      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.GetInspectionIndexChart(this.query)
                this.GetInspectionIndexTable(this.query)
              } else {
                this.$message.error(resp.msg)

              }
            }
          )
          .catch(error => {

          })
      },
      GetInspectionIndexChart(params) {
        this.options.xAxis.data = []
        this.options.series[0].data = []
        this.percent = []
        GetInspectionIndexChart(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.$message.error(resp.msg)
            }
          })
          .catch(error => {

          })
      },
      GetInspectionIndexTable(params) {
        GetInspectionIndexTable(params)
          .then(rs => {
            var resp = rs.data
            console.log("resp",resp)
            if (resp.state == 1) {
              this.tableData = []
              for (let i = 0; i < resp.data.data.length; i++) {
                this.tableData.push(resp.data.data[i])
              }
              this.total = resp.data.total

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

          })

      }
    },
    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.GetInspectionIndexInit()
      // this.GetDialysisBloodPressureTableData(this.query)

    }

  }

</script>


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

  .cell {
    text-align: center;
  }

  }
</style>
