<template>
  <div class="print-pay-fee-container">
      <el-row>
        <el-col :span="24">
          <div class="text-center">
            <div style="color:#000;font-size:36px">{{ printPayFeeInfo.communityName }} {{ printPayFeeInfo.apply ==
              'Y' ? $t('printPayFeeBangTai.applyForm') : $t('printPayFeeBangTai.receiptForm')}}</div>
            <span style="color:#000;font-size:20px">
              <span>{{ $t('printPayFeeBangTai.receiptNum') }}</span>：{{ printPayFeeInfo.receiptNum }}
            </span>
          </div>
          <div style="color:#000;font-size:20px;margin-left:20px">
            <div class="float-left">
              <span>{{ $t('printPayFeeBangTai.owner') }}</span>{{ printPayFeeInfo.payObjName }}
            </div>
            <div class="float-right text-right">
              <span>{{ $t('printPayFeeBangTai.paymentTime') }}</span>{{ printPayFeeInfo.feeTime }}
            </div>
          </div>
          <table class="table vc-table-border" style="color:#000;font-size:20px">
            <thead>
              <tr>
                <th scope="col" class="text-center" width="80px">{{ $t('printPayFeeBangTai.serialNum') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.feeItem') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.houseCar') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.feeRange') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.cycle') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.unitPrice') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.areaUsage') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.paymentMethod') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.amount') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.discountAmount') }}</th>
                <th scope="col" class="text-center">{{ $t('printPayFeeBangTai.remark') }}</th>
              </tr>
            </thead>
            <tbody class="vc-table-border" style="color:#000;font-size:20px">
              <tr v-for="(item, index) in printPayFeeInfo.fees" class="vc-table-border" :key="index">
                <th scope="row" class="text-center">{{ index + 1 }}</th>
                <td class="text-center">{{ item.feeName }}</td>
                <td class="text-center">{{ item.objName }}</td>
                <td class="text-center" v-if="item.preDegrees">
                  {{ formatDate(item.startTime) }}<span>{{ $t('printPayFeeBangTai.to') }}</span>{{ formatDate(item.endTime) }}<br>
                  {{ item.preDegrees }} {{ $t('printPayFeeBangTai.to') }} {{ item.curDegrees }}
                </td>
                <td class="text-center" v-else-if="item.feeTypeCd == '888800010006'">
                  {{ $t('printPayFeeBangTai.none') }}
                </td>
                <td class="text-center" v-else>
                  {{ formatDate(item.startTime) }}<span>{{ $t('printPayFeeBangTai.to') }}</span>{{ formatDate(item.endTime) }}
                </td>
                <td class="text-center">{{ item.cycle }}</td>
                <td class="text-center">{{ item.squarePrice }}</td>
                <td class="text-center">{{ item.area }}</td>
                <td class="text-center">{{ item.primeRate }}</td>
                <td class="text-center">{{ item.amount }}</td>
                <td class="text-center">{{ item.discountPrice }}</td>
                <td class="text-center" width="200px">{{ item.remark }}</td>
              </tr>
              <tr>
                <td colspan="3" class="text-center">
                  <span>{{ $t('printPayFeeBangTai.capitalRMB') }}</span>（元）
                </td>
                <td colspan="4" class="text-center">{{ changeNumMoneyToChinese(printPayFeeInfo.amount) }}</td>
                <td colspan="1" class="text-center">{{ computeSumArea() }}</td>
                <td colspan="3" class="text-center">{{ printPayFeeInfo.amount }}</td>
              </tr>
              <tr height="60px">
                <td colspan="6">
                  <div style="max-width: 600px;">
                  <div v-html="printPayFeeInfo.content"></div>
                  </div>
                </td>
                <td colspan="5">
                  <img :src="printPayFeeInfo.qrImg" width="100px" height="100px">
                </td>
              </tr>
            </tbody>
          </table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <div class="row" style="color:#000;font-size:20px;margin-left: 10px;">
            <div class="float-left" style="width: 20%;">
              <span>{{ $t('printPayFeeBangTai.departmentHead') }}</span>：
            </div>
            <div class="float-left" style="width: 20%;">
              <span>{{ $t('printPayFeeBangTai.handler') }}</span>：{{ userInfo.name }}
            </div>
            <div class="float-left" style="width: 20%;">
              <span>{{ $t('printPayFeeBangTai.financialCollection') }}</span>：
            </div>
            <div class="float-left" style="width: 20%;">
              <span>{{ $t('printPayFeeBangTai.customerConfirmation') }}</span>：
            </div>
          </div>
        </el-col>
        <el-col :span="4" id="print-btn">
          <el-button type="primary" class="float-right" @click="printPurchaseApplyDiv">
            <i class="el-icon-printer"></i>&nbsp;{{ $t('printPayFeeBangTai.print') }}
          </el-button>
          <el-button type="warning" class="float-right" style="margin-right:20px;" @click="closePage">
            {{ $t('printPayFeeBangTai.cancel') }}
          </el-button>
        </el-col>
      </el-row>
  </div>
</template>

