<template>
    <div class="main-contain">
       <div class="position">
         <bread-crumb :crumbs="crumbs"></bread-crumb>
        
       </div>
       <div class="app-container">
         <div class="filter-container">
            <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"
                    style="width:160px;"
                    >
                    <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-input v-model="listQuery.search" style="width: 200px;" placeholder="请输入患者姓名或透析号"></el-input>
                <el-button type="primary" size="small" @click="toSeach">搜索</el-button>
                </el-form-item>
            </el-form>

            <label class="title" style="text-align:left;">
              <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"
            ></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"
            ></el-date-picker>

            <el-container>
                <div style="width:160px">
                    <div class="tableTitle" style="margin-bottom: 10px;">患者列表</div>
                    <el-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"
                    ref="singleTable"
                    >
                    <el-table-column prop="dialysis_no" label="透析号" width="70">
                        <template slot-scope="scope">{{scope.row.dialysis_no}}</template>
                    </el-table-column>
                    <el-table-column prop="name" label="姓名" width="90">
                        <template slot-scope="scope">{{ scope.row.name }}</template>
                    </el-table-column>
                    </el-table>
                </div>
                <div style="padding-left:10px;flex:1">
                  <div class="tableTitle" style="margin-top: 10px;margin-bottom: 10px;">统计表</div>
                  <div>
                    <el-button type="primary" @click="exportList" style="margin-bottom: 10px;">导出</el-button>
                    <el-table 
                     :data="DialysisData" style="width: 100%" border :row-style="{ color: '#303133' }"
                     :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                     highlight-current-row
                     
                      >
                            <el-table-column  label="医嘱名称" min-width="200" align="center">
                               <template slot-scope="scope">
                                   {{ scope.row.advice_name }}
                               </template>
                            </el-table-column>
                            <!-- <el-table-column  label="生产厂家" width="140">
                                <template slot-scope="scope">
                                 
                                </template>
                            </el-table-column> -->
                            <el-table-column  label="规格" min-width="200" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.specification_name }}
                                </template>
                            </el-table-column>
                            <el-table-column  label="数量" min-width="200" align="center">
                                <template slot-scope="scope">
                                   {{ getCount(scope.row.child) }}
                                </template>
                                
                            </el-table-column>
                          
                     </el-table>

                    <el-pagination
                    align="right"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[20, 40, 60, 80, 100,200,300,500,1000]"
                    :page-size="10"
                    background
                    style="margin-top:20px;"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    ></el-pagination>
                   </div>
                </div>
            </el-container>
         </div>
      </div> 
    </div>
