<template>
  <el-dialog :title="$t('common.edit')" :visible.sync="visible" width="80%" @close="resetForm">
    <el-form :model="form" :rules="rules" label-width="150px" ref="form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('feeConfigManage.feeType')" prop="feeTypeCd" >
            <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" >
            <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" >
            <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" >
            <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" >
            <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" >
            <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" >
            <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" >
              <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" >
              <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" >
              <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: [],
      rules: {
        feeTypeCd: [{ required: true, message: this.$t('feeConfigManage.feeType'), trigger: 'change' }],
        feeName: [{ required: true, message: this.$t('feeConfigManage.enterFeeItem'), trigger: 'blur' }],
        feeFlag: [{ required: true, message: this.$t('feeConfigManage.selectFeeFlag'), trigger: 'change' }],
        paymentCd: [{ required: true, message: this.$t('feeConfigManage.selectPaymentType'), trigger: 'change' }],
        paymentCycle: [{ required: true, message: this.$t('feeConfigManage.enterPaymentCycle'), trigger: 'blur' }],
        prepaymentPeriod: [{ required: true, message: this.$t('feeConfigManage.enterPrepaymentPeriod'), trigger: 'blur' }],
        units: [{ required: true, message: this.$t('feeConfigManage.enterUnit'), trigger: 'blur' }],
        computingFormula: [{ required: true, message: this.$t('feeConfigManage.selectFormula'), trigger: 'change' }],
        computingFormulaText: [{ required: true, message: this.$t('feeConfigManage.enterFormula'), trigger: 'blur' }]
      }
    }
  },
  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更新
      const {code,msg} = await updateFeeConfig(this.form)
      if(code != 0){
        this.$message.error(msg)
        return
      }

        this.$message.success(this.$t('common.operationSuccess'))
        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>