<template>
  <div class="user-edit-container">
    <!-- 标题区域 -->
    <div class="header">
      <h2 class="title">修改用户信息</h2>
      <el-icon class="close-icon" @click="handleCancel" size="20">
        <Close />
      </el-icon>
    </div>

    <!-- 表单主体 -->
    <el-form 
      ref="editFormRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px"
      label-position="right"
      class="edit-form"
      status-icon
    >
      <!-- 用户号 -->
      <el-form-item label="用户号" prop="name">
        <el-input 
          v-model="form.name" 
      
          placeholder="请输入"
          class="form-input"
        />
      </el-form-item>
      
      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phone">
        <el-input 
          v-model="form.phone" 
          placeholder="请输入手机号" 
          class="form-input"
          maxlength="11"
          prefix-icon="Iphone"
        />
      </el-form-item>
      
      <!-- 时间信息 -->
      <div class="time-group">
        <!-- 创建时间 -->
        <el-form-item label="创建时间" prop="createTime">
          <el-input 
            v-model="form.createTime" 
            placeholder="-" 
            disabled
            class="time-input"
          />
        </el-form-item>
        
        <!-- 修改时间 -->
        <el-form-item label="修改时间" prop="updateTime">
          <el-input 
            v-model="form.updateTime" 
            placeholder="-" 
            disabled
            class="time-input"
          />
        </el-form-item>
      </div>
      
      <!-- 状态 -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status" class="status-radio">
          <el-radio :label="1" size="large">
            <span class="radio-label">正常</span>
          </el-radio>
          <el-radio :label="0" size="large">
            <span class="radio-label">停用</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 角色 -->
      <el-form-item label="用户权限" prop="role">
        <el-select 
          v-model="form.role" 
          placeholder="请选择权限"
          class="form-select"
          clearable
        >
          <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="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          placeholder="请输入备注信息"
          :rows="3"
          class="form-textarea"
          resize="none"
          show-word-limit
          maxlength="200"
        />
      </el-form-item>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button @click="handleCancel" class="cancel-btn">
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          class="submit-btn"
          :loading="submitting"
        >
          确认
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { dayjs, ElMessage, ElMessageBox } from 'element-plus';
import {staffUpdateInfoApi } from '../../../api/staff';

const props = defineProps(["rowData"]);
const emit = defineEmits(['closeEditDrawer', 'tableDataRefresh']);

watch(() => props.rowData, (newVal) => {
  if (newVal) {
    console.log('抽屉已打开，执行初始化代码');
    initFormData();
  }
});

// 组件状态
const editFormRef = ref(null);
const submitting = ref(false);

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

// 表单数据
const form = reactive({
  name: '',
  phone: '',
  status: 1,
  role: '',
  createTime: '',
  updateTime: '',
  remark: ''
});

// 表单验证规则
const rules = reactive({
    name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的11位手机号', 
      trigger: 'blur' 
    }
  ],
  role: [
    { required: true, message: '请选择用户权限', trigger: 'change' }
  ]
});

// 初始化表单数据
const initFormData = () => {
  if (!props.rowData) return;
  
  const { status, role, ...rest } = props.rowData;
  console.log(props.rowData,"8888888888888888888888");
  // 映射状态值
  Object.assign(form, {
    ...rest,
    status: status ? 1 : 0  ,
    role: role===0 ? 'admin' : 'operator'
  });
  console.log("645555555555",form)
};

// 提交表单
const handleSubmit = async () => {
  try {
    submitting.value = true;
    await editFormRef.value.validate();
    let { status, role,gender, id,phone,remark } = form;
    // 准备提交数据
    const submitData = {
      status, 
      role:role ==="operator" ? 1 : 0,
      gender,
      id,
      phone,
      remark 
    };
    
    // 模拟API请求
    console.log('提交数据:', submitData);
    staffUpdateInfoApi(submitData).then(res => {
      submitting.value = true;
      console.log(res,"--------898989---------------");
      if(res.code === 200){
        ElMessage.success('用户信息修改成功');
        emit('tableDataRefresh');
        emit('closeEditDrawer');
      }else{
        ElMessage.error(res.msg);
      }
    }).catch(err => {
      console.log(err);
      ElMessage.error('用户信息修改失败');
    })
    // await new Promise(resolve => setTimeout(resolve, 800));
    
    // ElMessage.success('用户信息修改成功');
    // emit('tableDataRefresh');
    emit('closeEditDrawer');
  } catch (error) {
    console.error('表单验证失败:', error);
   
  } finally {
    submitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消修改吗？未保存的内容将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }

    ).then(() => {
    console.log('取消修改');
    emit('closeEditDrawer');
  }).catch(() => {

  });
};

onMounted(() => {
  initFormData();
});
</script>

<style scoped lang="scss">
.user-edit-container {

  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
//   box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  
   // 标题栏样式
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    // padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .close-icon {
      cursor: pointer;
      color: #909399;
      transition: all 0.2s;
      padding: 4px;
      border-radius: 50%;

      &:hover {
        color: #f56c6c;
        background-color: #fef0f0;
      }
    }
  }
  
  .edit-form {
    max-width: 800px;
    margin: 0 auto;
    
    .form-input,
    .form-select,
    .time-input {
      width: 100%;
      max-width: 300px;
    }
    
    .time-group {
      display: flex;
      flex-wrap: wrap;
      gap: 0 20px;
      
      .el-form-item {
        flex: 1;
        min-width: 300px;
      }
    }
    
    .status-radio {
      display: flex;
      gap: 20px;
      
      .radio-label {
        margin-left: 6px;
      }
    }
    
    .form-textarea {
      width: 100%;
      max-width: 500px;
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
    
    .cancel-btn {
      width: 100px;
    }
    
    .submit-btn {
      width: 100px;
    }
  }
}

@media (max-width: 768px) {
  .user-edit-container {
    padding: 15px;
    
    .edit-form {
      .form-input,
      .form-select,
      .time-input {
        max-width: 100%;
      }
      
      .time-group {
        .el-form-item {
          min-width: 100%;
        }
      }
    }
  }
}
</style>