<template>
  <div>
    <div style="display: flex;justify-content: space-between;margin-bottom:10px;">
      <div>


        <el-select size="small" v-model="item_time_type" placeholder="请选择"
                   style="width:150px;margin-left:10px;" @change="changeTimeItem">

          <el-option
            label="处方时间"
            value="0">
          </el-option>

          <el-option
            label="结算时间"
            value="1">
          </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>
      </div>
      <div>

        <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"
              max-height="600"
              :span-method="merge"
              highlight-current-row>

      <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 { getDictionaryDataConfig } from '@/utils/data'
import BreadCrumb from '@/xt_pages/components/bread-crumb'
import { GetSummaryDetail } from '@/api/his/his'
// import NewStatementPrint from './newStatementPrint'
const moment = require('moment')
export default {
  components: {
    BreadCrumb

  },
  data() {
    return {
      gather_loading: false,
      crumbs: [],
      tempArr: [],
      sameRowArr: [],
      keywords: '',
      pos: 0,
      all_table_data: [],
      costClassify: getDictionaryDataConfig('system', 'cost_classify'),
      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',
      new_item_type: 0,
      item_time_type: '1',
      items: [
        { id: 1, name: '药品' },
        { id: 4, name: '检验费' },
        { id: 5, name: '治疗费' },
        { id: 6, name: '护理费' },
        { id: 7, 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()
    }, changeTimeItem() {
      this.getSummaryDetailList()
    },
    changeItem() {
      this.new_item_type = this.item_type
      if (this.item_type == 1) {
        this.new_item_type = -100
      } else if (this.item_type == 5) {
        this.new_item_type = -200
      }
      this.getSummaryDetailList()
    }, uniquepid(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.p_id) && res.set(arr.p_id, 1))
    },
    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: 0,
        keyword: this.keywords,
        time_type: this.item_time_type
      }
      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 = []
          this.all_table_data = []

          let tempData = response.data
          tempPatientsTwo = tempData

          let infos = this.unique2(tempPatientsTwo)
          let sum = 0
          for (let e = 0; e < infos.length; e++) {
            let obj = {
              'sum': 0,
              'price': 0,
              'cost_classify': infos[e].cost_classify,
              'item_name': this.getName(infos[e].cost_classify)
            }
            let price = 0
            for (let d = 0; d < tempPatientsTwo.length; d++) {
              if (tempPatientsTwo[d].cost_classify == infos[e].cost_classify) {
                price = parseFloat(price.toString()) + parseFloat((parseFloat(tempPatientsTwo[d].cnt.toString()) * parseFloat(tempPatientsTwo[d].pric.toString()).toFixed(2)).toString())
              }
              obj.price = price
            }
            sum = sum + price

            this.tableData.push(obj)
          }
          for(let i = 0; i < this.tableData.length;i++){
            this.tableData[i].sum = sum
          }

          // for (let i = 0; i < tempPatientsThree.length; i++) {
          //   let sum = 0
          //   for (let b = 0; b < tempPatientsThree[i].length; b++) {
          //     let obj = {
          //       cost_classify: tempPatientsThree[i].items[b].cost_classify,
          //       price: tempPatientsThree[i].items[b].price,
          //       item_name: tempPatientsThree[i].items[b].item_name,
          //       sum: 0
          //     }
          //     sum = sum + tempPatientsThree[i].items[b].price
          //     this.tableData.push(obj)
          //     this.all_table_data.push(obj)
          //   }
          //   for (let c = 0; c < this.tableData.length; c++) {
          //     this.tableData[c].sum = sum
          //   }
          // }

          console.log(this.tableData)

          this.handleSpanTempArr()
        }
      })
    }, getName(cost_classify) {
      if (cost_classify == -1000) {
        return '药品费'
      } else if (cost_classify == -100) {
        return '耗材费'
      } else {
        var costClassify = getDictionaryDataConfig('system', 'cost_classify')
        var name = ''
        for (let i = 0; i < costClassify.length; i++) {
          if (cost_classify == costClassify[i].id) {
            name = costClassify[i].name
          }
        }
        return name
      }
    }, 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
    }, unique2(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].cost_classify === res[j].cost_classify) {
            break
          }
        }
        // 如果array[i]是唯一的，那么执行完循环，j等于resLen
        if (j === resLen) {
          res.push(array[i])
        }
      }
      return res
    }, unique3(array) {
      console.log('-----11122222')

      console.log(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].patient_id === res[j].patient_id) {
            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 === 2) {
        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>
