<template>
  <div class="member-management">
    <!-- 顶部操作区 -->
    <div class="header">
      <el-button type="primary" @click="showAddMemberSidebar">
        <el-icon><Plus /></el-icon>添加成员
      </el-button>

      <!-- 底部操作区 -->
      <div class="bitch-actions">
        <el-button @click="selectAll" :class="{ 'active': isSelectAll }">选择全部</el-button>
        <el-button @click="reverseSelect">反向选择</el-button>
        <el-button @click="clearSelect">清除选择</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </div>
    </div>

    <!-- 成员表格 -->
    <div class="table-container">
      <el-table
          ref="memberTable"
          :data="filteredMembers"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#fafafa', color: '#606266'}"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="staffName" label="姓名" width="120" />
        <el-table-column prop="code" label="工号" width="120" />
        <el-table-column prop="dept" label="部门" width="180" />
        <el-table-column prop="type" label="聘用方式" width="120" />
        <el-table-column prop="projectRole" label="项目角色" width="150">
          <template #default="{ row }">
            <div
                :class="['role-tag', row.projectRole === '项目管理员' ? 'admin' : 'member']"
                @click="toggleProjectRole(row)"
                style="cursor: pointer;"
            >
              {{ row.projectRole }}
              <el-icon><Refresh /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="deleteMember(row.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalMembers"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加成员侧边栏 -->
    <el-drawer
        v-model="showSidebar"
        title="添加成员"
        direction="rtl"
        size="50%"
        :before-close="handleClose"
    >
      <div class="add-member-container">
        <div class="leftdiv" style="float: left;margin: 10px;width: 45%;padding: 10px;background-color: #f8f8f8">

          <div class="equipment-type-tabs">
            <el-button
                :class="{ 'active': equipmentType === 'company' }"
                @click="searchAllStaff"
            >
              企业人员
            </el-button>
            <el-button
                :class="{ 'active': equipmentType === 'project'}"
                @click="equipmentType = 'project'"
            >
              项目人员
            </el-button>
          </div>
          <div v-if="equipmentType === 'project'" class="project-select" style="margin-bottom: 10px">
            <el-select v-model="selectedProject"
                       placeholder="请选择项目"
                       @change="(value)=>{handleProjectChange(value)}"
            >
              <el-option
                  v-for="project in allProject"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"

              />
            </el-select>
          </div>
          <div class="batch-add" @click="showBatchSelect" v-if="equipmentType === 'company'" style="border: 1px solid #8c939d;background-color: white;margin-bottom: 10px">
            <el-icon><Plus /></el-icon>
            <span>批量添加</span>
          </div>
          <div class="search-box">
            <el-input
                v-model="searchQuery"
                placeholder="搜索成员"
                clearable
            >
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>

          <div class="content-container" style="background-color: white;padding: 10px">
            <div class="member-list">
              <el-checkbox-group v-model="selectedMembers">
                <div
                    v-if="equipmentType === 'company'"
                    v-for="member in filteredMemberList"
                    :key="member.id"
                    class="member-item"
                >
                  <el-checkbox :label="member.id">{{ member.name }}</el-checkbox>
                </div>
                <div
                    v-else
                    v-for="member in filteredMemberList"
                    :key="member.staffId"
                    class="member-item"
                >
                  <el-checkbox :label="member.staffId">{{ member.staffName }}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="rightdiv" style="float: left;margin: 10px;background-color: #f8f8f8;width: 48%;padding: 10px">
          <div class="selected-members">
            <div class="sync-options">
              <div class="sync-item">
                <span>设备</span>
                <el-switch v-model="syncOptions.device" />
              </div>
              <div class="sync-item">
                <span>无形资产</span>
                <el-switch v-model="syncOptions.intangible" />
              </div>
              <div class="sync-item">
                <span>建筑物</span>
                <el-switch v-model="syncOptions.building" />
              </div>
            </div>
            <div class="sync-hint">
              开启后人员关联的设备、无形资产或建筑物将同步添至项目
            </div>
            <el-divider />

            <div class="selected-list" style="background-color: white">
              <div
                  v-if="equipmentType==='company'"
                  v-for="member in selectedMemberNames"
                  :key="member.id"
                  class="selected-item"
              >
                <span>{{ member.name }}</span>
                <el-icon @click="removeSelectedMember(member.id)"><Close /></el-icon>
              </div>
              <div
                  v-else
                  v-for="member in selectedMemberNames"
                  :key="member.staffId"
                  class="selected-item"
              >
                <span>{{ member.staffName }}</span>
                <el-icon @click="removeSelectedMember(member.staffId)"><Close /></el-icon>
              </div>
            </div>
          </div>
        </div>

        <div class="fixed-bottom-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 批量选择弹出框 -->
    <el-drawer
        v-model="showBatchDialog"
        title="批量选择"
        width="50%"
        :before-close="handleBatchClose"
    >
      <div class="add-member-container" style="padding: 20px">
        <div class="non-exist-hint">
          不存在的选项：（确认时会自动过滤）
        </div>
        <el-input
            v-model="batchInput"
            type="textarea"
            :rows="10"
            placeholder="请输入设备名称，每行一个"
        />
        <div class="batch-actions">
          <el-button @click="clearBatchInput">清空</el-button>
          <el-button @click="cancelBatchSelect">取消</el-button>
          <el-button type="primary" @click="confirmBatchSelect">确认</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, reactive, watch} from 'vue'
