<template>
    <div>
        <div class="cell clearfix">
          <el-select v-model="query.admin_user_id" placeholder="请选择" style="width:120px;margin-right:10px"               @change="changeNurse"
          >
            <el-option
              v-for="item in nurse_options"
              :key="item.id"
              :label="item.user_name"
              :value="item.admin_user_id"
            ></el-option>
          </el-select>
          <el-select
            v-model="query.statistics_type"
            placeholder="请选择"
            @change="changeProject"
            style="width:120px;margin-right:10px"
          >
            <el-option
              v-for="item in project_options"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
          <label class="title">
            <span class="name">月份查询</span> :
          </label>
          <el-date-picker
            @change='changeMonth'
            v-model="monthValue"
            type="month"
            placeholder="选择月">
          </el-date-picker>
          <label class="title">
            <span class="name">日期查询</span> :
          </label>
          <el-date-picker
            v-model="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="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="bar"></line-chart>
        </div>
        <div class="tableTitle">统计表</div>
        <div>
          <!--<el-table :data="tableData" style="width: 100%" :height="tableHeight">-->
            <!--<el-table-column fixed label="姓名" align="center">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.user_name}}-->

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

            <!--<el-table-column label="治疗人次" align="center">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.p_count?scope.row.p_count:''}}-->

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

            <!--<el-table-column label="病程记录" align="center">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.course_count?scope.row.course_count:''}}-->

                <!--&lt;!&ndash;{{// scope.row.patient.lapseto == 1 ? '留治':'转出'}}&ndash;&gt;-->
              <!--</template>-->
            <!--</el-table-column>-->

            <!--<el-table-column label="抢救记录" align="center">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.rescue_count?scope.row.rescue_count:''}}-->

                <!--&lt;!&ndash;{{scope.row.last_after_weight?scope.row.last_after_weight:''}}&ndash;&gt;-->

                <!--&lt;!&ndash;<div v-if="scope.row.before.systolic_blood_pressure">{{scope.row.before.systolic_blood_pressure}} / {{scope.row.before.diastolic_blood_pressure}}</div>&ndash;&gt;-->
              <!--</template>-->
            <!--</el-table-column>-->

            <!--<el-table-column label="合计" align="center">-->
              <!--<template slot-scope="scope">-->
                <!--{{scope.row.p_count + scope.row.course_count + scope.row.rescue_count?scope.row.p_count + scope.row.course_count + scope.row.rescue_count:''}}-->

                <!--&lt;!&ndash;<div v-if="scope.row.min_monitor.systolic_blood_pressure">{{ scope.row.min_monitor.systolic_blood_pressure}} /{{ scope.row.min_monitor.diastolic_blood_pressure}}</div>&ndash;&gt;-->
              <!--</template>-->
            <!--</el-table-column>-->


          <!--</el-table>-->
          <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 fixed label="姓名" align="center">
              <template slot-scope="scope">
                {{scope.row.user_name}}

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

            <el-table-column label="穿刺" align="center">
              <template slot-scope="scope">
                {{scope.row.puncture_count?scope.row.puncture_count:''}}

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


            <el-table-column label="治疗" align="center">
              <template slot-scope="scope">
                {{scope.row.cure_count?scope.row.cure_count:''}}

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


            <el-table-column label="宣教/小结" align="center">
              <template slot-scope="scope">
                {{scope.row.mission_count?scope.row.mission_count:''}}
              </template>
            </el-table-column>

            <el-table-column label="合计" align="center">
              <template slot-scope="scope">
                {{scope.row.puncture_count + scope.row.cure_count + scope.row.mission_count ?scope.row.puncture_count  + scope.row.cure_count + scope.row.mission_count:''}}
              </template>
            </el-table-column>
          </el-table>
    </div>
  </div>
