<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>{{ t('configPerson.deviceList') }}</h3>
          <div class="dept-select">
            <el-tree-select
              clearable
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              filterable
              :placeholder="t('configPerson.deviceListHolder')"
              @node-click="handleDeptDeviceTreeNodeClick"
            />
          </div>

          <!-- 设备搜索框 -->
          <div class="filter-input">
            <el-input
              v-model="deviceFilterText"
              :placeholder="t('devicePerson.filterDevicePlaceholder')"
              :disabled="!devicesLoaded"
              clearable
              prefix-icon="Search"
            />
          </div>

          <el-scrollbar height="500px">
            <el-checkbox-group v-model="selectedDevices">
              <div
                v-for="device in filteredDevices"
                :key="device.id"
                class="checkbox-item"
              >
                <el-checkbox :label="device.id">
                  {{ device.deviceCode }} ({{ device.deviceName }}) - {{ device.deptName }} —— {{ device.devicePersons }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-scrollbar>
        </div>
      </el-col>

      <!-- 右侧部门选择 -->
      <el-col :span="12" class="col-height">
        <div class="card right-card">
          <h3>{{ t('configDevice.deptList') }}</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 selection-area">
        <div class="control-row">
          <!-- 左侧人员选择 -->
          <div class="control-group">
            <label class="control-title">{{ t('devicePerson.rp') }}</label>
            <div class="person-selector">
              <el-select
                v-model="selectedPersons"
                multiple
                filterable
                :placeholder="t('configPerson.selectPersons')"
                style="width: 100%"
              >
                <el-option
                  v-for="person in simpleUsers"
                  :key="person.id"
                  :label="person.nickname"
                  :value="person.id"
                />
              </el-select>
            </div>
          </div>

          <div class="control-group">
            <label class="control-title">{{ t('configDevice.reasonForAdjustment') }}<span class="required-star">*</span></label>
            <div class="reason-input-wrapper">
              <el-input
                v-model="formData.reason"
                :placeholder="t('configDevice.rfaHolder')"
                class="reason-input"
                type="textarea"
                :rows="4"
                resize="none"
                @input="updateTempRelations"
              />
            </div>
          </div>
        </div>
      </div>

      <div class="temp-list card" v-if="true">
        <h3>{{ t('configPerson.adjustmentRecords') }}</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>

      <el-button
        type="primary"
        size="large"
        style="min-width: 180px;"
        @click="submitRelations"
        :disabled="tempRelations.length === 0 || !formData.reason.trim()"
      >
        {{ t('iotMaintain.save') }}
      </el-button>

    </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 * as UserApi from "@/api/system/user";
import {IotDeviceApi, IotDeviceVO} from "@/api/pms/device";
import DeptTree2 from "@/views/pms/device/DeptTree2.vue";
import { useRouter } from 'vue-router'
import { useTagsViewStore } from "@/store/modules/tagsView";
import {UserVO} from "@/api/system/user";

const router = useRouter()
const { t } = useI18n() // 国际化
defineOptions({ name: 'ConfigDeviceAllot' })
const selectedDeptId = ref<number | string>('')
const simpleDevices = ref<IotDeviceVO[]>([])
const deptList = ref<Tree[]>([]) // 树形结构
const selectedDevices = ref<number[]>([]) // 改为数组存储多选
const { delView } = useTagsViewStore() // 视图操作
// 设备加载状态标记 只有加载完设备才能通过文本框筛选
const devicesLoaded = ref(false)

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 simpleUsers = ref<UserVO[]>([])     // 人员下拉列表选项
const selectedPersons = ref<number[]>([]) // 存储选中的人员ID

// 响应式数据
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})

// 监听部门变化
watch(selectedDeptId, (newVal) => {
  if (newVal) {
    loadDeptPersons(newVal as number)
  } else {
    simpleUsers.value = []
  }
  selectedPersons.value = [] // 切换部门时清空已选人员
})

// 修改部门变更处理方法
const handleDeptChange = (deptId) => {
  if (!deptId) {
    selectedDeptId.value = ''
    return
  }
  // 校验部门选择
  if (!validateDeptSelection(deptId)) {
    // 重置部门选择
    selectedDeptId.value = ''
    deptTreeRef.value?.treeRef?.setCurrentKey(undefined) // 清除树的选择状态
    deptTreeRef.value?.treeRef?.setCurrentNode(undefined)
    return
  }
  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 {
    // 查询到数据后才能进行搜索 筛选
    devicesLoaded.value = false

    const params = { deptId: formData.value.deptId }
    const data = await IotDeviceApi.simpleDevices(params)
    simpleDevices.value = data || []

    devicesLoaded.value = true
  } catch (error) {
    simpleDevices.value = []
    // 即使失败也启用搜索框（避免卡在禁用状态）
    devicesLoaded.value = true
    console.error('获取设备列表失败:', error)
  }
}

