<template>
  <el-dialog :close-on-click-modal="false" append-to-body title="修改结算比例" :visible.sync="editProportionVisible" width="30%">
    <el-form :rules="rules" ref="formRef" :model="form" label-width="auto">
      <el-form-item label="结算比例" prop="settlementRatio">
        <el-input v-model="form.settlementRatio" placeholder="请填写结算比例"></el-input>
        <div style="font-size: 12px; color: #cccc;">范围：0 - 1</div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editProportionVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { updateShopParticipationRecordApi } from '@/api/business'

export default {
  data() {
    return {
      editProportionVisible: false,
      form: {
        shopParticipationRecordId: '',
        settlementRatio: ''
      },
      rules: {
        settlementRatio: [
          { required: true, message: '请填写商家结算比例', trigger: 'blur' },
          {
            validator: (_, value, cb) => {
              const num = value * 1
              if (typeof num !== 'number') {
                cb(new Error('结算比例是一个数字'))
              }
              if (num < 0 || num > 1) {
                cb(new Error('结算比例范围应该在0 - 1之间'))
              }
              cb()
            },
            trigger: 'blur'
          }
        ]
      },

      isLoading: false
    }
  },

  watch: {
    editProportionVisible: {
      handler(value) {
        !value && (this.form = { shopParticipationRecordId: '', settlementRatio: '' })
      }
    },

    immediate: true
  },

  methods: {
    handleOpen(row) {
      if (!row || !row.id) return this.$message.error('数据错误')
      this.form.shopParticipationRecordId = row.id
      this.form.settlementRatio = row.settlementRatio
      this.editProportionVisible = true
    },

    async handleConfirm() {
      try {
        this.isLoading = true
        await this.$refs.formRef.validate()
        await updateShopParticipationRecordApi(this.form)
        this.$message.success('修改成功')
        this.$emit('update', { ...this.form })
        this.editProportionVisible = false
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>
