<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="report-table"
                :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                show-summary
                v-loading="settle_loading"
                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.other_name }}</template>
          </el-table-column>
        <el-table-column align="center" prop="item_name" label="身份证">
          <template slot-scope="scope">
            {{scope.row.id_card_no}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="item_name" label="治疗日期">
          <template slot-scope="scope">
            {{getTimes(scope.row.settle_accounts_date)}}
          </template>
        </el-table-column>

          <el-table-column align="center" prop="item_name" label="结算日期">
              <template slot-scope="scope">
                  {{scope.row.setl_time?scope.row.setl_time.split(" ")[0]:getTimes(scope.row.settle_accounts_date)}}
              </template>
          </el-table-column>

          <el-table-column align="center" prop="item_name" label="结算类型">
              <template slot-scope="scope">
                  <div v-if="scope.row.is_medicine_insurance == 0">自费</div>
                  <div v-if="scope.row.is_medicine_insurance == 1">医保</div>
              </template>
          </el-table-column>
          <el-table-column align="center" prop="item_name" label="处方类型">
              <template slot-scope="scope">
                  <div v-if="scope.row.med_type == '14'">门诊特殊病</div>
                  <div v-if="scope.row.med_type == '11'">普通门诊</div>
              </template>
          </el-table-column>
          <el-table-column align="center" prop="item_name" label="医疗费总额">
              <template slot-scope="scope">{{scope.row.medfee_sumamt.toFixed(2)}}</template>
          </el-table-column>
          <el-table-column align="center" prop="item_name" label="基金支付金额">
              <template slot-scope="scope">{{scope.row.fund_pay_sumamt.toFixed(2)}}</template>
          </el-table-column>
          <el-table-column align="center" prop="item_name" label="个人账户支付金额">
              <template slot-scope="scope">{{scope.row.acct_pay.toFixed(2)}}</template>
          </el-table-column>
          <el-table-column align="center" prop="item_name" label="个人支付金额">
              <template slot-scope="scope">{{scope.row.psn_cash_pay.toFixed(2)}}</template>
          </el-table-column>
          <el-table-column align="center" prop="item_name" label="基金统筹金额">
              <template slot-scope="scope">{{scope.row.hifp_pay.toFixed(2)}}</template>
          </el-table-column>

          <el-table-column align="center" prop="item_name" label="大额基金支付">
              <template slot-scope="scope">{{scope.row.hifob_pay.toFixed(2)}}</template>
          </el-table-column>


          <el-table-column align="center" prop="item_name" label="医疗救助基金">
              <template slot-scope="scope">{{scope.row.maf_pay.toFixed(2)}}</template>
          </el-table-column>

          <el-table-column align="center" prop="item_name" label="企业补充医疗保险基金支出">
              <template slot-scope="scope">{{scope.row.hifes_pay.toFixed(2)}}</template>
          </el-table-column>


          <el-table-column align="center" prop="item_name" label="居民大病保险资金支出">
              <template slot-scope="scope">{{scope.row.hifmi_pay.toFixed(2)}}</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>
</template>


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

    },
    data() {
      return {
        settle_loading:false,
        crumbs: [],
        tempArr: [],
        sameRowArr: [],
        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: '门诊特殊病' },
          { id: 4, name: '普通门诊' },
          { id: 5, name: '城乡居民基本医疗保险' },
          { id: 6, name: '职工基本医疗保险' }


        ]

      }
    },
    methods: {
      getTimes(time) {
        return uParseTime(time, '{y}-{m}-{d}')
      },
      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.getSummarySettleList()
      },
      changeItem() {
        this.getSummarySettleList()

      },
      searchAction() {
        this.item_type = '0'
        this.getSummarySettleList()

      },
      getSummarySettleList() {
        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
        }
        this.settle_loading = true
        GetSummarySettle(params).then(response => {
          if (response.data.state == 0) {
            this.settle_loading = false

            this.$message.error(response.data.msg)
            return false
          } else {
            this.settle_loading = false
            this.tableData = []
            let data = response.data.data.patients

            for (let i = 0; i < data.length; i++) {
              let total = 0
              for (let b = 0; b < data[i].orders.length; b++) {
                let order = data[i].orders[b]
                order['other_name'] = data[i].name
                order['id_card_no'] = data[i].id_card_no

                total = parseFloat((parseFloat(total.toString()) + parseFloat(data[i].orders[b].medfee_sumamt.toString())).toFixed(2).toString())
              }

              data[i]['total'] = total
            }
            console.log(data)

            for (let i = 0; i < data.length; i++) {
              for (let b = 0; b < data[i].orders.length; b++) {
                let order = data[i].orders[b]

                if(b == 0){
                  order['total'] = data[i].total

                }else{
                  order['total'] = 0

                }

                this.tableData.push(order)

              }
            }
            console.log(this.tableData)

            this.handleSpanTempArr()
          }
        })
      }, 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 === 1 || columnIndex === 15) {
          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 === '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)
          } 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.other_name
          let id_card_no = order.id_card_no

          let time = ''
          let balance_accounts = ""
          let med_type = ""
          let medfee_sumamt = ""
          let fund_pay_sumamt = ""
          let acct_pay = ""
          let psn_cash_pay = ""
          let hifes_pay = ""
          let hifmi_pay = ""
          let hifp_pay = ""
          let hifob_pay = ""
          let maf_pay = ""
          let time2 = ""
          time2 = this.getTimes(order.settle_accounts_date)

          let total = ""

          if(order.setl_time.length == 0){

            time = this.getTimes(order.settle_accounts_date)

          }else {

            time = order.setl_time.split(" ")[0]

          }

          if (order.is_medicine_insurance == 0) {
            balance_accounts = '自费'
          }

          if (order.is_medicine_insurance == 1) {
            balance_accounts = '医保'
          }

          if (order.med_type == '14') {
            med_type = '门诊特殊病'
          }

          if (order.med_type == '11') {
            med_type = '普通门诊'
          }

          medfee_sumamt = order.medfee_sumamt
          fund_pay_sumamt = order.fund_pay_sumamt

          acct_pay = order.acct_pay

          psn_cash_pay = order.psn_cash_pay
          hifes_pay = order.hifes_pay
          hifmi_pay = order.hifmi_pay
          hifp_pay = order.hifp_pay
          hifob_pay = order.hifob_pay
          maf_pay = order.maf_pay
          total = order.total


          let obj = {
            '患者姓名': name,
            '身份证': id_card_no,
            '治疗日期': time2,
            '结算日期': time,
            '结算类型': balance_accounts,
            '处方类型': med_type,
            '医疗费总额': medfee_sumamt,
            '基金支付金额': fund_pay_sumamt,
            '基金统筹金额': hifp_pay,
            '大额基金支付':hifob_pay,
            '医疗救助基金':maf_pay,
            '个人账户支付金额': acct_pay,
            '个人支付基金': psn_cash_pay,
            '企业补充医疗保险基金支出': hifes_pay,
            '居民大病保险资金支出': hifmi_pay,
            '费用总额':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['report-table'].$el
          })
        })

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

    }
  }
</script>
