<template>
  <div class="page_doctor">
    <!-- <van-sticky> -->
    <div class="none1" style="width:100%;overflow-x:auto;">
      <div class="optionsBox">
        <div class="toolOne" @click="startShow = true">
          <div style="display: flex;align-items: center;">
            {{ query.start_time }}
            <van-icon name="arrow-down" />
          </div>
        </div>
        <div class="toolOne" @click="endShow = true">
          <div style="display: flex;align-items: center;">
            {{ query.end_time }}
            <van-icon name="arrow-down" />
          </div>
        </div>

        <div class="optionsOne" @click="typeShow = true">
          <div style="display: flex;align-items: center;">
            {{ type }}
            <van-icon name="arrow-down" />
          </div>
        </div>
        <div class="optionsOne" @click="projectShow = true">
          <div style="display: flex;align-items: center;">
            {{ project }}
            <van-icon name="arrow-down" />
          </div>
        </div>

      </div>
    </div>
    <!-- </van-sticky> -->

    <div class="chart1">统计图</div>
    <div>
      <bar-chart :options="options"></bar-chart>
    </div>
    <div class="chart1" style="margin-bottom:0.625rem">统计表</div>
    <div>
      <el-table ref="tab" :data="tableData" style="width: 100%" :height="tableHeight" v-loadmore="loadMore" border :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.change_nuser_count?scope.row.change_nuser_count:''}}
           </template>
       </el-table-column>

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

        <el-table-column label="开瘘" align="center">
           <template slot-scope="scope">
              {{scope.row.new_nuser_count?scope.row.new_nuser_count:''}}
           </template>
        </el-table-column>

        <el-table-column label="上机" align="center" min-width="200">
            <template slot-scope="scope">
               {{scope.row.start_nuser_count?scope.row.start_nuser_count:''}}
               <span v-if="getTotalCount(scope.row.admin_user_id)!=''">({{getTotalCount(scope.row.admin_user_id)}})</span>
             </template>
       </el-table-column>

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

        <el-table-column width="110" label="冲管" align="center">
          <template slot-scope="scope">
            {{scope.row.washpipe_nuser_count?scope.row.washpipe_nuser_count:''}}
          </template>
        </el-table-column>

        <el-table-column width="110" label="下机" align="center">
          <template slot-scope="scope">
            {{scope.row.finish_nuser_count?scope.row.finish_nuser_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:''}} -->
             {{scope.row.washpipe_nuser_count,scope.row.finish_nuser_count,scope.row.puncture_count + scope.row.cure_count + scope.row.mission_count + scope.row.change_nuser_count+scope.row.difficult_nuser_count+scope.row.new_nuser_count +scope.row.start_nuser_count ?scope.row.puncture_count  + scope.row.cure_count + scope.row.mission_count+scope.row.change_nuser_count+scope.row.difficult_nuser_count+scope.row.new_nuser_count+scope.row.start_nuser_count:''}}
          </template>
        </el-table-column>


      </el-table>

    </div>

    <scroll-top></scroll-top>

    <div>
      <!-- <van-popup v-model="stateShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="stateShow = false"
        />
      </van-popup> -->
      <van-popup v-model="typeShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="doctor_columns"
          @confirm="chooseType"
          @cancel="typeShow = false"
        />

      </van-popup>
      <van-popup v-model="projectShow" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          :columns="project_columns"
          @confirm="chooseProject"
          @cancel="projectShow = false"
        />
      </van-popup>
      <van-popup v-model="startShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate1"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getstartTime"
          @cancel="startShow = false"
        />
      </van-popup>
      <van-popup v-model="endShow" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate2"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getstartTime2"
          @cancel="endShow = false"
        />
      </van-popup>
    </div>
  </div>
</template>


