<template>
  <div class="container">
    <!-- 用户列表 -->
    <!--    <div>
          <div><t-input label="搜索" placeholder="搜索格式：公司 用户名" @change="SearchUsers" /></div>

          <div>
            <t-dropdown-menu style="height:32px;border:none">
              <t-dropdown-item :options="product.options" :value="product.value" @change="databaseChanges" :disabled="disDbDrop" />
            </t-dropdown-menu>
          </div>
        </div>-->
    <div style="display: flex; align-items: center; gap: 10px">
      <!-- 输入框部分 - 自适应剩余宽度 -->
      <div style="flex: 1">
        <t-input label="搜索"
                 placeholder="公司 用户名"
                 clearable
                 @change="SearchUsers" />
      </div>

      <!-- 下拉菜单部分 - 固定宽度 -->
      <div style="width: 90px">
        <t-dropdown-menu style="height:32px; border:none; width:100%">
          <t-dropdown-item :options="product.options"
                           :value="product.value"
                           @change="databaseChanges" />
        </t-dropdown-menu>
      </div>
    </div>
    <t-list :async-loading="loading">
      <div v-for="user in nowUsers" :key="user.id" class="user-list-div" @click="openEditDialog(user)"
           style="position: relative; width: auto; padding: 5px; height: 55px; border-radius: 3px; margin: 2px;">
        <!-- 头像 -->
        <t-avatar class="avatar-example--small external-class-content" shape="circle" size="44px" style="margin-right: 10px;" @click.stop="openAvatarDialog(user)">{{ user.userName[0] + user.userName[1] }}</t-avatar>
        <!-- 主体 -->
        <span class="user-name" style="position: absolute; top: 3px; left: 55px; font-size: 12px; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">用户：<span style="font-size: 14px; font-weight: 500">{{ user.userName }}</span></span>
        <span class="user-company" style="position: absolute; bottom: 3px; left: 55px; font-size: 12px; ">公司:<span style="font-size:15px;font-weight:bold">{{ user.customerName }}</span></span>
        <!-- 操作 -->
        <span class="user-actions" style="position: absolute; bottom: 3px; right: 0px;">
          <t-button theme="danger"
                    @click.stop="openDelDialog(user)"
                    variant="outline"
                    :disabled="!((user.userName != 'MomoWen') && (user.userName != 'Admin'))"
                    size="extra-small">删除</t-button>
          <span>&nbsp;</span>
          <!--          <t-button theme="primary"
            @click="openEditDialog(user)"
            variant="outline"
            size="extra-small">修改</t-button>-->
        </span>
      </div>

    </t-list>
    <!-- 删除对话框 -->
    <t-dialog v-model:visible="isDelDialogVis"
              close-on-overlay-click
              content="操作不可逆，确认删除？"
              cancel-btn="取消"
              :confirm-btn="{ content: '确认删除', theme: 'danger' }"
              @confirm="isDelUser"
              @cancel="isDelUserCancel"
              @close="isDelUserCancel">
    </t-dialog>
    <!-- 编辑/新增对话框 -->
    <t-dialog v-model:visible="editDialogVisible"
              :header="currentUser.id ? '编辑用户' : '新增用户'"
              cancel-btn="取消"
              confirm-btn="保存"
              @confirm="handleSave">
      <t-form>
        <t-form-item label="用户名">
          <t-input v-model="currentUser.userName" :disabled="!!currentUser.id" />
        </t-form-item>
        <t-form-item label="所属公司">
          <!--<t-input v-model="currentUser.company" />-->
          <t-dropdown-menu>
            <t-dropdown-item :options="companies"
                             :value="currentUser.companyId"
                             zIndex="19999"
                             @change="currentUserComChange" />
          </t-dropdown-menu>
        </t-form-item>
        <t-form-item label="手机号">
          <t-input v-model="currentUser.mobile" />
        </t-form-item>
        <t-form-item label="微信号">
          <t-input v-model="currentUser.weiXin" />
        </t-form-item>
        <t-form-item label="Email">
          <t-input v-model="currentUser.email" />
        </t-form-item>

        <t-form-item label="权限管理">
          <div class="permission-group-btn">
            <t-button size="extra-small"
                      theme="primary"
                      variant="outline"
                      :disabled="!((currentUser.userName != 'MomoWen') && (currentUser.userName != 'Admin'))"
                      @click="permissionBtn('pages')">展开权限菜单</t-button>
          </div>

        </t-form-item>
        <t-checkbox :checked="currentUser.resetpsw"
                    :label="currentUser.id ? '重置密码' : '初始化密码'"
                    :disabled="currentUser.id ? false : true"
                    icon="rectangle"/>
      </t-form>
    </t-dialog>

    <!-- 页面权限弹出层 -->
    <t-popup v-model:visible="popupVisible.pages"
             placement="bottom"
             :style="{ height: '92%' }"
             header="权限设置">
      <!-- 数据库权限 -->
      <div style="padding:10px">
        <t-checkbox :block="false" v-model="allSelected" label="全选" @change="checkboxGroupChangeAll" />
        <t-checkbox-group class="box" borderless @change="checkboxGroupChange" v-model="selectedCheckboxes">
          <span v-for="(item, index) in dbOptions" :key="index">
            <t-checkbox :block="false" :value="item.label" :label="item.label" />
            <span>&nbsp;&nbsp;</span>
          </span>
        </t-checkbox-group>

      </div>
      <!-- 表权限 -->
      <div style="padding:10px">

      </div>

      <div class="popup-footer">
        <t-button theme="default" size="extra-small" @click="popupVisible.pages = false"> 取 消 </t-button>
        <div style="display: inline-block; width:10px"></div>
        <t-button theme="primary" size="extra-small" @click="handleFormConfirm">确 认</t-button>
      </div>
    </t-popup>


    <!-- 新增 悬浮按钮 -->
    <t-fab icon="+"
           draggable="true"
           style="font-size:25px"
           @click="openCreateDialog"
           class="fab-button" />
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, inject, computed } from 'vue';
  import { Toast } from 'tdesign-mobile-vue';
  import { ElTree } from 'element-plus'


  // 初始化加载数据
  onMounted(() => {
    loading.value = true;
    loadingUsers()
    loading.value = false;
  });
  // 用户数据
  const users = ref([]);
  const loading = ref(true);
  const tableData = reactive([]);

  // 对话框控制
  const editDialogVisible = ref(false);
  const currentUser = reactive({
    id: 0,
    userName: '',
    companyId: null,
    companyName: '',
    mobile: '',
    weiXin: '',
    email: '',
    resetpsw: true,
    permissions: []
  });
  const companies = ref([]);

  const $http = inject('$http')


  const dbNames = ref([])
  // 初始化用户列表
  const loadingUsers = () => {
    var formdata = {
      IsAll: true,
      ID: 0
    }

    // 调用API获取用户列表
    $http.post('Company/GetCompanyInfo', formdata)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          companies.value = rs.data.response
          product.options = [{ value: '全选', label: '全选' }]
          companies.value.forEach(item => {
            item.label = item.customerName
            item.value = item.id
            product.options.push({
              label: item.customerName,
              value: item.customerName
            })
          });
          //console.log(product)
          $http.post('Users/GetUserInfo', formdata)
            .then(rsu => {
              if (rsu.data.isok) {
                const companyMap = new Map(companies.value.map(company => [company.id, company.customerName]));
                users.value = rsu.data.response.sort((a, b) => {
                  const nameA = a.userName.toUpperCase(); // 转换为大写以进行不区分大小写的比较
                  const nameB = b.userName.toUpperCase(); // 转换为大写以进行不区分大小写的比较
                  if (nameA < nameB) {
                    return -1;
                  }
                  if (nameA > nameB) {
                    return 1;
                  }
                  // 如果userName相同，则保持原始顺序（稳定排序）
                  return 0;
                });
                //console.log(users.value)
                users.value.forEach(user => {
                  // 检查companyId是否存在于公司映射中
                  if (companyMap.has(user.companyId)) {
                    // 如果存在，将公司名称添加到用户对象中
                    user.customerName = companyMap.get(user.companyId);
                  }
                });


                if (search.value) {
                  SearchUsers(search.value)
                } else {
                  nowUsers.value = JSON.parse(JSON.stringify(users.value))
                }

              } else {
                Toast(rsu.data.message)
              }
            })
            .catch(error => {
              // 处理错误情况
              console.error(error);
            })

        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })
    let requestBody = {
      key: "getDbName",
      CmdType: "sys",
      DBQueryData: []
    }
    $http.post('DataHandle/R_InfoCommon', requestBody)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          dbNames.value = [];
          rs.data.response.forEach(item => {
            if (item.Database.slice(0, 3) == "uts" && item.Database != "uts_manage") {
              dbNames.value.push(item.Database)
              //console.log(dbNames.value)
            }
          })
        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })
  }

  const product = reactive({
    value: '全选',
    options: [
      {
        value: '全选',
        label: '全选'
      }
    ],
  })
  // 搜索
  const databaseChanges = (db) => {
    if (db == "全选") {
      SearchUsers("")
    } else {
      SearchUsers(db)
    }

  }
  const search = ref('')
  const nowUsers = ref([]);
  const SearchUsers = (s) => {
    search.value = s
    if (s) {
      //nowUsers.value = users.value.filter(user => user.userName.includes(s));
      const keywords = s.trim().split(/\s+/); // 按空格分割关键词
      nowUsers.value = users.value.filter(user =>
        keywords.every(key =>
          (user.userName || '').toLowerCase().includes(key.toLowerCase()) ||
          (user.customerName || '').toLowerCase().includes(key.toLowerCase())
        )
      );
    } else {
      nowUsers.value = JSON.parse(JSON.stringify(users.value))
    }
  }

  // 打开编辑公司对话框
  const currentUserComChange = (cid) => {
    //console.log(cid)
    const usc = companies.value.forEach(item => {
      if (cid == item.id) {
        // 将公司名称和id添加到用户对象中
        currentUser.companyId = item.id
        currentUser.companyName = item.companyName
      }
    })
  };
  // 打开编辑对话框
  const openEditDialog = (user) => {
    Object.assign(currentUser, user);
    currentUser.resetpsw = false;
    editDialogVisible.value = true;
  };

  // TODO 头像修改（未做）
  const openAvatarDialog = (user) => {
    //console.log(user)
  }

  const isDelDialogVis = ref(false)
  // 打开删除用户确认框
  const openDelDialog = (user) => {
    isDelDialogVis.value = true;
    Object.assign(currentUser, user);
  };
  // 取消删除
  const isDelUserCancel = () => {
    isDelDialogVis.value = false;
  }
  // 确认删除
  const isDelUser = () => {
    // TODO 删除用户API
    var us = {
      id: currentUser.id
    }
    $http.post('Users/DelUser', us)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          Toast({
            className: 'toast-root--success',
            theme: 'success',
            direction: 'column',
            message: '删除成功！',
          });
          loadingUsers()
        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })

  }

  // 打开新增对话框
  const openCreateDialog = () => {
    Object.assign(currentUser, {
      id: 0,
      userName: '',
      companyId: null,
      companyName: '',
      mobile: '',
      weiXin: '',
      email: '',
      resetpsw: true,
      permissions: []
    });
    editDialogVisible.value = true;
  };

  const selectedCheckboxes = ref([]);

  const allSelected = computed({
    get() {
      return selectedCheckboxes.value.includes('all');
    },
    set(isChecked) {
      if (isChecked) {
        selectedCheckboxes.value = ['all', ...dbOptions.value.map(opt => opt.label)];
      } else {
        selectedCheckboxes.value = [];
      }
    }
  });

  const checkboxGroupChange = (check) => {
    selectedCheckboxes.value = check;
    if (check.length === dbOptions.value.length && !check.includes('all')) {
      selectedCheckboxes.value = ['all', ...check];
    } else {
      selectedCheckboxes.value = check.filter(item => item !== 'all');
    }
  };

  const checkboxGroupChangeAll = (isChecked) => {
    allSelected.value = isChecked;
  };
  /*  const checkboxGroupChange = (check) => {
      const selected = new Set(check); // 使用Set便于判断存在性
      const hasAll = selected.has('all');
      const labels = dbOptions.value.map(opt => opt.label);
      const filtered = check.filter(item => item !== 'all');

      // 情况1：选中了"all"（可能单独或与其他一起）
      if (hasAll) {
        // 如果当前选中仅"all"，则全选
        if (check.length === 1) {
          selectedCheckboxes.value = [...labels, 'all'];
        }
        // 如果已全选且包含"all"，则维持
        else if (filtered.length === labels.length) {
          selectedCheckboxes.value = [...labels, 'all'];
        }
        // 如果选中了"all"但未全选，移除"all"
        else {
          selectedCheckboxes.value = filtered;
        }
        return;
      }

      // 情况2：未选中"all"，但勾选了全部选项
      if (filtered.length === labels.length) {
        selectedCheckboxes.value = [...labels, 'all']; // 自动补全"all"
      }
      // 情况3：正常选择
      else {
        selectedCheckboxes.value = filtered;
      }
    }*/
  // 保存处理
  const handleSave = () => {

    if (currentUser.id != 0) {
      let us = {
        Id: currentUser.id,
        UserName: currentUser.userName,
        CompanyId: currentUser.companyId,
        Mobile: currentUser.mobile,
        WeiXin: currentUser.weiXin,
        Email: currentUser.email,
        IsValid: true
      }
      // TODO: 调用更新用户API
      $http.post('Users/EditUser', us)
        .then(rs => {
          //console.log(rs)
          if (rs.data.isok) {

            if (currentUser.resetpsw == true) {
              handleResetPassword(currentUser)
            }
            Toast({
              className: 'toast-root--success',
              theme: 'success',
              direction: 'column',
              message: '修改成功！',
            });
          } else {
            Toast(rs.data.message)
          }
        })
        .catch(error => {
          // 处理错误情况
          console.error(error);
        })
        .finally(() => {
          loadingUsers()
        })

    } else {
      // TODO: 调用新增用户API
      let us = {
        Id: currentUser.id,
        UserName: currentUser.userName,
        CompanyId: currentUser.companyId,
        Mobile: currentUser.mobile,
        WeiXin: currentUser.weiXin,
        Email: currentUser.email
      }
      $http.post('Users/AddUser', us)
        .then(rs => {
          //console.log(rs)
          if (rs.data.isok) {

            Toast({
              className: 'toast-root--success',
              theme: 'success',
              direction: 'column',
              message: '新增成功！',
            });
          } else {
            Toast(rs.data.message)
          }
        })
        .catch(error => {
          // 处理错误情况
          console.error(error);
        })
        .finally(() => {
          loadingUsers()
        })
    }

  };

  // 重置密码
  const handleResetPassword = (user) => {
    // TODO: 调用重置密码API
    var us = {
      id: user.id
    }
    $http.post('Users/NewPassWord', us)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {


        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
  };

  // 弹出层控制
  const popupVisible = reactive({
    pages: false,
    model: false,
    db: false,
  });

  // 页面权限表单数据
  const formItems = ref([
    { label: '/home', isOpen: true },
    { label: '/user', isOpen: true },
    { label: '/usermanage', isOpen: true },
    { label: '/scopemanage', isOpen: true },
    /*    { label: '/', isOpen: true },
        { label: '/', isOpen: true },
        { label: '/', isOpen: true },*/
  ]);

  // 数据库权限多选数据
  const dbOptions = ref([]);


  // 按钮点击处理
  const permissionBtn = (type) => {
    switch (type) {
      case 'pages':
        // TODO: 这里可以添加初始化表单数据的接口调用
        dbOptions.value = []
        dbNames.value.forEach(db => {
          let dbv = { label: db, isOpen: false }
          dbOptions.value.push(dbv)
        })
        popupVisible.pages = true;
        break;
      case 'db':
        // TODO: 这里可以添加初始化多选数据的接口调用
        dbOptions.value = []
        dbNames.value.forEach(db => {
          let dbv = { label: db, isOpen: false }
          dbOptions.value.push(dbv)
        })
        popupVisible.db = true;
        break;
      case 'model':
        // TODO: 这里可以添加初始化多选数据的接口调用
        popupVisible.model = true;
        break;
      default:
        console.error('未知操作类型');
    }
  };
  // 全选或取消全选
  const isAllOpenPages = (tof) => {
    if (tof) {
      formItems.value.forEach(item => {
        item.isOpen = true;
      });
    } else {
      formItems.value.forEach(item => {
        item.isOpen = false;
      });
    }
  }
  // 全选或取消全选
  const isAllOpenDB = (tof) => {
    //console.log(tof)
    if (tof) {
      dbOptions.value.forEach(item => {
        item.isOpen = true;
      });
    } else {
      dbOptions.value.forEach(item => {
        item.isOpen = false;
      });
    }
  }
  // 表单确认处理
  const handleFormConfirm = () => {
    // TODO: 调用接口保存 formItems.value

    //console.log('提交表单数据:', formItems.value);
    popupVisible.pages = false;
  };

  // 机型权限确认处理
  const handleModelConfirm = () => {
    // TODO: 调用接口保存 selectedModels.value
    //console.log('选中机型:', selectedModels.value);
    popupVisible.model = false;
  };
  // 数据库权限确认处理
  const handleDBConfirm = () => {
    // TODO: 调用接口保存 selectedDBs.value
    //console.log('选中数据库:', selectedDBs.value);
    popupVisible.db = false;
  };


</script>

<style scoped>

  .container {
    padding: 10px;
  }

  .fab-button {
    position: fixed;
    bottom: 32px;
    right: 16px;
  }

  /*  .t-dialog__body {
      overflow-y: auto !important;
    }
  */

  .t-list {
    z-index: 0;
    position: relative;
  }

  .container {
    padding: 0;
  }

  /* 底部操作栏 */
  .popup-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px;
    display: block;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
  }

  /* 多选组样式 */
  /*.checkbox-group {
      padding: 16px;
      height: calc(100% - 60px);
      overflow-y: auto;
    }*/
  .t-dropdown-item {
    top: 145px !important
  }

  .user-list-div {
    border: 1px solid #E9E9E960;
    background-color: #80808030;
    transition: all 0.3s ease;
  }

    .user-list-div:hover {
      border-color: #409eff;
      background-color: #80808010;
      /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);  可选阴影 */
    }


  /* PC端样式 */
  @media (min-width: 768px) {
  }
</style>
