<template>
  <div class="container">
    <el-row :gutter="20" class="equal-height-row">
      <!-- 左侧设备列表 -->
      <el-col :span="12">
        <div class="card">
          <h3>{{ t('configPerson.deviceList') }}</h3>
          <div class="dept-select">
            <el-tree-select
              clearable
              v-model="formData.deptId1"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              filterable
              :placeholder="t('configPerson.deviceListHolder')"
              @node-click="handleDeptDeviceTreeNodeClick"
              @clear="handleClearDeptForDevice"
            />
          </div>
          <!-- 设备搜索框 -->
          <div class="filter-input">
            <el-input
              v-model="deviceFilterText"
              :placeholder="t('devicePerson.filterDevicePlaceholder')"
              :disabled="!devicesLoaded"
              clearable
              prefix-icon="Search"
            />
          </div>

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

      <!-- 右侧责任人选择 -->
      <el-col :span="12">
        <div class="card">
          <h3>{{ t('configPerson.rp') }}</h3>
          <div class="dept-select">
            <el-tree-select
              clearable
              v-model="formData.deptIds"
              :data="deptList"
              :props="defaultProps"
              multiple
              show-checkbox
              check-strictly
              node-key="id"
              filterable
              :placeholder="t('configPerson.rpHolder')"
              @node-click="handleDeptCheckChange"
              @clear="handleClearDeptForPerson"
            />
          </div>

          <!-- 责任人搜索框 -->
          <div class="filter-input">
            <el-input
              v-model="userFilterText"
              :placeholder="t('devicePerson.filterUserPlaceholder')"
              :disabled="!personLoaded"
              clearable
              prefix-icon="Search"
            />
          </div>

          <el-scrollbar height="450px">
            <el-checkbox-group v-model="selectedUsers" @change="handleUserSelectionChange">
              <div
                v-for="user in filteredUsers"
                :key="user.id"
                class="list-item"
              >
                <el-checkbox :label="user.id">
                  {{ user.nickname }} ({{ user.deptName }})
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-scrollbar>
        </div>
      </el-col>
    </el-row>

    <!-- 暂存关联列表 -->
    <div class="submit-area">
      <div class="card">
        <h3>{{ t('configPerson.reasonForAdjustment') }}<span class="required-star">*</span></h3>
        <el-input
          v-model="formData.reason"
          :placeholder="t('configPerson.rfaHolder')"
          class="reason-input"
          type="textarea"
          :rows="3"
          @input="handleReasonInput"
          :disabled="selectedDevices.length === 0 || selectedUsers.length === 0"
        />
      </div>
      <div class="temp-list card">
        <h3>{{ t('configPerson.adjustmentRecords') }}</h3>
        <el-table :data="tempRelations" style="width: 100%">
          <el-table-column prop="deviceNames" :label="t('devicePerson.deviceName')" width="200" />
          <el-table-column prop="userNames" :label="t('devicePerson.rp')" />
          <el-table-column prop="reason" :label="t('configPerson.reasonForAdjustment')" />
          <el-table-column :label="t('devicePerson.operation')" width="120">
            <template #default="{ row }">
              <el-button
                type="danger"
                size="small"
                @click="removeTempRelation(row.deviceIds)"
              >
                {{ t('fault.del') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="submit-area">
          <el-button
            type="primary"
            size="large"
            @click="submitRelations"
            :disabled="isSaveDisabled"
          >
            {{ t('iotMaintain.save') }}
          </el-button>
        </div>
      </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 {IotDevicePersonApi, IotDevicePersonVO} from "@/api/pms/iotdeviceperson";
import * as UserApi from "@/api/system/user";
import {simpleUserList, UserVO} from "@/api/system/user";
import { useRouter } from 'vue-router'
const router = useRouter()
const { t } = useI18n() // 国际化
import { useTagsViewStore } from "@/store/modules/tagsView";

defineOptions({ name: 'ConfigDevicePerson' })

const simpleDevices = ref<IotDeviceVO[]>([])
const simpleUsers = ref<UserVO[]>([])

const deptList = ref<Tree[]>([]) // 树形结构
const { delView } = useTagsViewStore() // 视图操作

const formData = ref({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  model: undefined,
  deptId: undefined as string | undefined,
  deptId1: undefined as string | undefined,
  deviceStatus: undefined,
  assetProperty: undefined,
  reason: '',
  picUrl: undefined,
  deptIds: [] as number[], // 改为部门ID数组
})

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

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

// 响应式数据
const selectedDevices = ref<number[]>([])
// 责任人过滤文本
const userFilterText = ref('')
const selectedUsers = ref<number[]>([])
const tempRelations = ref<Array<{
  deviceIds: number[]
  deviceNames: string
  userIds: number[]
  userNames: string
  reason: string
}>>([])

watch(selectedDevices, async (newVal, oldVal) => {
  // 找出新增的设备
  const addedDevices = newVal.filter(id => !oldVal.includes(id));
  // 找出取消选择的设备
  const removedDevices = oldVal.filter(id => !newVal.includes(id))

  // 移除对应设备的关联记录
  tempRelations.value = tempRelations.value.filter(
    r => !removedDevices.includes(r.deviceIds[0])
  )

  // 为新增的设备创建关联记录
  if (addedDevices.length > 0) {
    const addedDeviceObjects = simpleDevices.value.filter(d =>
      addedDevices.includes(d.id)
    );
    addedDeviceObjects.forEach(device => {
      // 使用当前已选的责任人和调整原因
      updateDeviceRelation(device, selectedUsers.value);
    });
  }

  // 当没有选中设备时清空其他选项
  if (newVal.length === 0) {
    selectedUsers.value = []
    formData.value.reason = ''
  }

  // 获取设备部门ID集合
  const deptIdSet = new Set<number>()
  newVal.forEach(deviceId => {
    const device = simpleDevices.value.find(d => d.id === deviceId)
    if (device?.deptId) deptIdSet.add(device.deptId)
  })
  formData.value.deptIds = Array.from(deptIdSet)
  // 部门更新后自动加载人员
  await getUserList()
}, { deep: true })

// 监听部门ID变化 部门变化后重新筛选用户
watch(
  () => formData.value.deptIds,
  async (newVal, oldVal) => {
    // 找出被删除的部门
    const deletedDeptIds = oldVal?.filter(id => !newVal?.includes(id)) || []

    if (deletedDeptIds.length > 0) {
      // 找出被删除部门下的用户ID
      const usersToRemove = simpleUsers.value
        .filter(user => deletedDeptIds.includes(user.deptId))
        .map(user => user.id)

      // 同步更新已选用户
      selectedUsers.value = selectedUsers.value.filter(
        id => !usersToRemove.includes(id)
      )

      // 更新关联记录
      tempRelations.value = tempRelations.value.map(relation => {
        const validUserIds = relation.userIds.filter(
          id => !usersToRemove.includes(id)
        )

        // 获取有效用户名称
        const validUsers = simpleUsers.value.filter(
          u => validUserIds.includes(u.id)
        )

        return {
          ...relation,
          userIds: validUserIds,
          userNames: validUsers.map(u => u.nickname).join(', ')
        }
      })
    }

    // 重新加载人员列表
    await getUserList()
  },
  { deep: true } // 深度监听数组变化
)

const handleUserSelectionChange = (userIds: number[]) => {
  // 处理清空责任人的情况
  if (userIds.length === 0) {
    tempRelations.value.forEach(relation => {
      relation.userIds = []
      relation.userNames = ''
    })
    return
  }

  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请先选择设备')
    selectedUsers.value = []
    return
  }

  // 获取所有选中设备
  const devices = simpleDevices.value.filter(d =>
    selectedDevices.value.includes(d.id)
  )

  // 更新所有设备的关联关系
  devices.forEach(device => {
    updateDeviceRelation(device, userIds)
  })
}

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

// 新增计算属性：判断保存按钮是否禁用
const isSaveDisabled = computed(() => {
  // 当没有调整记录或调整原因为空时禁用按钮
  return tempRelations.value.length === 0 || !formData.value.reason.trim();
});

/** 获得 部门下的设备 列表 */
const getDeviceList = async () => {
  try {
    // 查询到数据后才能进行搜索 筛选
    devicesLoaded.value = false

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

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

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

/** 获得 部门下的人员 列表 */
const getUserList = async () => {
  try {
    // 开始加载时禁用搜索框
    personLoaded.value = false

    // 保留当前选中但不在被删除部门的用户
    const currentDeptIds = formData.value.deptIds || []
    const validUserIds = simpleUsers.value
      .filter(user => currentDeptIds.includes(user.deptId))
      .map(user => user.id)

    selectedUsers.value = selectedUsers.value.filter(
      id => validUserIds.includes(id)
    )

    const params = {
      deptIds: formData.value.deptIds,
      // deptId: formData.value.deptId,
      pageNo: 1,
      pageSize: 10 }
    const data = await UserApi.simpleUserList(params)
    simpleUsers.value = data || []

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

// 设备加载状态标记 只有加载完设备才能通过文本框筛选
const devicesLoaded = ref(false)

// 人员加载状态标记 只有加载完人员才能通过文本框筛选
const personLoaded = ref(false)

// 设备过滤文本
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)
    )
  })
})

