<template>
  <div class="equipment-management">
    <!-- 顶部操作区 -->
    <div class="header">
      <el-button type="primary" @click="showAddEquipmentSidebar">
        <el-icon><Plus /></el-icon>添加无形资产
      </el-button>


      <!-- 底部操作区 -->
      <div class="footer-actions" style="float: right">
        <el-button @click="selectAll" :class="{ 'active': isSelectAll }">选择全部</el-button>
        <el-button @click="reverseSelect">反向选择</el-button>
        <el-button @click="clearSelect">清除选择</el-button>
<!--        <el-button type="primary" plain @click="showBatchSetUsers">批量设置使用人</el-button>-->
<!--        <el-button type="primary" plain @click="showBatchRemoveUsers">批量移除使用人</el-button>-->
<!--        <el-button type="primary" plain @click="showBatchSetFollowStatus">批量设置跟随状态</el-button>-->
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </div>

    </div>

    <!-- 设备表格 -->
    <div class="table-container">
      <el-table
          ref="equipmentTable"
          :data="filteredEquipments"
          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="intangibleName" label="无形资产名称" width="150">
          <template #header="{ column }">
            <div class="filter-header">
              <span>{{ column.label }}</span>
              <el-icon @click.stop="showFilter('name', $event)"><ArrowDown /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assetType" label="类型" width="180">
          <template #header="{ column }">
            <div class="filter-header">
              <span>{{ column.label }}</span>
              <el-icon @click.stop="showFilter('type', $event)"><ArrowDown /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="用途" width="120">
          <template #header="{ column }">
            <div class="filter-header">
              <span>{{ column.label }}</span>
              <el-icon @click.stop="showFilter('purpose', $event)"><ArrowDown /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="users" label="使用人" width="250">
          <template #default="{ row }">

            <div class="manager-tags" v-for="user in state.tabelDataUser" :key="user.userId" style="float: left">
              <template v-if="user.intangibleId===row.intangibleId">
                <span class="name-circle"
                      @click="editUsers(row)"
                      :style="{ backgroundColor: getRandomColor(user.userName) }">
                     {{ user.userName.slice(-2) }}
                </span>
              </template>
            </div>

