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

        <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>

        <el-button size="small" type="primary" @click="export_detail_two" v-if="this.$store.getters.xt_user.org_id == 9478">收入统计</el-button>

      </div>
    </div>
    <el-table ref="tables" :data="tableData" border :row-style="{ color: '#303133' }"
              :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
              v-loading="settle_loading"
              max-height="600"
              highlight-current-row>

      <el-table-column align="center" prop="name" label="患者名字" fixed>
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" prop="id_card_no" label="身份证">
        <template slot-scope="scope">
          {{scope.row.id_card_no}}
        </template>
      </el-table-column>


      <el-table-column align="center" prop="dis"   label="透析次数">
        <template slot-scope="scope">
          {{scope.row.dis.length}}

        </template>
      </el-table-column>

      <el-table-column align="center" prop="s_count"  label="结算次数">
        <template slot-scope="scope">
          {{scope.row.orders.length}}
        </template>
      </el-table-column>

      <el-table-column align="center" prop="medfee_sumamt" label="医疗费总额">
        <template slot-scope="scope">{{GetMedfeeSumam(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="fund_pay_sumamt" label="基金支付金额">
        <template slot-scope="scope">{{GetFundPaySumamt(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="acct_pay" label="个人账户支付金额">
        <template slot-scope="scope">{{GetAcctPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="psn_cash_pay" label="个人支付金额">
        <template slot-scope="scope">{{GetPsnCashPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="hifp_pay" label="基金统筹金额">
        <template slot-scope="scope">{{GetHifpPay(scope.row)}}</template>
      </el-table-column>

      <el-table-column align="center" prop="hifob_pay" label="大额基金支付">
        <template slot-scope="scope">{{GetHiFobPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="preselfpay_amt" label="先行自付金额">
        <template slot-scope="scope">{{GetPreselfpaAmt(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="overlmt_self_pay" label="超限价金额">
        <template slot-scope="scope">{{GetOverlmtSelfPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="fulamt_ownpay_amt" label="全自费金额">
        <template slot-scope="scope">{{GetFulamtOwnpayAmt(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="inscp_scp_amt" label="符合政策范围金额">
        <template slot-scope="scope">{{GetInscpScpAmt(scope.row)}}</template>
      </el-table-column>

      <el-table-column align="center" prop="maf_pay" label="医疗救助基金">
        <template slot-scope="scope">{{GetMafPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="hifes_pay" label="企业补充医疗保险基金支出">
        <template slot-scope="scope">{{GetHifesPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="hifmi_pay" label="居民大病保险资金支出">
        <template slot-scope="scope">{{GetHifmiPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="oth_pay" label="其他支付">
        <template slot-scope="scope">{{GetOthPay(scope.row)}}</template>
      </el-table-column>
      <el-table-column align="center" prop="cvlserv_pay" label="公务员医疗补助资金支出">
        <template slot-scope="scope">{{GetCvlservPay(scope.row)}}</template>
      </el-table-column>


    </el-table>

  </div>
</template>


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

  },
  data() {
    return {
      settle_loading:false,
      crumbs: [],
      tempArr: [],
      sameRowArr: [],
      modeOptions:this.$store.getters.treatment_mode,
      tableData: [],
      config:{},
      sick:{},
      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: 2, name: '自费' },
        { id: 5, name: '城乡居民基本医疗保险' },
        { id: 6, name: '职工基本医疗保险' }
      ]

    }
  },
  methods: {
    GetMedfeeSumam(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].medfee_sumamt
      }
      return medfee.toFixed(2)

    }, GetFundPaySumamt(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].fund_pay_sumamt
      }
      return medfee.toFixed(2)

    },GetAcctPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].acct_pay
      }
      return medfee.toFixed(2)

    },GetPsnCashPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].psn_cash_pay
      }
      return medfee.toFixed(2)

    },GetHifpPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].hifp_pay
      }
      return medfee.toFixed(2)

    },GetHiFobPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].hifob_pay
      }
      return medfee.toFixed(2)

    },GetPreselfpaAmt(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].preselfpay_amt
      }
      return medfee.toFixed(2)

    },GetOverlmtSelfPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].overlmt_self_pay
      }
      return medfee.toFixed(2)
    },GetFulamtOwnpayAmt(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].fulamt_ownpay_amt
      }
      return medfee.toFixed(2)

    },GetMafPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].maf_pay
      }
      return medfee.toFixed(2)

    },GetHifesPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].hifes_pay
      }
      return medfee.toFixed(2)

    },GetHifmiPay(row){

      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].hifmi_pay
      }
      return medfee.toFixed(2)
    },GetInscpScpAmt(row){

      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].inscp_scp_amt
      }
      return medfee.toFixed(2)

    },GetOthPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].oth_pay
      }
      return medfee.toFixed(2)

    },GetCvlservPay(row){
      let medfee = 0
      for(let i = 0; i < row.orders.length; i++){
        medfee = medfee + row.orders[i].cvlserv_pay
      }
      return medfee.toFixed(2)
    },
    change(id,desc,type){
      let params = {
        id: id,
        desc: desc,
        change_type: type
      }
      changeOrderDesc(params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg)
        } else {
          this.$message.success(response.data.data.msg)
        }
      })
    },
    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))
    },getSickName(sick_id){
      let name = ""
      for(let i = 0;i < this.sick.length;i++){
        if(sick_id == this.sick[i].id){
          name = this.sick[i].class_name + "(" + this.sick[i].content_code +")"
        }
      }
      return name
    },getTypeName(row){
      let name = ""
      if(row.insutype == '390'){
        // let a =  config.mdtrtarea_admvs.slice(0, 4); //就医地前4位编码
        let a =  this.config.mdtrtarea_admvs.slice(0, 3); //就医地前3位编码


        // let aa=  row.his.insuplc_admdvs.slice(0, 4); //参保地前4位编码
        let b=  row.his.insuplc_admdvs.slice(0, 3); //参保地前3位编码
        if(a == b){
          name = "本地城乡"
        }else{
          name = "异地城乡"
        }

      }else if(row.insutype == '310'){
        // let c =  config.mdtrtarea_admvs.slice(0, 4); //就医地前4位编码
        let a = this.config.mdtrtarea_admvs.slice(0, 3); //就医地前3位编码


        // let d=  row.his.insuplc_admdvs.slice(0, 4); //参保地前4位编码
        let b=  row.his.insuplc_admdvs.slice(0, 3); //参保地前3位编码
        if(a == b){

          name = "本地职工"
        }else{
          name = "异地职工"
        }

      }else{
        name = "其他"

      }
      return name
    },getName(id){
      var name = ""
      var options =  this.$store.getters.insuplc_admdvs
      for(let i = 0; i < options.length; i++){
        if(id == options[i].value){
          name = options[i].label
        }
      }
      return name
    },
    changeDate() {
      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,
        s_type:2,
      }
      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 = []
          this.config = response.data.data.config
          this.sick = response.data.data.sick
          let data = response.data.data.patients
          this.tableData = data
          console.log( 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) {
        const _row = this.tempArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },export_detail_two(){
      let start_time = this.chargeDate[0]
      let end_time = this.chargeDate[1]
      let params = {
        start_time: start_time,
        end_time: end_time,
      }
      // this.settle_loading = true
      newsummary(params).then(response => {
        if (response.data.state == 0) {
          this.settle_loading = false

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

          let org_info = response.data.data.org_info
          let result = response.data.data.result


          let list = []
          for (let i = 0; i < result.length; i++) {
            let order = result[i]
            let name = order.PsnName


            let type_name = ""
            if(order.TypeName == '城乡'){
              // let c =  this.config.mdtrtarea_admvs.slice(0, 4); //就医地前4位编码
              let a =  org_info.mdtrtarea_admvs.slice(0, 3); //就医地前3位编码

              let e =  org_info.mdtrtarea_admvs.slice(0, 2); //就医地前3位编码

              let f=  order.CanBaoDi.slice(0, 2); //参保地前4位编码
              let b=  order.CanBaoDi.slice(0, 3); //参保地前3位编码
              if(a == b){
                type_name = "本地城乡"
              }else{
                if(e == f){
                  type_name = "省内异地城乡"
                }else{
                  type_name = "省外异地城乡"
                }
              }

            }else if(order.TypeName == '职工'){
              // let c =  this.config.mdtrtarea_admvs.slice(0, 4); //就医地前4位编码
              let a = this.config.mdtrtarea_admvs.slice(0, 3); //就医地前3位编码
              let e =  this.config.mdtrtarea_admvs.slice(0, 2); //就医地前3位编码
              let f= order.CanBaoDi.slice(0, 2); //参保地前4位编码
              // let d=  row.his.insuplc_admdvs.slice(0, 4); //参保地前4位编码
              let b=  order.CanBaoDi.slice(0, 3); //参保地前3位编码
              if(a == b){
                type_name = "本地职工"
              }else{
                if (e == f){
                  type_name = "省内异地职工"
                }else{
                  type_name = "省外异地职工"
                }
              }
            }else{
              type_name = "自费"
            }



            let total = order.Total

            let xt = order.XtCount
            let xl = order.XlCount
            let gl = order.GlCount


            let obj = {
              '患者姓名': name,
              '类型': type_name,
              "合计次数": total,
              '血透': xt,
              "血滤": xl,
              '灌流': gl,
              "西药费":order.WesternMedicineFee,
              "中成药费":order.ChinesePatentMedicineFee,
              '耗材费': order.HealthMaterialsFee,
              '挂号费': order.RegistrationFee,
              '治疗费': order.TreatmentFee,
              '检查费': order.ExaminationFee,
              '化验费': order.LaboratoryFee,
              '护理费': order.NursingFee,
              '其他费': order.OtherFee,
              '床位费': order.BedsFee,
              '诊察费': order.ConsultationFee,
              '中药饮片费': order.ChineseMedicineFee,
              '一般诊疗费': order.GeneralTreatmentFee,
              '合计': order.TotalMedicalFee,
              '自费金额': order.SelfPay,
              '个人账户支付': order.AcctPay,
              '退费': order.Return,
              '优惠': order.YouHui,
              '应收': order.YingShou,
              '挂账': order.GuaZhang,
              '冲账': order.ChongZhang,
              '实收': order.ShiShou,
              '已收': order.YiShou,
            }
            list.push(obj)
          }

          if(list.length > 0){
            import('@/vendor/Export2Excel').then(excel => {
              const tHeader = ['患者姓名', '类型', "合计次数", '血透', '血滤', "灌流", "西药费", "中成药费", '耗材费', '挂号费', '治疗费', '检查费', '化验费', '护理费', "其他费", "床位费", "诊察费", "中药饮片费", "一般诊疗费", "合计", "自费金额", '个人账户支付', '退费', "优惠", "应收", "挂账", "冲账", "实收", "已收"]
              const filterVal = ['患者姓名', '类型', "合计次数", '血透', '血滤', "灌流", "西药费", "中成药费", '耗材费', '挂号费', '治疗费', '检查费', '化验费', '护理费', "其他费", "床位费", "诊察费", "中药饮片费", "一般诊疗费", "合计", "自费金额", '个人账户支付', '退费', "优惠", "应收", "挂账", "冲账", "实收", "已收"]

              const data = this.formatJson(filterVal, list)
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: '收入统计'
              })
            })
          }


        }
      })


    },
  export_detail() {

      let list = []
      for (let i = 0; i < this.tableData.length; i++) {
        let order = this.tableData[i]
        let name = order.name

        let obj = {
          '患者姓名': name,
        }
        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.getSummarySettleList()


  }
}
</script>
