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

          <el-scrollbar height="400px">
            <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.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              filterable
              :placeholder="t('configPerson.rpHolder')"
              @node-click="handleDeptUserTreeNodeClick"
            />
          </div>

          <el-scrollbar height="450px">
            <el-checkbox-group v-model="selectedUsers" @change="handleUserSelectionChange">
              <div
                v-for="user in simpleUsers"
                :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,
})

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

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

// 响应式数据
const selectedDevice = ref<number>(0)
const selectedDevices = ref<number[]>([])

const selectedDept = ref('')
const selectedUsers = ref<number[]>([])
const tempRelations = ref<Array<{
  deviceIds: number[]
  deviceNames: string
  userIds: number[]
  userNames: string
  reason: string
}>>([])

watch(selectedDevices, (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 = ''
  }
})

const handleUserSelectionChange = (userIds: number[]) => {
  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 {
    const params = { deptId: formData.value.deptId1 }
    const data = await IotDeviceApi.simpleDevices(params)
    simpleDevices.value = data || []
  } catch (error) {
    simpleDevices.value = []
    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 {
    const params = {
      deptId: formData.value.deptId,
      pageNo: 1,
      pageSize: 10 }
    const data = await UserApi.simpleUserList(params)
    simpleUsers.value = data || []
  } catch (error) {
    simpleUsers.value = []
    console.error('获取人员列表失败:', error)
  }
}

// 设备过滤文本
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 clearSelection = () => {
  selectedDevice.value = ''
  selectedUsers.value = []
  selectedDept.value = ''
}

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 {
    // 校验所有调整原因
    const hasEmptyReason = tempRelations.value.some(
      item => !item.reason?.trim()
    )
    if (hasEmptyReason) {
      ElMessage.error('请填写调整原因')
      return
    }
    // 转换为后端需要的格式
    const submitData = tempRelations.value.flatMap(relation => {
      return relation.deviceIds.map(deviceId => ({
        deviceId,
        userIds: relation.userIds,
        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 () => {
  // 初始化部门树 根据选择的部门 查询设备列表 部门人员列表
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
})

</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>