<!--            <div class="user-tags">-->
<!--              <el-tag-->
<!--                  v-for="(user, index) in row.users"-->
<!--                  :key="index"-->
<!--                  class="user-tag"-->
<!--                  @click="editUsers(row)"-->
<!--              >-->
<!--                {{ user.name }}-->
<!--              </el-tag>-->
<!--            </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="confirmDelete(row.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 筛选弹出框 -->
    <div
        v-if="activeFilter"
        class="filter-popover"
        :style="popoverStyle"
        v-click-outside="closeFilter"
    >
      <template v-if="activeFilter === 'purpose'">
        <el-select
            v-model="filters.purpose"
            placeholder="请选择用途"
            clearable
        >
          <el-option label="公用" value="公用" />
          <el-option label="专用" value="专用" />
        </el-select>
      </template>
      <template v-else-if="activeFilter === 'type'">
        <el-select
            v-model="filters.type"
            placeholder="请选择类型"
            clearable
        >
          <el-option label="非专利技术" value="非专利技术" />
          <el-option label="专利权" value="专利权" />
          <el-option label="软件" value="软件" />
        </el-select>
      </template>
      <template v-else>
        <el-input
            v-model="filters[activeFilter]"
            :placeholder="`请输入${filterLabels[activeFilter]}`"
            clearable
        />
      </template>
      <div class="filter-actions">
        <el-button size="small" type="primary" @click="applyFilter">查询</el-button>
        <el-button size="small" @click="resetFilter">重置</el-button>
      </div>
    </div>

    <!-- 编辑使用人弹出框 -->
    <el-dialog
        v-model="showUserEditDialog"
        title="编辑使用人"
        width="600px"
    >
      <div class="equipment-info">
        <div class="info-item">
          <span class="label">名称/类型</span>
          <span class="value">{{ state.cureentdevice.intangibleId}} / {{ state.cureentdevice.intangibleName }}</span>
        </div>
        <div class="info-item">
          <span class="label">用途</span>
          <span class="value">{{ state.cureentdevice.purpose }}</span>
        </div>
      </div>

      <div class="form-item">
        <span class="label required">使用人</span>
        <div class="user-tags-edit" >
          <!-- 显示已有使用人 -->
          <div v-for="user in state.existingUsers" :key="user.userId" class="user-tag">
            {{ user.userName }}
            <el-icon @click="removeExistingUser(user.id)"><Close /></el-icon>
          </div>

          <!-- 显示新添加的使用人 -->
          <div v-for="(userId, index) in state.newSelectedUsers" :key="'new-'+index" class="user-tag">
            {{ getUserName(userId) }}
            <el-icon @click="removeNewUser(index)"><Close /></el-icon>
          </div>


          <el-select
              v-model="state.tempSelectedUsers"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词搜索用户"
              :remote-method="searchUsers"
              :loading="userLoading"
              style="width: 100%; margin-top: 8px;"
          >
            <el-option
                v-for="user in availableUsers"
                :key="user.id"
                :label="user.name"
                :value="user.id"
            >
              <span>{{ user.name }}</span>
            </el-option>
          </el-select>
        </div>
      </div>

      <div class="form-item">
        <span class="label">已移除使用人</span>
        <el-tooltip
            effect="dark"
            content="不影响已记录的设备工时，在新增工时不显示已移除使用人"
            placement="top"
        >
          <el-icon><InfoFilled /></el-icon>
        </el-tooltip>
      </div>

      <template #footer>
        <el-button @click="showUserEditDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUsers">保存</el-button>
      </template>
    </el-dialog>



    <!-- 分页 -->
    <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="filteredEquipments.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加无形资产侧边栏 -->
    <el-drawer
        v-model="showSidebar"
        title="添加无形资产"
        direction="rtl"
        size="50%"
        :before-close="handleClose"
    >
      <div class="add-equipment-container">
        <div class="leftdiv">
          <div class="equipment-type-tabs">
            <el-button
                :class="{ 'active': equipmentType === 'company' }"
                @click="searchAllDevice"
            >
              企业资产
            </el-button>
            <el-button
                :class="{ 'active': equipmentType === 'project' }"
                @click="equipmentType = 'project'"
            >
              项目资产
            </el-button>
          </div>
          <div v-if="equipmentType === 'project'" class="project-select">
            <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">
            <el-icon><Plus /></el-icon>
            <span>批量添加</span>
          </div>
          <div class="purpose-buttons-container">
            <div class="purpose-buttons" style="font-size: 8px">
              <button
                  v-for="purpose in purposeOptions"
                  :key="purpose.value"
                  :class="{
        'active': state.selectedPurposes.includes(purpose.value),
        'inactive': !state.selectedPurposes.includes(purpose.value)
      }"
                  @click="togglePurpose(purpose.value)"
                  style="width: 60px;height: 28px;"
              >
                {{ purpose.label }}
              </button>
            </div>
          </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">
            <el-checkbox-group v-model="selectedEquipments">
              <div
                  v-if="equipmentType === 'project'"
                  v-for="equipment in filteredEquipmentList"
                  :key="equipment.intangibleId"
                  class="equipment-item"
              >
                <el-checkbox :label="equipment.intangibleId">{{ equipment.intangibleName }}</el-checkbox>
              </div>
              <div
                  v-else
                  v-for="equipment in filteredEquipmentList"
                  :key="equipment.id"
                  class="equipment-item"
              >
                <el-checkbox :label="equipment.id">{{ equipment.name }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>

        <div class="rightdiv">
          <div class="follow-status">
            <span>默认跟随状态：</span>
            <el-select v-model="followStatus" placeholder="请选择">
              <el-option label="不跟随" value="none" />
              <el-option label="跟随使用人" value="user" />
              <el-option label="跟随设备" value="equipment" />
            </el-select>
            <el-tooltip
                effect="dark"
                content="如果采用跟随模式，为了您的使用体验请尽量避免同一个使用人关联超过10个设备。"
                placement="top"
            >
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="follow-hint">
            使用人记录研发工时按照记录工时同步记录使用设备的研发工时。人员工时与设备工时相同。
          </div>

          <div class="selected-list">
            <div
                v-if="equipmentType==='company'"
                v-for="equipment in state.newSelectedEquipment"
                :key="equipment.id"
                class="selected-item"
            >
              <div style="width: 200px">{{ equipment.name }}
                <el-icon @click="removeSelectedEquipment(equipment.id)"><Close /></el-icon>
              </div>
              <div class="user-selector-container">
                <el-select
                    v-model="equipment.selectedUserIds"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词搜索用户"
                    :remote-method="searchUsers"
                    :loading="userLoading"
                    @change="(value)=>{handleUserChange(value,equipment.id)}"
                    style="width: 100%; margin-top: 8px;"
                >
                  <el-option
                      v-for="user in userOptions"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                      :disabled="isUserSelected(equipment, user.id)"
                      :class="{ 'selected-user': isUserSelected(equipment, user.id) }"
                  >
    <span :style="{ color: isUserSelected(equipment, user.id) ? '#409EFF' : 'inherit' }">
      {{ user.name }}
      <el-icon v-if="isUserSelected(equipment, user.id)" style="margin-left: 5px;">
        <Check />
      </el-icon>
    </span>
                  </el-option>
                </el-select>
              </div>
            </div>
            <div
                v-else
                v-for="equipment in state.newSelectedEquipment"
                :key="equipment.intangibleId"
                class="selected-item"
            >
              <div style="width: 200px">{{ equipment.intangibleName }}
                <el-icon @click="removeSelectedEquipment(equipment.intangibleId)"><Close /></el-icon>
              </div>
              <div class="user-selector-container">
                <el-select
                    v-model="equipment.selectedUserIds"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词搜索用户"
                    :remote-method="searchUsers"
                    :loading="userLoading"
                    @change="(value)=>{handleUserChange(value,equipment.id)}"
                    style="width: 100%; margin-top: 8px;"
                >
                  <el-option
                      v-for="user in userOptions"
                      :key="user.id"
                      :label="user.name"
                      :value="user.id"
                      :disabled="isUserSelected(equipment, user.id)"
                      :class="{ 'selected-user': isUserSelected(equipment, user.id) }"
                  >
    <span :style="{ color: isUserSelected(equipment, user.id) ? '#409EFF' : 'inherit' }">
      {{ user.name }}
      <el-icon v-if="isUserSelected(equipment, user.id)" style="margin-left: 5px;">
        <Check />
      </el-icon>
    </span>
                  </el-option>
                </el-select>
              </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="showBatchSetUsersDialog"
        title="批量设置使用人"
        direction="rtl"
        size="50%"
        :before-close="handleBatchClose"
    >
      <div class="batch-set-users-container" style="padding: 20px">
        <div class="search-box">
          <el-input
              v-model="userSearchQuery"
              placeholder="搜索使用人"
              clearable
          >
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>

        <div class="follow-status">
          <span>默认跟随状态：</span>
          <el-select v-model="batchFollowStatus" placeholder="请选择">
            <el-option label="不跟随" value="none" />
            <el-option label="跟随使用人" value="user" />
            <el-option label="跟随设备" value="equipment" />
          </el-select>
        </div>

        <div class="user-list">
          <el-checkbox-group v-model="selectedBatchUsers">
            <div
                v-for="user in filteredUserList"
                :key="user.id"
                class="user-item"
            >
              <el-checkbox :label="user.id">{{ user.name }}</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>

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

    <!-- 批量移除使用人侧边栏 -->
    <el-drawer
        v-model="showBatchRemoveUsersDialog"
        title="批量移除使用人"
        direction="rtl"
        size="50%"
        :before-close="handleBatchClose"
    >
      <div class="batch-remove-users-container"  style="padding: 20px">
        <div class="search-box">
          <el-input
              v-model="userSearchQuery"
              placeholder="搜索使用人"
              clearable
          >
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>

        <div class="user-list">
          <el-checkbox-group v-model="selectedBatchUsers">
            <div
                v-for="user in filteredUserList"
                :key="user.id"
                class="user-item"
            >
              <el-checkbox :label="user.id">{{ user.name }}</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>

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

    <!-- 批量设置跟随状态弹出框 -->
    <el-dialog
        v-model="showBatchSetFollowDialog"
        title="批量设置跟随状态"
        width="600px"
    >
      <div class="follow-options">
        <el-radio-group v-model="batchFollowStatus">
          <el-radio label="none" class="follow-option">
            不跟随
          </el-radio>
          <div class="option-hint">
            使用人记录研发工时不自动记录使用设备研发工时
          </div>
          <el-radio label="user" class="follow-option">
            跟随使用人
          </el-radio>
          <div class="option-hint">
            使用人记录研发工时按照记录工时同步记录使用设备的研发工时。人员工时与设备工时相同。
          </div>
          <el-radio label="equipment" class="follow-option">
            跟随设备
          </el-radio>
          <div class="option-hint">
            使用人记录研发工时按照设备的班次同步记录使用设备的研发工时。人员工时与设备工时可能不同。
          </div>
        </el-radio-group>
      </div>

      <template #footer>
        <el-button @click="showBatchSetFollowDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBatchFollowStatus">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量选择弹出框 -->
    <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,
  ArrowDown,
  Delete,
  Refresh,
  Search,
  Close,
  InfoFilled
} from '@element-plus/icons-vue'
import {add, del, get, update} from "@/api/public/basic";
import {ElMessage, ElMessageBox} from "element-plus";
import {useUserInfosState} from "@/stores/userInfos";
//i2xg3ANLThU
const userInfos = useUserInfosState();
const props = defineProps({
  projectId: {
    type: String,
    required: true
  }
})

