<template>
  <el-dialog :title="$t('common.add')" :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" required>
            <el-select v-model="form.feeTypeCd" @change="changeAddFeeTypeCd"
              :placeholder="$t('feeConfigManage.feeType')" 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" :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" :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-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" :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="saveFeeConfigInfo">{{ $t('common.save') }}</el-button>
    </div>
  </el-dialog>
</template>

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

export default {
  name: 'AddFeeConfig',
  data() {
    return {
      visible: false,
      form: {
        feeTypeCd: '',
        feeName: '',
        feeFlag: '',
        paymentCd: '1200',
        paymentCycle: '',
        prepaymentPeriod: '1',
        computingFormula: '',
        squarePrice: '',
        additionalAmount: '0.00',
        units: '元',
        deductFrom: 'Y',
        payOnline: 'Y',
        scale: '1',
        decimalPlace: '2',
        state: 'Y',
        computingFormulaText: '',
        startTime: '2025-01-01',
        endTime: '2050-01-01',
        billType: '002',
        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() {
      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'))
      }
    },

    changeAddFeeTypeCd() {
      const feeTypeCd = this.form.feeTypeCd

      // 水费、电费、煤气费
      if (['888800010015', '888800010016', '888800010009'].includes(feeTypeCd)) {
        this.form.feeFlag = '2006012'
        this.form.computingFormula = '5005'
        this.form.paymentCd = '2100'
      }

      // 押金
      if (feeTypeCd === '888800010006') {
        this.form.feeFlag = '2006012'
      }

      // 取暖费
      if (feeTypeCd === '888800010011') {
        this.form.feeFlag = '4012024'
        this.form.computingFormula = '3003'
      }

      // 物业费
      if (feeTypeCd === '888800010001') {
        this.form.feeFlag = '1003006'
        this.form.computingFormula = '1001'
      }

      // 租金
      if (feeTypeCd === '888800010018') {
        this.form.feeFlag = '1003006'
        this.form.computingFormula = '1101'
      }

      // 停车费
      if (feeTypeCd === '888800010008') {
        this.form.feeFlag = '1003006'
        this.form.computingFormula = '2002'
        this.form.paymentCycle = '1'
      }

      // 公摊费
      if (feeTypeCd === '888800010017') {
        this.form.feeFlag = '2006012'
        this.form.computingFormula = '4004'
        this.form.paymentCd = '2100'
      }
    },

    async saveFeeConfigInfo() {
      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 = '0'
        }

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

        // 调用API保存
       const {code,msg} = await saveFeeConfig(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 = {
        feeTypeCd: '',
        feeName: '',
        feeFlag: '',
        paymentCd: '1200',
        paymentCycle: '',
        prepaymentPeriod: '1',
        computingFormula: '',
        squarePrice: '',
        additionalAmount: '0.00',
        units: '元',
        deductFrom: 'Y',
        payOnline: 'Y',
        scale: '1',
        decimalPlace: '2',
        state: 'Y',
        startTime: '2025-01-01',
        endTime: '2050-01-01',
        billType: '002',
        computingFormulaText: '',
        communityId: this.getCommunityId()
      }
    },
  }
}
</script>

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