<template>
  <div class="container" >
    <el-row :gutter="20" class="equal-height-row">
      <!-- 左侧设备列表 -->
      <el-col :span="12" class="col-height">
        <div class="card left-card">
          <h3>设备列表</h3>
          <div class="dept-select">
            <el-tree-select
              clearable
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              filterable
              placeholder="请选择设备所属部门"
              @node-click="handleDeptDeviceTreeNodeClick"
            />
          </div>
          <el-scrollbar height="500px">
            <el-checkbox-group v-model="selectedDevices">
              <div
                v-for="device in simpleDevices"
                :key="device.id"
                class="checkbox-item"
              >
                <el-checkbox :label="device.id">
                  {{ device.deviceCode }} ({{ device.deviceName }}) - {{ device.deptName }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-scrollbar>
        </div>
      </el-col>

      <!-- 右侧部门选择 -->
      <el-col :span="12" class="col-height">
        <div class="card right-card">
          <h3>部门列表</h3>
          <ContentWrap class="dept-tree-container" height="400px">
            <DeptTree2 ref="deptTreeRef" v-model="selectedDeptId" height="100%" @update:modelValue="handleDeptChange"/>
          </ContentWrap>
        </div>
      </el-col>
    </el-row>

    <!-- 暂存关联列表 -->
    <div class="submit-area">
      <div class="card">
        <el-input
          v-model="formData.reason"
          placeholder="请输入调拨原因"
          class="reason-input"
          type="textarea"
          :rows="3"
          @input="updateTempRelations"
        />
      </div>
      <el-button
        type="primary"
        size="large"
        @click="submitRelations"
        :disabled="tempRelations.length === 0"
      >
        保 存
      </el-button>
      <div class="temp-list card" v-if="false">
        <h3>设备调拨记录</h3>
        <el-table :data="tempRelations" style="width: 100%">
          <el-table-column prop="deviceNames" label="设备" width="200" />
          <el-table-column prop="deptName" label="部门" />
          <el-table-column prop="deptId" label="部门id" v-if="false"/>
          <el-table-column prop="reason" label="调拨原因" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="danger"
                size="small"
                @click="removeTempRelation(row.deviceId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {defaultProps, handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import {IotDeviceApi, IotDeviceVO} from "@/api/pms/device";
import DeptTree2 from "@/views/pms/device/DeptTree2.vue";

defineOptions({ name: 'ConfigDeviceAllot' })
const selectedDeptId = ref<number | string>('')
const simpleDevices = ref<IotDeviceVO[]>([])
const deptList = ref<Tree[]>([]) // 树形结构
const selectedDevices = ref<number[]>([]) // 改为数组存储多选

const formData = ref({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  model: undefined,
  deptId: undefined as string | undefined,
  deviceStatus: undefined,
  reason: '',
  assetProperty: undefined,
  picUrl: undefined,
})

const queryParams = reactive({
  deptId: formData.value.deptId,
})

const deptTreeRef = ref<InstanceType<typeof DeptTree2>>()

const emit = defineEmits(['success', 'node-click']) // 定义 success 树点击 事件，用于操作成功后的回调

// 响应式数据
const tempRelationsMap = ref(new Map<number, {
  deviceId: number
  deviceNames: string
  deptId: number
  deptName: string
  reason: string
}>())

// 计算属性转换 Map 为数组
const tempRelations = computed(() =>
  Array.from(tempRelationsMap.value.values())
)

const updateTempRelations = () => {
  if (!selectedDeptId.value) {
    // 未选择部门时清除所有关联
    tempRelationsMap.value.clear()
    return
  }

  // 获取部门信息
  const treeNode = deptTreeRef.value?.treeRef?.getNode(selectedDeptId.value)
  const deptName = treeNode?.data?.name || '未知部门'

  // 创建当前应该存在的设备集合
  const currentDeviceIds = new Set(selectedDevices.value)

  // 清理无效关联（包含：1.当前部门外的关联 2.未选中的设备）
  Array.from(tempRelationsMap.value.entries()).forEach(([deviceId, relation]) => {
    if (relation.deptId !== selectedDeptId.value || !currentDeviceIds.has(deviceId)) {
      tempRelationsMap.value.delete(deviceId)
    }
  })

  // 添加/更新当前选中设备的关联
  selectedDevices.value.forEach(deviceId => {
    const device = simpleDevices.value.find(d => d.id === deviceId)
    if (device) {
      tempRelationsMap.value.set(deviceId, {
        deviceId,
        deviceNames: `${device.deviceCode} (${device.deviceName})`,
        deptId: selectedDeptId.value as number,
        deptName,
        reason: formData.value.reason
      })
    }
  })
}

// 添加设备选择监听
watch([selectedDevices, selectedDeptId], () => {
  updateTempRelations();
}, {deep: true, immediate: true, debounce: 100})

// 修改部门变更处理方法
const handleDeptChange = (deptId) => {
  selectedDeptId.value = deptId
  updateTempRelations()
}

/** 处理 部门-设备 树 被点击 */
const handleDeptDeviceTreeNodeClick = async (row: { [key: string]: any }) => {
  emit('node-click', row)
  formData.value.deptId = row.id
  selectedDevices.value = []
  await getDeviceList()
}

/** 获得 部门下的设备 列表 */
const getDeviceList = async () => {
  try {
    const params = { deptId: formData.value.deptId }
    const data = await IotDeviceApi.simpleDevices(params)
    simpleDevices.value = data || []
  } catch (error) {
    simpleDevices.value = []
    console.error('获取设备列表失败:', error)
  }
}

const removeTempRelation = (deviceId: number) => {
  tempRelationsMap.value.delete(deviceId)
  selectedDevices.value = selectedDevices.value.filter(id => id !== deviceId)
};

const submitRelations = async () => {
  try {
    // 转换为后端需要的格式
    const submitData = tempRelations.value.map(r => ({
      deviceId: r.deviceId,
      deptId: r.deptId,
      reason: r.reason
    }))
    await IotDeviceApi.saveDeviceAllot(submitData)
    // 模拟API调用
    console.log('提交数据:', submitData)
    ElMessage.success('提交成功')
    tempRelations.value = []
  } catch (error) {
    ElMessage.error('提交失败，请重试')
  }
}

/** 初始化 */
onMounted(async () => {
  // 初始化部门树 根据选择的部门 查询设备列表 部门人员列表
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  nextTick(() => {
    // 强制重新计算布局
    window.dispatchEvent(new Event('resize'))
  })
})

</script>

<style scoped>
.container {
  padding: 20px;
}

.card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  background: white;
  display: flex;
  flex-direction: column;
  height: 100%; /* 根据实际需要调整整体高度 */
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  transition: box-shadow 0.2s;
}

.card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

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

.dept-select {
  margin-bottom: 20px;
}

.user-list {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.action-bar {
  text-align: right;
}

.temp-list {
  margin-top: 20px;
}

.submit-area {
  margin-top: 5px;
  text-align: center;
}

h3 {
  margin: 0 0 15px 0;
  color: #303133;
}

.dept-select {
  flex-shrink: 0; /* 防止搜索框被压缩 */
}

.el-scrollbar__wrap {
  overflow-x: hidden;
}

.tree-container .el-tree {
  height: 100% !important;
}

/* 左侧滚动区域 */
.el-scrollbar,
.tree-container {
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc transparent;
}

.left-card,
.right-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%; /* 继承父级高度 */
}

.dept-tree-container {
  flex: 1;
  min-height: 0; /* 关键：允许内容区域收缩 */
  position: relative;
  overflow: hidden;
}

/* 调整树形组件内部滚动 */
:deep(.el-tree) {
  height: 100%;
  overflow: auto;
}

.equal-height-row {
  display: flex;
  align-items: stretch; /* 关键：等高布局 */
}

.col-height {
  display: flex;
  flex-direction: column;
  min-height: 400px;/* 统一最小高度 */
}

</style>
