<template>
  <Dialog
    ref="dialog"
    :dialog-actions="{
      width,
      title,
    }"
    @confirm="handleConfirm"
    @cancel="handleCancel"
  >
    <template #content>
      <div class="confirm-content">
        <p v-if="message" class="tip-message">{{ message }}</p>
        <el-input
          v-model="inputValue"
          type="textarea"
          :rows="5"
          :placeholder="placeholder"
          :class="{ 'error-border': showError }"
          @input="handleInput"
        />
        <transition name="el-zoom-in-top">
          <p v-if="showError" class="error-msg">{{ errorMessage }}</p>
        </transition>
      </div>
    </template>
  </Dialog>
</template>

<script>
import Dialog from '@/components/Dialog/index.vue'

export default {
  name: 'InputConfirmDialog',
  components: { Dialog },
  props: {
    prop: {
      type: String,
      default: 'inputValue'
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '提示'
    },
    width: {
      type: String,
      default: '620px'
    },
    message: String,
    placeholder: {
      type: String,
      default: '请输入确认内容'
    },
    errorMessage: {
      type: String,
      default: '输入内容不能为空'
    },
    // 新增验证规则
    validate: {
      type: Function,
      default: (value) => value.trim().length > 0
    }
  },
  data() {
    return {
      inputValue: '',
      showError: false
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          val ? this.$refs.dialog.open() : this.$refs.dialog.close()
          if (!val) this.resetState()
        })
      }
    }
  },
  methods: {
    // 输入实时验证
    handleInput() {
      this.showError = !this.validate(this.inputValue)
    },

    // 确认处理
    handleConfirm() {
      if (!this.validate(this.inputValue)) {
        this.showError = true
        return
      }

      const result = { [this.prop]: this.inputValue }
      this.$emit('confirm', result)
      this.closeDialog()
    },

    // 关闭处理
    handleCancel() {
      this.$emit('cancel')
      this.closeDialog()
    },

    // 状态重置
    resetState() {
      this.inputValue = ''
      this.showError = false
    },

    // 统一关闭方法
    closeDialog() {
      this.resetState()
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
.confirm-content {
  padding: 12px 0;
}

.tip-message {
  color: #606266;
  margin-bottom: 12px;
  font-size: 14px;
}

.error-msg {
  color: #f56c6c;
  font-size: 12px;
  margin: 8px 0 0;
  transition: all 0.3s;
}

.error-border {
  :deep(.el-textarea__inner) {
    border-color: #f56c6c !important;
  }
}
</style>
