<template>
  <div>
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-button
                type="info"
                plain
                icon="Upload"
                @click="handleImportTenantMenuList"
                style="margin-bottom: 20px"
                >导入</el-button
              >
            </div>
            <div class="head-container">
              <el-input
                v-model="deptTreeParams.deptName"
                placeholder="请输入部门名称"
                clearable
                prefix-icon="Search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="deptOptions"
                :props="{ label: 'deptName', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                node-key="deptBizId"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
            >
              <el-form-item label="账号" prop="userName">
                <el-input
                  v-model="queryParams.userName"
                  placeholder="请输入账号"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile">
                <el-input
                  v-model="queryParams.mobile"
                  placeholder="请输入手机号码"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="info" plain icon="Upload" @click="handleImportTenantUserList"
                  >导入</el-button
                >
              </el-form-item>
            </el-form>

            <el-table
              v-loading="loading"
              :data="userList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="账号" align="center" key="userName" prop="userName" />
              <el-table-column
                label="真实姓名"
                align="center"
                key="realName"
                prop="realName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="用户昵称"
                align="center"
                key="nickName"
                prop="nickName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="手机号码"
                align="center"
                key="mobile"
                prop="mobile"
                width="120"
              />
              <el-table-column prop="gender" label="性别">
                <template #default="scope">
                  <dict-tag :options="sys_gender" :value="scope.row.gender" />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="150"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNo"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 部门导入（根据权限从部门池导入进来） -->
    <el-dialog
      :title="importMenuTitle"
      v-model="importTenantMenuListOpen"
      width="500px"
      append-to-body
    >
      <!-- 权限分配区域 -->
      <div class="permission-section">
        <el-tree
          ref="treeRef"
          :data="menuTree"
          :props="defaultProps"
          node-key="deptBizId"
          show-checkbox
          highlight-current
          :check-strictly="isCheckStrictly"
          :expand-on-click-node="false"
          class="permission-tree"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ data.deptName }}</span>
            </span>
          </template>
        </el-tree>

        <div class="tree-actions mt-4">
          <el-button type="primary" @click="saveImportSelectedMenuList">确定</el-button>
        </div>
        <!-- <el-card :header="importMenuTitle" class="mt-4">

        </el-card> -->
      </div>
    </el-dialog>
    <!-- 用户导入（根据权限从用户池导入进来） -->
    <el-dialog
      :title="importUserTitle"
      v-model="importTenantUserListOpen"
      width="800px"
      append-to-body
    >
      <el-form
        :model="importTenantUserListQueryParams"
        ref="importTenantUserListQueryRef"
        v-show="importTenantUserListShowSearch"
        :inline="true"
        label-width="55px"
      >
        <el-form-item label="账号" prop="userName">
          <el-input
            v-model="importTenantUserListQueryParams.userName"
            placeholder="请输入账号"
            clearable
            style="width: 240px"
            @keyup.enter="importTenantUserListHandleQuery"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="importTenantUserListQueryParams.realName"
            placeholder="请输入姓名"
            clearable
            style="width: 240px"
            @keyup.enter="importTenantUserListHandleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="importTenantUserListQueryParams.mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 240px"
            @keyup.enter="importTenantUserListHandleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="importTenantUserListHandleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="importTenantUserListResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="importTenantUserListLoading"
        :data="importTenantUserList"
        @selection-change="importTenantUserListHandleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="账号" prop="userName" />
        <el-table-column label="姓名" prop="realName" />
        <el-table-column label="昵称" prop="nickName" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="手机号" prop="mobile" />
        <el-table-column prop="gender" label="性别">
          <template #default="scope">
            <dict-tag :options="sys_gender" :value="scope.row.gender" />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="importTenantUserListTotal > 0"
        :total="importTenantUserListTotal"
        v-model:page="importTenantUserListQueryParams.pageNo"
        v-model:limit="importTenantUserListQueryParams.pageSize"
        @pagination="getImportTenantUserList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="importTenantUserListSubmitForm">确 定</el-button>
          <el-button @click="importTenantUserListCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import useAppStore from '@/store/modules/app'
import {
  deptTreeList,
  importGetDeptTreeList,
  getDeptTreeIds,
  addDeptPermissionTreeList,
  getDeptUserList,
  getImportDeptUserList,
  addImportDeptUserList,
  deleteImportDeptUser
} from '@/api/system/tenantPermission'
// delUser,
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { ref } from 'vue'

const props = defineProps({
  tenantBizId: {
    type: String,
    default: () => undefined
  },
  activeTab: {
    type: String,
    default: () => 'project'
  }
})