const state=reactive({
  cureentdevice: {},
  existingUsers: [], // 已有使用人
  newSelectedUsers: [], // 新选择的使用人
  tempSelectedUsers: [], // 临时选择的使用人



  ids:[],
  newSelectedEquipment:[],
  selectedEquipmentNames:[],
  queryParams: {
    // 页码
    pageNum: 1,
    // 每页大小
    pageSize: 10,
    projectId:'',
  },
  tableDataDevice:[],
  devicetotal:0,
  loading: false,
  projectIdmain:'',

  tabelDataUser:[],
  queryParams: {
    // 页码
    pageNum: 1,
    // 每页大小
    pageSize: 10,
    projectId:'',
  },
  queryParamsUser: {
    // 页码
    pageNum: 1,
    // 每页大小
    pageSize: 10,
    projectId:'',
  },
  deviceOptions:[],
  cureentdevice:{},
  newselectdeviceadduser:[],
  // 其他原有状态...
  selectedPurposes: ['专用', '公用'] // 初始选中所有类型
})
const handleQuery = () => {
  state.queryParams.projectId=state.projectIdmain
  get(state.queryParams, 'i2xg3ANLThU').then((response: any) => {
    state.tableDataDevice= response.data.result;
    state.devicetotal = response.data.count;
    state.loading = false;
    handleQueryuser()
  });
};
const handleQuery2 = () => {
  get(state.queryParams, 'i2xg3ANLThU').then((response: any) => {
    state.deviceOptions= response.data.result;
    //state.devicetotal = response.data.count;
    state.loading = false;
    handleQueryuser()
  });
};
const handleQueryuser = () => {
  state.queryParamsUser.projectId=state.projectIdmain
  get(state.queryParamsUser, 'i2nDoydLem5').then((response: any) => {
    state.tabelDataUser= response.data.result;
    state.loading = false;
  });
};
onMounted(() => {
  state.projectIdmain=props.projectId
  handleQuery()
  handleQueryAll()
  fetchAllproject()
})
//从设备表里面查询所有设备
const handleQueryAll = () => {
  state.queryParams.projectId=''
  get(state.queryParams, 'i2nBeMVze4E').then((response: any) => {
    state.deviceOptions= response.data.result;
    //state.devicetotal = response.data.count;
    state.loading = false;
//    state.queryParamsperson.projectId=state.projectIdmain;
  });
};
const handleQueryAllStaff= () => {
  state.queryParams.projectId=''
  get(state.queryParams, 'i272x8hCGVw').then((response: any) => {
    userOptions.value= response.data.result;
    //state.devicetotal = response.data.count;
    state.loading = false;
//    state.queryParamsperson.projectId=state.projectIdmain;
  });
};
const userOptions = ref([]) // 下拉框选项



const allProject= ref([]) // 所有项目数据（用于添加成员）
const fetchAllproject = async () => {
  try {
    const response = await get({}, 'i1XuaQDK9zw') // 获取所有项目
    allProject.value = response.data.result || []
    console.log(allProject.value.length+"9999990")
  } catch (error) {
    ElMessage.error('获取所有项目失败')
    console.error(error)
  }
}

