<template>
  <div>
    <el-dialog :title="title" :visible.sync="isOpen" width="600px" append-to-body @close="cancel"
               :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-position="top" :rules="rules" label-width="80px">
        <div style="width: 100%; height: 350px; display: flex;">
          <div v-if="!faceId" style="width: 45%; height: 100%; padding: 5px">
            <div class="upload-box" @click="triggerFileInput">
              <!-- 加号和文字 -->
              <div v-if="!form.imageUrl" style="display: flex; flex-direction: column; align-items: center;">
                <i class="el-icon-plus" style="font-size: 32px; color: #909399;"></i>
              </div>
              <!-- 图片预览 -->
              <img v-if="form.imageUrl" :src="form.imageUrl" alt="图片预览"
                   style="width: 100%; height: 100%; object-fit: contain;"
              />
              <!-- 隐藏的文件输入框 -->
              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                style="display: none;"
                @change="handleFileChange"
              />
            </div>
          </div>
          <div :style="{ width: faceId ? '100%' : '55%' }" style="height: 100%; padding: 5px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" maxlength="30" minlength="1" placeholder="请输入名称"/>
            </el-form-item>
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" maxlength="18" minlength="15" placeholder="请输入身份证号"/>
            </el-form-item>
            <el-form-item label="其他信息" prop="otherInfo">
              <el-input v-model="form.otherInfo" type="textarea" maxlength="1000"
                        show-word-limit placeholder="请输入内容"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getData, addData, updateData } from '@/api/face/faceData'

export default {
  props: {
    open: {
      type: Boolean,
      default: false,
      required: true
    },
    groupCode: {
      type: [String, null],
      default: ''  // 如果没有传递值，默认为 0
    },
    getList: {
      type: Function,
      required: true
    },
    title: {
      type: String,
      required: true
    },
    faceId: {
      type: [Number, null],
      default: 0  // 如果没有传递值，默认为 0
    }
  },
  computed: {
    isOpen: {
      get() {
        return this.open
      },
      set(value) {
        this.$emit('dialog-cancel') // 通知父组件
      }
    }
  },
  data() {
    return {
      // 表单参数
      form: {
        imageUrl: '' // 用于存储图片的预览路径
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' }
        ]
      },
      file: null  // 用于存储选中的文件
    }
  },
  watch: {
    isOpen(newVal, oldVal) {
      if (this.faceId && newVal) {
        getData(this.faceId).then(response => {
          this.form = response.data
        })
      }
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click() // 触发文件选择框
    },
    handleFileChange(event) {
      const file = event.target.files[0]
      if (file) {
        // 校验文件类型
        if (!file.type.startsWith('image/')) {
          this.$modal.msgError('请选择图片文件')
          return
        }
        // 校验文件大小（例如 2MB）
        if (file.size > 5 * 1024 * 1024) {
          this.$modal.msgError('图片大小不能超过 5MB')
          return
        }
        this.file = file // 保存文件到 data 中
        this.form.imageUrl = URL.createObjectURL(file) // 使用临时路径显示图片预览
      }
    },
    /** 提交按钮 */
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const formData = new FormData()
          // 添加表单数据
          formData.append('name', this.form.name)
          formData.append('idCard', this.form.idCard)
          formData.append('otherInfo', this.form.otherInfo)
          formData.append('groupCode', this.groupCode)

          // 根据是否是更新操作来调用不同的 API
          if (this.form.faceId != null) {
            formData.append('faceId', this.form.faceId)
            updateData(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.isOpen = false
              this.getList()
            })
          } else {
            // 添加图片文件
            if (this.file) {
              formData.append('file', this.file)
            } else {
              this.$modal.msgWarning('请选择图片')
              return
            }
            addData(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.isOpen = false
              this.getList()
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.isOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        imageUrl: '',
        name: null,
        idCard: null,
        description: null
      }
      this.$refs['form'].resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
.upload-box {
  width: 100%;
  height: 100%;
  border: 1px dashed #dfe4ed;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
  }
}
</style>
