<template>
    <el-card v-if="shouldShowDiscounts">
      <div slot="header" class="flex justify-between">
        <span>{{ $t('payFeeDiscount.discountInfo') }}</span>
      </div>

      <el-table :data="feeDiscounts" border style="width: 100%">
        <el-table-column align="center" width="60">
          <template slot-scope="scope">
            <el-checkbox v-model="selectDiscountIds" :label="scope.row.discountId"
              @change="computeFeeDiscount"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="discountType" align="center" :label="$t('payFeeDiscount.discountType')">
          <template slot-scope="scope">
            {{ getDiscountTypeName(scope.row.discountType) }}
          </template>
        </el-table-column>
        <el-table-column prop="discountName" align="center" :label="$t('payFeeDiscount.discountName')" />
        <el-table-column prop="ruleName" align="center" :label="$t('payFeeDiscount.ruleName')" />
        <el-table-column align="center" :label="$t('payFeeDiscount.rule')">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.feeDiscountSpecs" :key="index">
              {{ item.specName }}：{{ item.specValue }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('payFeeDiscount.discountAmount')">
          <template slot="header">
            <span>{{ $t('payFeeDiscount.discountAmount') }}</span>
            <el-tooltip effect="dark" :content="$t('payFeeDiscount.discountTooltip')" placement="top">
              <i class="el-icon-info" style="margin-left:5px"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            {{ formatDiscountPrice(scope.row) }}
            <span>{{ $t('payFeeDiscount.yuan') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'
import { dateAdd } from '@/utils/dateUtil'
import { computeFeeDiscount } from '@/api/fee/payFeeOrderApi'

export default {
  name: 'PayFeeDiscount',
  data() {
    return {
      dialogVisible: false,
      feeDiscounts: [],
      feeId: '',
      payerObjId: '',
      payerObjType: '',
      endTime: '',
      custEndTime: '',
      communityId: '',
      cycles: 1,
      selectDiscountIds: [],
      totalDiscountMoney: 0.0
    }
  },
  computed: {
    shouldShowDiscounts() {
      return (this.feeDiscounts.length > 0) ||
        (this.selectDiscountIds.length === 0 && this.feeDiscounts.length !== 0) ||
        (this.selectDiscountIds.length !== this.feeDiscounts.length && this.totalDiscountMoney === 0)
    }
  },
  methods: {
    open(params) {
      this.feeId = params.feeId
      this.payerObjId = params.payerObjId
      this.payerObjType = params.payerObjType
      this.endTime = params.endTime
      this.custEndTime = params.custEndTime
      this.cycles = params.cycles || 1
      this.listFeeDiscounts()
    },
    close() {
      this.dialogVisible = false
    },
    async listFeeDiscounts() {
      try {
        this.communityId = await getCommunityId()
        let cycles = this.cycles

        const params = {
          page: 1,
          row: 20,
          feeId: this.feeId,
          communityId: this.communityId,
          cycles,
          payerObjId: this.payerObjId,
          payerObjType: this.payerObjType,
          endTime: this.endTime,
          custEndTime: this.custEndTime ? dateAdd(this.custEndTime) : ''
        }

        const response = await computeFeeDiscount(params)
        this.feeDiscounts = response.data || []
        this.selectDiscountIds = this.feeDiscounts.map(item => item.discountId)
        this.computeFeeDiscount()
      } catch (error) {
        console.error('查询折扣信息失败:', error)
      }
    },
    getDiscountTypeName(type) {
      const types = {
        '1001': this.$t('payFeeDiscount.discount'),
        '2002': this.$t('payFeeDiscount.penalty'),
        '3003': this.$t('payFeeDiscount.specialDiscount')
      }
      return types[type] || type
    },
    formatDiscountPrice(row) {
      if (row.discountType === '1001' || row.discountType === '3003') {
        return row.discountPrice < 0 ? row.discountPrice : row.discountPrice * -1
      } else if (row.discountType === '2002') {
        return row.discountPrice > 0 ? row.discountPrice : row.discountPrice * -1
      }
      return row.discountPrice
    },
    computeFeeDiscount() {
      let totalDiscountMoney = 0.0
      let selectDiscount = []

      this.selectDiscountIds.forEach(item => {
        this.feeDiscounts.forEach(disItem => {
          if (disItem.feeDiscountSpecs && disItem.feeDiscountSpecs.length > 0) {
            let specValue = ""
            disItem.feeDiscountSpecs.forEach(feeItem => {
              if (feeItem.specName === this.$t('payFeeDiscount.monthSpec')) {
                specValue = feeItem.specValue
              }
            })
            if ((disItem.discountType === '1001' || disItem.discountType === '3003') &&
              parseFloat(this.cycles) < parseFloat(specValue)) {
              return
            }
          }

          if (item === disItem.discountId && disItem.discountPrice !== 0 && disItem.ruleId !== "102020008") {
            if (disItem.feeDiscountSpecs && disItem.feeDiscountSpecs.length > 0) {
              let specValue = ""
              disItem.feeDiscountSpecs.forEach(feeItem => {
                if (feeItem.specName === this.$t('payFeeDiscount.monthSpec')) {
                  specValue = feeItem.specValue
                }
              })
              if (specValue && parseFloat(this.cycles) >= parseFloat(specValue)) {
                totalDiscountMoney += parseFloat(disItem.discountPrice)
                selectDiscount.push(disItem)
              }

              specValue = ""
              disItem.feeDiscountSpecs.forEach(feeItem => {
                if (feeItem.specName === this.$t('payFeeDiscount.penaltySpec')) {
                  specValue = feeItem.specValue
                }
              })
              if (specValue) {
                totalDiscountMoney += parseFloat(disItem.discountPrice)
                selectDiscount.push(disItem)
              }
            }
          } else if (item === disItem.discountId && disItem.ruleId === "102020008") {
            if (disItem.feeDiscountSpecs != null && disItem.feeDiscountSpecs != undefined &&
              disItem.feeDiscountSpecs.length > 0) {
              let specValue = ""
              disItem.feeDiscountSpecs.forEach(feeItem => {
                if (feeItem.specName === this.$t('payFeeDiscount.monthSpec')) {
                  specValue = feeItem.specValue
                }
              })
              if (specValue !== "" && parseFloat(this.cycles) >= parseFloat(specValue)) {
                selectDiscount.push(disItem)
              }
            }
          }
        })
      })

      this.totalDiscountMoney = totalDiscountMoney
      this.$emit('changeDiscountPrice', {
        totalDiscountMoney,
        selectDiscount
      })
    },
    handleClose() {
      this.feeDiscounts = []
      this.selectDiscountIds = []
      this.totalDiscountMoney = 0.0
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
</style>