const getRandomColor = (seed) => {
  // 基于名称生成固定颜色
  let hash = 0;
  for (let i = 0; i < seed.length; i++) {
    hash = seed.charCodeAt(i) + ((hash << 5) - hash);
  }

  const h = hash % 360;
  return `hsl(${h}, 70%, 65%)`;
};

const selectedUserIds = ref([]) // 选中的用户ID
const userLoading = ref(false) // 加载状态
// const handleUserChange = (selectedIds,equipmentId) => {
//
//   console.log(selectedIds)
//   console.log(1111111111111111111111111111)
//   // 原用户
//   const orginUser = state.selectedEquipmentNames.filter(item=>item.id==equipmentId) ||[]
//   // 找出新增的用户
//   const newSelectedUsers = selectedIds
//       .map(id => userOptions.value.find(user => user.id === id))
//       .filter(user => !orginUser.some(u => u.id === user.id))
//
//   // 找出被移除的用户
//   const removedUserIds = orginUser
//       .filter(user => !selectedIds.includes(user.id))
//       .map(user => user.id)
//
//   // 更新选中用户列表
//   state.selectedEquipmentNames.forEach(item=>{
//     if(item.id ==equipmentId){
//       item.selectedUsers = newSelectedUsers
//       //item.selectedUsers?.filter(user => selectedIds.includes(user.id))
//       //  .concat(newSelectedUsers)
//       console.log(item.selectedUsers)
//       console.log(newSelectedUsers)
//       console.log("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk")
//     }
//   })
//   state.newSelectedEquipment = [...state.selectedEquipmentNames]
//   console.log(state.newSelectedEquipment)
// }



const handleUserChange = (selectedIds, equipmentId) => {
  // 找出当前设备
  const equipment = state.newSelectedEquipment.find(item => item.id === equipmentId)
  if (!equipment) return

  // 过滤掉已存在的用户
  const newUserIds = selectedIds.filter(id =>
      !equipment.selectedUsers?.some(user => user.id === id)
  )

  // 找出新增的用户
  const newSelectedUsers = newUserIds
      .map(id => userOptions.value.find(user => user.id === id))
      .filter(Boolean)

  // 更新选中用户列表
  equipment.selectedUsers = [
    ...(equipment.selectedUsers || []),
    ...newSelectedUsers
  ]

  // 更新selectedUserIds
  equipment.selectedUserIds = selectedIds
}


const isUserSelected = (equipment, userId) => {
  return equipment.selectedUsers?.some(user => user.id === userId) || false
}
const isUserSelected2 = (device, userId) => {
  return device.users?.some(user => user.userId === userId) ||
      state.newselectdeviceadduser.includes(userId);
};
const removeSelectedUser = (userId, index) => {
  state.newselectdeviceadduser.splice(index, 1);
  deldeviceanduser()
};
const searchUsers = (query) => {
  handleQueryAllStaff()
}

const deldeviceanduser = (row)=>{
  ElMessageBox({
    message: '是否确认删除的数据项?',
    title: '警告',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(function () {
  console.log(row.id+"LLlllll")
  const ids = row['id'] ? [row['id']] : state.ids;
  del({ ['id']: ids }, 'i2nDoydLem5').then(() => {
    handleQuery(); // 刷新数据
    handleQueryAllStaff();
  }).catch(error => {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  });
  });
}
const formcombined=reactive({})
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的无形资产')
    return
  }
  const idsToDelete = selectedRows.value.map(row => row.id)
  for (const id of idsToDelete) {
    // console.log('建筑物名称:', equipment.name);
    console.log('无形资产 ID:', id);
    formcombined.projectId = '';
    try {
      ElMessageBox.confirm(
          '确定要删除记录吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
      update(id, formcombined, 'i2xg3ANLThU').then((response) => {
        //ElMessage.success('删除成功');
        handleQuery(); // 刷新数据
        handleQueryAllStaff();
        state.loading = false;
      });
          })
          .catch(() => {
            // 用户点击了取消
            ElMessage.info('已取消删除')
          })
    } catch (error) {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }
  // handleQuery(); // 刷新数据
  // handleQueryAllStaff();
  clearSelect()
  ElMessage.success('批量删除成功')
//  clearSelect()
}

const deleteEquipment = (id) => {
  try{
    console.log(id+"aaaaaaaaaaa")
    formcombined.projectId='';
    update(id, formcombined, 'i2xg3ANLThU').then((response) => {
      ElMessage.success('删除成功');
      state.loading = false;
      handleQuery(); // 刷新数据
      handleQueryAllStaff();
    });
  }catch (error) {
    ElMessage.error('删除失败');
    console.error(error);
  }
  // equipments.value = equipments.value.filter(equipment => equipment.id !== id)
  //ElMessage.success('删除成功')
}
const confirmDelete = (id) => {
  ElMessageBox.confirm(
      '确定要删除记录吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 用户点击了确定，执行删除操作
        deleteEquipment(id)
      })
      .catch(() => {
        // 用户点击了取消
        ElMessage.info('已取消删除')
      })
}











const vClickOutside = {
  mounted(el, binding) {
    el.clickOutsideEvent = function(event) {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value()
      }
    }
    document.addEventListener('click', el.clickOutsideEvent)
  },
  unmounted(el) {
    document.removeEventListener('click', el.clickOutsideEvent)
  }
}