// 新增输入处理方法
const handleReasonInput = (value: string) => {
  formData.value.reason = value
  // 同步到所有已选设备的记录
  selectedDevices.value.forEach(deviceId => {
    const relation = tempRelations.value.find(
      r => r.deviceIds[0] === deviceId
    )
    if (relation) {
      relation.reason = value
    }
  })
}

// 更新设备关联关系
const updateDeviceRelation = (device: IotDeviceVO, userIds: number[]) => {
  // 获取当前选择的人员
  const users = simpleUsers.value.filter(u => userIds.includes(u.id))

  const newRelation = {
    deviceIds: [device.id],
    deviceNames: `${device.deviceCode} (${device.deviceName})`,
    userIds: users.map(u => u.id),
    userNames: users.map(u => u.nickname).join(', '),
    reason: formData.value.reason
  }

  const existIndex = tempRelations.value.findIndex(
    // r => r.deviceIds[0] === device.id
    r => r.deviceIds.includes(device.id)
  )

  if (existIndex > -1) {
    tempRelations.value[existIndex] = newRelation
  } else {
    tempRelations.value.push(newRelation)
  }
}

// 处理 设备关联 部门选择清空事件
const handleClearDeptForDevice = () => {
  simpleDevices.value = []
  selectedDevices.value = []
  devicesLoaded.value = false  // 清空时禁用搜索框
  deviceFilterText.value = ''
}

