<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 allLockUsers"
              :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
                    v-for="user in addedLockUsers[group.id] || []"
                    :key="user.userId"
                    class="user-card"
                    @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.userId"
              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, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as RoleUser from '@/api/system/user'
import * as JobUserApi from '@/api/job/jobUser'
import * as JobApi from '@/api/job/index'
import * as JobPointGroupApi from '@/api/job/jobPointGroup'

import { Check, Close } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const allGroup = ref<any[]>([])
const allLockUsers = ref<any[]>([]) // 全量锁定人
const allCoLockUsers = ref<any[]>([]) // 全量共锁人

const addedLockUsers = ref<Record<string, any[]>>({})
const addedCoLockUsers = ref<any[]>([])

const selectedGroupId = ref<string>('')
const existingUserList = ref<any[]>([])

// 共锁人动态可选
const jtcolocker = computed(() => {
  return allCoLockUsers.value.filter(u => {
    return !addedCoLockUsers.value.some(a => a.userId === u.id)
  })
})

onMounted(async () => {
  const groupData = await JobPointGroupApi.getJobTicketGroupPage({
    pageNo: 1,
    pageSize: -1,
    ticketId: route.query.ticketId
  })
  allGroup.value = groupData.list

  allLockUsers.value = await RoleUser.getRoleUser('jtlocker')
  allCoLockUsers.value = await RoleUser.getRoleUser('jtcolocker')

  if (route.query.groupId && route.query.groupId !== '0') {
    selectedGroupId.value = route.query.groupId
  } else {
    selectedGroupId.value = groupData.list?.[0]?.id || ''
  }

  const jobData = await JobApi.selectJobTicketById(route.query.ticketId)
  if (Array.isArray(jobData.ticketUserList)) {
    existingUserList.value = jobData.ticketUserList
    jobData.ticketUserList.forEach(user => {
      if (user.userRole === 'jtlocker') {
        const groupId = user.groupId
        if (!addedLockUsers.value[groupId]) {
          addedLockUsers.value[groupId] = []
        }
        addedLockUsers.value[groupId].push({
          userId: user.userId,
          nickname: user.userName
        })
      } else if (user.userRole === 'jtcolocker') {
        addedCoLockUsers.value.push({
          userId: user.userId,
          nickname: user.userName
        })
      }
    })
  }
})

// 选组
const selectGroup = (groupId: string) => {
  selectedGroupId.value = groupId
}

// 判断选中
const isUserInSelectedGroup = (user) => {
  const list = addedLockUsers.value[selectedGroupId.value] || []
  return list.some(u => u.userId === user.id)
}

// 添加/移除
const selectUser = (user, type: 'lock' | 'coLock') => {
  if (type === 'lock') {
    if (!selectedGroupId.value) {
      ElMessage.warning('请先选择一个分组')
      return
    }
    const list = addedLockUsers.value[selectedGroupId.value] || []
    const exists = list.findIndex(u => u.userId === user.id)
    if (exists >= 0) {
      list.splice(exists, 1)
    } else {
      list.push({
        userId: user.id,
        nickname: user.nickname
      })
    }
    addedLockUsers.value[selectedGroupId.value] = list
  } else {
    const idx = addedCoLockUsers.value.findIndex(u => u.userId === user.id)
    if (idx >= 0) {
      addedCoLockUsers.value.splice(idx, 1)
    } else {
      addedCoLockUsers.value.push({
        userId: user.id,
        nickname: user.nickname
      })
    }
  }
}

const removeLockUser = (user, groupId) => {
  const list = addedLockUsers.value[groupId]
  addedLockUsers.value[groupId] = list.filter(u => u.userId !== user.userId)
}

const removeCoLockUser = (user) => {
  addedCoLockUsers.value = addedCoLockUsers.value.filter(u => u.userId !== user.userId)
}

const submit = async () => {
  const ticketId = route.query.ticketId
  // 校验每个分组是否都有上锁人
  const missingGroups: string[] = []

  allGroup.value.forEach(group => {
    const users = addedLockUsers.value[group.id] || []
    if (users.length === 0) {
      missingGroups.push(group.name || group.id)
    }
  })

  if (missingGroups.length > 0) {
    ElMessage.error(`以下分组缺少上锁人：${missingGroups.join('、')}`)
    return
  }
  const finalList: any[] = []

if(addedLockUsers.value){
  console.log(addedLockUsers.value,allGroup.value,'分组信息和选人信息')
}
  Object.entries(addedLockUsers.value).forEach(([groupId, users]) => {
    users.forEach(u => {
      finalList.push({
        ticketId,
        groupId,
        userId: u.userId,
        userName: u.nickname,
        userType: 0,
        userRole: 'jtlocker'
      })
    })
  })

  addedCoLockUsers.value.forEach(u => {
    finalList.push({
      ticketId,
      groupId: null,
      userId: u.userId,
      userName: u.nickname,
      userType: 0,
      userRole: 'jtcolocker'
    })
  })

  const toAdd = finalList.filter(newU =>
    !existingUserList.value.some(e =>
      e.userId === newU.userId &&
      e.userRole === newU.userRole &&
      e.groupId === newU.groupId
    )
  )

  const toDelete = existingUserList.value.filter(e =>
    !finalList.some(newU =>
      newU.userId === e.userId &&
      newU.userRole === e.userRole &&
      newU.groupId === e.groupId
    )
  ).map(e => e.id)

  if (!toAdd.length && !toDelete.length) {
    ElMessage.warning('无更改')
    return
  }

  if (toDelete.length) {
    await JobUserApi.deleteJobTicketUserList(toDelete.join(','))
  }

  if (toAdd.length) {
    await JobUserApi.insertJobTicketUser(toAdd)
  }

  ElMessage.success('保存成功')
}

const cancel = () => {
  router.push({
    path: '/jobTicket/jobTicket/job/UpdateJob',
    query: {
      id: route.query.ticketId,
      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>