// 表格数据
// const equipments = ref([
//   { id: '1', code: 'DMDS生产工艺', type: '非专利技术', purpose: '专用',
//     users: [{ id: 'u1', name: '张三' }, { id: 'u2', name: '李四' }], updateTime: '2023-05-10 14:30', operator: '管理员' },
//   { id: '2', code: 'DMS醚化技术', type: '专利权', purpose: '公用',
//     users: [{ id: 'u3', name: '王五' }], updateTime: '2023-05-09 10:15', operator: '管理员' },
//   { id: '3', code: '精馏控制系统', type: '软件', purpose: '专用',
//     users: [{ id: 'u4', name: '赵六' }, { id: 'u5', name: '钱七' }], updateTime: '2023-05-08 16:45', operator: '管理员' },
//   { id: '4', code: '热能利用技术', type: '非专利技术', purpose: '公用',
//     users: [{ id: 'u6', name: '孙八' }], updateTime: '2023-05-07 09:20', operator: '管理员' },
//   { id: '5', code: '尾气回收系统', type: '专利权', purpose: '专用',
//     users: [{ id: 'u7', name: '周九' }, { id: 'u8', name: '吴十' }], updateTime: '2023-05-06 11:30', operator: '管理员' },
//   { id: '6', code: '原料预处理技术', type: '非专利技术', purpose: '公用',
//     users: [{ id: 'u1', name: '张三' }, { id: 'u9', name: '郑十一' }], updateTime: '2023-05-05 13:25', operator: '管理员' },
//   { id: '7', code: '蒸馏塔控制软件', type: '软件', purpose: '专用',
//     users: [{ id: 'u10', name: '王十二' }], updateTime: '2023-05-04 15:10', operator: '管理员' },
//   { id: '8', code: '碱洗工艺技术', type: '非专利技术', purpose: '专用',
//     users: [{ id: 'u2', name: '李四' }, { id: 'u3', name: '王五' }], updateTime: '2023-05-03 17:50', operator: '管理员' }
// ])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
//const totalEquipments = computed(() => equipments.value.length)

// 筛选相关
const activeFilter = ref('')
const popoverStyle = ref({})
const filters = ref({
  name: '',
  type: '',
  purpose: ''
})

const filterLabels = {
  name: '无形资产名称',
  type: '类型',
  purpose: '用途'
}

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

// 编辑使用人相关
const showUserEditDialog = ref(false)
const currentEquipment = ref({})
const currentEquipmentIndex = ref(-1)

// 添加设备侧边栏相关
const showSidebar = ref(false)
const equipmentType = ref('company')
const selectedProject = ref('')
const selectedPurpose = ref('')
const searchQuery = ref('')
const selectedEquipments = ref([])
const followStatus = ref('none')
const purposeOptions = ref([
  { label: '专用', value: '专用' },
  { label: '公用', value: '公用' },
])


// 批量操作相关
const showBatchSetUsersDialog = ref(false)
const showBatchRemoveUsersDialog = ref(false)
const showBatchSetFollowDialog = ref(false)
const batchFollowStatus = ref('none')
const userSearchQuery = ref('')
const selectedBatchUsers = ref([])

// 批量选择相关
const showBatchDialog = ref(false)
const batchInput = ref('')
// 项目选项
const projectOptions = ref([{},])

// 部门树和用户数据
const departmentTree = ref([
  {
    id: 'dept1',
    label: '技术部门',
    children: [
      { id: 'u1', label: '张三' },
      { id: 'u2', label: '李四' }
    ]
  },
  {
    id: 'dept2',
    label: '研发中心',
    children: [
      { id: 'u3', label: '王五' },
      { id: 'u4', label: '赵六' },
      { id: 'u5', label: '钱七' }
    ]
  },
  {
    id: 'dept3',
    label: '质检部',
    children: [
      { id: 'u6', label: '孙八' },
      { id: 'u7', label: '周九' }
    ]
  }
])


const allUsers = computed(() => {
  const users = []
  const traverse = (nodes) => {
    nodes.forEach(node => {
      if (!node.children) {
        users.push({ id: node.id, name: node.label })
      } else {
        traverse(node.children)
      }
    })
  }
  traverse(departmentTree.value)
  return users
})

// 计算属性
const filteredEquipments = computed(() => {
  let result = state.tableDataDevice
      //[...equipments.value]

  // 设备编号筛选
  if (filters.value.name) {
    result = result.filter(equipment =>
        equipment.name.includes(filters.value.name))
  }

  // 类型筛选
  if (filters.value.type) {
    result = result.filter(equipment =>
        equipment.assetType === filters.value.type)
  }

  // 用途筛选
  if (filters.value.purpose) {
    result = result.filter(equipment =>
        equipment.purpose === filters.value.purpose)
  }

  return result
})

const filteredEquipmentList = computed(() => {
  const projectDeviceIds = state.tableDataDevice.map(device => device.intangibleId);
  // let result = state.deviceOptions.filter(device =>
  //     !projectDeviceIds.includes(device.id)
  // );
  let result=state.deviceOptions;
  if(equipmentType.value==='project')
  {
    result = state.deviceOptions.filter(device => {
      const isIncluded = projectDeviceIds.includes(device.intangibleId)
      return !isIncluded
    });
  }else{
    result = state.deviceOptions.filter(device => {
      const isIncluded = projectDeviceIds.includes(device.id)
      return !isIncluded
    });
  }
  // 用途筛选
  if (state.selectedPurposes.length > 0) {
    result = result.filter(equipment =>
        state.selectedPurposes.includes(equipment.purpose)
    );
  }
  // // 用途筛选
  // if (selectedPurpose.value) {
  //   result = result.filter(equipment => equipment.purpose === selectedPurpose.value)
  // }

  // 搜索筛选
  if (searchQuery.value) {
    result = result.filter(equipment =>
        equipment.name.includes(searchQuery.value))
  }

  return result
})