import {
  Plus,
  Delete,
  Refresh,
  Search,
  Close
} from '@element-plus/icons-vue'
import { get, add, update, del } from '@/api/public/basic'
import { ElMessage, ElMessageBox } from 'element-plus'
import {useUserInfosState} from "@/stores/userInfos";
import cityData from "@/assets/city";
const userInfos = useUserInfosState();


const props = defineProps({
  projectId: {
    type: String,
    required: true
  }
})
const state=reactive({
  queryParams: {
    // 页码
    pageNum: 1,
    // 每页大小
    pageSize: 10,
    projectId:'',
  },
})
// 表格数据
const members = ref([])
const allMembers = ref([]) // 所有人员数据（用于添加成员）
const projectMembers = ref([]) // 其他项目的人员数据（用于添加成员）
const allProject= ref([]) // 所有项目数据（用于添加成员）
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalMembers = ref(0)

// 表格选择相关
const memberTable = ref(null)
const selectedRows = ref([])
const isSelectAll = ref(false)

// 添加成员侧边栏相关
const showSidebar = ref(false)
const searchQuery = ref('')
const selectedMembers = ref([])
const syncOptions = ref({
  device: false,
  intangible: false,
  building: false
})

// 计算属性
const filteredMembers = computed(() => {
  return members.value
})

// const filteredMemberList = computed(() => {
//   let result = [...allMembers.value]
//
//   // 搜索筛选
//   if (searchQuery.value) {
//     result = result.filter(member =>
//         member.name.includes(searchQuery.value))
//   }
//
//   // 过滤掉已经是当前项目成员的人员
//   const currentMemberIds = members.value.map(m => m.id)
//   console.log(currentMemberIds.length)
//   // console.log("111111111111111111112145578909765432")
//   result = result.filter(member => !currentMemberIds.includes(member.id))
//   console.log(result.length)
//   console.log("111111111111111111112145578909765432")
//   return result
// })



// const filteredMemberList = computed(() => {
//   let result = [...allMembers.value]
//
//   // 先筛选搜索
//   if (searchQuery.value) {
//     result = result.filter(member =>
//         member.name.includes(searchQuery.value))
//   }
//   console.log("members.value 数据:", members.value)
//   console.log("allMembers.value 数据:", allMembers.value)
//   // 确保 currentMemberIds 是字符串数组（如果 ID 是字符串）
//   const currentMemberIds = members.value.map(m => ({
//     id:m.staffId
//   }))
//   console.log(currentMemberIds.length)
//   console.log("111111111111111111112145578909765432")
//   // 过滤掉已在当前项目的成员
//   result = result.filter(member =>
//       !currentMemberIds.includes(member.id)
//   )
//   console.log(result.length)
//   console.log("111111111111111111112145578909765432")
//   console.log("最终筛选结果:", result)
//   return result
// })


const filteredMemberList = computed(() => {
  let result = [...allMembers.value]

  console.log("members.value 数据:", members.value)
  console.log("allMembers.value 数据:", allMembers.value)

  // 正确提取成员ID数组
  const currentMemberIds = members.value.map(m => m.staffId.toString())
  console.log("当前成员ID列表:", currentMemberIds)


  if(equipmentType.value === 'project'){
    // 先筛选搜索
    if (searchQuery.value) {
      result = result.filter(member =>
          member.staffName.includes(searchQuery.value)
      )
    }
    // 过滤掉已在当前项目的成员
    result = result.filter(member => {
      const isIncluded = currentMemberIds.includes(member.staffId)
      console.log(`成员 ${member.staffName} (ID: ${member.staffId}) 是否已存在: ${isIncluded}`)
      return !isIncluded
    })

    console.log("过滤后剩余成员数量:", result.length)
    console.log("最终筛选结果:", result)
  }
  else{
    // 先筛选搜索
    if (searchQuery.value) {
      result = result.filter(member =>
          member.name.includes(searchQuery.value)
      )
    }
    // 过滤掉已在当前项目的成员
    result = result.filter(member => {
      const isIncluded = currentMemberIds.includes(member.id.toString())
      console.log(`成员 ${member.name} (ID: ${member.id}) 是否已存在: ${isIncluded}`)
      return !isIncluded
    })

    console.log("过滤后剩余成员数量:", result.length)
    console.log("最终筛选结果:", result)
  }

  return result
})