// 选择部门后 加载部门人员
const loadDeptPersons = async (deptId: number) => {
  if (!deptId) {
    simpleUsers.value = []
    return
  }
  try {
    // 调用API获取部门人员
    const params = { deptId: deptId, pageNo: 1, pageSize: 10 }
    const data = await UserApi.simpleUserList(params)
    simpleUsers.value = data.map(user => ({
      id: user.id,
      nickname: user.nickname || user.username
    }))
  } catch (error) {
    console.error('获取部门人员失败:', error)
    simpleUsers.value = []
  }
}

// 计算选中的设备原部门集合
const originDeptIds = computed(() =>
  selectedDevices.value
    .map(deviceId =>
      simpleDevices.value.find(d => d.id === deviceId)?.deptId
    )
    .filter(Boolean) as number[]
)

// 部门选择校验方法
const validateDeptSelection = (deptId: number) => {
  if (originDeptIds.value.includes(deptId)) {
    ElMessage.error('不能选择设备原属部门作为调拨部门')
    return false
  }
  return true
}

// 设备过滤文本
const deviceFilterText = ref('')

// 计算属性：过滤设备列表
const filteredDevices = computed(() => {
  const searchText = deviceFilterText.value.toLowerCase().trim()
  if (!searchText) return simpleDevices.value

  return simpleDevices.value.filter(device => {
    return (
      (device.deviceCode || '').toLowerCase().includes(searchText) ||
      (device.deviceName || '').toLowerCase().includes(searchText)
    )
  })
})

// 在计算属性区域添加 selectedPersonNames
const selectedPersonNames = computed(() => {
  return selectedPersons.value.map(id => {
    const user = simpleUsers.value.find(u => u.id === id)
    return user?.nickname || ''
  }).filter(Boolean) // 过滤掉空值
})

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

const submitRelations = async () => {
  try {
    // 提交前二次校验
    const invalidDept = tempRelations.value.some(r =>
      originDeptIds.value.includes(r.deptId)
    )
    if (invalidDept) {
      ElMessage.error('存在调拨部门与设备原属部门相同的情况，请检查')
      return
    }
    // 转换为后端需要的格式
    const submitData = tempRelations.value.map(r => ({
      deviceId: r.deviceId,
      deptId: r.deptId,
      reason: r.reason,
      personIds: selectedPersons.value || [], // 添加人员ID列表
      personNames: [...selectedPersonNames.value]
    }))
    await IotDeviceApi.saveDeviceAllot(submitData)
    // 模拟API调用
    console.log('提交数据:', submitData)
    ElMessage.success('提交成功')
    tempRelations.value = []
    delView(unref(router.currentRoute.value))
    router.back()
  } catch (error) {
    ElMessage.error('提交失败，请重试')
  }
}

/** 初始化 */
onMounted(async () => {
  try {
    // 初始化部门树
    const deptData = await DeptApi.getSimpleDeptList()
    deptList.value = handleTree(deptData) // 转换为树形结构

    // 设置默认选中的部门（转换后树的第一个节点）
    if (deptList.value.length > 0) {
      // 获取转换后树的第一个节点
      const firstRootNode = deptList.value[0]

      // 设置设备部门的默认值
      formData.value.deptId1 = firstRootNode.id
      // 触发设备部门的节点点击事件，加载设备列表
      await handleDeptDeviceTreeNodeClick(firstRootNode)
    } else {
      console.warn("部门树数据为空，无法设置默认值")
    }
  } catch (error) {
    console.error("初始化部门树失败:", error)
    ElMessage.error("加载部门数据失败")
  }

  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: 20px;
  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;/* 统一最小高度 */
}

.filter-input {
  margin-bottom: 15px;
}

.no-data {
  padding: 20px;
  text-align: center;
  color: #999;
}

.control-row {
  display: flex;
  width: 100%;
  gap: 20px;
}

/* 调整文本域高度 */
.reason-input-wrapper :deep(.el-textarea__inner) {
  height: 100% !important;
  min-height: 100px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .control-row {
    flex-direction: column;
    gap: 15px;
  }

  .control-group {
    width: 100%;
  }
}

.selection-area {
  display: flex;
}

.control-group {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

.control-title {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #606266;
}

.person-selector,
.reason-input-wrapper {
  flex: 1;
  min-height: 100px;
}

.required-star {
  color: #ff4d4f;
  margin-left: 3px;
  vertical-align: middle;
}
</style>
