<template>
  <el-dialog :title="$t('common.edit')" :visible.sync="visible" width="80%" @close="resetForm">
    <el-form :model="form" label-width="150px" ref="form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.feeType')" prop="feeTypeCd" required>
            <el-select 
              v-model="form.feeTypeCd" 
              :disabled="form.isDefault === 'T'"
              :placeholder="$t('feeConfigManage.selectFeeType')"
              class="full-width-select"
            >
              <el-option v-for="item in feeTypeCds" :key="item.statusCd" :label="item.name" :value="item.statusCd" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.feeItem')" prop="feeName" required>
            <el-input v-model="form.feeName" :disabled="form.isDefault === 'T'"
              :placeholder="$t('feeConfigManage.enterFeeItem')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.feeFlag')" prop="feeFlag" required>
            <el-select 
              v-model="form.feeFlag" 
              :disabled="form.isDefault === 'T'"
              :placeholder="$t('feeConfigManage.selectFeeFlag')"
              class="full-width-select"
            >
              <el-option v-for="item in feeFlags" :key="item.statusCd" :label="item.name" :value="item.statusCd" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.paymentType')" prop="paymentCd" required>
            <el-select 
              v-model="form.paymentCd" 
              :placeholder="$t('feeConfigManage.selectPaymentType')"
              class="full-width-select"
            >
              <el-option v-for="item in paymentCds" :key="item.statusCd" :label="item.name" :value="item.statusCd" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.feeFlag != '2006012'">
          <el-form-item :label="$t('feeConfigManage.paymentCycle')" prop="paymentCycle" required>
            <el-input v-model="form.paymentCycle" :placeholder="$t('feeConfigManage.enterPaymentCycle')" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.paymentCd == '1200'">
          <el-form-item :label="$t('feeConfigManage.prepaymentPeriod')" prop="prepaymentPeriod" required>
            <el-input v-model="form.prepaymentPeriod" :placeholder="$t('feeConfigManage.enterPrepaymentPeriod')" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.unit')" prop="units" required>
            <el-input v-model="form.units" :placeholder="$t('feeConfigManage.enterUnit')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.accountDeduction')" prop="deductFrom">
            <el-select v-model="form.deductFrom" class="full-width-select">
              <el-option :label="$t('common.yes')" value="Y" />
              <el-option :label="$t('common.no')" value="N" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.mobilePayment')" prop="payOnline">
            <el-select v-model="form.payOnline" class="full-width-select">
              <el-option :label="$t('common.yes')" value="Y" />
              <el-option :label="$t('common.no')" value="N" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.roundingMethod')" prop="scale">
            <el-select v-model="form.scale" class="full-width-select">
              <el-option :label="$t('feeConfigManage.roundHalfUp')" value="1" />
              <el-option :label="$t('feeConfigManage.roundUp')" value="3" />
              <el-option :label="$t('feeConfigManage.roundDown')" value="4" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.decimalPlaces')" prop="decimalPlace">
            <el-select v-model="form.decimalPlace" class="full-width-select">
              <el-option :label="$t('feeConfigManage.integer')" value="0" />
              <el-option :label="$t('feeConfigManage.oneDecimal')" value="1" />
              <el-option :label="$t('feeConfigManage.twoDecimal')" value="2" />
              <el-option :label="$t('feeConfigManage.threeDecimal')" value="3" />
              <el-option :label="$t('feeConfigManage.fourDecimal')" value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('common.status')" prop="state">
            <el-select v-model="form.state" class="full-width-select">
              <el-option :label="$t('common.enabled')" value="Y" />
              <el-option :label="$t('common.disabled')" value="N" />
              <el-option :label="$t('feeConfigManage.disabledAndEndFee')" value="NA" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="$t('feeConfigManage.formula')" prop="computingFormula" required>
            <el-select 
              v-model="form.computingFormula" 
              :disabled="form.isDefault === 'T'"
              :placeholder="$t('feeConfigManage.selectFormula')"
              class="full-width-select"
            >
              <el-option v-for="item in computingFormulas" :key="item.statusCd" :label="item.name" :value="item.statusCd" />
            </el-select>
          </el-form-item>
        </el-col>

        <template v-if="shouldShowUnitPrice">
          <el-col :span="24">
            <el-form-item :label="$t('feeConfigManage.unitPrice')" prop="squarePrice" required>
              <el-input v-model="form.squarePrice" :placeholder="$t('feeConfigManage.enterUnitPrice')" />
            </el-form-item>
          </el-col>
        </template>

        <template v-if="shouldShowAdditionalAmount">
          <el-col :span="24">
            <el-form-item :label="additionalAmountLabel" prop="additionalAmount" required>
              <el-input v-model="form.additionalAmount" :placeholder="$t('feeConfigManage.enterAdditionalFee')" />
            </el-form-item>
          </el-col>
        </template>

        <template v-if="form.computingFormula == '7007'">
          <el-col :span="24">
            <el-form-item :label="$t('feeConfigManage.formula')" prop="computingFormulaText" required>
              <el-input type="textarea" v-model="form.computingFormulaText"
                :placeholder="$t('feeConfigManage.enterFormula')" :rows="4" />
            </el-form-item>
          </el-col>
          <el-col :span="24" class="text-left">
            <el-form-item :label="$t('common.explanation')">
              <div>C {{ $t('feeConfigManage.explanationC') }}</div>
              <div>F {{ $t('feeConfigManage.explanationF') }}</div>
              <div>U {{ $t('feeConfigManage.explanationU') }}</div>
              <div>R {{ $t('feeConfigManage.explanationR') }}</div>
              <div>X {{ $t('feeConfigManage.explanationX') }}</div>
              <div>L {{ $t('feeConfigManage.explanationL') }}</div>
              <div>{{ $t('feeConfigManage.example1') }}</div>
              <div>{{ $t('feeConfigManage.example2') }}</div>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>

    <div slot="footer">
      <el-button @click="visible = false">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="editFeeConfig">{{ $t('common.save') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateFeeConfig } from '@/api/fee/feeConfigManageApi'
import { getDict } from '@/api/community/communityApi'

export default {
  name: 'EditFeeConfig',
  data() {
    return {
      visible: false,
      form: {
        configId: '',
        feeTypeCd: '',
        feeName: '',
        feeFlag: '',
        startTime: '',
        endTime: '',
        computingFormula: '',
        squarePrice: '',
        additionalAmount: '0.00',
        isDefault: '',
        paymentCycle: '',
        paymentCd: '',
        computingFormulaText: '',
        deductFrom: '',
        payOnline: 'Y',
        scale: '1',
        decimalPlace: '2',
        units: '元',
        prepaymentPeriod: '1',
        state: 'Y',
        communityId: this.getCommunityId()
      },
      feeTypeCds: [],
      computingFormulas: [],
      feeFlags: [],
      paymentCds: []
    }
  },
  computed: {
    shouldShowUnitPrice() {
      return !['2002', '7007', '8008', '1101', '1102', '4004', '9009'].includes(this.form.computingFormula)
    },
    shouldShowAdditionalAmount() {
      return !['7007', '8008', '1101', '1102', '4004', '9009'].includes(this.form.computingFormula)
    },
    additionalAmountLabel() {
      return this.form.computingFormula == '1001'
        ? this.$t('feeConfigManage.additionalFee')
        : this.$t('feeConfigManage.fixedFee')
    }
  },
  created() {
    this.loadDicts()
  },
  methods: {
    open(feeConfig) {
      this.form = { ...feeConfig }
      this.visible = true
    },

    async loadDicts() {
      try {
        const [feeTypeCds, computingFormulas, feeFlags, paymentCds] = await Promise.all([
          getDict('pay_fee_config', 'fee_type_cd'),
          getDict('pay_fee_config', 'computing_formula'),
          getDict('pay_fee_config', 'fee_flag'),
          getDict('pay_fee_config', 'payment_cd')
        ])
        
        this.feeTypeCds = feeTypeCds
        this.computingFormulas = computingFormulas
        this.feeFlags = feeFlags
        this.paymentCds = paymentCds
      } catch (error) {
        console.error('Failed to load dictionaries:', error)
        this.$message.error(this.$t('common.loadFailed'))
      }
    },

    async editFeeConfig() {
      try {
        // 处理特殊公式
        if (this.form.computingFormula === '2002') {
          this.form.squarePrice = "0.00"
        }

        if (['7007', '8008', '1101', '1102', '4004', '9009'].includes(this.form.computingFormula)) {
          this.form.squarePrice = "0.00"
          this.form.additionalAmount = "0.00"
        }

        if (this.form.feeFlag === '2006012') {
          this.form.paymentCycle = '1'
        }

        if (this.form.paymentCd === '1200' && !this.form.prepaymentPeriod) {
          throw new Error(this.$t('feeConfigManage.prepaymentPeriodRequired'))
        }

        if (this.form.paymentCd !== '1200') {
          this.form.prepaymentPeriod = '0'
        }

        // 表单验证
        await this.$refs.form.validate()
        this.form.communityId = this.getCommunityId()

        // 调用API更新
        await updateFeeConfig(this.form)

        this.$message.success(this.$t('common.saveSuccess'))
        this.visible = false
        this.$emit('success')
      } catch (error) {
        this.$message.error(error.message || this.$t('common.saveFail'))
      }
    },

    resetForm() {
      this.$refs.form.resetFields()
      this.form = {
        configId: '',
        feeTypeCd: '',
        feeName: '',
        feeFlag: '',
        startTime: '',
        endTime: '',
        computingFormula: '',
        squarePrice: '',
        additionalAmount: '0.00',
        isDefault: '',
        paymentCycle: '',
        paymentCd: '',
        computingFormulaText: '',
        deductFrom: '',
        payOnline: 'Y',
        scale: '1',
        decimalPlace: '2',
        units: '元',
        prepaymentPeriod: '1',
        state: 'Y',
        communityId: this.getCommunityId()
      }
    },

 
  }
}
</script>

<style scoped>
.full-width-select {
  width: 100%;
}
</style>