<template>
  <div class="add-user-modal">
    <!-- 标题栏 -->
    <div class="modal-header">
      <h2 class="title">新增用户</h2>
      <el-icon class="close-icon" @click="handleClose" size="20">
        <Close />
      </el-icon>
    </div>

    <!-- 表单主体 -->
    <el-form 
      ref="addUserFormRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px" 
      label-position="left"
      class="add-user-form"
      status-icon
    >
      <!-- 用户账号 -->
      <el-form-item label="用户账号" prop="name" class="form-item">
        <el-input 
          v-model="form.name" 
          placeholder="请输入用户账号" 
          class="input-field"
          prefix-icon="User"
          clearable
        />
      </el-form-item>

      <!-- 用户密码 -->
      <el-form-item label="用户密码" prop="password" class="form-item">
        <el-input 
          v-model="form.password" 
          placeholder="请输入用户密码" 
          type="password" 
          class="input-field"
          prefix-icon="Lock"
          show-password
          clearable
        />
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phone" class="form-item">
        <el-input 
          v-model="form.phone" 
          placeholder="请输入手机号" 
          class="input-field"
          prefix-icon="Phone"
          maxlength="11"
          clearable
        />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="gender" class="form-item">
        <el-radio-group v-model="form.gender" class="radio-group">
          <el-radio :label="1" class="radio-btn" size="large">男</el-radio>
          <el-radio :label="2" class="radio-btn" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态" prop="status" class="form-item">
        <el-radio-group v-model="form.status" class="radio-group">
          <el-radio :label="0" class="radio-btn" size="large">正常</el-radio>
          <el-radio :label="1" class="radio-btn" size="large">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 角色 -->
      <el-form-item label="角色" prop="role" class="form-item">
        <el-select 
          v-model="form.role" 
          placeholder="请选择角色" 
          class="select-field"
          prefix-icon="UserFilled"
        >
          <el-option 
            v-for="item in roleOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 头像上传 -->
      <el-form-item label="头像上传" prop="avatar" class="form-item">
        <div class="avatar-uploader">
          <UpdataImg  @getAvatar="getAvatar" :updataImageCount="1" ref="avatarUploader"></UpdataImg>
        </div>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="remark" class="form-item">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          placeholder="请输入备注信息" 
          :rows="3" 
          class="textarea-field"
          show-word-limit
          maxlength="200"
        />
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <div class="modal-footer">
      <el-button @click="handleCancel" class="cancel-btn" size="default">取消</el-button>
      <el-button 
        @click="handleSubmit" 
        type="primary" 
        class="confirm-btn"
        size="default"
        :loading="submitting"
      >
        确认
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close, } from '@element-plus/icons-vue';
import UpdataImg from './updataImg.vue';
import  {staffAddInfoApi} from '../../../api/staff'
// 表单引用
const addUserFormRef = ref(null);
// 提交加载状态
const submitting = ref(false);
const avatarUploader = ref(null);
const emit = defineEmits(['closeAddDrawer','tableDataRefresh']);

// 角色选项数据
const roleOptions = ref([
  { label: '管理员', value: 0 },
  { label: '巡察员', value: 1 }
]);

// 表单数据
const form = reactive({
  name: '', // 用户账号
  password: '', // 用户密码
  phone: '', // 手机号
  gender: 1, // 性别：1-男，2-女
  status: 0, // 状态：0-正常，1-停用
  role: '', // 角色
  avatar: '', // 头像URL
  remark: '' // 备注
});

const getAvatar = (data) => {
    console.log("000000000000000000000")
    form.avatar = data;

}
// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入正确的汉字', trigger: 'blur' },
    { min: 2, max: 10, message: '账号长度在4-20个字符之间', trigger: 'blur' },
  
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '账号只能包含汉字', trigger: 'blur' }

  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度在6-30个字符之间', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码需包含字母和数字', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
});

// // 头像上传前验证
// const beforeAvatarUpload = (rawFile) => {
//   const isJpgOrPng = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
//   const isLt2M = rawFile.size / 1024 / 1024 < 2;

//   if (!isJpgOrPng) {
//     ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
//   }
//   if (!isLt2M) {
//     ElMessage.error('上传头像图片大小不能超过 2MB!');
//   }
  
//   return isJpgOrPng && isLt2M;
// };

// // 头像上传处理（自定义上传）
// const handleAvatarUpload = async (options) => {
//   try {
//     const formData = new FormData();
//     formData.append('file', options.file);
    
//     // 模拟上传请求
//     await new Promise(resolve => setTimeout(resolve, 1000));
    
//     // 模拟返回的头像URL
//     const avatarUrl = `https://example.com/avatars/${Date.now()}.jpg`;
//     form.avatar = avatarUrl;
//     options.onSuccess({ data: { url: avatarUrl } });
//   } catch (error) {
//     options.onError(error);
//     ElMessage.error('头像上传失败，请重试');
//   }
// };

