<template>
  <div>
      <div style="display: flex;justify-content: space-between;margin-bottom:10px;">
          <div>
              <!--<el-button size="small" style="margin-left:10px;" class="filter-item" type="primary"-->
              <!--@click="Action">-->
              <!--导出-->
              <!--</el-button>-->
              <el-input size="small" style="width:150px;" v-model="keywords" @input="searchAction"
                        @keyup.enter.native='searchAction'
                        placeholder="请输入患者姓名"

                        class="filter-item"/>
              <el-select size="small" v-model="item_type" placeholder="请选择"
                          style="width:150px;margin-left:10px;" @change="changeItem">
                  <el-option
                          label="全部"
                          value="0">
                  </el-option>
                  <el-option
                          v-for="item,index in items"
                          :key="index"
                          :label="item.name"
                          :value="item.id">
                  </el-option>
              </el-select>
              <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-radio v-model="radio" label="1">明细</el-radio>-->
              <!--<el-radio v-model="radio" label="2">汇总</el-radio>-->
          </div>
          <div>
              <!-- <el-popover
                placement="bottom"
                width="210"
                trigger="click">
                <el-button size="small" ref="button_two" @click="open(1)">打印清单</el-button>
                <el-button size="small" ref="button_six" @click="open(2)">打印汇总</el-button>
                <el-button slot="reference" style="margin:0 10px;" type="primary" size="small">打印</el-button>

              </el-popover> -->
              <el-button size="small" type="primary" @click="export_detail">报表下载</el-button>
          </div>
      </div>
      <el-table :data="tableData" border :row-style="{ color: '#303133' }" ref="tables"
                :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                v-loading="gather_loading"
                show-summary
                max-height="600"
                :span-method="merge"
                :summary-method="getTotal"
                highlight-current-row>

          <el-table-column align="center" prop="name" label="患者名字">
              <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <!--<el-table-column align="center" prop="name" label="患者类型">-->
          <!--<template slot-scope="scope"></template>-->
          <!--</el-table-column>-->

          <el-table-column align="center" prop="item_name" label="项目类别">
              <template slot-scope="scope">{{scope.row.item_name}}</template>
          </el-table-column>
          <el-table-column align="center" prop="price" label="费用">
              <template slot-scope="scope">{{scope.row.price.toFixed(2)}}</template>
          </el-table-column>
          <el-table-column align="center" prop="sum" label="费用总额">
              <template slot-scope="scope">
                  <div>{{scope.row.sum.toFixed(2)}}</div>
              </template>
          </el-table-column>

      </el-table>
  </div>
</template>