const selectedEquipmentNames = computed(() => {
  return filteredEquipmentList.value.filter(equipment =>
      selectedEquipments.value.includes(equipment.id))
})

const filteredUserList = computed(() => {
  let result = [...userOptions.value]

  // 搜索筛选
  if (userSearchQuery.value) {
    result = result.filter(user =>
        user.name.includes(userSearchQuery.value))
  }

  return result
})

// 方法
const showFilter = (type, event) => {
  activeFilter.value = type
  if (event) {
    const rect = event.target.getBoundingClientRect()
    popoverStyle.value = {
      top: `${rect.bottom + window.scrollY - 85}px`,
      left: `${rect.left + window.scrollX-325}px`
    }
  }
}

const closeFilter = () => {
  activeFilter.value = ''
}

const applyFilter = () => {
  // 筛选逻辑已经在 computed 中处理
  closeFilter()
}

const resetFilter = () => {
  filters.value = {
    code: '',
    type: '',
    purpose: ''
  }
  closeFilter()
}

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

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

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

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

// const batchDelete = () => {
//   if (selectedRows.value.length === 0) {
//     ElMessage.warning('请先选择要删除的设备')
//     return
//   }
//
//   const idsToDelete = selectedRows.value.map(row => row.id)
//   equipments.value = equipments.value.filter(equipment => !idsToDelete.includes(equipment.id))
//   ElMessage.success('批量删除成功')
//   clearSelect()
// }

// const deleteEquipment = (id) => {
//   equipments.value = equipments.value.filter(equipment => equipment.id !== id)
//   ElMessage.success('删除成功')
// }
const editUsers = (row) => {
  state.cureentdevice = row
  // 获取当前设备已有的使用人
  state.existingUsers = state.tabelDataUser
      .filter(user => user.deviceId === row.deviceId)
  state.newSelectedUsers = []
  state.tempSelectedUsers = []
  showUserEditDialog.value = true
}
// 移除已有使用人
const removeExistingUser = async (userId) => {

  ElMessageBox.confirm('确定要删除该成员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 这里可以调用API从服务器删除关联
    console.log(userId+"：：：：要删除的userID")
    await del({ id: [userId] }, 'i2nDoydLem5').then(() => {
      state.existingUsers = state.existingUsers.filter(u => u.id !== userId)
      ElMessage.success('已移除使用人')
    })
  }).catch(() => {
    ElMessage.error('删除失败')
    console.error(error)
  })
  handleQuery()
}
// 移除新添加的使用人
const removeNewUser = (index) => {
  state.newSelectedUsers.splice(index, 1)
}
// 获取可选择的用户（排除已存在的）
const availableUsers = computed(() => {
  return userOptions.value.filter(user =>
      !state.existingUsers.some(u => u.userId === user.id) &&
      !state.newSelectedUsers.includes(user.id)
  )
})
// 获取用户名
const getUserName = (userId) => {
  const user = userOptions.value.find(u => u.id === userId)
  return user ? user.name : ''
}















const removeUser = (index) => {
  currentEquipment.value.users.splice(index, 1)
}

const showBatchSelect = () => {
  showBatchDialog.value = true
}

const clearBatchInput = () => {
  batchInput.value = ''
}

const cancelBatchSelect = () => {
  showBatchDialog.value = false
  clearBatchInput()
}

const updateBatchPreview = () => {
  // 输入内容自动在预览区显示
}


const confirmBatchSelect = () => {
  const names = batchInput.value.split('\n')
      .filter(name => name.trim())
      .map(name => name.trim().toLowerCase());

  filteredEquipmentList.value.forEach(equipment => {
    const equipmentName = (equipmentType.value === 'project'
        ? equipment.intangibleName
        : equipment.name).toLowerCase();

    // 模糊匹配：设备名称包含输入的关键词
    if (names.some(name => equipmentName.includes(name))) {
      const id = equipmentType.value === 'project'
          ? equipment.intangibleId
          : equipment.id;
      selectedEquipments.value.push(id);
    }
  });
  showBatchDialog.value=false
  console.log(selectedEquipments.value)
  console.log("888888888888888")
  if(equipmentType.value==='project') {
    state.selectedEquipmentNames =filteredEquipmentList.value.filter(equipment =>
        Object.values(selectedEquipments.value).includes(equipment.intangibleId))
    console.log("4333333", state.selectedEquipmentNames)
  }else{
    state.selectedEquipmentNames =filteredEquipmentList.value.filter(equipment =>
        Object.values(selectedEquipments.value).includes(equipment.id))
    console.log("43534", state.selectedEquipmentNames)
  }
  state.newSelectedEquipment =[... state.selectedEquipmentNames]
};
const handleBatchClose = (done) => {
  // 可以添加确认逻辑
  done()
}



const showAddEquipmentSidebar = () => {
  showSidebar.value = true
}

const handleClose = (done) => {
  // 可以添加确认逻辑
  done()
}

const removeSelectedEquipment = (id) => {
  selectedEquipments.value = selectedEquipments.value.filter(equipmentId => equipmentId !== id)
}

const handleUserCheck = (data, checked) => {
  // 处理用户选择
  showUserSelector.value = !showUserSelector.value
  console.log(data, checked)
}

// const togglePurpose = (purpose) => {
//   selectedPurpose.value = selectedPurpose.value === purpose ? '' : purpose
// }
const togglePurpose = (purpose) => {
  // 判断当前用途是否已选中
  const isSelected = state.selectedPurposes.includes(purpose);

  if (isSelected) {
    // 移除选中状态
    state.selectedPurposes = state.selectedPurposes.filter(p => p !== purpose);
  } else {
    // 添加选中状态
    state.selectedPurposes.push(purpose);
  }
};
const showBatchSetUsers = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要设置使用人的设备')
    return
  }
  showBatchSetUsersDialog.value = true
}

