<template>
  <div class="batch-pay-fee-order-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="payer-object-card">
          <div class="card-title">收费对象</div>
          <div class="checkbox-list">
            <el-checkbox-group v-model="batchPayFeeOrderInfo.payerObjNames" @change="_chanagePayerObjName">
              <el-checkbox v-for="(item, index) in batchPayFeeOrderInfo.payObjs" :key="index" :label="item"
                class="checkbox-item">{{ item }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card>
          <div slot="header" class="flex justify-between">
            <span>{{ $t('batchPayFeeOrder.title') }}</span>
            <el-button type="primary" size="small" class="float-right" @click="_goBack">{{ $t('common.back')
            }}</el-button>
          </div>

          <el-table :data="batchPayFeeOrderInfo.batchFees" border style="width: 100%" v-loading="loading"
            @selection-change="handleSelectionChange" ref="batchFeeTable">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="feeTypeCdName" :label="$t('batchPayFeeOrder.feeType')"
              align="center"></el-table-column>
            <el-table-column prop="feeName" :label="$t('batchPayFeeOrder.feeItem')" align="center"></el-table-column>
            <el-table-column prop="feeFlagName" :label="$t('batchPayFeeOrder.feeFlag')"
              align="center"></el-table-column>
            <el-table-column :label="$t('batchPayFeeOrder.payerObj')" align="center">
              <template slot-scope="scope">
                {{ _getBatchPayFeeRoomName(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('batchPayFeeOrder.receivablePeriod')" align="center" width="180">
              <template slot-scope="scope">
                <div>{{ _getEndTime(scope.row) }}</div>
                <div>{{ _getDeadlineTime(scope.row) }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('batchPayFeeOrder.receivable')" align="center">
              <template slot-scope="scope">
                {{ scope.row.receivableAmount }}/{{ scope.row.amountOwed }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('batchPayFeeOrder.paymentCycle')" align="center" width="150">
              <template slot-scope="scope">
                <div v-if="scope.row.feeFlag != '2006012'">
                  <div v-if="scope.row.tempCycle == '-102'" class="cycle-text">周期：{{ scope.row.cycles }}个月</div>
                  <div v-else-if="scope.row.tempCycle == '-101'" class="custom-amount">
                    自定义金额<br>{{ scope.row.receivedAmount }}</div>
                  <div v-else-if="scope.row.tempCycle == '-103'" class="custom-end-time">
                    结束时间<br>{{ scope.row.custEndTime }}</div>
                  <el-select v-else v-model="scope.row.cycles" @change="_changeMonth(scope.row.cycles, scope.row)"
                    style="width:100%">
                    <el-option v-for="item in _getBatchPaymentCycles(scope.row)" :key="item"
                      :label="`${item}${$t('batchPayFeeOrder.month')}`" :value="item"></el-option>
                  </el-select>
                  <el-button type="text" icon="el-icon-setting" @click="_settingsFeeCycle(scope.row)"></el-button>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('batchPayFeeOrder.actualAmount')" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-if="scope.row.receivedAmountSwitch == '1'" v-model="scope.row.receivedAmount"
                  :placeholder="$t('batchPayFeeOrder.enterActualAmount')" @change="_doComputeTotalFee"></el-input>
                <span v-else>{{ scope.row.receivedAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('batchPayFeeOrder.remark')" align="center" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" :placeholder="$t('batchPayFeeOrder.enterRemark')"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <div class="margin-top">
          <pay-fee-user-account ref="payFeeUserAccount"
            @changeUserAmountPrice="changeUserAmountPrice"></pay-fee-user-account>
        </div>
        <pay-fee-deposit ref="payFeeDeposit"></pay-fee-deposit>

        <el-row class="footer-row text-left">
          <el-col :span="16">
            <div class="tips">
              <p>温馨提示：批量缴费不支持优惠折扣和优惠券抵扣功能，如需要请到缴费页面缴费</p>
              <p><b>缴费金额：缴费金额等于所有实收</b></p>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="total-amount">
              缴费金额：<span class="amount">{{ batchPayFeeOrderInfo.feePrices }}元</span>
            </div>
          </el-col>
          <el-col :span="4" class="text-right">
            <el-button type="success" size="medium" @click="_openPayFee('qrCode')">{{ $t('batchPayFeeOrder.scanPay')
            }}</el-button>
            <el-button type="primary" size="medium" @click="_openPayFee('common')">{{ $t('batchPayFeeOrder.submitPay')
            }}</el-button>
          </el-col>
        </el-row>

      </el-col>
    </el-row>

    <batch-pay-confirm ref="batchPayConfirm"></batch-pay-confirm>
    <batch-fee-cycle ref="batchFeeCycle" @changeMonth="batchChangeMonth"></batch-fee-cycle>
  </div>
</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'
import PayFeeUserAccount from '@/components/fee/payFeeUserAccount'
import PayFeeDeposit from '@/components/fee/payFeeDeposit'
import BatchPayConfirm from '@/components/fee/batchPayConfirm'
import BatchFeeCycle from '@/components/fee/batchFeeCycle'
import { listFee, listFeeObj } from '@/api/fee/batchPayFeeOrderApi'
import { dateFormat, dateAdd } from '@/utils/dateUtil'

export default {
  name: 'BatchPayFeeOrderList',
  components: {
    PayFeeUserAccount,
    PayFeeDeposit,
    BatchPayConfirm,
    BatchFeeCycle
  },
  data() {
    return {
      loading: false,
      batchPayFeeOrderInfo: {
        batchFees: [],
        allBatchFees: [],
        selectPayFeeIds: [],
        feePrices: 0.00,
        communityId: '',
        ownerId: '',
        payerObjType: '',
        remark: '',
        payerObjNames: [],
        payObjs: [],
        accountAmount: 0.0,
        acctId: ''
      }
    }
  },
  created() {
    this.communityId = getCommunityId()
    this._initData()
  },
  methods: {
    // 新增：处理表格选择变化
    handleSelectionChange(selection) {
      console.log('选中的行:', selection)

      // 更新 selectPayFeeIds 数组
      this.batchPayFeeOrderInfo.selectPayFeeIds = selection.map(item => item.feeId)

      console.log('更新后的 selectPayFeeIds:', this.batchPayFeeOrderInfo.selectPayFeeIds)

      // 重新计算总费用
      this._doComputeTotalFee()
    },

    // 新增：设置表格选中状态
    setTableSelection() {
      // 根据 selectPayFeeIds 设置表格的选中状态
      this.$nextTick(() => {
        if (this.$refs.batchFeeTable) {
          this.batchPayFeeOrderInfo.batchFees.forEach(row => {
            if (this.batchPayFeeOrderInfo.selectPayFeeIds.includes(row.feeId)) {
              this.$refs.batchFeeTable.toggleRowSelection(row, true)
            }
          })
        }
      })
    },

    async _initData() {
      const ownerId = this.$route.query.ownerId
      const payerObjType = this.$route.query.payerObjType

      if (!ownerId) {
        this.$message.error('非法操作')
        this.$router.go(-1)
        return
      }

      this.batchPayFeeOrderInfo.ownerId = ownerId
      this.batchPayFeeOrderInfo.payerObjType = payerObjType

      await this._loadBatchFees()

      setTimeout(() => {
        this.$refs.payFeeUserAccount.open({ ownerId: this.batchPayFeeOrderInfo.ownerId })
        this.$refs.payFeeDeposit.open({ payerObjId: this.batchPayFeeOrderInfo.ownerId, payerObjType: this.batchPayFeeOrderInfo.payerObjType })
      }, 1000)
    },

    async _loadBatchFees() {
      this.loading = true
      try {
        const params = {
          page: 1,
          row: 500,
          communityId: this.communityId,
          ownerId: this.batchPayFeeOrderInfo.ownerId,
          payerObjType: this.batchPayFeeOrderInfo.payerObjType,
          state: '2008001'
        }

        const res = await listFee(params)

        let _batchFees = []
        let _selectPayFeeIds = []

        res.fees.sort(this._batchRoomFeeCompare).forEach(feeItem => {
          _batchFees.push({
            ...feeItem,
            cycles: feeItem.paymentCycle,
            receivableAmount: feeItem.feeTotalPrice,
            receivedAmount: feeItem.feeTotalPrice,
            tempCycle: '-100'
          })
          _selectPayFeeIds.push(feeItem.feeId)
        })

        this.batchPayFeeOrderInfo = {
          ...this.batchPayFeeOrderInfo,
          allBatchFees: _batchFees,
          selectPayFeeIds: _selectPayFeeIds,
          batchFees: _batchFees
        }

        this._pushPayObjs()
        this._doComputeTotalFee()

        // 设置表格选中状态
        this.setTableSelection()
      } catch (error) {
        console.error('请求失败:', error)
      } finally {
        this.loading = false
      }
    },

    _batchRoomFeeCompare(a, b) {
      if (a.payerObjName < b.payerObjName) return -1
      if (a.payerObjName > b.payerObjName) return 1
      return 0
    },

    _pushPayObjs() {
      const _allBatchFees = this.batchPayFeeOrderInfo.allBatchFees
      const _payObjs = []
      const _payerObjNames = []

      _allBatchFees.forEach(fee => {
        if (!fee.feeAttrs) return

        let _payerObjName = ''
        fee.feeAttrs.forEach(item => {
          if (item.specCd === '390012') {
            _payerObjName = item.value
          }
        })

        if (_payerObjName && !this._hasPayObjsIn(_payerObjName, _payObjs)) {
          _payObjs.push(_payerObjName)
          _payerObjNames.push(_payerObjName)
        }
      })

      this.batchPayFeeOrderInfo.payObjs = _payObjs
      this.batchPayFeeOrderInfo.payerObjNames = _payerObjNames
    },

    _hasPayObjsIn(payerObjName, payObjs) {
      return payObjs.includes(payerObjName)
    },

    _hasPayObjNamesIn(payerObjName) {
      return this.batchPayFeeOrderInfo.payerObjNames.includes(payerObjName)
    },

    _chanagePayerObjName() {
      const _allBatchFees = this.batchPayFeeOrderInfo.allBatchFees
      const _batchFees = []

      _allBatchFees.forEach(fee => {
        let _payerObjName = ''
        if (fee.feeAttrs) {
          fee.feeAttrs.forEach(item => {
            if (item.specCd === '390012') {
              _payerObjName = item.value
            }
          })
        }

        if (_payerObjName && this._hasPayObjNamesIn(_payerObjName)) {
          _batchFees.push(fee)
        }
      })

      this.batchPayFeeOrderInfo.batchFees = _batchFees

      // 更新 selectPayFeeIds，只保留当前显示的费用ID
      const currentFeeIds = _batchFees.map(fee => fee.feeId)
      this.batchPayFeeOrderInfo.selectPayFeeIds = this.batchPayFeeOrderInfo.selectPayFeeIds.filter(id =>
        currentFeeIds.includes(id)
      )

      this._doComputeTotalFee()

      // 重新设置表格选中状态
      this.setTableSelection()
    },

    _openPayFee(payType) {
      if (this.batchPayFeeOrderInfo.selectPayFeeIds.length <= 0) {
        this.$message.warning('未选择费用')
        return
      }

      const _payerObjName = this.batchPayFeeOrderInfo.payerObjNames.join(',')
      const params = {
        fees: this._getPayFees(),
        payType: payType,
        feePrices: this.batchPayFeeOrderInfo.feePrices,
        payerObjName: _payerObjName,
        acctId: this.batchPayFeeOrderInfo.acctId,
        accountAmount: this.batchPayFeeOrderInfo.accountAmount
      }

      this.$refs.batchPayConfirm.open(params)
    },

    _getPayFees() {
      const _selectPayFeeIds = this.batchPayFeeOrderInfo.selectPayFeeIds
      const _batchFees = this.batchPayFeeOrderInfo.batchFees
      const _fees = []

      _selectPayFeeIds.forEach(id => {
        _batchFees.forEach(fee => {
          if (id === fee.feeId) {
            _fees.push(fee)
          }
        })
      })

      return _fees
    },

    _goBack() {
      this.$router.go(-1)
    },

    _getDeadlineTime(fee) {
      if (fee.amountOwed === 0 && fee.endTime === fee.deadlineTime) return "-"
      if (fee.state === '2009001') return "-"
      return dateFormat(fee.deadlineTime)
    },

    _getEndTime(fee) {
      if (fee.state === '2009001') return "-"
      return dateFormat(fee.endTime)
    },

    _getBatchPayFeeRoomName(fee) {
      if (!fee.feeAttrs) return ""

      let _feeName = ''
      fee.feeAttrs.forEach(item => {
        if (item.specCd === '390012') {
          _feeName = item.value
        }
      })

      return _feeName
    },

    _getBatchPaymentCycles(fee) {
      const paymentCycles = []
      for (let i = 1; i < 13; i++) {
        paymentCycles.push(i * parseFloat(fee.paymentCycle))
      }
      return paymentCycles
    },

    _doComputeTotalFee() {
      const _selectPayFeeIds = this.batchPayFeeOrderInfo.selectPayFeeIds
      const _batchFees = this.batchPayFeeOrderInfo.batchFees
      const _accountAmount = this.batchPayFeeOrderInfo.accountAmount

      let _totalFee = 0

      _selectPayFeeIds.forEach(id => {
        _batchFees.forEach(fee => {
          if (id === fee.feeId && fee.receivedAmount) {
            _totalFee += parseFloat(fee.receivedAmount)
          }
        })
      })

      if (_accountAmount) {
        _totalFee = _totalFee - parseFloat(_accountAmount)
      }

      this.batchPayFeeOrderInfo.feePrices = Math.max(0, _totalFee).toFixed(2)
    },

    async _changeMonth(cycles, fee) {
      if (!cycles) {
        cycles = fee.cycles
      }

      if (fee.tempCycle === '-101') {
        this._doComputeTotalFee()
        return
      }

      try {
        const params = {
          communityId: this.communityId,
          feeId: fee.feeId,
          page: 1,
          row: 1,
          cycle: cycles
        }

        if (fee.tempCycle === '-103') {
          params.custEndTime = dateAdd(fee.custEndTime)
        }

        const res = await listFeeObj(params)
        if (res.code === 0) {
          fee.receivableAmount = res.data.feeTotalPrice
          fee.receivedAmount = fee.receivableAmount
          this._doComputeTotalFee()
        }
      } catch (error) {
        console.error('请求失败:', error)
      }
    },

    _settingsFeeCycle(batchFee) {
      this.$refs.batchFeeCycle.open(batchFee)
    },

    changeUserAmountPrice(data) {
      this.batchPayFeeOrderInfo.accountAmount = data.totalUserAmount;
      if (data.selectAccount && data.selectAccount.length > 0) {
        data.selectAccount.forEach(_acct => {
          if (_acct.acctType == '2003') {
            this.batchPayFeeOrderInfo.acctId = _acct.acctId;
          }
        })
      }
      this._doComputeTotalFee();
    },
    batchChangeMonth(fee) {
      this._changeMonth(fee.cycle, fee)
    }
  }
}
</script>

<style lang="scss" scoped>
.batch-pay-fee-order-container {
  padding: 20px;

  .payer-object-card {
    height: 100%;

    .card-title {
      padding: 10px;
      font-weight: bold;
    }

    .checkbox-list {
      padding: 10px;

      .checkbox-item {
        display: block;
        margin: 5px 0;
      }
    }
  }

  .footer-row {
    margin-top: 20px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;

    .tips {
      color: #666;
      line-height: 1.6;
    }

    .total-amount {
      font-size: 16px;

      .amount {
        font-size: 30px;
        color: #f56c6c;
        margin-left: 5px;
      }
    }
  }

  .cycle-text,
  .custom-amount,
  .custom-end-time {
    line-height: 1.5;
    padding: 5px 0;
  }
}
</style>