<template>
  <el-dialog
    :title="title"
    :visible="visible"
    width="30%"
    :before-close="handleClose"
    append-to-body
    @update:visible="val => $emit('update:visible', val)"
  >
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item :label="label" prop="value">
        <el-input v-model="form.value" :placeholder="'请输入' + label"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { updateOrder } from "@/api/system/Order"

export default {
  name: "EditInfo",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      required: true
    },
    label: {
      type: String,
      required: true
    },
    value: {
      type: String,
      default: ''
    },
    orderInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        value: ''
      }
    }
  },
  computed: {
    rules() {
      return {
        value: [
          { required: true, message: this.label + '不能为空', trigger: 'blur' },
          ...(this.label === '电话' ? [{
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }] : [])
        ]
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.form.value = this.value
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.orderInfo) {
            // 修改表格行数据
            const data = {
              id: this.orderInfo.id,
              [this.label === '姓名' ? 'name' : 'phone']: this.form.value
            }
            updateOrder(data).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.$emit('success', this.form.value)
              this.handleClose()
            })
          } else {
            // 修改查询条件
            this.$emit('success', this.form.value)
            this.handleClose()
          }
        }
      })
    },
    handleClose() {
      this.$refs.form.resetFields()
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style> 