// 处理 人员关联 部门选择清空事件
const handleClearDeptForPerson = () => {
  formData.value.deptIds = []
  simpleUsers.value = []
  selectedUsers.value = []
  personLoaded.value = false  // 清空时禁用搜索框
  userFilterText.value = ''

  // 清空所有暂存记录中的责任人
  tempRelations.value.forEach(relation => {
    relation.userIds = []
    relation.userNames = ''
  })
}

// 新增部门选择监听
const handleDeptCheckChange = () => {
  // getUserList() // 选择变化时重新加载人员
}

// 过滤后的人员列表计算属性
const filteredUsers = computed(() => {
  const searchText = userFilterText.value.toLowerCase().trim()
  if (!searchText) return simpleUsers.value

  return simpleUsers.value.filter(user => {
    return (user.nickname || '').toLowerCase().includes(searchText)
  })
})

const removeTempRelation = (deviceIds: number[]) => {
  tempRelations.value = tempRelations.value.filter(
    r => r.deviceIds.join() !== deviceIds.join()
  )
  // 同步取消勾选设备
  selectedDevices.value = selectedDevices.value.filter(
    id => !deviceIds.includes(id)
  )
}

const submitRelations = async () => {
  try {
    // 校验必须选择设备
    if (selectedDevices.value.length === 0) {
      ElMessage.error(t('iotMaintain.deviceHolder')) // 请选择设备
      return
    }
    // 校验必须选择责任人
    if (selectedUsers.value.length === 0) {
      ElMessage.error(t('configPerson.selectPersons')) // 请选择责任人
      return
    }
    // 校验所有调整原因
    const hasEmptyReason = tempRelations.value.some(
      item => !item.reason?.trim()
    )
    if (hasEmptyReason) {
      ElMessage.error(t('configPerson.rfaHolder'))
      return
    }
    // 校验 设备 责任人 必须都选择 不能为空
    // 转换为后端需要的格式
    const submitData = tempRelations.value.flatMap(relation => {
      return relation.deviceIds.map(deviceId => ({
        deviceId,
        userIds: relation.userIds,
        userNames: relation.userNames,
        reason: relation.reason
      }))
    })
    await IotDevicePersonApi.saveDevicePersonRelation(submitData)
    // 模拟API调用
    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)

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

</script>

<style scoped>
.equal-height-row {
  display: flex;
  align-items: stretch;
}

.container {
  padding: 20px;
}

.card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  background: white;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  transition: box-shadow 0.2s;
}

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

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

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

.radio-item {
  width: 100%;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
}

.radio-item .el-radio {
  width: 100%;
  height: 100%;
}

.radio-item .el-radio__label {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

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

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

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