<template>
  <el-dialog :title="$t('payFeeOrderResult.title')" :visible.sync="dialogVisible" width="40%" @close="handleClose"
    :close-on-click-modal="false">
    <div class="result-content">
      <p>{{ $t('payFeeOrderResult.success') }}</p>
      <p v-if="!receiptId">{{ $t('payFeeOrderResult.receiptTip') }}</p>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="back">{{ $t('payFeeOrderResult.back') }}</el-button>
      <el-button v-if="receiptId" type="primary" @click="printSmallAndBack">
        {{ $t('payFeeOrderResult.printSmall') }}
      </el-button>
      <el-button v-if="receiptId" type="primary" @click="printAndBack('ON')">
        {{ $t('payFeeOrderResult.mergePrint') }}
      </el-button>
      <el-button v-if="receiptId" type="primary" @click="printAndBack('OFF')">
        {{ $t('payFeeOrderResult.printReceipt') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'
import { listFeePrintPages, queryFeeReceipt } from '@/api/fee/payFeeOrderApi'

export default {
  name: 'PayFeeOrderResult',
  data() {
    return {
      dialogVisible: false,
      receiptId: '',
      printUrl: '/#/pages/property/printPayFee'
    }
  },
  created() {
    this.listFeePrintPages()
  },
  methods: {
    open(params) {
      if (!params) {
        this.dialogVisible = true
        return
      }
      this.queryPayFeeReceiptId(params)
    },
    close() {
      this.dialogVisible = false
    },
    async queryPayFeeReceiptId(params) {
      try {
        const communityId = await getCommunityId()
        const response = await queryFeeReceipt({
          detailIds: params.detailId,
          communityId,
          page: 1,
          row: 1
        })

        if (response.code === 0 && response.data && response.data.length > 0) {
          this.receiptId = response.data[0].receiptId
        }
        this.dialogVisible = true
      } catch (error) {
        console.error('查询收据ID失败:', error)
      }
    },
    async listFeePrintPages() {
      try {
        const communityId = getCommunityId()
        const response = await listFeePrintPages({
          page: 1,
          row: 1,
          state: 'T',
          communityId
        })

        if (response.data && response.data.length > 0) {
          this.printUrl = response.data[0].url
        }
      } catch (error) {
        console.error('获取打印页面失败:', error)
      }
    },
    printAndBack(merge) {
      window.open(`${this.printUrl}?receiptId=${this.receiptId}&merge=${merge}`)
    },
    printSmallAndBack() {
      window.open(`/#/pages/property/printSmallPayFee?receiptId=${this.receiptId}`)
    },
    back() {
      this.close()
      this.$router.go(-1)
    },
    handleClose() {
      this.receiptId = ''
    }
  }
}
</script>

<style scoped>
.result-content {
  text-align: center;
  padding: 20px;
}

.dialog-footer {
  text-align: center;
}
</style>