<script>
  import BreadCrumb from '@/xt_pages/components/bread-crumb'
  import { GetSummaryDetail } from '@/api/his/his'
  import { uParseTime } from '@/utils/tools'
  // import NewStatementPrint from './newStatementPrint'
  const moment = require('moment')
  export default {
    components: {
      BreadCrumb

    },
    data() {
      return {
        gather_loading:false,
        crumbs: [],
        tempArr: [],
        sameRowArr: [],
        keywords: '',
        pos:0,

        tableData: [],
        chargeDate: [moment(new Date()).add('year', 0).format('YYYY-MM-DD'), moment(new Date()).add('year', 0).format('YYYY-MM-DD')],
        item_type: '0',
        items: [
          { id: 1, name: '药品' },
          { id: 2, name: '项目' },
          { id: 3, name: '耗材' },

        ]

      }
    },
    methods: {

      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          if (rowIndex % 2 === 0) {
            return {
              rowspan: 2,
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
      unique(arr) {
        const res = new Map()
        return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
      },
      changeDate() {
        // console.log(this.chargeDate)
        this.getSummaryDetailList()
      },
      changeItem() {
        this.getSummaryDetailList()
      },
      searchAction() {
        this.item_type = '0'
        this.getSummaryDetailList()
      },
      getSummaryDetailList() {
        this.gather_loading = true
        let start_time = this.chargeDate[0]
        let end_time = this.chargeDate[1]
        let params = {
          start_time: start_time,
          end_time: end_time,
          type: this.item_type,
          keyword: this.keywords
        }
        GetSummaryDetail(params).then(response => {
          if (response.data.state == 0) {
            this.gather_loading = false

            this.$message.error(response.data.msg)
            return false
          } else {
            this.gather_loading = false

            let tempPatients = []
            let tempPatientsTwo = []
            this.tableData = []
            let tempData = response.data.data.patients
            let data = response.data.data.patients
            let orders = this.unique(tempData)
            for (let i = 0; i < orders.length; i++) {
              let obj = {
                patient_id: orders[i].id,
                name: orders[i].name,
                orders: []
              }
              for (let b = 0; b < data.length; b++) {
                if (orders[i].id == data[b].id) {
                  obj.orders = obj.orders.concat(data[b].orders)
                }
              }
              tempPatients.push(obj)
            }

            for (let i = 0; i < tempPatients.length; i++) {
              let obj = {
                patient_id: tempPatients[i].patient_id,
                name: tempPatients[i].name,
                order_info: []
              }
              let orders = tempPatients[i].orders
              for (let b = 0; b < orders.length; b++) {
                for (let c = 0; c < orders[b].order_info.length; c++) {
                  let newObj = {}

                  newObj['count'] = orders[b].order_info[c].cnt
                  newObj['price'] = orders[b].order_info[c].pric
                  if (orders[b].order_info[c].advice_id > 0 && orders[b].order_info[c].project_id == 0) {
                    newObj['type'] = 1
                    newObj['item_name'] = orders[b].order_info[c].advice.advice_name
                    newObj['item_id'] = orders[b].order_info[c].advice.drug_id

                  }
                  if (orders[b].order_info[c].advice_id == 0 && orders[b].order_info[c].project_id > 0) {
                    newObj['item_id'] = orders[b].order_info[c].project.project_id
                    if (orders[b].order_info[c].project.type == 2) {
                      newObj['type'] = 2
                      newObj['item_name'] = orders[b].order_info[c].project.project.project_name
                    } else if (orders[b].order_info[c].project.type == 3) {
                      newObj['type'] = 3
                      newObj['item_name'] = orders[b].order_info[c].project.good_info.good_name
                    }
                  }
                  obj.order_info.push(newObj)
                }
              }
              tempPatientsTwo.push(obj)
            }
            console.log(tempPatientsTwo)

            for (let d = 0; d < tempPatientsTwo.length; d++) {
              tempPatientsTwo[d]['new_order_info'] = []
              let project = []
              let advice = []
              for (let b = 0; b < tempPatientsTwo[d].order_info.length; b++) {
                if (tempPatientsTwo[d].order_info[b].type == 1) {
                  advice.push(tempPatientsTwo[d].order_info[b])
                } else {
                  project.push(tempPatientsTwo[d].order_info[b])
                }
              }
              // project = this.uniqueProjectAndAdvice(project)
              // advice = this.uniqueProjectAndAdvice(advice)

              let obj = {}
              let price = 0

              let obj2 = {}
              let price2 = 0

              let obj3 = {}
              let price3 = 0

              for (let i = 0; i < project.length; i++) {
                if (project[i].type == 2) {
                  price = parseFloat(price.toString()) + parseFloat((parseFloat(project[i].count.toString()) * parseFloat(project[i].price.toString()).toFixed(2)).toString())
                } else if (project[i].type == 3) {
                  price3 = parseFloat(price3.toString()) + parseFloat((parseFloat(project[i].count.toString()) * parseFloat(project[i].price.toString()).toFixed(2)).toString())
                }
              }


              for (let i = 0; i < advice.length; i++) {
                price2 = parseFloat(price2.toString()) + parseFloat((parseFloat(advice[i].count.toString()) * parseFloat(advice[i].price.toString()).toFixed(2)).toString())
              }


              switch (parseInt(this.item_type)) {
                case 0:

                  obj['sum'] = price + price2 + price3
                  obj['price'] = price
                  obj['item_name'] = '项目'
                  obj['name'] = tempPatientsTwo[d].name
                  obj['patient_id'] = tempPatientsTwo[d].patient_id
                  this.tableData.push(obj)

                  obj2['sum'] = 0
                  obj2['price'] = price2
                  obj2['item_name'] = '药品'
                  obj2['name'] = tempPatientsTwo[d].name
                  obj2['patient_id'] = tempPatientsTwo[d].patient_id
                  this.tableData.push(obj2)

                  obj3['sum'] = 0
                  obj3['price'] = price3
                  obj3['item_name'] = '耗材'
                  obj3['name'] = tempPatientsTwo[d].name
                  obj3['patient_id'] = tempPatientsTwo[d].patient_id
                  this.tableData.push(obj3)
                  break
                case 1:
                  obj2['sum'] = price2
                  obj2['price'] = price2
                  obj2['item_name'] = '药品'
                  obj2['name'] = tempPatientsTwo[d].name
                  obj2['patient_id'] = tempPatientsTwo[d].patient_id
                  this.tableData.push(obj2)
                  break
                case 2:

                  obj['sum'] = price
                  obj['price'] = price
                  obj['item_name'] = '项目'
                  obj['name'] = tempPatientsTwo[d].name
                  obj['patient_id'] = tempPatientsTwo[d].patient_id
                  this.tableData.push(obj)
                  break
                case 3:
                  obj3['sum'] = price3
                  obj3['price'] = price3
                  obj3['item_name'] = '耗材'
                  obj3['name'] = tempPatientsTwo[d].name
                  obj3['patient_id'] = tempPatientsTwo[d].patient_id
                  this.tableData.push(obj3)
                  break

              }



            }

            this.handleSpanTempArr()
            // this.tableData = tempPatientsTwo

            // console.log(tempPatientsTwo.length)
            //

          }
          //
          // console.log('去重前')
          // console.log(advice)
          // console.log(project)
          // //
          // //

          // //
          // console.log('去重后')
          //
          // console.log(advice.length)
          // console.log(project.length)
          //
          // for (let i = 0; i < project.length; i++) {
          //   let obj = {}
          //   let count = 0
          //   for (let a = 0; a < tempPatientsTwo.length; a++) {
          //     if (project[i].patient_id == tempPatientsTwo[a].patient_id && project[i].item_id == tempPatientsTwo[a].item_id && project[i].price == tempPatientsTwo[a].price) {
          //       count = count + tempPatientsTwo[a].count
          //       obj['count'] = count
          //
          //     }
          //     obj['price'] = project[i].price
          //     obj['type'] = project[i].type
          //     obj['item_name'] = project[i].item_name
          //     obj['item_id'] = project[i].item_id
          //     obj['name'] = project[i].name
          //     obj['patient_id'] = project[i].patient_id
          //     obj['count'] = count
          //     this.tableData.push(obj)
          //   }
          // }
          //
          //
          // for (let i = 0; i < advice.length; i++) {
          //   let obj = {}
          //   let count = 0
          //   for (let a = 0; a < tempPatientsTwo.length; a++) {
          //     if (advice[i].patient_id == tempPatientsTwo[a].patient_id && advice[i].item_id == tempPatientsTwo[a].item_id && advice[i].price == tempPatientsTwo[a].price) {
          //       count = count + tempPatientsTwo[a].count
          //       obj['count'] = count
          //
          //     }
          //     obj['price'] = advice[i].price
          //     obj['type'] = advice[i].type
          //     obj['item_name'] = advice[i].item_name
          //     obj['item_id'] = advice[i].item_id
          //     obj['name'] = advice[i].name
          //     obj['patient_id'] = advice[i].patient_id
          //     this.tableData.push(obj)
          //   }
          // }
          // console.log(this.tableData.length)
          // this.tableData = this.sort(this.tableData)

        })
      }, uniqueProjectAndAdvice(array) {
        // res用来存储结果
        var res = []
        for (var i = 0, arrayLen = array.length; i < arrayLen; i++) {
          for (var j = 0, resLen = res.length; j < resLen; j++) {
            if (array[i].item_id === res[j].item_id && array[i].price === res[j].price) {
              break
            }
          }
          // 如果array[i]是唯一的，那么执行完循环，j等于resLen
          if (j === resLen) {
            res.push(array[i])
          }
        }
        return res
      }, sort(arr) {
        for (var i = 0; i < arr.length - 1; i++) {
          for (var j = 0; j < arr.length - i - 1; j++) {
            if (arr[j].patient_id > arr[j + 1].patient_id) {// 相邻元素两两对比
              var hand = arr[j]
              arr[j] = arr[j + 1]
              arr[j + 1] = hand

            }
          }
        }
        return arr
      }, handleSpanTempArr() {
        this.tempArr = []

        for (let i = 0; i < this.tableData.length; i++) {
          if (i === 0) {
            this.tempArr.push(1)
            this.pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同
            if (this.tableData[i].patient_id === this.tableData[i - 1].patient_id) {
              this.tempArr[this.pos] += 1
              this.tempArr.push(0)
            } else {
              this.tempArr.push(1)
              this.pos = i
            }
          }
        }

        let sameRowArr = [], sIdx = 0
        this.tableData.forEach((item, index) => {
          item.index = index
          if (index === 0) {
            sameRowArr.push([index])
          } else {
            if (item.patient_id === this.tableData[index - 1].patient_id) {
              sameRowArr[sIdx].push(index)
            } else {
              sIdx = sIdx + 1
              sameRowArr.push([index])
            }
          }
        })
        this.sameRowArr = sameRowArr
      }, merge({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 3) {
          const _row = this.tempArr[rowIndex]
          const _col = _row > 0 ? 1 : 0
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      }, getTotal(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          console.log(data)
          const values = data.map(item => Number(item[column.property]))
          if (column.property === 'sum') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else {
            sums[index] = ''
          }
        })

        return sums
      }, export_detail() {

        let list = []
        for (let i = 0; i < this.tableData.length; i++) {
          let order = this.tableData[i]
          let name = order.name
          let item_name = order.item_name
          let pay_sumamt = order.price.toFixed(2)
          let total = order.sum.toFixed(2)


          let obj = {
            '患者姓名': name,
            '项目类别': item_name,
            '费用': pay_sumamt,
            '费用总额':total,
          }
          list.push(obj)
        }
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [ '患者姓名', '项目名称', '费用', '费用总额']
          const filterVal = [ '患者姓名', '项目名称', '费用', '费用总额']
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel1({
            header: tHeader,
            data,
            filename: '汇总',
            ref:this.$refs['tables'].$el
          })
        })

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

    }
  }
</script>