const appStore = useAppStore()
const { proxy } = getCurrentInstance()
const { sys_gender } = proxy.useDict('sys_gender')

const userList = ref([])
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dateRange = ref([])
const deptName = ref('')
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const importTenantMenuListOpen = ref(false)
const importMenuTitle = ref('')
const importUserTitle = ref('')
const importTenantUserListShowSearch = ref(true)
const importTenantUserListLoading = ref(true)
const importTenantUserList = ref([])
const importTenantUserListTotal = ref(0)
const importTenantUserListIds = ref([])
const importTenantUserListOpen = ref(false)
const importTenantUserListNames = ref([])
const deptTreeRef = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    userName: undefined,
    mobile: undefined,
    status: undefined,
    tenantBizId: props.tenantBizId,
    deptBizId: undefined
  },
  importTenantUserListQueryParams: {
    pageNo: 1,
    pageSize: 10,
    tenantBizId: props.tenantBizId,
    userName: undefined,
    realName: undefined,
    mobile: undefined,
    deptBizId: undefined
  },
  deptTreeParams: {
    deptName: undefined,
    tenantBizId: props.tenantBizId
  },
  rules: {
    userName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
    ],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phonenumber: [
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }
})

// 菜单树数据（直接从接口获取树形结构）
const menuTree = ref([])
// 树组件引用
const treeRef = ref(null)
// 添加响应式变量控制严格模式
const isCheckStrictly = ref(false) // 默认关闭严格模式（启用联动）
const deptBizIdValue = ref(undefined) //部门Id
// 树形配置
const defaultProps = {
  children: 'children',
  label: 'deptName'
}
const { queryParams, form, rules, importTenantUserListQueryParams, deptTreeParams } = toRefs(data)

//========部门-导入逻辑开始=========
/** 部门列表-导入部门 */
const handleImportTenantMenuList = () => {
  loadMenuTree()
  importTenantMenuListOpen.value = true
  importMenuTitle.value = '导入部门'
}
// 加载部门树
const loadMenuTree = async () => {
  try {
    const res = await importGetDeptTreeList(deptTreeParams.value)
    menuTree.value = res.data // 直接使用后端返回的树形结构

    loadImportSelectedMenuList() // 加载选中的菜单列表，更新树勾选
  } catch (error) {
    console.error('加载菜单树失败:', error)
    proxy.$modal.msgError('菜单加载失败')
  }
}
// 修改加载选中部门列表的逻辑
const loadImportSelectedMenuList = async () => {
  try {
    const res = await getDeptTreeIds(props.tenantBizId)
    const targetKeys = res.data || []

    // 开启严格模式（禁用联动）
    isCheckStrictly.value = true

    // 等待DOM更新（确保严格模式生效）
    await nextTick()

    //清空并设置选中状态（此时不会触发联动）
    if (treeRef.value) {
      treeRef.value.setCheckedKeys([])
      treeRef.value.setCheckedKeys(targetKeys)
    }

    //等待选中状态渲染完成
    await nextTick()

    //关闭严格模式（恢复联动）
    isCheckStrictly.value = false
  } catch (error) {
    console.error('加载选中的菜单列表失败:', error)
    proxy.$modal.msgError('加载选中的菜单列表失败')
    // 异常时也要恢复严格模式状态
    isCheckStrictly.value = false
  }
}
// 保存
const saveImportSelectedMenuList = async () => {
  try {
    // 获取当前选中的节点
    const checkedKeys = treeRef.value.getCheckedKeys()
    // 获取半选中的节点（下级勾选，上级没勾选，把上级没勾选带出来）
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys()

    // 合并选中节点（根据业务需求选择是否包含半选节点）
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

    await addDeptPermissionTreeList({
      tenantBizId: props.tenantBizId,
      deptBizIdList: allCheckedKeys
    })
    getDeptTree()
    importTenantMenuListOpen.value = false
    proxy.$modal.msgSuccess('更新成功')
  } catch (error) {
    console.error('更新失败:', error)
    proxy.$modal.msgError('更新失败')
  }
}
//========部门-导入逻辑结束=========

