<template>
  <div class="main-contain new-main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div
      class="app-container"
      style="display: flex; flex: 1; padding: 10px 20px 0px 20px"
    >
      <div class="mainLeft">
        <div>
          <div
            style="
              margin: 10px 0;
              display: flex;
              justify-content: space-between;
            "
          >
            <el-input
              size="small"
              style="width: 130px"
              v-model="keywords"
              class="filter-item"
              placeholder="请输入患者名称"
            />
            <el-button
              size="small"
              class="filter-item"
              type="primary"
              @click="searchAction"
              >搜索
            </el-button>
          </div>

          <el-table
            :row-class-name="tableRowClassName"
            @row-click="onRowClick"
            :data="patientTableData"
            :height="tableHeight"
            border
            style="width: 100%"
            :row-style="{ color: '#303133' }"
            :header-cell-style="{
              backgroundColor: 'rgb(245, 247, 250)',
              color: '#606266',
            }"
            highlight-current-row
            ref="singleTable"
            @current-change="handleCurrentChange"
          >
            <el-table-column align="center" prop="name" label="姓名" wdith="89">
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="mainRight">
        <el-date-picker
          v-model="chargeDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          @change="changeDate"
          end-placeholder="结束日期"
        >
        </el-date-picker>
         <el-button  size="small" type="primary" @click="exportList" style="width:50px">导出</el-button>
        <el-table
        :data="tableList"
         border
        style="width: 100%">
         <el-table-column prop="date" label="姓名"  width="100" align="center">
           <template slot-scope="scope" >
            {{ scope.row.name }}
           </template>
        </el-table-column>
        <el-table-column  prop="date"  label="身份证"  width="200" align="center">
           <template slot-scope="scope" >
            {{ scope.row.id_card_no }}
           </template> 
        </el-table-column>
        <el-table-column prop="name"  label="医保类型" width="100" align="center">
          <template slot-scope="scope" >
            <span v-if="scope.row.insutype == 0">居民</span>
            <span v-if="scope.row.insutype == 310">职工</span>
            <span v-if="scope.row.insutype == 390">居民</span>
           </template>  
        </el-table-column>
        <el-table-column  prop="address" label="年"  width="50" align="center">
          <template slot-scope="scope" >
            {{getTime(scope.row.settle_accounts_date)}}
         </template>  
        </el-table-column>
         <el-table-column prop="address" label="月"  width="50"  align="center">
          <template slot-scope="scope">
            {{getTimeOne(scope.row.settle_accounts_date)}}
           </template>  
        </el-table-column>
         <el-table-column prop="address" label="收费项目"  width="100" align="center">
           <template slot-scope="scope" >
            <!-- {{getTime(scope.row.settle_accounts_date)}} -->
            <span v-if="scope.row.med_chrgitm_type == '01'">床位费</span>
            <span v-if="scope.row.med_chrgitm_type == '02'">诊察费</span>
            <span v-if="scope.row.med_chrgitm_type == '03'">检查费</span>
            <span v-if="scope.row.med_chrgitm_type == '04'">化验费</span>
            <span v-if="scope.row.med_chrgitm_type == '05'">治疗费</span>
            <span v-if="scope.row.med_chrgitm_type == '06'">手术费</span>
            <span v-if="scope.row.med_chrgitm_type == '08'">材料费</span>
            <span v-if="scope.row.med_chrgitm_type == '09'">西药费</span>
            <span v-if="scope.row.med_chrgitm_type == '11'">中成费</span>
            <span v-if="scope.row.med_chrgitm_type == '14'">其他费</span>
           </template>  
        </el-table-column>
         <el-table-column prop="address" label="数量"  width="100" align="center">
           <template slot-scope="scope" >
            {{getCount(scope.row.child)}}
           </template>  
          </el-table-column>
       
         <el-table-column  prop="address"  label="金额"  width="130" align="center">
         <template slot-scope="scope" >
            {{getAllPrice(scope.row.child)}}
           </template>  
        </el-table-column>
         </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { GetDetailPatients,getHisOrderList } from "@/api/his/his_tools";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