const showBatchRemoveUsers = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要移除使用人的设备')
    return
  }
  showBatchRemoveUsersDialog.value = true
}

const showBatchSetFollowStatus = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要设置跟随状态的设备')
    return
  }
  showBatchSetFollowDialog.value = true
}

const saveBatchUsers = () => {
  // 批量设置使用人逻辑
  ElMessage.success('批量设置使用人成功')
  showBatchSetUsersDialog.value = false
}

const removeBatchUsers = () => {
  // 批量移除使用人逻辑
  ElMessage.success('批量移除使用人成功')
  showBatchRemoveUsersDialog.value = false
}

const saveBatchFollowStatus = () => {
  // 批量设置跟随状态逻辑
  ElMessage.success('批量设置跟随状态成功')
  showBatchSetFollowDialog.value = false
}

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


function getCurrentDateTime() {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(now.getDate()).padStart(2, '0'); // 日期补零
  const hours = String(now.getHours()).padStart(2, '0'); // 小时补零
  const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟补零
  const seconds = String(now.getSeconds()).padStart(2, '0'); // 秒补零

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const formprojectdevice=reactive({})
const formDeviceUser = reactive({})
const formadduser = reactive({})

//编辑使用人
const saveUsers = async () => {

  for(const id of state.tempSelectedUsers)
  {
    console.log(id)
    formDeviceUser.projectId=state.projectIdmain;
    formDeviceUser.intangibleId=state.cureentdevice.intangibleId
    formDeviceUser.intangibleName=state.cureentdevice.intangibleName
    const user = userOptions.value.find(u => u.id === id);
    formDeviceUser.userId = user.id;
    formDeviceUser.userName = user.name;
    formDeviceUser.role = user.projectRole;
    formDeviceUser.dept = user.dept;
    await add(formDeviceUser, 'i2nDoydLem5');

  }
  console.log(state.cureentdevice.id)
  const updateTime = getCurrentDateTime();
  await update(state.cureentdevice.id,{updateTime}, 'i2xg3ANLThU');
  handleQuery()
  showUserEditDialog.value = false
  ElMessage.success('保存成功')
}
const handleUserChange2=(value,device)=>{
  console.log(value)
  console.log(device.id)
  formadduser.intangibleId=device.id;
  formadduser.intangibleName=device.name;
}
//添加无形资产
const handleSubmit = async () => {
  if (selectedEquipments.value.length === 0) {
    ElMessage.warning('请至少选择一个设备')
    return
  }
  formprojectdevice.projectId=state.projectIdmain;
  //formprojectdevice.hasUser=1;
  formDeviceUser.projectId=state.projectIdmain;

  for (const equipment of state.newSelectedEquipment) {

    if(equipmentType.value==='project') {

      formprojectdevice.intangibleId=equipment.intangibleId
      formprojectdevice.intangibleName=equipment.intangibleName
      console.log('设备名称project:', equipment.intangibleName);
      console.log('设备 IDproject:', equipment.intangibleId);
      console.log('选中用户列表:');

      formDeviceUser.intangibleId=equipment.intangibleId
      formDeviceUser.intangibleName=equipment.intangibleName
    }else {
      formprojectdevice.intangibleId=equipment.id
      formprojectdevice.intangibleName=equipment.name
      console.log('设备名称:', equipment.name);
      console.log('设备 ID:', equipment.id);
      console.log('选中用户列表:');
      formDeviceUser.intangibleId=equipment.id
      formDeviceUser.intangibleName=equipment.name
    }
    formprojectdevice.code=equipment.code
    formprojectdevice.spec=equipment.spec
    formprojectdevice.purpose=equipment.purpose
    formprojectdevice.assetType=equipment.assetType
    formprojectdevice.followStatus=followStatus.value
    // formprojectdevice.deviceId=equipment.id
    // formprojectdevice.deviceName=equipment.name
    //formprojectdevice.updateTime=new Date().toISOString().split('T')[0]
    formprojectdevice.updateTime = getCurrentDateTime();
    formprojectdevice.operator=userInfos.userInfos.nickname

    await Promise.all(equipment.selectedUsers.map(async (user) => {
      console.log('用户 ID:', user.id, '用户姓名:', user.name);
      formDeviceUser.userId = user.id;
      formDeviceUser.userName = user.name;
      formDeviceUser.role = user.projectRole;
      formDeviceUser.dept = user.dept;
      try {
        await add(formDeviceUser, 'i2nDoydLem5');
      } catch (error) {
        ElMessage.error('添加成员失败');
        console.error(error);
      }
    }));//i2nDoydLem5
    await add(formprojectdevice, 'i2xg3ANLThU');
  }
  ElMessage.success('添加成功');
  handleQuery()
  state.loading = false;
  showSidebar.value = false
}

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

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

// 控制部门树显示
const showUserSelector = ref(false)

// 已选择的人员
const selectedUsers = ref([])
const handleProjectChange = (projectId) => {
  console.log(projectId+"kllllgggghhhjjjjsssdd")
  state.queryParams.projectId=projectId
  handleQuery2()
  //fetchProjectMembers2()
}
const searchAllDevice=()=>{
  equipmentType.value = 'company'
  handleQueryAll()
}
watch(()=>selectedEquipments.value,()=>{
  console.log(selectedEquipments.value)
  console.log("888888888888888")
  if(equipmentType.value==='project') {
    state.selectedEquipmentNames =filteredEquipmentList.value.filter(equipment =>
        Object.values(selectedEquipments.value).includes(equipment.intangibleId))
    console.log("4333333", state.selectedEquipmentNames)
  }else{
    state.selectedEquipmentNames =filteredEquipmentList.value.filter(equipment =>
        Object.values(selectedEquipments.value).includes(equipment.id))
    console.log("43534", state.selectedEquipmentNames)
  }
  state.newSelectedEquipment =[... state.selectedEquipmentNames]
})
</script>

<style scoped>
.equipment-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  margin-bottom: 20px;
}

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

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.filter-header .el-icon {
  cursor: pointer;
  margin-left: 5px;
}