<script>
import { queryFeeReceipt, queryFeeReceiptDetail, queryFeePrintSpec } from '@/api/fee/printPayFeeBangTaiApi'
import { getCommunityId,getCommunityName } from '@/api/community/communityApi'
import { getUserId,getUserName } from '@/api/user/userApi'
import { dateFormat } from '@/utils/dateUtil'
import { changeNumMoneyToChinese } from '@/utils/moneyUtil'

export default {
  name: 'PrintPayFeeBangTaiList',
  data() {
    return {
      printPayFeeInfo: {
        communityName: '',
        receiptId: '',
        receiptIds: '',
        roomName: '',
        amount: 0.00,
        fees: [],
        feeTime: '',
        wechatName: '',
        content: '',
        qrImg: '',
        payObjName: '',
        feeReceipt: [],
        apply: 'N',
        receiptNum: '',
        merge: ''
      },
      printFlag: '0',
      userInfo: {},
      communityId: ''
    }
  },
  created() {
    this.initData()
    this.loadData()
  },
  methods: {
    initData() {
      this.printPayFeeInfo.receiptId = this.$route.query.receiptId
      this.printPayFeeInfo.receiptIds = this.$route.query.receiptIds
      this.printPayFeeInfo.apply = this.$route.query.apply || 'N'
      this.printPayFeeInfo.merge = this.$route.query.merge
      this.communityId = getCommunityId()
      this.userInfo = {
        userId: getUserId(),
        name: getUserName()
      }
    },
    async loadData() {
      this.printPayFeeInfo.communityName = getCommunityName()
      await this.loadReceipt()
      await this.loadPrintSpec()
    },
    async loadReceipt() {
      try {
        const params = {
          page: 1,
          row: 30,
          receiptId: this.printPayFeeInfo.receiptId,
          receiptIds: this.printPayFeeInfo.receiptIds,
          communityId: this.communityId
        }
        const { data } = await queryFeeReceipt(params)
        const _feeReceipt = data
        let _amount = 0
        _feeReceipt.forEach(item => {
          _amount += parseFloat(item.amount)
        })

        this.printPayFeeInfo.amount = _amount.toFixed(2)
        this.printPayFeeInfo.roomName = _feeReceipt[0].objName
        this.printPayFeeInfo.feeTime = _feeReceipt[0].createTime
        this.printPayFeeInfo.payObjName = _feeReceipt[0].payObjName
        this.printPayFeeInfo.feeReceipt = _feeReceipt
        this.printPayFeeInfo.receiptNum = _feeReceipt[0].receiptCode
        await this.loadReceiptDetail()
      } catch (error) {
        console.error('Failed to load receipt:', error)
      }
    },
    async loadReceiptDetail() {
      try {
        const params = {
          page: 1,
          row: 100,
          receiptId: this.printPayFeeInfo.receiptId,
          receiptIds: this.printPayFeeInfo.receiptIds,
          communityId: this.communityId,
          mergeFee: this.printPayFeeInfo.merge
        }
        const { data } = await queryFeeReceiptDetail(params)
        const _feeReceiptDetails = data
        this.printPayFeeInfo.receiptNum = this.printPayFeeInfo.receiptNum + "(" + _feeReceiptDetails[0].payOrderId + ")"
        _feeReceiptDetails.forEach(item => {
          this.printPayFeeInfo.feeReceipt.forEach(im => {
            if (item.receiptId == im.receiptId) {
              item.objName = im.objName
              item.feeTypeCd = im.feeTypeCd
            }
          })
        })
        this.printPayFeeInfo.fees = _feeReceiptDetails
      } catch (error) {
        console.error('Failed to load receipt detail:', error)
      }
    },
    async loadPrintSpec() {
      try {
        const params = {
          page: 1,
          row: 1,
          specCd: 2020,
          communityId: this.communityId
        }
        const { data } = await queryFeePrintSpec(params)
        if (data.length > 0) {
          this.printPayFeeInfo.content = data[0].content
          this.printPayFeeInfo.qrImg = data[0].qrImg
          if (data[0].printName) {
            this.printPayFeeInfo.communityName = data[0].printName
          }
        }
      } catch (error) {
        console.error('Failed to load print spec:', error)
      }
    },
    computeSumArea() {
      let _sum = 0.00
      this.printPayFeeInfo.fees.forEach(item => {
        if (item.area && this.isNumber(item.area)) {
          _sum += parseFloat(item.area)
        }
      })
      return _sum.toFixed(2)
    },
    isNumber(value) {
      return !isNaN(parseFloat(value)) && isFinite(value)
    },
    formatDate(date) {
      if (!date) return ''
      return dateFormat(date)
    },
    changeNumMoneyToChinese,
    printPurchaseApplyDiv() {
      this.printFlag = '1'
      document.getElementById("print-btn").style.display = "none"
      window.print()
      window.opener = null
      window.close()
    },
    closePage() {
      window.opener = null
      window.close()
    }
  }
}
</script>

<style scoped>
.print-pay-fee-container {
  padding: 20px;
}

.text-center {
  text-align: center;
}

.float-left {
  float: left;
}

.float-right {
  float: right;
}

.vc-table-border {
  border: 1px solid #000;
  border-collapse: collapse;
}

.vc-table-border th,
.vc-table-border td {
  border: 1px solid #000;
  padding: 5px;
}

#print-btn {
  text-align: right;
  margin-top: 20px;
}
</style>