const moment = require("moment");
import { uParseTime } from '@/utils/tools'
export default {
  components: {
    BreadCrumb,
  },
  data() {
    return {
      currentRowIndex: 0,
      patientTableData: [],
      tableHeight: 400,
      crumbs: [
        { path: false, name: "His工具" },
        { path: false, name: "明细汇总统计" },
      ],
      titleType: "明细",
      patient_id: 0,
      keywords: "",
      tableList:[],
      tableData:[],
     chargeDate: [
        moment(new Date()).add("year", 0).format("YYYY-MM-DD"),
        moment(new Date()).add("year", 0).format("YYYY-MM-DD"),
      ],
      start_time:"",
      end_time:"",

    };
  },

  // beforeRouteEnter(to, from, next){
  //     if(from.path == '/hisTool/detailPrint'){
  //       next((vm) => {
  //         vm.titleType = "明细"
  //       })
  //     }else if(from.path == '/hisTool/gatherPrint'){
  //       vm.titleType = "汇总"
  //       next((vm) => {
  //         vm.titleType = "汇总"
  //       })
  //     }else{
  //       next()
  //     }
  // },

  //判断列表页是否刷新
  beforeRouteLeave(to, from, next) {
    console.log(to, "beforeRouteEnter");
    if (to.path != "/hisTool/detailPrint"&&to.path != "/hisTool/gatherPrint") {
      this.$store.getters.pagedata.list.table_id = 0
      next()
    } else {
     next()
    }
  },

  watch:{
    'titleType':{
      handler(val){
        this.$store.commit('SET_PAGENAME',val)
      }
    }
  },

  methods: {
    getPatientList() {
      var params = {
        keyword: this.keywords,
      };
      GetDetailPatients(params).then((response) => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.patientTableData = response.data.data.patient;
          this.patient_id = this.patientTableData[0].id;
          if (this.$store.getters.pagedata.list.table_id == 0) {
            this.$refs.singleTable.setCurrentRow(this.patientTableData[0]);
          } else {
            this.$refs.singleTable.setCurrentRow(
              this.patientTableData[
                this.$store.getters.pagedata.list.table_id
              ]
            );
          }
        }
      });
    },

    tableRowClassName({ row, rowIndex }) {
      row.row_index = rowIndex;
    },

    onRowClick(row, event, column) {
      this.currentRowIndex = row.row_index;
      this.$store.commit("SET_PAGEDATA", {
        table_id: this.currentRowIndex,
      });
      // console.log(this.$store.getters.pagedata.list.table_id, "列表行id");
    },
    searchAction() {
      this.getPatientList();
    },
    handleCurrentChange(row) {
      this.patient_id = row.id;
      this.tableList = []
      this.tableData = []
      this.getHisOrderList(row.id)
    },
    getHisOrderList(id){
       var params = {
        patient_id:id,
        start_time:this.start_time,
        end_time:this.end_time,
       } 
     console.log("params223332233232",params)
     getHisOrderList(params).then(response=>{
       if(response.data.state == 1){
        //  var list = response.data.data.list
        //  console.log("list23232232323",list)
         var groupList = response.data.data.groupList
          
         var arr = []
         for(let i=0;i<groupList.length;i++){
            //已经结算
           if(groupList[i].order.order_status == 2){
              arr.push(groupList[i])
           }
         }
         console.log("已结算数据",arr)
         if(arr.length > 0){
         let objInfo = {};
          if(arr.length > 0) {
             arr.forEach((item, index) => {
              let { med_chrgitm_type } = item;
              if (!objInfo[med_chrgitm_type]) {
                objInfo[med_chrgitm_type] = {
                  med_chrgitm_type:item.med_chrgitm_type,
                  child: [],
                  count: item.cnt,
                  pric:item.pric,
                  order_id:item.order_id,
                  name:item.patient.name,
                  id_card_no:item.patient.id_card_no,
                  insutype:item.order.insutype,
                  settle_accounts_date:item.order.settle_accounts_date,
                  det_item_fee_sumamt:item.det_item_fee_sumamt,
                };
              }
            });

            let newArr = Object.values(objInfo);
            console.log("newAR23232323232323323",newArr.length)

            if(newArr.length > 0){
             console.log("尽力33232233232",newArr)
              for(let i=0;i<newArr.length;i++){
                for(let j=0;j<arr.length;j++){
                   if(newArr[i].med_chrgitm_type == arr[j].med_chrgitm_type){
                      newArr[i].child.push(arr[j])
                   }
                }
              }
            }
            console.log("分类后的数据",newArr)
            this.tableList = newArr
            this.tableData = newArr
          }
          
         }

         //console.log("grouplist2323322",groupList)
         
       }
     })
    },
    changeDate(){
      this.start_time = this.chargeDate[0];
      this.end_time = this.chargeDate[1];  
      this.tableData = []
      this.tableList = []
      this.getHisOrderList(this.patient_id) 
    },
   getTime(val) {
     if(val < 0){
       return ""
      }
     if(val == ""){
       return ""
      }else {
      return uParseTime(val, '{y}')
      }
    },
   getTimeOne(val) {
     if(val < 0){
       return ""
      }
     if(val == ""){
       return ""
      }else {
      return uParseTime(val, '{m}')
      }
    },
    getCount(val){
      var count = 0
      for(let i=0;i<val.length;i++){
        count +=val[i].cnt
      }
      if(count >0){
        return count
      }else{
        return ""
      }
    },
    getAllPrice(val){
      var total_price = 0
      for(let i=0;i<val.length;i++){
        total_price +=val[i].cnt * val[i].pric
      }
      if(total_price >0){
        return total_price.toFixed(2)
      }else{
        return ""
      }
    },
      exportList(){
         import('@/vendor/Export2Excel').then(excel => {
          console.log("tabledat3323232322323wode",this.tableData)
          for(let i=0;i<this.tableData.length;i++){
             if(this.tableData[i].insutype == 310){
              this.tableData[i].insutype = "职工"
             }
             if(this.tableData[i].insutype == 390){
              this.tableData[i].insutype = "居民"
             }
             
             this.tableData[i].year = this.getTime(this.tableData[i].settle_accounts_date)
             this.tableData[i].month = this.getTimeOne(this.tableData[i].settle_accounts_date)
              
             if(this.tableData[i].med_chrgitm_type == "01"){
               this.tableData[i].med_chrgitm_type = "床位费"
             }
             if(this.tableData[i].med_chrgitm_type == "02"){
               this.tableData[i].med_chrgitm_type = "诊察费"
             }
             if(this.tableData[i].med_chrgitm_type == "03"){
               this.tableData[i].med_chrgitm_type = "检查费"
             }
             if(this.tableData[i].med_chrgitm_type == "04"){
               this.tableData[i].med_chrgitm_type = "化验费"
             }
             if(this.tableData[i].med_chrgitm_type == "05"){
               this.tableData[i].med_chrgitm_type = "治疗费"
             }
             if(this.tableData[i].med_chrgitm_type == "06"){
               this.tableData[i].med_chrgitm_type = "治疗费"
             }
             if(this.tableData[i].med_chrgitm_type == "08"){
               this.tableData[i].med_chrgitm_type = "材料费"
             }
             if(this.tableData[i].med_chrgitm_type == "09"){
               this.tableData[i].med_chrgitm_type = "西药费"
             }
             if(this.tableData[i].med_chrgitm_type == "11"){
               this.tableData[i].med_chrgitm_type = "中成费"
             }
             if(this.tableData[i].med_chrgitm_type == "14"){
               this.tableData[i].med_chrgitm_type = "其他费"
             }
             
             this.tableData[i].sum_count = this.getCount(this.tableData[i].child)

             this.tableData[i].find_price = this.getAllPrice(this.tableData[i].child)
          }
         const tHeader = ['姓名','身份证','医保类型','年','月','收费项目','数量','金额']
         const filterVal = ['name', 'id_card_no','insutype','year','month','med_chrgitm_type','sum_count','find_price']

         const data = this.formatJson(filterVal,this.tableData)

         excel.export_json_to_excel({
           header: tHeader,
           data,
           filename: '药品信息'
         })
          this.downloadLoading = false

        })
       },
       formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
       },
  },
  created() {

    let type = this.$store.getters.pagedata.pagestate
    if(type == ""){
      this.titleType = "明细"
    }else{
      this.titleType = type
    }
    const tableHeight = document.body.clientHeight - 290;
    this.tableHeight = tableHeight;
    this.start_time = moment(new Date()).add("year", 0).format("YYYY-MM-DD")
    this.end_time = moment(new Date()).add("year", 0).format("YYYY-MM-DD")
    this.getPatientList();
    
  },

  mounted() {}
};
</script>

