<template>
  <div class="h5-container">
    <van-nav-bar title="添加人员" @click-left="onClickLeft">
      <template #right>
        <van-icon name="add" size="25" color="#000" @click="handleDepartmentLeaderNameOne" />
      </template>
    </van-nav-bar>

    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list v-model:loading="isLoading" :finished="isFinished" finished-text="没有更多了" offset="200" @load="onLoad">
        <div v-for="(item, idx) in resultData" :key="item.id || item.userId || idx">
          <van-swipe-cell title-style="color: #007aff" style="height: 80px;" :ref="el => getSwipeCellRef(el, idx)">
            <template #default>
              <div class="swipe-cell-default">
                <van-cell style="height: 100%; display: flex; align-items: center;">
                  <template #title>
                    <div class="cell-title">
                      {{ item.userName }}
                    </div>
                  </template>
                  <template #label>
                    <div>工号：{{ item.userCode }}</div>
                  </template>
                </van-cell>
                <div class="swipe-cell-default-icon">
                  <van-icon v-if="openStatus[idx]" name="arrow-double-left" @click.stop="openSwipe(idx)" />
                  <van-icon v-else name="arrow-double-right" @click.stop="closeSwipe(idx)" />
                </div>
              </div>
            </template>

            <template #right>
              <van-button square class="delete-button" text="删除" @click="deleteRowUser(item)" />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 人员选择组件 -->
    <OrganizationalWithLeafUserForCourse
        ref="PopupDepartmentLeaderNameRef2"
        :multiple="false"
        @receiveFromChild="getDepartmentLeaderNameOne"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { showFailToast, showSuccessToast, showToast, showConfirmDialog } from 'vant';
import OrganizationalWithLeafUserForCourse from '@/components/OrganizationalWithLeafUserForCourse.vue';
import { useRoute, useRouter } from 'vue-router';

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const onClickLeft = () => {
  history.back();
};

const guid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};

const leaderKey = guid();
const ClassId = ref('');
const planInfo = ref({});

if (route.query.data) {
  planInfo.value = JSON.parse(route.query.data);
  ClassId.value = planInfo.value.id;
  sessionStorage.setItem('id', ClassId.value);
}

if (!planInfo.value || !ClassId.value) {
  showToast({
    type: 'error',
    message: '请退出重试'
  });
}

const PopupDepartmentLeaderNameRef2 = ref();
const handleDepartmentLeaderNameOne = () => {
  if (PopupDepartmentLeaderNameRef2.value) {
    PopupDepartmentLeaderNameRef2.value.open();
  }
};


const getDepartmentLeaderNameOne = (item) => {
  // 检查 item 和 item.user 是否存在
  if (!item || !item.user) {
    showFailToast('用户数据无效');
    return;
  }

  // 获取当前已有的用户列表（从 resultData 中提取，格式为 userCode-userName）
  const currentUsers = resultData.value
    .filter(user => user && user.userCode)
    .map(user => `${user.userCode}-${user.userName || user.userDesc || ''}`);
  
  // 检查用户是否已存在
  const newUserStr = `${item.user.userCode}-${item.user.userDesc || ''}`;
  if (currentUsers.includes(newUserStr)) {
    showFailToast('该用户已添加，请勿重复添加');
    return;
  }

  // 构建新的用户列表（包含已有用户和新用户），格式为 userCode-userName
  const allUsers = [...currentUsers, newUserStr];
  userNameArr.value = allUsers.join(',');

  // 保存用户
  usersave();
};


const userNameArr = ref([]);
const getDepartmentLeaderName = (userArray) => {
  // 处理用户对象数组，提取 userCode
  if (userArray && userArray.length > 0) {
    if (typeof userArray[0] === 'string') {
      // 如果是字符串数组，直接使用
      userNameArr.value = userArray.join(',');
    } else {
      // 如果是对象数组，提取 userCode
      userNameArr.value = userArray.map(user => user.userCode).join(',');
    }
  } else {
    userNameArr.value = '';
  }
  usersave();
};

const usersave = () => {
  const classId = sessionStorage.getItem('id') || ClassId.value;
  
  if (!classId) {
    showFailToast('课程ID不存在，请重新进入页面');
    return;
  }

  if (!userNameArr.value || userNameArr.value.trim() === '') {
    showFailToast('用户列表为空，无法保存');
    return;
  }

  const url = '/sgsafe/Class/userSave';
  const param = {
    json: userNameArr.value,
    classId: classId
  };

  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0' || response.data.code === 0) {
      showSuccessToast('保存成功');
      // 重新获取用户列表
      getClassUserData();
    } else {
      // 根据错误信息显示更友好的提示
      const errorMsg = response.data.msg || '未知错误';
      if (errorMsg.includes('未配置小节') || errorMsg.includes('小节')) {
        showFailToast('该课程未配置小节，请先添加小节后再添加人员');
      } else {
        showFailToast('操作失败：' + errorMsg);
      }
    }
  }).catch(error => {
    showFailToast('保存失败：' + (error.message || '网络错误'));
  });
};

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);
const resultData = ref([]);
const tableData = ref([]);

const getClassUserData = async () => {
  const classId = sessionStorage.getItem('id') || ClassId.value;
  if (!classId) {
    return;
  }

  const url = '/sgsafe/Class/queryUserById';
  const param = {
    params: classId
  };

  try {
    const response = await proxy.$axios.get(url, param);
    if (response.data.code == '0') {
      const userList = response.data.data || [];
      tableData.value = userList;
      totalRows.value = userList.length;
      
      // 直接更新 resultData，确保数据能立即显示
      resultData.value = [...userList];
      openStatus.value = new Array(resultData.value.length).fill(true);
      isFinished.value = true;
      isLoading.value = false;
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + (response.data.msg || '未知错误')
      });
    }
  } catch (error) {
    showToast({
      type: 'error',
      message: '获取数据失败：' + (error.message || '网络错误')
    });
  }
};

const onRefresh = () => {
  basicReset();
  onLoad();
};

const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }

  try {
    await getClassUserData();
    // getClassUserData 已经直接更新了 resultData，这里只需要标记完成
    isLoading.value = false;
  } catch (error) {
    isFinished.value = true;
    isLoading.value = false;
  }
};

const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

const deleteRowUser = (row) => {
  showConfirmDialog({
    title: '提示',
    message: '确定要删除吗？'
  }).then(() => {
    const qiyongUser = ref({});
    qiyongUser.value = { ...row };
    qiyongUser.value.cancelFlag = '1';
    const url = '/sgsafe/Class/delectUser';
    const param = {
      json: JSON.stringify(qiyongUser.value)
    };
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        showSuccessToast('删除成功');
        getClassUserData();
      } else {
        showToast({
          type: 'error',
          message: '操作失败！' + response.data.msg
        });
      }
    });
  }).catch(() => {
  });
};

const openStatus = ref([]);
const swipeCellRefs = ref([]);
const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
};

const openSwipe = (idx) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = false;
    swipeCellRefs.value[idx].open('right');
  }
  document.addEventListener('click', handleDocumentClick);
};

const handleDocumentClick = (event) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
};

const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = true;
    swipeCellRefs.value[idx].close();
  }
};

onMounted(() => {
  // 确保 ClassId 已设置
  const classId = sessionStorage.getItem('id') || ClassId.value;
  if (classId) {
    if (!ClassId.value) {
      ClassId.value = classId;
    }
    getClassUserData();
  }
});
</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.cell-title {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: calc(1.5em * 2);
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
}

.delete-button {
  height: 100%;
  border: none;
  color: #ff0000;
  background-image: url('@/assets/img/del.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}
</style>