//========用户-导入逻辑开始=========
/** 用户列表-导入-查询导入租户用户关系列表 */
function getImportTenantUserList() {
  importTenantUserListLoading.value = true
  importTenantUserListQueryParams.value.deptBizId = deptBizIdValue.value
  getImportDeptUserList(importTenantUserListQueryParams.value).then(response => {
    importTenantUserList.value = response.data.records
    importTenantUserListTotal.value = response.data.total
    importTenantUserListLoading.value = false
  })
}
/** 用户列表-导入用户 */
function handleImportTenantUserList() {
  getImportTenantUserList()
  importTenantUserListOpen.value = true
  importUserTitle.value = '导入用户'
}
/** 用户列表-导入-搜索按钮操作  做到这了*/
function importTenantUserListHandleQuery() {
  importTenantUserListQueryParams.value.pageNo = 1
  getImportTenantUserList()
}
/** 用户列表-导入-重置按钮操作 */
function importTenantUserListResetQuery() {
  proxy.resetForm('importTenantUserListQueryRef')
  importTenantUserListHandleQuery()
}
/** 用户列表-导入-多选框选中数据 */
function importTenantUserListHandleSelectionChange(selection) {
  importTenantUserListIds.value = selection.map(item => item.userBizId)
  importTenantUserListNames.value = selection.map(item => item.userName)
}
/** 用户列表-导入-导入用户提交 */
function importTenantUserListSubmitForm() {
  const userBizIdList = importTenantUserListIds.value
  const importTenantUserListNameList = importTenantUserListNames.value
  const tenantBizId = props.tenantBizId
  const deptBizId = deptBizIdValue.value

  proxy.$modal
    .confirm('是否确认导入用户账号为"' + importTenantUserListNameList + '"的数据项?')
    .then(function () {
      const data = {
        userBizIdList: userBizIdList,
        tenantBizId: tenantBizId,
        deptBizId: deptBizId
      }
      return addImportDeptUserList(data)
    })
    .then(() => {
      importTenantUserListOpen.value = false
      getList()
      proxy.$modal.msgSuccess('导入成功')
    })
    .catch(() => {})
}

/** 用户列表-导入-取消 */
function importTenantUserListCancel() {
  importTenantUserListOpen.value = false
  proxy.resetForm('importTenantUserListQueryRef')
}
//========用户-导入逻辑结束=========
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs['deptTreeRef'].filter(val)
})

/** 查询用户列表 */
const getList = () => {
  queryParams.value.deptBizId = deptBizIdValue.value
  loading.value = true
  getDeptUserList(queryParams.value).then(res => {
    if (res.code == 200) {
      loading.value = false
      userList.value = res.data.records
      total.value = res.data.total
    } else {
      proxy.$modal.msgError(res.msg)
      loading.value = false
    }
  })
}

/** 查询部门下拉树结构 */
const getDeptTree = () => {
  deptTreeList(deptTreeParams.value).then(response => {
    if (response.code == 200) {
      if (response.data && response.data.length > 0) {
        deptBizIdValue.value = response.data[0].deptBizId
        deptOptions.value = response.data
        enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
        // getList()
        // 等待 DOM 更新后选中第一个节点
        nextTick(() => {
          selectFirstTreeNode()
        })
      }
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 过滤禁用的部门 */
const filterDisabledDept = deptList => {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}
// 选中树形结构的第一个节点
const selectFirstTreeNode = () => {
  if (deptOptions.value && deptOptions.value.length > 0) {
    // 获取第一个节点的 key (使用 deptBizId)
    const firstNodeKey = findFirstNodeKey(deptOptions.value[0])

    if (firstNodeKey && deptTreeRef.value) {
      // 设置当前选中节点
      deptTreeRef.value.setCurrentKey(firstNodeKey)

      // 如果需要触发节点点击事件
      deptBizIdValue.value = firstNodeKey
      handleQuery() // 重新获取列表数据
    }
  }
}

// 递归查找第一个节点的 key
const findFirstNodeKey = node => {
  if (node.deptBizId) {
    return node.deptBizId
  }

  // 如果有子节点，继续查找
  if (node.children && node.children.length > 0) {
    return findFirstNodeKey(node.children[0])
  }

  return null
}
/** 节点单击事件 */
const handleNodeClick = data => {
  deptBizIdValue.value = data.deptBizId
  handleQuery()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  proxy.resetForm('queryRef')
  queryParams.value.deptId = undefined
  proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 删除部门用户关系 */
function handleDelete(row) {
  //租户和项目关系表主键id
  const id = row.id
  const userName = row.userName
  proxy.$modal
    .confirm('是否确认删除账号为"' + userName + '"的租户和部门关系的数据项?')
    .then(function () {
      return deleteImportDeptUser({ id: id })
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
/** 选择条数  */
const handleSelectionChange = selection => {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 监听tab切换
watch(
  () => props.activeTab,
  newTab => {
    if (newTab == 'dept') {
      getDeptTree()
      dateRange.value = []
      proxy.resetForm('queryRef')
      queryParams.value.deptId = undefined
      proxy.$refs.deptTreeRef.setCurrentKey(null)
    }
  },
  { immediate: true }
)
</script>
<style scoped>
.tree-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
