<template>
  <div>
    <el-dialog :title="$t('batchPayConfirm.title')" :visible.sync="visible" width="600px" :before-close="handleClose">
      <el-form label-width="120px">
        <el-form-item :label="$t('batchPayConfirm.amount')">
          <span>{{ batchPayConfirmInfo.feePrices }} {{ $t('batchPayConfirm.yuan') }}</span>
        </el-form-item>
        <el-form-item :label="$t('batchPayConfirm.accountAmount')">
          <span>{{ batchPayConfirmInfo.accountAmount }} {{ $t('batchPayConfirm.yuan') }}</span>
        </el-form-item>
        <el-form-item :label="$t('batchPayConfirm.paymentMethod')">
          <el-select v-model="batchPayConfirmInfo.primeRate" style="width:100%"
            :placeholder="$t('batchPayConfirm.selectPaymentMethod')">
            <el-option v-for="item in filteredPrimeRates" :key="item.statusCd" :label="item.name"
              :value="item.statusCd"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="batchPayConfirmInfo.payType === 'qrCode'">
          <el-input v-model="batchPayConfirmInfo.authCode" :placeholder="$t('batchPayConfirm.scanCodeTip')"
            @keyup.enter.native="_qrCodePayFee"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.close') }}</el-button>
        <el-button type="primary" @click="_doPayFee" v-if="batchPayConfirmInfo.payType === 'common'">{{
          $t('batchPayConfirm.confirmPay') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="$t('batchPayConfirm.payResult')" :visible.sync="resultVisible" width="500px">
      <div class="result-content">
        <p>{{ $t('batchPayConfirm.paySuccess') }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="_back">{{ $t('common.back') }}</el-button>
        <el-button type="primary" @click="_printAndBack('ON')">{{ $t('batchPayConfirm.mergePrint') }}</el-button>
        <el-button type="primary" @click="_printAndBack('OFF')">{{ $t('batchPayConfirm.printReceipt') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCommunityId, getDict } from '@/api/community/communityApi'
import { payBatchFee, qrCodePayment, checkPayFinish, listFeePrintPage } from '@/api/fee/batchPayFeeOrderApi'

export default {
  name: 'BatchPayConfirm',
  data() {
    return {
      visible: false,
      resultVisible: false,
      batchPayConfirmInfo: {
        payType: '',
        fees: [],
        primeRate: '',
        primeRates: [],
        payerObjName: '',
        orderId: '',
        paymentPoolId: '',
        authCode: '',
        feePrices: '',
        detailIds: '',
        printUrl: '/#/pages/property/printPayFee',
        accountAmount: '',
        acctId: ''
      }
    }
  },
  computed: {
    filteredPrimeRates() {
      if (this.batchPayConfirmInfo.payType === 'qrCode') {
        return this.batchPayConfirmInfo.primeRates.filter(
          item => item.statusCd === '3' || item.statusCd === '4'
        )
      } else {
        return this.batchPayConfirmInfo.primeRates.filter(
          item => item.statusCd !== '5' && item.statusCd !== '6' && item.statusCd !== '8'
        )
      }
    }
  },
  created() {
    this._initDictData()
    this._listFeePrintPages()
  },
  methods: {
    async _initDictData() {
      try {
        const data = await getDict('pay_fee_detail', 'prime_rate')
        this.batchPayConfirmInfo.primeRates = data
      } catch (error) {
        console.error('获取字典数据失败:', error)
      }
    },

    async _listFeePrintPages() {
      try {
        const params = {
          page: 1,
          row: 1,
          state: 'T',
          communityId: getCommunityId()
        }
        const res = await listFeePrintPage(params)
        if (res.code === 0 && res.data && res.data.length > 0) {
          this.batchPayConfirmInfo.printUrl = res.data[0].url
        }
      } catch (error) {
        console.error('请求失败:', error)
      }
    },

    open(params) {
      this.batchPayConfirmInfo = {
        ...this.batchPayConfirmInfo,
        ...params
      }
      this.visible = true

      if (params.payType === 'qrCode') {
        this.$nextTick(() => {
          document.getElementById("authCode").focus()
        })
      }
    },

    handleClose() {
      this.visible = false
    },

    async _doPayFee() {
      if (!this.batchPayConfirmInfo.primeRate) {
        this.$message.warning(this.$t('batchPayConfirm.selectPaymentMethodTip'))
        return
      }

      const fees = this.batchPayConfirmInfo.fees.map(fee => ({
        ...fee,
        primeRate: this.batchPayConfirmInfo.primeRate
      }))

      try {
        const data = {
          communityId: getCommunityId(),
          fees,
          acctId: this.batchPayConfirmInfo.acctId,
          accountAmount: this.batchPayConfirmInfo.accountAmount
        }

        const res = await payBatchFee(data)
        if (res.code === 0) {
          this._doDealPayResult(res)
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.error('请求失败:', error)
        this.handleClose()
        this.$message.error('缴费失败')
      }
    },

    async _qrCodePayFee() {
      if (!this.batchPayConfirmInfo.primeRate) {
        this.$message.warning(this.$t('batchPayConfirm.selectPaymentMethodTip'))
        return
      }

      const fees = this.batchPayConfirmInfo.fees.map(fee => ({
        ...fee,
        primeRate: this.batchPayConfirmInfo.primeRate
      }))

      try {
        const data = {
          communityId: getCommunityId(),
          fees,
          acctId: this.batchPayConfirmInfo.acctId,
          accountAmount: this.batchPayConfirmInfo.accountAmount,
          authCode: this.batchPayConfirmInfo.authCode,
          receivedAmount: this.batchPayConfirmInfo.feePrices,
          payerObjName: this.batchPayConfirmInfo.payerObjName,
          subServiceCode: 'fee.payBatchFee'
        }

        const res = await qrCodePayment(data)
        if (res.code === 404) {
          this.$message.warning(res.msg)
          if (res.data && res.data.orderId) {
            this.batchPayConfirmInfo.orderId = res.data.orderId
            this.batchPayConfirmInfo.paymentPoolId = res.data.paymentPoolId
            setTimeout(() => this._qrCodeCheckPayFinish(), 5000)
          }
        } else if (res.code === 0) {
          this._doDealPayResult(res)
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.error('请求失败:', error)
        this.$message.error('扫码支付失败')
      }
    },

    async _qrCodeCheckPayFinish() {
      const fees = this.batchPayConfirmInfo.fees.map(fee => ({
        ...fee,
        primeRate: this.batchPayConfirmInfo.primeRate
      }))

      try {
        const data = {
          communityId: getCommunityId(),
          fees,
          acctId: this.batchPayConfirmInfo.acctId,
          accountAmount: this.batchPayConfirmInfo.accountAmount,
          authCode: this.batchPayConfirmInfo.authCode,
          receivedAmount: this.batchPayConfirmInfo.feePrices,
          subServiceCode: 'fee.payBatchFee',
          orderId: this.batchPayConfirmInfo.orderId,
          paymentPoolId: this.batchPayConfirmInfo.paymentPoolId
        }

        const res = await checkPayFinish(data)
        if (res.code === 404) {
          this.$message.warning(res.msg)
        } else if (res.code === 41) {
          setTimeout(() => this._qrCodeCheckPayFinish(), 5000)
        } else {
          this._doDealPayResult(res)
        }
      } catch (error) {
        console.error('请求失败:', error)
        this.$message.error('支付状态查询失败')
      }
    },

    _doDealPayResult(res) {
      this.handleClose()
      const detailIds = res.data.details.join(',')
      this.batchPayConfirmInfo.detailIds = detailIds

      setTimeout(() => {
        this.resultVisible = true
      }, 2000)
    },

    _printAndBack(merge) {
      this.resultVisible = false
      window.open(`${this.batchPayConfirmInfo.printUrl}?detailIds=${this.batchPayConfirmInfo.detailIds}&merge=${merge}`)
    },

    _back() {
      this.resultVisible = false
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
.result-content {
  text-align: center;
  font-size: 16px;
  padding: 20px;
}
</style>