<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div class="app-container">
      <div class="page_patientControlAnalysis">
        <div class="cell clearfix">
          <el-form :inline="true" :model="listQuery">
            <el-form-item label>
               <el-autocomplete
                class="checkSearch"
                popper-class="my-autocomplete"
                v-model.trim="listQuery.search"
                :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>
          <el-select v-model="lapstor" placeholder="请选择" style="margin-right:20px;width:100px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <label class="title">
            <span class="name">日期查询</span> :
          </label>
          <el-date-picker
            v-model="listQuery.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 class>-</span>
          <el-date-picker
            v-model="listQuery.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>
        <div class="cell clearfix">
          <p class="chartTitle">统计图</p>
        </div>
        <div>
          <line-chart :options="chart"></line-chart>
        </div>
        <div class="cell clearfix">
          <p class="chartTitle">统计表</p>
        </div>
        <div>
          <el-table :data="tableData" border style="width: 100%" :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
            <el-table-column fixed prop="name" label="姓名" width="120"></el-table-column>
            <el-table-column   label="透析号" width="150">
              <template slot-scope="scope">
                  <!-- {{getDialysisNo(scope.row.name)}} -->
                  {{scope.row.dialysis_no}}
              </template>
            </el-table-column>
            <el-table-column
              :label="modeItem.item_name"
              property="number"
              align="center"
              min-width="100"
              v-for="(modeItem, index) in normData"
              :key="index"
            >
            <template slot-scope="scope">
                 <span v-if="scope.row.data[modeItem.item_name].inspect_value == ''">0</span>
                 <span v-if="scope.row.data[modeItem.item_name].inspect_value !=''&& (parseInt(scope.row.data[modeItem.item_name].inspect_value) < parseInt(scope.row.data[modeItem.item_name].range_min))">{{scope.row.data[modeItem.item_name].inspect_value}}↓</span>
                <span v-if="scope.row.data[modeItem.item_name].inspect_value !=''&& (parseInt(scope.row.data[modeItem.item_name].inspect_value) > parseInt(scope.row.data[modeItem.item_name].range_max))">{{scope.row.data[modeItem.item_name].inspect_value}}↑</span>
                <span v-if="scope.row.data[modeItem.item_name].inspect_value !=''&& (parseInt(scope.row.data[modeItem.item_name].inspect_value) >= parseInt(scope.row.data[modeItem.item_name].range_min))&& (parseInt(scope.row.data[modeItem.item_name].inspect_value) <= parseInt(scope.row.data[modeItem.item_name].range_max)) ">{{scope.row.data[modeItem.item_name].inspect_value}}</span>
            </template>
        </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button @click="handleClick(scope.row.patient_id,scope.row.inspect_date)" type="text" size="small">查看</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            align="right"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listQuery.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>
    </div>
  </div>
</template>

