<template>
    <!-- <div class="main-contain outpatientChargesManagement">
        <div class="position">
            <bread-crumb :crumbs='crumbs'></bread-crumb>
        </div> -->
    <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="table"
                  :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                  :span-method="merge"
                  show-summary
                  :summary-method="getTotal"
                  max-height="600"

                  v-loading="detail_loading"
                  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="name" label="项目名称">
                <template slot-scope="scope">{{scope.row.item_name}}</template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="规格">
                <template slot-scope="scope">{{scope.row.item_spec}}</template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="数量">
                <template slot-scope="scope">{{scope.row.count}}</template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="单价">
                <template slot-scope="scope">{{scope.row.price.toFixed(2)}}</template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="费用">
                <template slot-scope="scope">
                    <div>{{(scope.row.price.toFixed(2)*scope.row.count).toFixed(2)}}</div>
                </template>
            </el-table-column>

            <el-table-column align="center" prop="total" label="费用总额">
                <template slot-scope="scope">
                    <div>{{scope.row.total.toFixed(2)}}</div>
                </template>
            </el-table-column>

        </el-table>
    </div>

    <!-- </div> -->
</template>


<script>
  import BreadCrumb from '@/xt_pages/components/bread-crumb'
  import { GetSummaryDetail } from '@/api/his/his'
  import { uParseTime } from '@/utils/tools'
  import axios from 'axios'

  // import NewStatementPrint from './newStatementPrint'
  const moment = require('moment')
  export default {
    components: {
      BreadCrumb

    },
    data() {
      return {
        detail_loading: false,
        tempArr: [],
        pos: 0,

        sameRowArr: [],
        keywords: '',
        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: {
      Action(){
        var that = this
        axios.get('http://127.0.0.1:9531/handelExcel', {
          params: {}
        })
          .then(function(response) {
            if (response.data.state == 0) {
              that.$message.error(response.data.msg)


              return false
            } else {

              var list = []
              for(let i = 0; i < response.data.data.list.length; i++){
                let team =  response.data.data.list[i]
                for(let b = 0; b < team.list.length; b++){
                  let name = ""
                  if(team.list[b].type == 2){
                    name = team.list[b].project.project_name
                  }else{

                    name = team.list[b].good_info.good_name

                  }

                  let obj = {
                    '客户组合编码': team.id,
                    '客户组合名称': team.project_team,
                    '客户单项编码': team.list[b].id,
                    '客户单项名称': name,
                    '中心组合编码': '',
                    '中心组合名称': '',
                    '中心单项编码': '',
                    '中心单项名称': '',
                  }

                  list.push(obj)
                }
              }

              import('@/vendor/Export2Excel').then(excel => {
                const tHeader = [ '客户组合编码', '客户组合名称', '客户单项编码', '客户单项名称', '中心组合编码', '中心组合名称', '中心单项编码', '中心单项名称']
                const filterVal = [ '客户组合编码', '客户组合名称', '客户单项编码', '客户单项名称', '中心组合编码', '中心组合名称', '中心单项编码', '中心单项名称']
                const data = that.formatJson(filterVal, list)
                excel.export_json_to_excel({
                  header: tHeader,
                  data,
                  filename: "消费明细"
                })
              })


            }
          })
          .catch(function(error) {

          })




      },formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      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() {
        this.getSummaryDetailList()
      },
      changeItem() {
        this.getSummaryDetailList()
      },
      searchAction() {
        this.item_type = '0'
        this.getSummaryDetailList()

      },
      getSummaryDetailList() {
        this.detail_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.detail_loading = false

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

            this.tableData = []
            let tempPatients = []
            let tempPatientsTwo = []

            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.drug.min_unit != orders[b].order_info[c].advice.drug.dose_unit) {
                      newObj['item_spec'] =  orders[b].order_info[c].advice.drug.dose + orders[b].order_info[c].advice.drug.dose_unit + '*' + orders[b].order_info[c].advice.drug.min_number + orders[b].order_info[c].advice.drug.min_unit + '/' + orders[b].order_info[c].advice.drug.max_unit
                    } else {

                      newObj['item_spec'] = ''
                    }

                  }
                  if (orders[b].order_info[c].advice_id == 0 && orders[b].order_info[c].project_id > 0) {
                    newObj['type'] = 2
                    newObj['item_id'] = orders[b].order_info[c].project.project_id

                    if (orders[b].order_info[c].project.type == 2) {
                      newObj['item_spec'] =""
                      newObj['item_name'] = orders[b].order_info[c].project.project.project_name


                    } else if (orders[b].order_info[c].project.type == 3) {
                      newObj['item_spec'] =    orders[b].order_info[c].project.good_info.specification_name
                      newObj['item_name'] = orders[b].order_info[c].project.good_info.good_name


                    }
                  }
                  obj.order_info.push(newObj)
                }
              }
              tempPatientsTwo.push(obj)
            }

            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)

              for (let i = 0; i < project.length; i++) {
                let obj = {}
                let count = 0
                for (let a = 0; a < tempPatientsTwo[d].order_info.length; a++) {
                  if (project[i].item_id == tempPatientsTwo[d].order_info[a].item_id && project[i].price == tempPatientsTwo[d].order_info[a].price) {
                    count = count + tempPatientsTwo[d].order_info[a].count
                  }
                }



                obj['price'] = project[i].price
                obj['type'] = project[i].type
                obj['item_name'] = project[i].item_name
                obj['item_spec'] = project[i].item_spec

                obj['item_id'] = project[i].item_id
                obj['name'] = tempPatientsTwo[d].name
                obj['patient_id'] = tempPatientsTwo[d].patient_id
                obj['count'] = count
                tempPatientsTwo[d].new_order_info.push(obj)
              }

              for (let i = 0; i < advice.length; i++) {
                let obj = {}
                let count = 0
                for (let a = 0; a < tempPatientsTwo[d].order_info.length; a++) {
                  if (advice[i].item_id == tempPatientsTwo[d].order_info[a].item_id && advice[i].price == tempPatientsTwo[d].order_info[a].price) {
                    count = count + tempPatientsTwo[d].order_info[a].count
                  }
                }

                obj['price'] = advice[i].price
                obj['type'] = advice[i].type
                obj['item_name'] = advice[i].item_name
                obj['item_spec'] = advice[i].item_spec
                obj['item_id'] = advice[i].item_id
                obj['name'] = tempPatientsTwo[d].name
                obj['patient_id'] = tempPatientsTwo[d].patient_id
                obj['count'] = count
                tempPatientsTwo[d].new_order_info.push(obj)
              }

            }

            for (let i = 0; i < tempPatientsTwo.length; i++) {
              let total = 0
              for (let b = 0; b < tempPatientsTwo[i].new_order_info.length; b++) {
                let new_name = tempPatientsTwo[i].new_order_info[b].item_name
                // console.log('3 ' + new_name)
                if (new_name != undefined){
                  // console.log('3 ' + tempPatientsTwo[i].new_order_info[b].patient_id)
                  // console.log('3 ' + tempPatientsTwo[i].new_order_info[b].price)
                  // console.log('3 ' + tempPatientsTwo[i].new_order_info[b].count)
                  //
                  // new_name = new_name.replace('（ ', '')
                  // new_name = new_name.replace(' ）', '')
                  if (new_name.length != 0) {
                    total = parseFloat(total) + parseFloat((parseFloat(tempPatientsTwo[i].new_order_info[b].count.toString()) * parseFloat(tempPatientsTwo[i].new_order_info[b].price.toString().toString())).toFixed(2))
                  }



                }


              }
              tempPatientsTwo[i]['total'] = total
            }
            console.log('tempPatientsTwo', tempPatientsTwo)
            for (let i = 0; i < tempPatientsTwo.length; i++) {
              // console.log(111,tempPatientsTwo[i].total)
              if (tempPatientsTwo[i].new_order_info.length > 0) {

                for (let b = 0; b < tempPatientsTwo[i].new_order_info.length; b++) {
                  // let new_name = tempPatientsTwo[i].new_order_info[b].item_name
                  // console.log('2 ' + new_name)
                  //
                  // new_name = new_name.replace('（ ', '')
                  // new_name = new_name.replace(' ）', '')

                    let obj = {
                      name: tempPatientsTwo[i].name,
                      patient_id: tempPatientsTwo[i].patient_id,
                      price: tempPatientsTwo[i].new_order_info[b].price,
                      type: tempPatientsTwo[i].new_order_info[b].type,
                      item_name: tempPatientsTwo[i].new_order_info[b].item_name,
                      item_id: tempPatientsTwo[i].new_order_info[b].item_id,
                      count: tempPatientsTwo[i].new_order_info[b].count,
                      item_spec: tempPatientsTwo[i].new_order_info[b].item_spec
                    }


                    // if(b == 0){
                    obj['total'] = tempPatientsTwo[i].total
                    // }else{
                    //   obj['total'] = 0
                    // }
                    this.tableData.push(obj)


                }
              }
            }
            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 === 6) {
          const _row = this.tempArr[rowIndex]
          const _col = _row > 0 ? 1 : 0
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      }, 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 count = order.count
          let price = order.price.toFixed(2)
          let pay_sumamt = (order.price.toFixed(2) * order.count).toFixed(2)
          let total = order.total.toFixed(2)

          let obj = {
            '患者姓名': name,
            '项目名称': item_name,
            '数量': count,
            '单价': price,
            '费用': 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['table'].$el
          })
        })

      }, formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }, 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 === 'total') {
            // 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)
            let num = 0
            data.map(item => {
              num += item.price.toFixed(2) * item.count
            })
            sums[index] = num.toFixed(2)
          } else {
            sums[index] = ''
          }
        })

        return sums
      }
    },
    created() {
      this.getSummaryDetailList()

    }
  }
</script>