// // 头像上传成功回调
// const handleAvatarSuccess = (response) => {
//   form.avatar = response.data.url;
//   ElMessage.success('头像上传成功');
// };

// 提交表单
const handleSubmit =  () => {
  try {
    submitting.value = true;
    // 准备提交数据
    const submitData = {
      ...form,
      avatar:form.avatar,
    };
    
    // console.log('提交新增用户数据:', submitData);
    // 模拟API请求
    console.log('提交新增用户数据:', submitData,form.avatar);
    
    
 
    staffAddInfoApi(submitData).then(res => { 
      console.log('用户新增成功', res);
      if (res.code === 200) {
         // 成功后关闭抽屉
        emit('closeAddDrawer');
        // 通知父组件刷新列表
        emit('tableDataRefresh');
        ElMessage.success('用户新增成功！');
        addUserFormRef.value.resetFields();
          //  avatarUploader.value.handleRemove(form.avatar[0])
      } 

    }).catch(err => {
        ElMessage.error('用户新增失败');
      });
 
    
  
    
   
  } catch (error) {
    console.error('表单验证失败:', error);
 
  } finally {
    submitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消新增吗？已填写内容将不保存', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',  
    type:'warning',
    center: true
  }).then(() => {
    addUserFormRef.value.resetFields();
    emit('closeAddDrawer');
  }).catch(() => {});
};

// 关闭弹窗
const handleClose = () => {
  // 通知父组件关闭弹窗
  // emit('close');
  addUserFormRef.value.resetFields();
  handleCancel()
};

onMounted(() => {
  console.log('新增组件已挂载');
});
</script>

<style scoped lang="scss">
.add-user-modal {
  width: 100%;
  max-width: 550px;
  padding: 24px;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 8px;


  // 标题栏样式
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
      color: #1f2937;
    }

    .close-icon {
      cursor: pointer;
      color: #6b7280;
      transition: all 0.2s;

      &:hover {
        color:#ef4444;
        background-color: #f8fafc;
        border-radius: 50%;
      }
    }
  }

  // 表单样式
  .add-user-form {
    .form-item {
      margin-bottom: 20px;
    }

    .input-field, .select-field {
      width: 100%;
      max-width: 320px;
      transition: all 0.2s;
      
      .el-input__prefix-inner {
        margin-right:.5rem;
      }
    }
    
    .textarea-field {
      width: 100%;
      max-width: 320px !important;
      resize: vertical;
    }

    // 单选框样式
    .radio-group {
      display: flex;
      gap: 24px;
      padding: 4px 0;

      .radio-btn {
        padding: 6px 16px !important;
        border-radius: 4px !important;
        transition: all 0.2s;
        
        & .el-radio__label {
          font-size: 14px;
        }
        
        &:hover:not(.is-checked) {
          background-color: #f5f5f5;
        }
      }
    }
    
    // 选中状态样式
    :deep(.el-radio.is-checked .el-radio__inner) {
      border-color: #4096ff;
      background-color: #4096ff;
    }
    
    :deep(.el-radio__input.is-checked + .el-radio__label) {
      color: #4096ff;
    }
  }

  // 头像上传样式
  .avatar-uploader {
    margin-bottom: 12px;
    
    .avatar-upload {
      width: 120px !important;
      height: 120px !important;
      border: 1px dashed #d1d5db;
      border-radius: 8px;
      cursor:pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;

      &:hover {
        border-color: #4096ff;
        background-color: #f0f9ff;
      }

      .avatar-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s;
        
        &:hover {
          transform: scale(1.02);
        }
      }

      .avatar-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #f9fafb;
        color: #6b7280;
        gap: 8px;

        .avatar-icon {
          font-size: 28px;
        }
        
        .upload-text {
          font-size: 14px;
        }
      }
    }
    
    .upload-tip {
      margin: 8px 0 0;
      font-size: 12px;
      color: #9ca3af;
      line-height: 1.5;
    }
  }

  // 底部按钮样式
  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;

    .cancel-btn, .confirm-btn {
      width: 110px;
      height: 40px;
      transition: all 0.2s;
      
      &:hover {
        transform: translateY(-1px);
      }
    }
    
    .confirm-btn {
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    }
  }

  // 响应式适配
  @media (max-width: 768px) {
    padding: 16px;
    max-width: 100%;

    .add-user-form {
      .input-field, .select-field, .textarea-field {
        max-width: 100% !important;
      }
      
      .radio-group {
        gap: 16px;
        flex-wrap: wrap;
      }
    }
    
    .modal-footer {
      justify-content: center;
      gap: 12px;
      margin-top: 24px;
    }
  }
}
</style>