<style lang="scss" scoped>
.new-main-contain {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.app-container {
  height: 100%;
}

.mainCell {
  height: 36px;
  display: flex;
  align-items: center;
}

.mainLeft {
  width: 200px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .el-radio {
    margin-right: 5px;
  }
}
.mainRight {
  margin-left: 10px;
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;

  .cellSpan {
    min-width: 80px;
    display: inline-block;
    margin-right: 10px;
  }
}
.mainCenter {
  display: flex;
  flex: 1;
}

.centerLeft {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;

  .el-form-item {
    width: 32%;
    margin-right: 1%;
    float: left;
  }

  .el-form-item__label {
    text-align: left;
  }
}
.backColor {
  background: #f6f8f9;
  height: 5px;
  margin-bottom: 5px;
}

.tabsBox {
  position: relative;
  height: 76%;
  overflow-y: auto;
  margin-bottom: 60px;

  .el-tabs__item {
    padding: 0 10px;
  }
}
.preTabs {
  height: 100%;
  display: flex;
  flex-direction: column;

  .el-tabs__content {
    flex: 1;
    overflow-y: auto;
  }
}

.costBox {
  width: 100%;
  height: 60px;
  background: #fff;
  position: absolute;
  bottom: 0;
  display: flex;
  align-items: center;
}

.addTab {
  position: absolute;
  right: 0;
  top: 14px;
  z-index: 20;
}

.centerRight {
  width: 300px;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.rightTab {
  height: 40px;
  width: 100%;
  border: 1px solid #d2d2d2;
  box-sizing: border-box;

  p {
    width: 50%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background: #eee;
    float: left;
  }

  > p:last-child {
    border-left: 1px solid #d2d2d2;
    float: right;
  }

  .activeP {
    background: #409eff;
    color: #fff;
  }
}
.comfirmBox {
  width: 100%;
  height: 60px;
  background: #fff;
  position: absolute;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.mainHeader {
  width: 100%;
  background: #fff;
  position: fixed;
  z-index: 100;
  height: 36px;
}

.titleBox {
  position: fixed;
  z-index: 99;
  background: #fff;
}

.fixedCell {
  position: fixed;
  z-index: 99;
  right: 30px;
  background: #fff;
  width: 300px;
  display: flex;
  justify-content: space-between;
}
</style>

<style lang="scss">
.centerLeft {
  .el-form-item__label {
    text-align: left;
  }
}
.tabsBox {
  .el-tabs__item {
    padding: 0 10px;
  }

  .el-tabs--bottom
    .el-tabs--left
    > .el-tabs__header
    .el-tabs__item:nth-child(2),
  .el-tabs--bottom
    .el-tabs--right
    > .el-tabs__header
    .el-tabs__item:nth-child(2),
  .el-tabs--bottom.el-tabs--border-card
    > .el-tabs__header
    .el-tabs__item:nth-child(2),
  .el-tabs--bottom.el-tabs--card > .el-tabs__header .el-tabs__item:nth-child(2),
  .el-tabs--top .el-tabs--left > .el-tabs__header .el-tabs__item:nth-child(2),
  .el-tabs--top .el-tabs--right > .el-tabs__header .el-tabs__item:nth-child(2),
  .el-tabs--top.el-tabs--border-card
    > .el-tabs__header
    .el-tabs__item:nth-child(2),
  .el-tabs--top.el-tabs--card > .el-tabs__header .el-tabs__item:nth-child(2) {
    padding: 0 10px;
  }

  .el-tabs--bottom .el-tabs--left > .el-tabs__header .el-tabs__item:last-child,
  .el-tabs--bottom .el-tabs--right > .el-tabs__header .el-tabs__item:last-child,
  .el-tabs--bottom.el-tabs--border-card
    > .el-tabs__header
    .el-tabs__item:last-child,
  .el-tabs--bottom.el-tabs--card > .el-tabs__header .el-tabs__item:last-child,
  .el-tabs--top .el-tabs--left > .el-tabs__header .el-tabs__item:last-child,
  .el-tabs--top .el-tabs--right > .el-tabs__header .el-tabs__item:last-child,
  .el-tabs--top.el-tabs--border-card
    > .el-tabs__header
    .el-tabs__item:last-child,
  .el-tabs--top.el-tabs--card > .el-tabs__header .el-tabs__item:last-child {
    padding: 0 10px;
  }

  .el-tabs--card > .el-tabs__header .el-tabs__item.is-active.is-closable {
    padding: 0 10px;
  }
}
.centerRight {
  .el-tabs__nav-scroll {
    display: flex;
  }

  .el-tabs__nav {
    margin: 0 auto;
  }

  .el-table th .cell,
  .el-table td .cell {
    padding: 0 2px;
  }
}
.preTabs {
  .el-tabs__content {
  }
}
.rightTabs {
  height: 100%;

  .el-tabs__content {
  }
}
.centerDialog {
  .el-dialog__body {
    max-height: calc(100vh - 100px) !important;
    padding: 0 20px;
  }
}
</style>