<script>
import { PostSearch} from '@/api/patient'
import echarts from "echarts";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
import LineChart from "../qcd/components/LineChart";
import { getNormData,getPatientsControl,getCartogramlist,getPatientContorlAnalysis,getCurrentOrgPatients } from "@/api/common/common"
export default {
  components: {
    LineChart,
    BreadCrumb
  },
  data() {
    return {
      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: 20
      },
      total:0,
      lapstor:0,
      options: [
        {
          value: 0,
          label: "全部"
        },
        {
          value: 1,
          label: "留治"
        },
        {
          value: "2",
          label: "转出"
        },
      ],
      value: "",
      modesData: {
        xAxis: [],
        series: []
      },
      chart: {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: ["次数"],
          left: 0
        },
        xAxis: {
          data: ["达标", "未达标"]
        },
        yAxis: {
          axisLabel: {
            formatter: "{value} %"
          },
          show: false
        },
        series: [
          {
            name: "次数",
            type: "bar",
            data: ["78.57", "50"],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top",
                formatter: (params) => {
                  if(this.obj.length > 0){
                      let str = ''
                      str = '('+ this.obj[params.dataIndex] +'人'+',' + params.data +'%' +')'
                    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)"
              }
            }
          }
        ]
      },
      patientsArr:[],
      tableData: [],
      normData:[],
      paitents:[],
      tableName:[],
      total:0,
       obj:[],
      ObjectData:{},
      tablePatients:[],
      tableSort:[],
      dataName:[
        {id:0,name:"达标"},
        {id:1,name:"未达标"},
      ],
      dataCount:[
         {id:0,count:0},
         {id:1,count:0}
      ],
      patient_id:0,
    };
  },
  methods: {
    handleSizeChange(limit){
      this.listQuery.limit = limit
      this.getlist()
    },
    handleCurrentChange(page){
      this.listQuery.page = page

      this.getlist()
    },
    changeTime() {
        var time = this.getTimestamp(val) - this.getTimestamp(this.listQuery.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.start_time = "";
      } else {

      }

    },
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.listQuery.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.end_time = "";
      } else {

      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    handleClick(patientid,inspectdate) {
      // var id = 0
      // var dialysis_no = 0
      // for(let i=0;i<this.tablePatients.length;i++){
      //    if(name == this.tablePatients[i].name){
      //       id = this.tablePatients[i].patient_id
      //       dialysis_no = this.tablePatients[i].dialysis_no
      //    }
      // }
      this.$router.push({ path: "/qcd/patientComplianceDetails?patientid="+patientid+"&date="+inspectdate});
    },
    getDialysisNo(name){
        for(let i=0;i<this.tablePatients.length;i++){
          if(name == this.tablePatients[i].name){
             return this.tablePatients[i].dialysis_no
          }
        }
    },
    getNormData(){
      getNormData().then(response=>{
         if(response.data.state == 1){
           var normdata = response.data.data.normdata
        //  console.log("normdata",normdata)
          this.normData = normdata
           var a=[];
           for(let i=0;i<normdata.length;i++){
             a.push(normdata[i])
           }
          // console.log("a",a)
           this.newArr = a
           var arr = this.arrayToObj(a)
           this.ObjectData = arr


         }
      })
    },
    onSearch(){
         const params = {
            lapstor:this.lapstor,
            patientid:this.patient_id,
            startime:this.listQuery.start_time,
            endtime:this.listQuery.end_time,

         }
       getPatientContorlAnalysis(params).then(response=>{
           if(response.data.state == 1){
              var control = response.data.data.patientcontorDetail
              console.log("control",control)
              let dataInfo = {}
              control.forEach((item, index) => {
                let { inspect_date } = item
                if (!dataInfo[inspect_date]) {
                  dataInfo[inspect_date] = {
                    inspect_date,
                    name: item.name,
                    child: [],
                    patient_id: item.patient_id

                  }
                }
              })
              let list = Object.values(dataInfo)
              console.log("list",list)
              list.map(item => {
                for (let i = 0; i < control.length; i++) {
                  if (item.inspect_date == control[i].inspect_date && item.patient_id == control[i].patient_id) {
                    item.child.push(control[i])
                  }
                }
              })
                var newarrtwo = []
                list.map(item => {
                  item.child.map(it => {
                    newarrtwo.push(it)
                  })
                })

                // 配置的才显示
                var arrthree = []
                for (let i = 0; i < newarrtwo.length; i++) {
                  for (let j = 0; j < this.normData.length; j++) {
                    if (newarrtwo[i].item_id == this.normData[j].inspection_minor) {
                      arrthree.push(newarrtwo[i])
                    }
                  }
                }
                console.log("arrthree",arrthree)
                var arrfour = this.arrayDate(arrthree, newarrtwo)
                arrfour.map(item => {
                  item.item_name = ''
                  arrthree.push(item)
                })

                var dd = {}
                for (const index in arrthree) {
                  if (!(arrthree[index].inspect_date in dd)) {
                    dd[arrthree[index].inspect_date] = {}
                  }
                  if (!(arrthree[index].item_name in dd[arrthree[index].inspect_date]) && arrthree[index].item_name != 0) {
                    dd[arrthree[index].inspect_date][arrthree[index].item_name] = arrthree[index]
                  }
                }

                this.tableData = []

                for (const key in dd) {
                  for (const mkey in this.ObjectData) {
                    if (!(this.ObjectData[mkey].item_name in dd[key])) {
                      dd[key][this.ObjectData[mkey].item_name] = {
                        item_name: this.ObjectData[mkey].item_name,
                        name: mkey,
                        inspect_value: 0
                      }
                    }
                  }
                  this.tableData.push({ name: key, data: dd[key]})
                }
              let dataInfotwo = {}
              control.forEach((item, index) => {
                let { inspect_date } = item
                if (!dataInfotwo[inspect_date]) {
                  dataInfotwo[inspect_date] = {
                    inspect_date,
                    name: item.name,
                  }
                }
              })
              let listtwo = Object.values(dataInfotwo)
                listtwo.map(item=>{
                  this.tableData.map(it=>{
                    if(item.inspect_date == parseInt(it.name)){
                      it.name = item.name
                    }
                  })
                })
                //   let projectArr = []
                //   this.newArr.map(item => {
                //     projectArr.push(item.item_name)
                //   })

                //   this.tableData.map(item => {
                //     let newarr = Object.values(item.data)
                //     newarr.sort((a, b) => {
                //       return projectArr.indexOf(a.item_name) - projectArr.indexOf(b.item_name)
                //     })
                //     item.data = newarr
                //   })

                  // for (let i = 0; i < this.patientsArr.length; i++) {
                  //   for (let j = 0; j < this.tableData.length; j++) {
                  //     if (this.patientsArr[i].name == this.tableData[j].name) {
                  //       this.tableData[j].dialysis_no = this.patientsArr[i].dialysis_no
                  //       this.tableData[j].patient_id = this.patientsArr[i].id
                  //     }
                  //   }
                  // }

                }
          })
    },
    getlist(){
      getPatientsControl(this.lapstor,this.listQuery.start_time,this.listQuery.end_time,this.listQuery.page,this.listQuery.limit).then(response=>{
         if(response.data.state == 1){
           var patients = response.data.data.patients
            // console.log("patients",patients)
            this.tablePatients = patients
            var total = response.data.data.total
            this.total = total
            var control = response.data.data.control
            // console.log("control",control)
            var newArr = []
            // 分页
            for (let i = 0; i < control.length; i++) {
              for (let j = 0; j < patients.length; j++) {
                if (control[i].inspect_date == patients[j].inspect_date) {
                  newArr.push(control[i])
                }
              }
            }
          // console.log("newArr",newArr)
          let dataInfo = {}
          newArr.forEach((item, index) => {
            let { inspect_date } = item
            if (!dataInfo[inspect_date]) {
              dataInfo[inspect_date] = {
                inspect_date,
                name: item.name,
                child: [],
                patient_id: item.patient_id
              }
            }
          })
        let list = Object.values(dataInfo)


         list.map(item => {
            for (let i = 0; i < newArr.length; i++) {
              if (item.inspect_date == newArr[i].inspect_date) {
                item.child.push(newArr[i])
              }
            }
          })
        //  console.log("list",list)
         var newarrtwo = []
          list.map(item => {
            item.child.map(it => {
              newarrtwo.push(it)
            })
          })
        //  console.log("newarrtwo",newarrtwo)
          // 配置的才显示
         var arrthree = []
          for (let i = 0; i < newarrtwo.length; i++) {
            for (let j = 0; j < this.normData.length; j++) {
              if (newarrtwo[i].item_id == this.normData[j].inspection_minor) {
                arrthree.push(newarrtwo[i])
              }
            }
          }

          var arrfour = this.arrayDate(arrthree, newarrtwo)
          arrfour.map(item => {
            item.item_name = ''
            arrthree.push(item)
          })
          // console.log('arrthree', arrthree)
          var dd = {}
           for (const index in arrthree) {
             if (!(arrthree[index].inspect_date in dd)) {
               dd[arrthree[index].inspect_date] = {}
             }
             if (!(arrthree[index].item_name in dd[arrthree[index].inspect_date]) && arrthree[index].item_name != 0) {
               dd[arrthree[index].inspect_date][arrthree[index].item_name] = arrthree[index]

             }
           }

           let dataInfotwo = {}
          newArr.forEach((item, index) => {
            let { inspect_date } = item
            if (!dataInfotwo[inspect_date]) {
              dataInfotwo[inspect_date] = {
                inspect_date,
                name: item.name,
                inspect_value:item.inspect_value,
                id:item.id,
                inspect_date:item.inspect_date
              }
            }
          })
        let listtwo = Object.values(dataInfotwo)
        console.log("listtwo",listtwo)
          for (const key in dd) {
            for (const mkey in this.ObjectData) {
              if (!(this.ObjectData[mkey].item_name in dd[key])) {
                dd[key][this.ObjectData[mkey].item_name] = {
                  item_name: this.ObjectData[mkey].item_name,
                  name: mkey,
                  inspect_value: 0
                }
              }
            }
            this.tableData.push({ name: key, data: dd[key]})
          }

          listtwo.map(item=>{
            this.tableData.map(it=>{
              if(item.inspect_date == parseInt(it.name)){
                 it.name = item.name
                 it.id = item.id
                 it.inspect_date = item.inspect_date
              }
            })
          })
          for(let i=0;i<this.patientsArr.length;i++){
             for(let j=0;j<this.tableData.length;j++){
               if(this.patientsArr[i].name == this.tableData[j].name){
                   this.tableData[j].dialysis_no = this.patientsArr[i].dialysis_no
                   this.tableData[j].patient_id = this.patientsArr[i].id
               }
             }
          }
         console.log("表哥123",this.tableData)
         }
      })
    },
     arrayToObj(arr){
      return Object.assign({},arr);
    },

     arrayDate(array1,array2){
        var array1 = array1;
        var array2 = array2;
        var result = [];
        for(var i = 0; i < array2.length; i++){
            var obj = array2[i];
            var num = obj.item_id;   //staff_id   就是要对比的key
            var isExist = false;
            for(var j = 0; j < array1.length; j++){
                var aj = array1[j];
                var n = aj.item_id;
                if(n == num){
                    isExist = true;
                    break;
             }
            }
            if(!isExist){
                result.push(obj);
            }
        }
        return result;
    },

    getCartogramlist(){
       getCartogramlist(this.lapstor,this.listQuery.start_time,this.listQuery.end_time,this.limit,this.page).then(response=>{
           if(response.data.state == 1){
              var cartogramlist =  response.data.data.cartogramlist
            //  console.log("cartogramlist",cartogramlist)
              var totaltwo =  response.data.data.total
              // console.log("totaltwo",totaltwo)
               var cart = []
               for(let i=0;i<cartogramlist.length;i++){
                  if(cartogramlist[i].inspect_value != ''){
                    cart.push(cartogramlist[i])
                  }
               }
              // console.log("cart",cart)
               let dataInfo = {}
                cart.forEach((item, index) => {
                  let { inspect_date } = item
                  if (!dataInfo[inspect_date]) {
                    dataInfo[inspect_date] = {
                      inspect_date,
                      name:item.name,
                      child: [],
                      patient_id:item.patient_id,
                      total:0,
                      count:0,
                    }
                  }
                })
              let list = Object.values(dataInfo)
              console.log("list",list)

              var arr = []
              list.map(item=>{
                 for(let i=0;i<cart.length;i++){
                    if(item.inspect_date == cart[i].inspect_date && item.patient_id == cart[i].patient_id){
                        item.child.push(cart[i])
                    }
                 }
              })



             list.map(item=>{
                item.child.map(it=>{
                   if(parseInt(it.range_min)<=parseInt(it.inspect_value) && parseInt(it.inspect_value)<=parseInt(it.range_max)){
                       item.total ++
                   }
                })
             })
             var standardTotal = 0

             list.map(item=>{
               if(item.total == item.child.length){
                  item.count ++
               }
             })
             list.map(item=>{
               standardTotal += item.count
             })
             var totalCount = list.length
            //  console.log("arr",list)
            //  console.log("合格",standardTotal)
            //  console.log("总人数",totalCount)
             for(let i=0;i<this.dataCount.length;i++){
                this.dataCount[0].count = standardTotal
                this.dataCount[1].count =  totalCount - standardTotal
               this.obj.push(this.dataCount[i].count)
             }
            // console.log("dataCount",this.dataCount)
         for (let i = 0; i < this.dataName.length; i++) {
            this.modesData.xAxis.push(this.dataName[i].name)

          }
          for (let i = 0; i < this.dataCount.length; i++) {
              this.modesData.series.push(((this.dataCount[i].count / totalCount) * 100).toFixed(1))
            }
            this.chart.series[0].data = this.modesData.series
            this.chart.xAxis.data = this.modesData.xAxis
            //  console.log("this",this.modesData)
           }
       })
    },
     getCurrentOrgPatients(){
       getCurrentOrgPatients().then(response=>{
          if(response.data.state == 1){
            this.patientsArr =  response.data.data.patients
            // console.log("病人",this.patientsArr)
            //获取列表数据
            this.getlist()
          }
       })
     },
    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([])
          }
        })
      },
   handleSelect(val) {
        this.listQuery.search = val.name
        this.patient_id = val.id
        this.onSearch()
     },
  },
  created(){
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.listQuery.end_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    nowDate.setMonth(nowDate.getMonth() - 3);
    nowYear = nowDate.getFullYear();
    nowMonth = nowDate.getMonth() + 1;
    nowDay = nowDate.getDate();
    this.listQuery.start_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);



    this.getCurrentOrgPatients()
    //获取系统指标
    this.getNormData()
    //获取统计图数据
    this.getCartogramlist()


  }
};
</script>

<style lang="scss" scoped>
.page_patientControlAnalysis {
  .pointTitle {
    font-size: 13px;
  }
}
</style>

<style lang="scss">
.page_patientControlAnalysis {
  .el-form-item {
    margin-bottom: 0;
  }
  .cell {
    text-align: center;
  }
}
</style>
