<template>
  <div v-if="visible" class="modal-overlay">
    <div class="modal-content" :style="{ width: computedWidth }">
      <div class="modal-header">
        <h2>{{ title }}</h2>
        <span style="color: white;cursor:pointer" @click="close">✖</span>
      </div>
      <div class="modal-body">
        <div class="modal-body-left">
          <input
            type="file"
            accept="image/jpeg,image/png"
            style="display: none"
            ref="fileInput"
            @change="handleFileChange"
          />
          <img
            v-if="imageUrl"
            :src="imageUrl"
            class="avatar"
            @click="selectFile"
            alt="Avatar"
          />
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
            @click="selectFile"
          ></i>
        </div>
        <div class="modal-body-right">
          <el-form ref="form" :model="form" :rules="rules">
            <el-form-item prop="name">
              <el-input v-model="form.name" placeholder="请输入人员姓名" size="small"/>
            </el-form-item>
            <el-form-item prop="idCardNumber">
              <el-input v-model="form.idCardNumber" placeholder="请输入人员身份证号" size="small"/>
            </el-form-item>
            <el-form-item prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio label="男" style="color: white"></el-radio>
                <el-radio label="女" style="color: white"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="modal-footer">
        <el-button type="primary" size="mini" plain @click="submitForm">确定</el-button>
        <el-button plain size="mini" @click="confirm">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {updateFace} from '@/api/updateFace/updateFace'
import midPic from "@/views/updateFace/midPic.vue";
import faceListShowPic from "@/views/updateFace/faceListShowPic.vue";

const validationRules = {
  name: [
    {required: true, message: '人员名称不能为空', trigger: 'blur'},
    {min: 2, max: 15, message: '用户名称长度必须介于 2 和 15 之间', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        const chineseNamePattern = /^[\u4e00-\u9fa5·]{2,15}$/
        if (!chineseNamePattern.test(value)) {
          callback(new Error('姓名只能包含中文字符'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  idCardNumber: [
    {required: true, message: '人员身份证号不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        const idCardPattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$/;
        if (!idCardPattern.test(value)) {
          callback(new Error('身份证号码格式不正确'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ]
};

export default {
  props: {
    title: {
      type: String,
      default: '弹窗标题'
    },
    value: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '400px' // 默认宽度
    }
  },
  data() {
    return {
      visible: this.value,
      imageUrl: '',
      form: {
        name: '',
        idCardNumber: '',
        sex: ''
      },
      rules: validationRules
    };
  },
  watch: {
    value(val) {
      this.visible = val;
      this.$emit('visible-change', val);
      if (val) {
        this.resetParameters(); // 每次打开时清除参数
      }
    }
  },
  computed: {
    computedWidth() {
      return this.width; // 返回传入的宽度
    }
  },
  methods: {
    resetParameters() {
      this.imageUrl = '';
      this.form = {
        name: '',
        idCardNumber: '',
        sex: ''
      };
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.file) {
            this.$message.error("请选择人脸照片")
            return
          }
          let formData = new FormData();
          formData.append('name', this.form.name);
          formData.append('idCardNumber', this.form.idCardNumber);
          formData.append('sex', this.form.sex)
          formData.append('file', this.form.file)
          updateFace(formData).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.close();
            } else {
              this.$message.error(res.msg)
            }
          })

        }
      });
    },
    close() {
      this.visible = false;
      faceListShowPic.methods.getList();
      this.$emit('input', this.visible);
    },
    confirm() {
      this.close();
    },
    selectFile() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const maxSizeInMB = 20; // 最大文件大小（单位：MB）
        const maxSizeInBytes = maxSizeInMB * 1024 * 1024;

        if (file.size > maxSizeInBytes) {
          this.$message.error(`文件大小不能超过 ${maxSizeInMB} MB`);
          return;
        }
        this.imageUrl = URL.createObjectURL(file);
        this.form.file = file;
      }
    }
  }
};
</script>

<style lang="scss">
.modal-overlay {
  z-index: 1000;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-image: url("../../assets/images/backimg.png");
  background-size: 100% 100%;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  height: 40px;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 20px;

  h2 {
    color: white;
  }
}

.modal-body {
  padding: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}

.modal-body-left {
  width: 178px;
  height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #8c939d;
}

.avatar-uploader-icon:hover {
  color: #0C70FA;
  border: 1px dashed #0C70FA;
}

.modal-body-right {
  padding: 10px;
  width: 50%;
}

.modal-footer {
  padding: 10px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
