<template>
  <div class="page-container">
    <div class="main-layout">
      <!-- 左侧 -->
      <div class="left-side">
        <!-- 可选择的锁定人 -->
        <el-card class="card-block" style="height: 300px">
          <template #header>可选择的锁定人</template>
          <div class="user-list">
            <div
              v-for="user in jtlocker"
              :key="user.id"
              class="user-card"
              :class="{ selected: isUserInSelectedGroup(user) }"
              @click="selectUser(user, 'lock')"
            >
              <img src="@/assets/images/UserEmpty.png" />
              <div class="user-name">{{ user.nickname }}</div>
            </div>
          </div>
        </el-card>

        <!-- 可选择的共锁人 -->
        <el-card class="card-block" style="height: 350px">
          <template #header>可选择的共锁人</template>
          <div class="user-list">
            <div
              v-for="user in jtcolocker"
              :key="user.id"
              class="user-card"
              @click="selectUser(user, 'coLock')"
            >
              <img src="@/assets/images/UserEmpty.png" />
              <div class="user-name">{{ user.nickname }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧 -->
      <div class="right-side">
        <!-- 已添加的锁定人 -->
        <el-card class="card-block red-border" style="height: 300px">
          <template #header>已添加的锁定人</template>
          <div class="group-container">
            <div
              v-for="group in allGroup"
              :key="group.id"
              class="group-card"
              :class="{ active: selectedGroupId == group.id }"
              @click="selectGroup(group.id)"
            >
              <el-card class="inner-card">
                <template #header>{{ group.groupName }}</template>
                <div class="user-list">
                  <div
                    class="user-card"
                    v-for="user in addedLockUsers[group.id] || []"
                    :key="user.id"
                    @click.stop="removeLockUser(user, group.id)"
                  >
                    <img src="@/assets/images/UserBlack.png" />
                    <div class="user-name">{{ user.nickname }}</div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-card>

        <!-- 已添加的共锁人 -->
        <el-card class="card-block orange-border" style="height: 350px">
          <template #header>已添加的共锁人</template>
          <div class="user-list">
            <div
              v-for="user in addedCoLockUsers"
              :key="user.id"
              class="user-card"
              @click="removeCoLockUser(user)"
            >
              <img src="@/assets/images/UserBlack.png" />
              <div class="user-name">{{ user.nickname }}</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-btn">
      <el-button type="primary" @click="submit">
        <el-icon>
          <Check />
        </el-icon>
        确 定
      </el-button>
      <el-button @click="cancel">
        <el-icon>
          <Close />
        </el-icon>
        取 消
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as SopPointGroup from '@/api/sop/sopPointGroup'
import * as RoleUser from '@/api/system/user'
import * as SopUserApi from '@/api/sop/sopUser'
import * as SopApi from '@/api/sop/index'
import { Check, Close } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const allGroup = ref<any[]>([])
const jtlocker = ref<any[]>([])
const jtcolocker = ref<any[]>([])

const addedLockUsers = ref<Record<string, any[]>>({})
const addedCoLockUsers = ref<any[]>([])
const selectedGroupId = ref<string>('')
const toDeleteUserIds = ref<number[]>([]) //删除的人员

// 加载数据
onMounted(async () => {
  const groupData = await SopPointGroup.getSopGroupList({
    pageNo: 1,
    pageSize: -1,
    sopId: route.query.sopId
  })

  allGroup.value = groupData
  jtlocker.value = await RoleUser.getRoleUser('jtlocker')
  if(route.query.groupId){
    selectedGroupId.value=route.query.groupId
  }else {
    selectedGroupId.value = ''
  }


  const SopUserData = await SopApi.selectSopById(route.query.sopId)
  console.log(SopUserData,'SopUserData')
  if (Array.isArray(SopUserData.sopUserList) && SopUserData.sopUserList.length > 0) {
    const userList = SopUserData.sopUserList
    // 1. 渲染锁定人
    userList
      .filter((user) => user.userRole === 'jtlocker')
      .forEach((user) => {
        const groupId = user.groupId
        if (!groupId) return // 没分组就跳过

        if (!addedLockUsers.value[groupId]) {
          addedLockUsers.value[groupId] = []
        }

        addedLockUsers.value[groupId].push({
          id: user.id,
          userId: user.userId,
          nickname: user.userName
        })
      })

    // 2. 渲染共锁人（groupId 为 null）
    userList
      .filter((user) => user.userRole === 'jtcolocker')
      .forEach((user) => {
        addedCoLockUsers.value.push({
          id: user.id,
          userId: user.userId,
          nickname: user.userName
        })

        // 从左侧移除已分配的共锁人
        jtcolocker.value = jtcolocker.value.filter((u) => u.id !== user.userId)
      })
  } else {

    // 渲染初始化的

    jtcolocker.value = await RoleUser.getRoleUser('jtcolocker')
  }
})

// 切换分组
const selectGroup = (groupId: string) => {
  console.log('选中分组:', groupId)
  selectedGroupId.value = groupId
}

// 是否在选中的分组中（只检查当前选中的分组）
const isUserInSelectedGroup = (user) => {
  if (!selectedGroupId.value) return false
  const groupList = addedLockUsers.value[selectedGroupId.value] || []
  return groupList.some((u) => u.id === user.id)
}

// 添加 or 移除
const selectUser = (user, type: 'lock' | 'coLock') => {
  if (type === 'lock') {
    if (!selectedGroupId.value) {
      ElMessage.warning('请先选择一个分组')
      return
    }

    const groupList = addedLockUsers.value[selectedGroupId.value] || []
    const existingIndex = groupList.findIndex((u) => u.id === user.id)

    if (existingIndex !== -1) {
      groupList.splice(existingIndex, 1)
    } else {
      if (!addedLockUsers.value[selectedGroupId.value]) {
        addedLockUsers.value[selectedGroupId.value] = []
      }
      addedLockUsers.value[selectedGroupId.value].push(user)
    }
  } else {
    const index = jtcolocker.value.findIndex((u) => u.id === user.id)
    if (index !== -1) {
      addedCoLockUsers.value.push(user)
      jtcolocker.value.splice(index, 1)
    }
  }
}

// 移除锁定人
const removeLockUser = (user, groupId) => {
  const list = addedLockUsers.value[groupId]
  if (!list) return
  addedLockUsers.value[groupId] = list.filter((u) => u.id !== user.id)

  // 记录待删除
  toDeleteUserIds.value.push(user.id)
}

// 移除共锁人（同时回到左侧）
const removeCoLockUser = (user) => {
  addedCoLockUsers.value = addedCoLockUsers.value.filter((u) => u.id !== user.id)
  jtcolocker.value.push(user)

  // 记录待删除
  toDeleteUserIds.value.push(user.id)
  console.log(user,'user')
}

// 确认按钮事件
const submit = async () => {
  try {
    const sopId = route.query.sopId
    const userList: any[] = []

    // === 构造新增人员数据 ===
    Object.keys(addedLockUsers.value).forEach((groupId) => {
      const users = addedLockUsers.value[groupId] || []
      users.forEach((user) => {
        userList.push({
          sopId,
          groupId,
          userId: user.id,
          userName: user.nickname,
          userType: 0,
          userRole: 'jtlocker'
        })
      })
    })

    addedCoLockUsers.value.forEach((user) => {
      userList.push({
        sopId,
        groupId: null,
        userId: user.id,
        userName: user.nickname,
        userType: 0,
        userRole: 'jtcolocker'
      })
    })

    // === 没有任何操作则提示 ===
    if (userList.length === 0 && toDeleteUserIds.value.length === 0) {
      ElMessage.warning('请至少选择一个人员或移除一个人员')
      return
    }

    // === 删除操作 ===
    if (toDeleteUserIds.value.length > 0) {
      const deleteIds = toDeleteUserIds.value.join(',')
      await SopUserApi.deleteSopUserList(deleteIds)
      console.log('删除成功:', toDeleteUserIds.value)
    }

    // === 新增操作 ===
    if (userList.length > 0) {
      const result = await SopUserApi.insertSopUser(userList)
      if (result) {
        ElMessage.success('保存成功')
        // 成功后清空删除列表
        toDeleteUserIds.value = []
      } else {
        ElMessage.error(result?.msg || '保存失败')
      }
    }
  } catch (error) {}
}

const cancel = () => {
  if (route.query.type == 'update') {
    router.push({
      path: '/sopm/sopm/sop/UpdateSop',
      query: {
        id: route.query.sopId,
        type: route.query.type
      }
    })
  } else {
    router.push({
      path: '/sopm/sopm/sop/UpdateSop',
      query: {
        id: route.query.sopId,
        type: route.query.type
      }
    })
  }
}
</script>
<style lang="scss" scoped>
.page-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.main-layout {
  display: flex;
  gap: 20px;
}

.left-side,
.right-side {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-block {
  border-radius: 8px;
}

.red-border {
  border-top: 4px solid #d3342e;
}

.orange-border {
  border-top: 4px solid #f7941d;
}

.user-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.user-card {
  width: 80px;
  text-align: center;
  cursor: pointer;
  border: 2px solid transparent;
  padding: 4px;

  img {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border: 1px solid #ccc;
  }

  .user-name {
    margin-top: 4px;
    font-size: 14px;
  }

  &.selected {
    border: 2px solid red;

    .user-name {
      background: red;
      color: #fff;
      padding: 2px;
    }
  }
}

.group-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.group-card {
  min-width: 200px;
  min-height: 120px;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 6px;
  transition: border-color 0.3s;

  &.active {
    border: 2px solid red;
  }

  // 防止内部卡片影响外部点击
  .inner-card {
    height: 100%;

    :deep(.el-card__header) {
      padding: 8px 12px;
      font-size: 14px;
      font-weight: bold;
    }

    :deep(.el-card__body) {
      padding: 8px;
    }
  }
}

// 底部按钮
.bottom-btn {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  padding-top: 10px;
  border-top: 1px solid #eee;
}
</style>