<script>
  import echarts from "echarts";
  import BarChart from "../components/BarChart";
  import ScrollTop from "../components/ScrollTop";
  import {GetNurseWorkloadChartData,GetNurseWorkloadTableData,GetAllAdminUser} from "@/api/statistics";

  export default {
    components: {
      BarChart,
      ScrollTop
    },
    data() {
      return {
        isStop:false,
        currentDate1: new Date(new Date().setMonth(new Date().getMonth())),
        currentDate2: new Date(),
        minDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
        tableHeight: '',
        percent:[],
        value: "",
        query: {
          admin_user_id: "",
          statistics_type: 1,
          start_time: "",
          end_time: "",
          limit:20,
          page:1,
        },
        project: "治疗",
        projectShow: false,
        project_columns: ["治疗","穿刺","宣教/小结","换药","疑难穿刺","开瘘","上机"],
        type: "全部",
        typeShow: false,
        doctor_columns: [],
        columns2: ["杭州", "宁波", "温州", "嘉兴", "湖州"],
        startShow: false,
        endShow: false,
        currentDate: new Date(),
        startTime: "时间范围",
        endTime: "时间范围",
        maxDate: new Date(),
        admin_user:[],
        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: "bar",
              data: [
              ],
              barWidth: 20,
              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'],
                      ['#A9E0F3', '#9FBDFC'],
                      ['#A9E0F3', '#9FBDFC'],
                      ['#FFD7C0', '#FF9994'],
                      ['#FFD7C0', '#FF9994'],
                      ['#FFD7C0', '#FF9994'],
                      ['#D7C3FD', '#B3A8F7'],
                      ['#D7C3FD', '#B3A8F7'],
                      ['#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.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 // 锁定区域禁止缩放
            }
          ]
        },
        tableData: [],
        modeList:[]
      };
    },
    created(){
      this.tableHeight = (document.documentElement.clientHeight - (Number(document.documentElement.style.fontSize.slice(0, -2)) * 2.75)) + 'px'

      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.admin_user_id = 0
      this.query.end_time = year+"-"+month+"-"+day
      this.query.start_time = year+"-"+last_month+"-"+day
      this.query.statistics_type = 1
      this.GetAllDoctor()
      this.GetNurseWorkloadChartData(this.query)
      this.GetNurseWorkloadTableData(this.query)

    },
    methods: {
      GetAllDoctor(){
        GetAllAdminUser().then(response => {
          if (response.data.state == 1) {
            var adminUser = response.data.data.admin
            this.admin_user  = adminUser
            this.doctor_columns.push("全部")

            for (let i = 0; i < adminUser.length; i++){
              if(adminUser[i].user_type == 3){
                this.doctor_columns.push(adminUser[i].user_name)
              }
            }
          } else {
            this.$message.error('请求数据失败')
            return false
          }
        })

      },
      GetNurseWorkloadChartData(params) {
        this.options.xAxis.data = []
        this.options.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.options.xAxis.data.push(resp.data.data[i].user_name)
                if(this.query.statistics_type == 2){
                  this.options.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.options.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.options.series[0].data.push(resp.data.data[i].mission_count)
                  this.percent.push(resp.data.data[i].mission_ratio)
                }else if(this.query.statistics_type == 4){
                  this.options.series[0].data.push(resp.data.data[i].change_nuser_count)
                  this.percent.push(resp.data.data[i].change_nurse_ratio)
                }else if(this.query.statistics_type == 5){
                  this.options.series[0].data.push(resp.data.data[i].difficult_nuser_count)
                  this.percent.push(resp.data.data[i].difficult_nurse_ratio)
                }else if(this.query.statistics_type == 6){
                  this.options.series[0].data.push(resp.data.data[i].new_nuser_count)
                  this.percent.push(resp.data.data[i].new_nurse_ratio)
                }else if(this.query.statistics_type == 7){
                  this.bar.series[0].data.push(resp.data.data[i].start_nuser_count)
                  this.percent.push(resp.data.data[i].start_nurse_ratio)
                }else if(this.query.statistics_type == 8){
                  this.bar.series[0].data.push(resp.data.data[i].finish_nuser_count)
                  this.percent.push(resp.data.data[i].finish_nurse_ratio)
                }else if(this.query.statistics_type == 9){
                  this.bar.series[0].data.push(resp.data.data[i].washpipe_nuser_count)
                  this.percent.push(resp.data.data[i].washpipe_nurse_ratio)
                }
                this.getArrLength(this.options.xAxis.data)

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

          })
      },

      GetNurseWorkloadTableData(params) {
        GetNurseWorkloadTableData(params)
          .then(rs => {
            var resp = rs.data
            if (resp.state == 1) {
              this.tableData = []
              this.modeList = []
              let total_cure = 0
              let total_puncture = 0
              let total_mission = 0
              let total_change_nurse = 0
              let total_diffcult_nurse = 0
              let total_new_fistula_nurse = 0
              let total_start_nurse = 0
              let total_finsh_nurse = 0
              let total_washpipe_nuser = 0
              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

                total_change_nurse = total_change_nurse + resp.data.data[i].change_nuser_count
                total_diffcult_nurse = total_diffcult_nurse + resp.data.data[i].difficult_nuser_count
                total_new_fistula_nurse = total_new_fistula_nurse + resp.data.data[i].new_nuser_count
                total_start_nurse = total_start_nurse + resp.data.data[i].start_nuser_count
                total_finsh_nurse = total_finsh_nurse + resp.data.data[i].finish_nuser_count
                total_washpipe_nuser = total_washpipe_nuser + resp.data.data[i].washpipe_nuser_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,
                change_nuser_count:total_change_nurse,
                difficult_nuser_count:total_diffcult_nurse,
                new_nuser_count:total_new_fistula_nurse,
                start_nuser_count:total_start_nurse,
                finish_nuser_count:total_finsh_nurse,
                washpipe_nuser_count:total_washpipe_nuser
              })
              this.$nextTick(() => {
                this.$refs.tab.doLayout()
              })
              var dialysisCount = resp.data.dialysisCount
              for(let i=0;i<dialysisCount.length;i++){
                if(dialysisCount[i].mode_id == 1){
                  dialysisCount[i].mode_id = "HD"
                }
                if(dialysisCount[i].mode_id == 2){
                  dialysisCount[i].mode_id = "HDF"
                }
                if(dialysisCount[i].mode_id == 3){
                  dialysisCount[i].mode_id = "HD+HP"
                }
                 if(dialysisCount[i].mode_id == 4){
                  dialysisCount[i].mode_id = "HP"
                }
                 if(dialysisCount[i].mode_id == 5){
                  dialysisCount[i].mode_id = "HF"
                }
                 if(dialysisCount[i].mode_id == 6){
                  dialysisCount[i].mode_id = "SCUF"
                }
                 if(dialysisCount[i].mode_id == 7){
                  dialysisCount[i].mode_id = "IUF"
                }
                 if(dialysisCount[i].mode_id == 8){
                  dialysisCount[i].mode_id = "HFHD"
                }
                 if(dialysisCount[i].mode_id == 9){
                  dialysisCount[i].mode_id = "HFHD+HP"
                }
                 if(dialysisCount[i].mode_id == 10){
                  dialysisCount[i].mode_id = "PHF"
                }
               if(dialysisCount[i].mode_id == 11){
                  dialysisCount[i].mode_id = "HFR"
                }
                if(dialysisCount[i].mode_id == 12){
                  dialysisCount[i].mode_id = "HDF+HP"
                }
                if(dialysisCount[i].mode_id == 13){
                  dialysisCount[i].mode_id = "CRRT"
                }
               if(dialysisCount[i].mode_id == 14){
                  dialysisCount[i].mode_id = "腹水回输"
                }
                if(dialysisCount[i].mode_id == 21){
                  dialysisCount[i].mode_id = "HD+"
                }
              }
                let dataInfo = {}
                dialysisCount.forEach((item, index) => {
                let { start_nurse } = item
                  if (!dataInfo[start_nurse]) {
                    dataInfo[start_nurse] = {
                      child: [],
                      start_nurse: item.start_nurse,
                    }
                  }
               })
              let list = Object.values(dataInfo)

              list.map(item=>{
              for(let i=0;i<dialysisCount.length;i++){
                 if(item.start_nurse == dialysisCount[i].start_nurse){
                    item.child.push(dialysisCount[i])
                 }
               }
             })
             this.modeList.push(...list)
            } else {
              this.$toast({
                message: resp.msg
              })
            }
          })
          .catch(error => {

          })
      },
      chooseType(val) {
        this.type = val;
        this.typeShow = false;
        if (val == "全部"){
          this.query.admin_user_id = 0
        }else{

          for (let i = 0; i < this.admin_user.length; i++) {
            if (this.type == this.admin_user[i].user_name) {
              this.query.admin_user_id = this.admin_user[i].admin_user_id
            }
          }
        }
        this.GetNurseWorkloadChartData(this.query)
        this.GetNurseWorkloadTableData(this.query)

      },
      chooseProject(val) {
        switch (val) {
          case "穿刺":
            this.query.statistics_type = 2
            break
          case "治疗":
            this.query.statistics_type = 1
            break
          case "宣教/小结":
            this.query.statistics_type = 3
            break
          case "换药":
            this.query.statistics_type = 4
            break
          case "疑难穿刺":
            this.query.statistics_type = 5
            break
           case "开瘘":
            this.query.statistics_type = 6
            break
           case "上机":
            this.query.statistics_type = 7
            break
           case "下机":
            this.query.statistics_type = 8
            break
           case "冲管":
            this.query.statistics_type = 9
            break
        }
        this.project = val;
        this.projectShow = false;
        this.GetNurseWorkloadChartData(this.query)
      },
      getstartTime(value) {
        this.query.page = 1

        let year = value.getFullYear();
        let month = value.getMonth() + 1;
        let day = value.getDate();
        if (month >= 1 && month <= 9) {
          month = `0${month}`;
        }
        if (day >= 1 && day <= 9) {
          day = `0${day}`;
        }


        this.query.start_time = `${year}-${month}-${day}`;
        this.GetNurseWorkloadChartData(this.query)
        this.GetNurseWorkloadTableData(this.query)
        this.startShow = false;
      },
      getstartTime2(value) {
        this.query.page = 1

        let year = value.getFullYear();
        let month = value.getMonth() + 1;
        let day = value.getDate();
        if (month >= 1 && month <= 9) {
          month = `0${month}`;
        }
        if (day >= 1 && day <= 9) {
          day = `0${day}`;
        }
        this.query.end_time = `${year}-${month}-${day}`;
        this.GetNurseWorkloadChartData(this.query)
        this.GetNurseWorkloadTableData(this.query)

        this.endShow = false;
      },
      loadMore() {

        if (!this.isStop) {
          this.isStop = true
          this.query.page++
          GetNurseWorkloadTableData(this.query)
            .then(rs => {
              var resp = rs.data
              if (resp.state == 1) {
                for (let i = 0; i < resp.data.data.length; i++) {
                  this.tableData = []
                  this.tableData.push(resp.data.data[i])
                }
                if (resp.data.data.length <= 0) {
                  this.isStop = true

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

            })
        }

      },
      getArrLength(result){
        if(result.length > 6){
          var dataZoom_end = (6/result.length)*100;
          this.options.dataZoom[0].end = dataZoom_end
        }else{
          var dataZoom_end = 100;
          this.options.dataZoom[0].end = dataZoom_end
        }
      },
      getTotalCount(adminuserid){

        var name = ""
        for(let i=0;i<this.modeList.length;i++){
          for(let j=0;j<this.modeList[i].child.length;j++){
            if(adminuserid == this.modeList[i].child[j].start_nurse){
               name += (this.modeList[i].child[j].mode_id+"-"+this.modeList[i].child[j].Count) + "次"+"、"
            }
          }
        }
        return name.substr(0,name.length-1)
      }
    }
  };
</script>


<style lang="scss" scoped>
  .page_doctor {
  .optionsBox {
    display: flex;
    height: 3.125rem;
    align-items: center;
    width: 37.5rem;
    background: #fff;

  .optionsOne {
  //   max-width: 8.75rem;
  //   min-width: 6.25rem;
    padding: 0 0.75rem;
    height: 1.875rem;
    background: rgba(246, 246, 246, 1);
    border-radius: 5px;
    text-align: center;
    font-size: 0.8125rem;
    color: #646566;
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-left: 0.8125rem;
  }
  .toolOne {
    width: 6.25rem;
    height: 1.875rem;
    background: rgba(246, 246, 246, 1);
    border-radius: 5px;
    text-align: center;
    font-size: 0.8125rem;
    color: #646566;
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-left: 0.8125rem;
  }
  }
  .chart1 {
    font-size: 1rem;
    font-weight: bold;
    color: #000;
    margin: 0 0 0 0.8125rem;
  }
  .chart {
    font-size: 1rem;
    font-weight: bold;
    margin-left: 0.8125rem;
    color: #000;
  }
  }
  ::-webkit-scrollbar {
    height: 0;
    width: 0;
  }
  .none1::-webkit-scrollbar {
    display:none;
  }
</style>