const selectedMemberNames = computed(() => {
 if(equipmentType.value === 'company') {
   return allMembers.value.filter(member =>
       selectedMembers.value.includes(member.id))
 }else{
   return allMembers.value.filter(member =>
       selectedMembers.value.includes(member.staffId))
 }

})

// 方法
const fetchProjectMembers = async () => {
  try {
    state.queryParams.projectId=props.projectId
    const response = await get(state.queryParams, 'i2vsPpJc2Sh')
    members.value = response.data.result || []
    totalMembers.value = response.data.count || 0
  } catch (error) {
    ElMessage.error('获取项目成员失败')
    console.error(error)
  }
}
const fetchProjectMembers2 = async () => {
  try {
    const response = await get(state.queryParams, 'i2vsPpJc2Sh')
    allMembers.value = response.data.result || []
    // totalMembers.value = response.data.count || 0
  } catch (error) {
    ElMessage.error('获取项目成员失败')
    console.error(error)
  }
}
const fetchAllMembers = async () => {
  try {
    const response = await get({}, 'i272x8hCGVw') // 获取所有人员
    allMembers.value = response.data.result || []
  } catch (error) {
    ElMessage.error('获取所有人员失败')
    console.error(error)
  }
}
const fetchAllproject = async () => {
  try {
    const response = await get({}, 'i1XuaQDK9zw') // 获取所有人员
    allProject.value = response.data.result || []
  } catch (error) {
    ElMessage.error('获取所有人员失败')
    console.error(error)
  }
}
const toggleProjectRole = async (row) => {
  try {
    const newRole = row.projectRole === '项目管理员' ? '项目组员' : '项目管理员'
    await update(row.id,{
      projectRole: newRole,
      projectId: props.projectId,
      updateTime: currentDate,  // 添加格式化后的日期
      operator: userInfos.userInfos.nickname,
    }, 'i2vsPpJc2Sh')
    row.projectRole = newRole
    fetchProjectMembers()
    ElMessage.success('角色更新成功')
  } catch (error) {
    ElMessage.error('角色更新失败')
    console.error(error)
  }
}

const handleSelectionChange = (val) => {
  selectedRows.value = val
  isSelectAll.value = val.length === filteredMembers.value.length
}

const selectAll = () => {
  if (isSelectAll.value) {
    memberTable.value.clearSelection()
    isSelectAll.value = false
  } else {
    memberTable.value.toggleAllSelection()
    isSelectAll.value = true
  }
}

const reverseSelect = () => {
  filteredMembers.value.forEach(row => {
    memberTable.value.toggleRowSelection(row)
  })
  isSelectAll.value = selectedRows.value.length === filteredMembers.value.length
}

const clearSelect = () => {
  memberTable.value.clearSelection()
  isSelectAll.value = false
}

const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的成员')
    return
  }

  try {
    const idsToDelete = selectedRows.value.map(row => row.id)
    // 批量添加成员到项目
    for (const member of selectedRows.value) {
      await update(member.id,{
        projectId:'',
        projectRole: '项目成员',
      }, 'i272x8hCGVw')
    }
    //members.value = members.value.filter(member => !idsToDelete.includes(member.id))
    ElMessage.success('批量删除成功')
    clearSelect()
    fetchProjectMembers()
  } catch (error) {
    ElMessage.error('批量删除失败')
    console.error(error)
  }
}

const deleteMember = async (id) => {
  ElMessageBox.confirm('确定要删除该成员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
    await update(id,{
      projectId:'',
      projectRole: '项目成员',
      updateTime: currentDate  // 添加格式化后的日期
    }, 'i2vsPpJc2Sh')
    ElMessage.success('删除成功')
    fetchProjectMembers()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error(error)
  }
  }).catch(() => {

  })

}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProjectMembers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProjectMembers()
}

const showAddMemberSidebar = async () => {
  await fetchAllMembers()
  await fetchAllproject()
  selectedMembers.value = []
  showSidebar.value = true
}

