<template>
  <el-dialog :title="$t('oweFeeCallable.write.title')" :visible.sync="dialogVisible" width="50%" @close="handleClose">
    <el-form :model="form" label-width="120px" ref="form">
      <el-form-item :label="$t('oweFeeCallable.write.roomName')" prop="roomName">
        <el-input v-model="form.roomName" disabled></el-input>
      </el-form-item>
      <el-form-item :label="$t('oweFeeCallable.write.feeName')" prop="feeIds">
        <el-checkbox-group v-model="form.feeIds">
          <el-checkbox v-for="fee in form.fees" :key="fee.feeId" :label="fee.feeId">
            {{ fee.feeName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="$t('oweFeeCallable.write.remark')" prop="remark">
        <el-input type="textarea" :rows="5" v-model="form.remark"
          :placeholder="$t('oweFeeCallable.write.remarkPlaceholder')">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('common.submit') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { listFee } from '@/api/fee/feeApi'
import { writeOweFeeCallable } from '@/api/fee/oweFeeCallableApi'
import { getCommunityId } from '@/api/community/communityApi'

export default {
  name: 'WriteOweFeeCallable',
  data() {
    return {
      dialogVisible: false,
      form: {
        roomId: '',
        roomName: '',
        fees: [],
        feeIds: [],
        remark: '',
        communityId: ''
      }
    }
  },
  methods: {
    open(data) {
      this.form = {
        roomId: data.roomId,
        roomName: data.roomName,
        fees: [],
        feeIds: [],
        remark: '',
        communityId: getCommunityId()
      }
      this.loadFees()
      this.dialogVisible = true
    },
    async loadFees() {
      try {
        const params = {
          communityId: this.form.communityId,
          payerObjId: this.form.roomId,
          state: '2008001',
          page: 1,
          row: 100
        }
        const response = await listFee(params)
        this.form.fees = response.data.fees || []
      } catch (error) {
        console.error('加载费用数据失败:', error)
      }
    },
    async handleSubmit() {
      try {
        await writeOweFeeCallable(this.form)
        this.$message.success(this.$t('oweFeeCallable.write.success'))
        this.dialogVisible = false
        this.$emit('success')
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error(error.message || this.$t('oweFeeCallable.write.error'))
      }
    },
    handleClose() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-checkbox {
  margin-right: 15px;
}
</style>