<template>
  <div class="user-center-container">
    <!-- 头部操作按钮 -->
    <div class="header-actions">
      <el-button type="primary"
                 :icon="Edit"
                 @click="enableEdit"
                 v-show="!isEdit">
        编辑信息
      </el-button>
      <el-button type="success"
                 :icon="UploadFilled"
                 @click="submitForm"
                 v-show="isEdit && formModified">
        保存修改
      </el-button>
    </div>

    <!-- 用户信息表单 -->
    <el-form :model="userValue"
             :rules="rules"
             ref="formRef"
             label-width="100px"
             label-position="right"
             class="user-form">
      <el-form-item label="登录名" prop="username">
        <el-input v-model="userValue.username"
                  disabled="false"
                  placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="真实姓名" prop="realname">
        <el-input v-model="userValue.realname"
                  :disabled="!isEdit"
                  placeholder="请输入真实姓名" />
      </el-form-item>

<!--      <el-form-item label="所属公司" prop="comId">
        <el-select v-model="userValue.comId"
                   :disabled="!isEdit"
                   placeholder="请选择公司">
          <el-option v-for="company in companies"
                     :key="company.id"
                     :label="company.nameCn"
                     :value="company.id" />
        </el-select>
      </el-form-item>-->

<!--      <el-form-item label="职位" prop="position">
        <el-select v-model="userValue.position"
                   placeholder="请选择用户类型"
                   :disabled="!isEdit">
          <el-option v-for="item in positionList"
                     :key="item"
                     :label="item"
                     :value="item" />
        </el-select>
      </el-form-item>-->

      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="userValue.mobile"
                  :disabled="!isEdit"
                  placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userValue.email"
                  :disabled="!isEdit"
                  placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="微信号" prop="weixin">
        <el-input v-model="userValue.weixin"
                  :disabled="!isEdit"
                  placeholder="请输入微信号" />
      </el-form-item>

      <!-- 头像上传组件 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload class="avatar-uploader"
                   :disabled="!isEdit"
                   drag
                   accept="image/*"
                   :auto-upload="false"
                   :show-file-list="false"
                   :on-change="handleAvatarChange"
                   ref="avatarUploadRef">
          <div v-if="userValue.avatar" class="avatar-preview">
            <img :src="selectedFile ? avatarPreview : config.httpAds + userValue.avatar"
                 class="avatar-image" />
            <div v-show="isEdit" class="avatar-mask">
              <el-icon :size="23"><Edit /></el-icon>
              <div>点击更换头像</div>
            </div>
          </div>
          <template v-else>
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              拖拽图片到此 或 <em>点击上传</em>
            </div>
            <div class="el-upload__tip">
              支持JPG/PNG，大小不超过5MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, inject, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Delete, Edit, UploadFilled } from '@element-plus/icons-vue';

  const $http = inject('$http');
  const ajaxfile = inject('ajaxfile');
  const config = inject('config');

  // 初始状态定义
  const isEdit = ref(true);
  const formModified = ref(false);
  const formRef = ref(null);
  const avatarUploadRef = ref(null);
  const selectedFile = ref(null);
  const avatarPreview = ref('');
  const loading = ref(false);
  const companies = ref([]);
  const userValue = reactive({
    id: null,
    username: "",
    realname: "",
    comId: null,
    company: "",
    password: "",
    roleId: null,
    position: "",
    weixin: "",
    email: "",
    mobile: "",
    avatar: ""
  });
  // 监听表单变化
  watch(userValue, () => {
    formModified.value = true;
  }, { deep: true });

  // 启用编辑
  const enableEdit = () => {
    isEdit.value = true;
  };

  // 头像处理
  const handleAvatarChange = (file) => {
    selectedFile.value = file.raw;
    avatarPreview.value = URL.createObjectURL(file.raw);
  };
  // 验证规则
  const rules = reactive({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ],
    mobile: [
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ]
  });

  // 获取用户列表
  const getUser = async () => {
    try {
      loading.value = true;
      const rs = await $http.post('Company/GetComInfo', {
        IsAll: true,
        ID: 0,
      });
      if (rs.data.isok) {
        companies.value = rs.data.response;

        const rs1 = await $http.post('Users/GetUserInfo', {
          IsAll: false,
          ID: localStorage.getItem("uid"),
        });
        if (rs1.data.isok) {
          // 1. 创建公司映射表（提高查找效率）
          const companyMap = companies.value.reduce((map, company) => {
            map[company.id] = company.nameCn;
            return map;
          }, {});

          // 2. 处理用户数据
          Object.assign(userValue, rs1.data.response);
          userValue.company = companyMap[userValue.comId];

          console.log(userValue)
        } else {
          ElMessage.error(rs1.data.message);
        }
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败');
      console.error(error);
    } finally {
      loading.value = false;
    }
  };
  // 表单提交
  const submitForm = async () => {
    try {
      // 表单验证
      await formRef.value.validate();

      // 头像上传逻辑
/*      if (selectedFile.value) {
        let filedata = {
          File: selectedFile.value,
          Folder: "face"
        }
        const uploadRes = await ajaxfile(filedata);
        if (uploadRes?.fileName) {
          userValue.avatar = uploadRes.fileName;
        }
      }*/
       if (selectedFile.value) {
        const uploadRes = await ajaxfile(filedata);
        if (uploadRes?.fileName) {
          userValue.avatar = uploadRes.fileName; // 根据实际接口返回结构调整
        } else {
          ElMessage.error('头像上传失败: ' + uploadRes);
          return;
        }
      } else {
         userValue.avatar = userValue.avatar.substring(userValue.avatar.lastIndexOf('/') + 1);
      }
      // 更新用户信息
      const rs = await $http.post('Users/EditUser', userValue);
      if (rs.data.isok) {
        ElMessage.success('信息更新成功');
        isEdit.value = false;
        formModified.value = false;
        selectedFile.value = null;
        avatarUploadRef.value.clearFiles();
        await getUser(); // 刷新数据
      }
    } catch (error) {
      ElMessage.error('保存失败: ' + error.message);
    }
  };
   // 获取身份
  const positionList = ref([]);
  const getShengfen = () => {
    try {
      const rs = $http.post('ConfigPY/GetSingleValue', {
        VarName: "用户类型",
      }).then(rs => {
        //console.log(JSON.parse(rs.data.response));
        positionList.value = JSON.parse(rs.data.response)
      })
    } catch (error) {
      console.log(error);
    }
  };
  onMounted(() => {
    getUser()
    getShengfen()
  })


</script>

<style scoped>
  .user-center-container {
    padding: 20px;
    max-width: 444px;
    margin: 0;
  }

  .header-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;
  }

  .avatar-preview {
    position: relative;
    width: 178px;
    height: 178px;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

  /* 拖拽区域样式 */
  .avatar-uploader :deep(.el-upload-dragger) {
    width: 220px;
    height: 220px;
    padding: 20px;
    border-radius: 5%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
  }

  .avatar-uploader:hover :deep(.el-upload-dragger) {
    border-color: var(--el-color-primary);
  }

  /* 头像预览样式 */
  .avatar-preview {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
  }

  .avatar-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 5%;
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
  }

    .avatar-mask:hover {
      opacity: 1;
    }

  /* 图标和文字样式 */
  .el-icon--upload {
    font-size: 36px;
    color: var(--el-text-color-secondary);
    margin-bottom: 12px;
  }

  .el-upload__text {
    font-size: 14px;
    color: var(--el-text-color-regular);
    text-align: center;
  }

    .el-upload__text em {
      color: var(--el-color-primary);
      font-style: normal;
    }

  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 8px;
  }

</style>