const handleClose = (done) => {
  done()
}

const removeSelectedMember = (id) => {
  selectedMembers.value = selectedMembers.value.filter(memberId => memberId !== id)
}
// 格式化日期为 YYYY-MM-DD
const formatDate = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const currentDate = formatDate(new Date());
const handleSubmit = async () => {
  //console.log(selectedMemberNames[0].id+"kkkkkkkk"+selectedMembers.value[0]+"hdbchsdvcgshgfvs")
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请至少选择一个成员')
    return
  }
  console.log(selectedMemberNames.value)
  console.log("qqqqqqqqqqqqqqqqqqqqqqqqqq")
  // 获取当前时间并格式化为 YYYY-MM-DD
  try {
    // 批量添加成员到项目
    for (const member of selectedMemberNames.value) {
      console.log(member)
      console.log(member.code)
      console.log(member.name)
      await add({
        staffId:member.id,
        staffName:member.name,
        code:member.code,
        dept:member.dept,
        type:member.type,
        projectId: props.projectId,
        projectRole: '项目组员',
        updateTime: currentDate,
        operator: userInfos.userInfos.nickname,
      },'i2vsPpJc2Sh')
    }
    ElMessage.success('添加成员成功')
    showSidebar.value = false
    fetchProjectMembers()
  } catch (error) {
    ElMessage.error('添加成员失败')
    console.error(error)
  }
}

const handleCancel = () => {
  selectedMembers.value = []
  showSidebar.value = false
}

onMounted(() => {
  fetchProjectMembers()
  console.log(props.projectId+"youyouyouyou")
})

const equipmentType = ref('company')
const selectedProject = ref('')
// 批量选择相关
const showBatchDialog = ref(false)
const batchInput = ref('')
const showBatchSelect = () => {
  showBatchDialog.value = true
}
const handleBatchClose = (done) => {
  // 可以添加确认逻辑
  done()
}
const clearBatchInput = () => {
  batchInput.value = ''
}

const cancelBatchSelect = () => {
  showBatchDialog.value = false
  clearBatchInput()
}
const confirmBatchSelect = () => {
  const names = batchInput.value.split('\n').filter(name => name.trim())
  // 这里可以添加批量选择的逻辑
  console.log('批量选择的名称:', names)
  showBatchDialog.value = false
  clearBatchInput()
}

const handleProjectChange = (projectId) => {
  console.log(projectId+"kllllgggghhhjjjjsssdd")
  state.queryParams.projectId=projectId
  fetchProjectMembers2()
}
const searchAllStaff=()=>{
  equipmentType.value = 'company'
  fetchAllMembers()
}
</script>

<style scoped>
/* 保持原有的样式不变 */
.member-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  overflow: auto;
  margin-bottom: 20px;
}

.role-tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
}

.role-tag.admin {
  background-color: #13c2c2;
}

.role-tag.member {
  background-color: #1890ff;
}

.role-tag .el-icon {
  margin-left: 5px;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
}

.add-member-container {
  position: relative;
  height: 100%;
  padding-bottom: 60px;
}
.leftdiv {
  float: left;
  margin: 10px;
  width: 45%;
  padding: 10px;
  background-color: #f8f8f8;
}

.rightdiv {
  float: left;
  margin: 10px;
  background-color: #f8f8f8;
  width: 48%;
  padding: 10px;
}

.equipment-type-tabs {
  display: flex;
  margin-bottom: 15px;
}

.equipment-type-tabs .el-button {
  flex: 1;
  border-radius: 0;
}

.equipment-type-tabs .el-button:first-child {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

.equipment-type-tabs .el-button:last-child {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.equipment-type-tabs .el-button.active {
  background-color: #409eff;
  color: white;
}

.search-box {
  margin-bottom: 20px;
}

.content-container {
  display: flex;
  flex: 1;
  gap: 20px;
  overflow: hidden;
}

.member-list {
  flex: 1;
  overflow: auto;
  padding-right: 10px;
}

.member-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.selected-members {
  width: 300px;
  border-left: 1px solid #f0f0f0;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
}

.sync-options {
  margin-bottom: 10px;
}

.sync-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.sync-hint {
  font-size: 12px;
  color: #909399;
  margin-bottom: 15px;
}

.selected-list {
  flex: 1;
  overflow: auto;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.selected-item .el-icon {
  cursor: pointer;
  color: #f56c6c;
}

.fixed-bottom-actions {
  position: fixed;
  right: 20px;
  bottom: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #ebeef5;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
  width: calc(50% - 40px);
}
</style>