</template>
<script>
  const moment = require('moment')
  import echarts from "echarts";
  import BreadCrumb from "@/xt_pages/components/bread-crumb";
  import LineChart from "../../qcd/components/LineChart";

  import {GetNurseWorkloadChartData,GetNurseWorkloadTableData,GetAllAdminUser} from "@/api/common/statistics";

  export default {
    components: {
      BreadCrumb,
      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;;
          }
        },
        tableData: [
        ],
        loading: false,
        total: '',
        query: {
          admin_user_id: 0,
          statistics_type: 1,
          start_time: "",
          end_time: "",
          limit:20,
          page:1,
        },
        start_time:'',
        end_time:'',
        monthValue:'',
        nurse_options:[
          {id:0,user_name:"全部",admin_user_id:0}
        ],
        project_options:[
          {value:1, name:"治疗"},
          {value:2, name:"穿刺"},
          {value:3, name:"宣教/小结"},
        ],
        crumbs: [
          { path: false, name: "质控管理" },
          { path: false, name: "工作量分析统计" },
          { path: false, name: "护士" }
        ],
        activeName: "second",
        listQuery: {
          start_time: "",
          end_time: "",
          page: 1,
          limit: 10
        },

        value: "请选项",
        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.2)"
                }
              }
            }
          ],
          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: {
      changeNurse(val){
        this.query.admin_user_id = val
        this.query.page = 1
        this.GetNurseWorkloadChartData(this.query)
        this.GetNurseWorkloadTableData(this.query)

      },
      GetAllNurse(){
        GetAllAdminUser().then(response => {
          if (response.data.state == 1) {
            var adminUser = response.data.data.admin
            this.admin_user  = adminUser
            for (let i = 0; i < adminUser.length; i++){
              if(adminUser[i].user_type == 3){
                this.nurse_options.push(adminUser[i])
              }
            }
          } else {
            this.$message.error('请求数据失败')
            return false
          }
        })

      },
      changeProject(val){
        this.query.statistics_type = val
        this.query.page = 1
        this.GetNurseWorkloadChartData(this.query)
        // this.GetDialysisProcessIndexTableData(this.query)

      },
      handleSizeChange(limit) {
        this.query.limit = limit;
        this.GetNurseWorkloadTableData(this.query)
      },
      handleCurrentChange(page) {
        this.query.page = page;
        this.GetNurseWorkloadTableData(this.query)
      },GetNurseWorkloadTableData(params) {
        this.loading = true
        this.tableData = []
        GetNurseWorkloadTableData(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              let total_cure = 0
              let total_puncture = 0
              let total_mission = 0
              this.loading = false
              for (let i = 0; i < resp.data.data.length; i++) {
                total_cure = total_cure + resp.data.data[i].cure_count
                total_puncture = total_puncture + resp.data.data[i].puncture_count
                total_mission = total_mission + resp.data.data[i].mission_count
                this.tableData.push(resp.data.data[i])
              }
              this.tableData.push( {
                user_name:"合计",
                cure_count:total_cure,
                puncture_count:total_puncture,
                mission_count:total_mission
              })
            } else {
              this.loading = false
            }
          })
          .catch(error => {

          })
      },
      getTimestamp(time) {
        // 把时间日期转成时间戳
        return new Date(time).getTime() / 1000;
      },
      changeTime(val) {
        this.query.end_time = ''
        var time = this.getTimestamp(val) - this.getTimestamp(this.query.end_time);
        if (time > 0) {
          this.$message.error("结束时间不能小于开始时间");
          this.query.start_time = "";
        } else {
          // this.getDialysisList()
          console.log(val)
          this.query.page = 1;
          this.query.start_time = val
          this.query.end_time = this.end_time
          this.monthValue = ''
          sessionStorage.setItem("nurse_start_time", val)
          sessionStorage.removeItem("nurseMonth");
          this.GetNurseWorkloadChartData(this.query)
          this.GetNurseWorkloadTableData(this.query)

        }

      },  GetNurseWorkloadChartData(params) {

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

              for (let i = 0;  i < resp.data.data.length;i++){
                this.bar.xAxis.data.push(resp.data.data[i].user_name)
                if(this.query.statistics_type == 2){
                  this.bar.series[0].data.push(resp.data.data[i].puncture_count)
                  this.percent.push(resp.data.data[i].puncture_ratio)
                }else if(this.query.statistics_type == 1){
                  this.bar.series[0].data.push(resp.data.data[i].cure_count)
                  this.percent.push(resp.data.data[i].cure_ratio)
                }else if(this.query.statistics_type == 3){
                  this.bar.series[0].data.push(resp.data.data[i].mission_count)
                  this.percent.push(resp.data.data[i].mission_ratio)
                }
              }
              this.getArrLength(this.bar.xAxis.data)

            } else {
            }
          })
          .catch(error => {
          })
      },
      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.start_time = this.start_time
          this.query.end_time = val
          this.monthValue = ''
          this.query.page = 1;
          sessionStorage.setItem("nurse_end_time", val)
          sessionStorage.removeItem("nurseMonth");
          this.GetNurseWorkloadChartData(this.query)
          this.GetNurseWorkloadTableData(this.query)

        }
      },
      handleClick() {
        if (this.activeName == "first") {
          this.$router.push({ path: "/qcd/workAnalysis/doctor" });
        }
      },
      getArrLength(result){
        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
        }
      },
      changeMonth(value){
        // console.log('monthStartTime',value.getTime() / 1000)
        sessionStorage.removeItem("nurse_start_time");
        sessionStorage.removeItem("nurse_end_time");
        let monthStartTime = value.getTime() / 1000
        var nowDate = new Date(value);
        var cloneNowDate = new Date(value);
        var fullYear = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1; // getMonth 方法返回 0-11，代表1-12月
        var endOfMonth = new Date(fullYear, month, 0).getDate(); // 获取本月最后一天
        let monthEndTime = this.getFullDate(cloneNowDate.setDate(endOfMonth))
        this.query.start_time = moment(new Date(monthStartTime * 1000)).format('YYYY-MM-DD')
        this.query.end_time = moment(new Date(monthEndTime)).format('YYYY-MM-DD')
        this.end_time = ''
        this.start_time = ''
        sessionStorage.setItem("nurseMonth", monthStartTime);
        this.GetNurseWorkloadChartData(this.query)
        this.GetNurseWorkloadTableData(this.query)
      },
      getFullDate(targetDate) {
        var D, y, m, d;
        if (targetDate) {
          D = new Date(targetDate);
          y = D.getFullYear();
          m = D.getMonth() + 1;
          d = D.getDate();
        } else {
          y = fullYear;
          m = month;
          d = date;
        }
        m = m > 9 ? m : '0' + m;
        d = d > 9 ? d : '0' + d;
        return y + '-' + m + '-' + d;
      },
    },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.patient_id = 0
      this.query.end_time = year + '-' + month + '-' + day
      this.query.start_time = year + '-' + last_month + '-' + day
      this.query.statistics_type = 1
      
      this.start_time = year + '-' + last_month + '-' + day
      this.end_time = year + '-' + month + '-' + day

      if(sessionStorage.getItem("nurse_start_time") == null){
        sessionStorage.setItem("nurse_start_time", this.start_time);
      }else{
        this.start_time = sessionStorage.getItem("nurse_start_time")
        this.query.start_time = sessionStorage.getItem("nurse_start_time")
      }
      if(sessionStorage.getItem("nurse_end_time") == null){
        sessionStorage.setItem("nurse_end_time", this.end_time);
      }else{
        this.end_time = sessionStorage.getItem("nurse_end_time")
        this.query.end_time = sessionStorage.getItem("nurse_end_time")
      }
      if(sessionStorage.getItem("nurseMonth") != null){
        console.log("tjos")
        let value = parseInt(sessionStorage.getItem("nurseMonth")) * 1000
        let monthStartTime = new Date(value)
        this.monthValue = monthStartTime
        var nowDate = new Date(value);
        var cloneNowDate = new Date(value);
        var fullYear = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1; // getMonth 方法返回 0-11，代表1-12月
        var endOfMonth = new Date(fullYear, month, 0).getDate(); // 获取本月最后一天
        let monthEndTime = this.getFullDate(cloneNowDate.setDate(endOfMonth))
        this.query.start_time = moment(new Date(monthStartTime)).format('YYYY-MM-DD')
        this.query.end_time = moment(new Date(monthEndTime)).format('YYYY-MM-DD')
        this.start_time = ''
        this.end_time = ''
      }
      // console.log('this.query2',this.query)
      
      this.GetAllNurse()
      this.GetNurseWorkloadChartData(this.query)
      this.GetNurseWorkloadTableData(this.query)


    }
  };
</script>

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