.filter-popover {
  position: absolute;
  z-index: 2000;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  min-width: 200px;
}

.filter-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.user-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.user-tag {
  cursor: pointer;
  border-radius: 15px;
}

.footer-actions {
  margin-bottom: 20px;
}

.footer-actions .el-button {
  margin-right: 10px;
}

.footer-actions .el-button:not(.active):not(.el-button--danger) {
  border-color: #dcdfe6;
  color: #606266;
}

.footer-actions .el-button.active {
  border-color: #409eff;
  color: #409eff;
}

.footer-actions .el-button:hover:not(.active):not(.el-button--danger) {
  border-color: #409eff;
  color: #409eff;
}

.footer-actions .el-button--primary.is-plain {
  border-color: #409eff;
  color: #409eff;
}

.footer-actions .el-button--primary.is-plain:hover {
  background-color: #409eff;
  color: white;
}

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

.add-equipment-container {
  height: 100%;
  display: flex;
  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;
}
.add-equipment-container {
  height: 100%;
  display: flex;
  padding-bottom: 60px;
}
.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;
}
.purpose-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.purpose-buttons .el-button {
  flex: 1;
  min-width: 80px;
}

.purpose-buttons .el-button.active {
  background-color: #e6a23c;
  color: white;
}

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

.content-container {
  background-color: white;
  padding: 10px;
  height: calc(100% - 150px);
  overflow: auto;
}

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

.follow-status {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.follow-status .el-select {
  margin: 0 10px;
}

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

.selected-list {
  background-color: white;
  padding: 10px;
  margin-bottom: 15px;
  max-height: 700px;
}

.selected-item {

  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

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

.user-selector {
  background-color: white;
  padding: 10px;
  height: calc(100% - 300px);
  overflow: auto;
}

.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);
}

.add-equipment-container::after {
  content: "";
  display: table;
  clear: both;
}

.batch-set-users-container,
.batch-remove-users-container {
  height: 100%;
  padding-bottom: 60px;
}

.user-list {
  height: calc(100% - 100px);
  overflow: auto;
  padding: 10px;
  background-color: white;
}

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

.equipment-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
}

.label {
  display: inline-block;
  width: 100px;
  color: #606266;
}

.required::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.value {
  color: #303133;
}

.user-tags-edit {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  padding: 5px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 40px;
}

.follow-options {
  padding: 10px;
}

.follow-option {
  display: block;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;

}

.follow-option:hover {
  border-color: #409eff;
}

.option-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.option-hint {
  font-size: 12px;
  color: #909399;
}
.non-exist-hint {
  background-color: #fffbe6;
  padding: 10px;
  margin-bottom: 15px;
  font-weight: bold;
  color: #d48806;
}

.batch-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.purpose-buttons-container {
  margin-bottom: 20px;
}

.purpose-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.purpose-buttons .el-button {
  padding: 8px 12px;
  font-size: 12px;
}

.purpose-buttons .el-button.active {
  background-color: #ffd700; /* 黄色背景 */
  border-color: #d4b000; /* 深黄色边框 */
  color: white;
}

.purpose-buttons .el-button.inactive {
  background-color: #f5f5f5; /* 灰色背景 */
  border-color: #d9d9d9; /* 灰色边框 */
  color: #606266;
}

.purpose-buttons .el-button {
  /* 基础样式 */
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.active {
  background-color: #ffd700; /* 黄色背景 */
  border-color: #d4b000; /* 深黄色边框 */
  color: white;
  box-shadow: 0 0 4px rgba(255, 215, 0, 0.3);
}

.inactive {
  background-color: #f5f5f5; /* 浅灰色背景 */
  border-color: #d9d9d9; /* 灰色边框 */
  color: #606266;
}

.active:hover, .inactive:hover {
  transform: scale(1.02);
}
.equipment-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
}

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

.equipment-item:last-child {
  border-bottom: none;
}
.batch-add {
  display: flex;
  align-items: center;
  padding: 8px 0;
  margin-bottom: 15px;
  color: #606266;
  border-bottom: 1px dashed #dcdfe6;
  cursor: pointer;
}

.batch-add .el-icon {
  margin-right: 5px;
}

.batch-add:hover {
  color: #409eff;
}
.selected-list-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
}

.selected-item {

  align-items: center;
  padding: 8px;
  margin-bottom: 5px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

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

.user-selector-container {
  border: 1px dashed #8c939d;
  padding: 10px;
  cursor: pointer;
  min-height: 40px;
  position: relative;
}

.user-selector-container.active {
  border-color: #409eff;
}

.selected-user-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.user-tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  background-color: #f0f0f0;
  border-radius: 15px;
  font-size: 12px;
}

.user-tag .el-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
  cursor: pointer;
}

.user-tag .el-icon:hover {
  color: #f56c6c;
}

.department-tree-wrapper {
  position: absolute;
  left: 0;
  top: 100%;
  width: 100%;
  background-color: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 100000;
  padding: 10px;
  margin-top: 5px;
  max-height: 300px;
  overflow-y: auto;
}
.name-circle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  color: white;
  margin-right: 10px;
  font-size: 12px;
}
</style>
