<template>
  <div class="user-management">
    <!-- 操作栏 -->
    <!--    <div class="header">
        <el-button type="primary" @click="handleAdd" :icon="Plus">添加用户</el-button>
      </div>-->
    <div class="header">
      <span style="margin-left: 20px;">
        用户类型：
        <el-switch v-model="userType"
                   active-value="wy"
                   inactive-value="platform"
                   active-text="威云用户"
                   inactive-text="平台用户"
                   style="--el-switch-on-color: #409eff; --el-switch-off-color: #409eff" />
      </span>
      <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
      <el-button type="primary" @click="handleAdd" :icon="Plus" v-if="userType === 'platform'">添加用户</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table :data="userType == 'platform' ? allUsers : wyUsers" border style="width: 100%" v-loading="loading" empty-text="暂无数据">
      <el-table-column label="操作" :width="userType == 'platform' ? 105 : 65">
        <template #default="{ row }">
          <el-button type="info" :icon="Edit" circle plain @click="handleEdit(row)" />
          <!--<el-button type="danger" :icon="Delete" circle plain @click="handleDelete(row)" />-->
          <el-button type="danger"
                     :icon="Delete"
                     circle plain
                     @click="handleDelete(row)"
                     v-show="row.id != 1 && row.id != 2"
                     v-if="userType == 'platform'" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="130" sortable show-overflow-tooltip />
      <el-table-column prop="realname" label="真实姓名" width="90" />
      <el-table-column prop="company" label="所属公司" width="90" />
      <el-table-column prop="position" label="用户类型" width="135" />
      <el-table-column prop="mobile" label="手机号" width="128" />
      <el-table-column prop="email" label="邮箱" width="150" show-overflow-tooltip />
      <el-table-column prop="weixin" label="微信号" width="120" show-overflow-tooltip />
      <el-table-column label="头像" width="65">
        <template #default="{ row }">
          <el-image v-if="row.avatar"
                    style="width: 32px; height: 32px;"
                    hide-on-click-modal="true"
                    :src="config.httpAds + row.avatar"
                    :preview-src-list="[ config.httpAds + row.avatar]"
                    fit="cover" />
          <span v-else>无</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible"
               :title="isEdit ? '编辑用户' : '添加用户'"
               width="600px">
      <el-form :model="form"
               :rules="rules"
               ref="formRef"
               label-width="100px"
               label-position="right">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="form.username"
                    :disabled="isEdit"
                    placeholder="用户名" />
        </el-form-item>

        <el-form-item label="登录密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password"
                    type="password"
                    show-password
                    placeholder="密码" />
        </el-form-item>

        <el-form-item label="修改密码" prop="password" v-if="isEdit && userType !== 'wy'">
          <el-input v-model="form.password"
                    type="password"
                    show-password
                    placeholder="密码（为空则不修改）" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="真实姓名" :disabled="userType == 'wy'" />
        </el-form-item>

        <el-form-item label="公司" prop="comId">
          <el-select v-model="form.comId" placeholder="公司">
            <el-option v-for="item in companies"
                       :key="item.id"
                       :label="item.nameCn"
                       :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="用户类型" prop="position">
          <el-select v-model="form.position" placeholder="用户类型">
            <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="form.mobile" placeholder="手机号" :disabled="userType == 'wy'" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="邮箱" :disabled="userType == 'wy'" />
        </el-form-item>

        <el-form-item label="微信号" prop="weixin">
          <el-input v-model="form.weixin" placeholder="微信号" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar" v-if="userType !== 'wy'">
          <el-upload class="avatar-uploader"
                     drag
                     accept="image/*"
                     :auto-upload="false"
                     :show-file-list="false"
                     :on-change="handleAvatarChange"
                     ref="avatarUploadRef">
            <!-- 头像预览区域 -->
            <div v-if="form.avatar" class="avatar-preview">
              <img v-if="!selectedFile" :src="config.httpAds + form.avatar" class="avatar-image" />
              <img v-else :src="form.avatar" class="avatar-image" />
              <div 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-item label="头像" prop="avatar" v-if="userType === 'wy'">
                  <img :src="form.avatar" class="avatar-image" />
                </el-form-item>-->

      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </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 allUsers = ref([]);
  const loading = ref(false);
  const companies = ref([]);

  const nowUser = localStorage.getItem('username');
  // 对话框相关
  const dialogVisible = ref(false);
  const isEdit = ref(false);
  const currentUserId = ref(null);
  const formRef = ref(null);

  const userType = ref('platform'); // 新增用户类型状态
  const wyUsers = ref([]); // 新增威云用户数据

  // 表单数据
  const defaultForm = {
    username: '',
    password: '',
    realname: '',
    mobile: '',
    email: '',
    weixin: '',
    avatar: ''
  };

  const form = reactive({ ...defaultForm });

  // 验证规则
  const rules = reactive({
    username: [
      { required: true, message: '用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' }
    ],
    password: [
      { message: '密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ],
    mobile: [
      { required: true, pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    email: [
      { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ],
    comId: [
      { required: true, message: '公司不可为空', trigger: 'blur' }
    ],
    position: [
      { required: true, message: '用户类型不可为空', trigger: 'blur' }
    ],
    realname: userType.value === 'wy' ? [] : [
      { required: true, message: '真实姓名', trigger: 'blur' }
    ],
  });

  /*// 获取用户列表
  const getUsers = 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: true,
          ID: 0,
        });
        //console.log(rs1.data.response);
        if (rs1.data.isok) {
          // 1. 创建公司映射表（提高查找效率）
          const companyMap = companies.value.reduce((map, company) => {
            map[company.id] = company.nameCn;
            return map;
          }, {});

          // 2. 处理用户数据
          allUsers.value = rs1.data.response.reduce((acc, user) => {
            if (user.username !== "WYSERVER") {
              acc.push({
                ...user,
                company: companyMap[user.comId] || '未知公司' // 处理找不到公司的情况
              });
            }
            return acc;
          }, []);


          // 3. 排序（在映射之后）
          allUsers.value.sort((a, b) => a.username.localeCompare(b.username));

        } else {
          ElMessage.error(rs1.data.message);
        }
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败');
      console.error(error);
    } finally {
      loading.value = false;
    }
  };*/

  // 获取身份
  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);
    }
  };

  // 新增代码：上传组件引用和文件状态
  const avatarUploadRef = ref(null);
  const selectedFile = ref(null);

  // 修改头像处理逻辑
  const handleAvatarChange = (uploadFile) => {
    const file = uploadFile.raw;
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 5;

    if (!isImage) {
      ElMessage.error('只能上传图片文件!');
      return false;
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过5MB!');
      return false;
    }

    // 预览本地文件
    const reader = new FileReader();
    reader.onload = (e) => {
      form.avatar = e.target.result;
    };
    reader.readAsDataURL(file);

    selectedFile.value = file;
    return false; // 阻止自动上传
  };

  // 修改后的提交逻辑
  const submitForm = async () => {

    await formRef.value.validate();
    try {
      // 如果有新选择的头像文件，先上传
      let filedata = {
        File: selectedFile.value,
        Folder: "face",
      }
      if (selectedFile.value) {
        const uploadRes = await ajaxfile(filedata);
        if (uploadRes?.fileName) {
          form.avatar = uploadRes.fileName; // 根据实际接口返回结构调整
        } else {
          ElMessage.error('头像上传失败: ' + uploadRes);
          return;
        }
      } else if (form.avatar) {
        form.avatar = form.avatar.substring(form.avatar.lastIndexOf('/') + 1);
      }
      var apiPrefix = '';

      if (isEdit.value) {
        apiPrefix = userType.value === 'wy' ? 'WyUsers/EditMyUser' : 'Users/EditUser';
      } else {
        apiPrefix = userType.value === 'wy' ? 'WyUsers/AddMyUser' : 'Users/AddUser';
      }
      // 提交用户数据
      const api = `${apiPrefix}`;
      // 提交用户数据
      const data = isEdit.value ? { ...form, id: currentUserId.value } : form;
      if (isEdit.value) data.id = currentUserId.value;
      const rs = await $http.post(api, data);
      if (rs.data.isok) {
        ElMessage.success(isEdit.value ? '修改成功' : '添加成功');
        // 重置状态
        selectedFile.value = null;
        avatarUploadRef.value?.clearFiles();
        await getUsers();
        dialogVisible.value = false;
      } else {
        ElMessage.error(rs.data.message);
      }
    } catch (error) {
      ElMessage.error('操作失败');
      console.error(error);
    }
  };

  // 修改打开对话框逻辑
  const handleAdd = () => {
    Object.assign(form, defaultForm);
    isEdit.value = false;
    selectedFile.value = null;
    avatarUploadRef.value?.clearFiles();
    dialogVisible.value = true;
  };

  const handleEdit = (row) => {
    Object.assign(form, row);
    isEdit.value = true;
    currentUserId.value = row.id;
    selectedFile.value = null;
    avatarUploadRef.value?.clearFiles();
    dialogVisible.value = true;
  };

  // 删除用户
  const handleDelete = (row) => {
    ElMessageBox.confirm('确定删除该用户吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const rs = await $http.post('Users/DelUser', { Id: row.id });
        if (rs.data.isok) {
          ElMessage.success('删除成功');
          await getUsers();
        } else {
          ElMessage.error(rs.data.message);
        }
      } catch (error) {
        ElMessage.error('删除失败');
        console.error(error);
      }
    }).catch(() => { });
  };

  // 头像上传处理
  const handleAvatarSuccess = (res) => {
    form.avatar = res.data.url;  // 根据实际接口返回调整
  };

  const beforeAvatarUpload = (file) => {
    const isImage = /^image\/(jpeg|png|gif)$/.test(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
      ElMessage.error('只能上传图片文件!');
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过2MB!');
    }
    return isImage && isLt2M;
  };



  watch(userType, (newVal) => {
    getUsers();
  });
  // 修改后的获取用户列表方法
  const getUsers = 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 apiPrefix = userType.value === 'wy' ? 'WyUsers' : 'Users';
        const rs1 = await $http.post(`${apiPrefix}/GetUserInfo`, {
          IsAll: true,
          ID: 0,
        });

        if (rs1.data.isok) {
          const processData = (data) => {
            const companyMap = companies.value.reduce((map, company) => {
              map[company.id] = company.nameCn;
              return map;
            }, {});

            return data.reduce((acc, user) => {
              if (user.username !== "WYSERVER") {
                acc.push({
                  ...user,
                  company: companyMap[user.comId] || '未知公司'
                });
              }
              return acc;
            }, []);
          };

          if (userType.value === 'wy') {
            wyUsers.value = processData(rs1.data.response);
          } else {
            allUsers.value = processData(rs1.data.response);
            allUsers.value.sort((a, b) => a.username.localeCompare(b.username));
          }
        }
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败');
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    getUsers();
    getShengfen()
  });
</script>

<style scoped>
  .user-management {
    padding: 12px;
  }

  .header {
    margin-bottom: 10px;
  }



  .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>