</template>
<script>
    import {getPatientsByName,getDocAdviceByPatientId} from '@/api/advice'
    import BreadCrumb from "@/xt_pages/components/bread-crumb";
    export default {
        components: {
             BreadCrumb
         }, 
        data(){
          
          return{
            crumbs: [
              { path: false, name: "透析管理" },
              { path: false, name: "药品统计" }
           ], 
           listQuery:{
            search:"",
            start_time:"",
            end_time:"",
            page:1,
            limit:10,
           },
           patientsData:[],
           DialysisData:[],
           total:0,
           patient_id:0
          }
         
        },
        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() - 1);
            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.getPatientsByName()
          },
        methods:{
            getPatientsByName(){
                  var keyword = this.listQuery.search
                  var params = {
                    keyword:keyword,
                  }
                getPatientsByName(params).then(response=>{
                    if(response.data.state == 1){
                    var patients = response.data.data.patients
                    
                    this.patientsData = patients
                     
                    
                    this.$nextTick(()=>{
                        // 别忘了标签上定义ref  这里的 myTable就说获取的标签上的ref命的名
                        this.$refs.singleTable.setCurrentRow(this.patientsData[0])
                    })
                    
                   
                    }
                })
             },
            handleSelect(){

            },
            changeTime(){
              this.handleChange(this.patient_id)
            },
            changeEndTime(){
              this.handleChange(this.patient_id)
            },
            handleSizeChange(){

            },
            handleCurrentChange(){

            },
            exportList(){
                var params = {
                  patient_id:0,
                  start_time:this.listQuery.start_time,
                  end_time:this.listQuery.end_time,
                  limit:this.listQuery.limit,
                  page:this.listQuery.page,
                }
                console.log("paramswowowoow",params)
                
              getDocAdviceByPatientId(params).then(response=>{
                  if(response.data.state == 1){
                    var list =  response.data.data.list
                    var tableData = []
                    if(list!=null && list.length>0){
                        let dataInfo = {}
                        list.forEach((item, index) => {
                        let { patient_id } = item
                        if (!dataInfo[patient_id]) {
                            dataInfo[patient_id] = {
                            patient_id:item.patient_id,
                            child: [],
                            }
                        }
                       })
                       let arr = Object.values(dataInfo)

                       if(arr!=null && arr.length>0){
                         for(let i=0;i<list.length;i++){
                           for(let j=0;j<arr.length;j++){
                              if(list[i].patient_id == arr[j].patient_id){
                                  arr[j].child.push(list[i])
                              } 
                           } 
                         }
                       }

                       console.log("arrwowoowowo",arr)

                      if(arr!=null && arr.length>0){
                         for(let i=0;i<arr.length;i++){
                            let dataInfo = {}
                            arr[i].child.forEach((item, index) => {
                            let { advice_name} = item
                            if (!dataInfo[advice_name]) {
                                    dataInfo[advice_name] = {
                                    advice_name:item.advice_name,
                                    childOne: [],
                                    count:0,
                                    specification_name:item.advice_desc +item.drug_spec_unit,
                                    patient_id:item.patient_id,
                                 }
                                }
                            })
                            let newArr = Object.values(dataInfo)
                            console.log("newArrwoowow",newArr)
                            if(newArr!=null && newArr.length>0){
                              for(let z=0;z<arr[i].child.length;z++){
                                for(let y=0;y<newArr.length;y++){
                                   if(arr[i].child[z].advice_name == newArr[y].advice_name){
                                     newArr[y].childOne.push(arr[i].child[z])
                                   }

                                }
                              }
                            }
                            console.log("newArrwoowow",newArr)
                            tableData.push(...newArr)
                         }           
                      }
                    console.log("tableDatawpwwwoow",tableData)
                   
                    for(let i=0;i<tableData.length;i++){
                       tableData[i].index = i+1
                       tableData[i].count_name = this.getCount(tableData[i].childOne)
                       tableData[i].specification_name =tableData[i].specification_name
                       tableData[i].query_date = this.listQuery.start_time + "~" + this.listQuery.end_time
                      tableData[i].patient_name = this.getPatientName(tableData[i].patient_id)
                
                     }
                     import('@/vendor/Export2Excel').then(excel => {
                        
                            const tHeader = ['序号','患者姓名','查询日期','药品名称','规格&单位','数量']
                            const filterVal = ['index','patient_name','query_date','advice_name','specification_name','count_name']

                            const data = this.formatJson(filterVal,tableData)

                            excel.export_json_to_excel({
                            header: tHeader,
                            data,
                            filename: '患者药品使用查询表'
                            })
                        })
                    }
                  }
              })
           
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
            getPatientName(id){
                var patient_name = ""
                for(let i=0;i<this.patientsData.length;i++){
                if(id == this.patientsData[i].id){
                    patient_name = this.patientsData[i].name
                }
                }
                return patient_name
            },
            handleChange(val){
                console.log("valwoowowowwo",val)
                this.patient_id =val.id
                var params = {
                  patient_id:val.id,
                  start_time:this.listQuery.start_time,
                  end_time:this.listQuery.end_time,
                  limit:this.listQuery.limit,
                  page:this.listQuery.page,
                }
                console.log("paramswowowoow",params)
              getDocAdviceByPatientId(params).then(response=>{
                  if(response.data.state == 1){
                    var list =  response.data.data.list

                    if(list!=null && list.length>0){
                        let dataInfo = {}
                        list.forEach((item, index) => {
                        let { advice_name } = item
                        if (!dataInfo[advice_name]) {
                            dataInfo[advice_name] = {
                            advice_name:item.advice_name,
                            child: [],
                            count:0,
                            specification_name:item.advice_desc +item.drug_spec_unit,
                            patient_id:item.patient_id,
                            }
                        }
                       })
                       let arr = Object.values(dataInfo)

                       if(arr!=null && arr.length>0){
                         for(let i=0;i<list.length;i++){
                           for(let j=0;j<arr.length;j++){
                              if(list[i].advice_name == arr[j].advice_name){
                                  arr[j].child.push(list[i])
                              } 
                           } 
                         }
                       }

                       this.DialysisData= []

                       this.DialysisData = arr

                       console.log("arrwoowowowowo",arr)
                    }
                   
                  }
              })
            },
            toSeach(){
              this.getPatientsByName()
            },
            getCount(val){
               var count =0
               if(val!=null && val.length>0){
                for(let i=0;i<val.length;i++){
                    count+=val[i].prescribing_number
                }
               }
               return count
               
            }
        }   
    }
</script>

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