<template>
  <div class="container">
    <el-row :gutter="20" class="equal-height-row">
      <!-- 左侧设备列表 -->
      <el-col :span="12" class="col-wrapper">
        <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"  @change="handleDeviceChange">
              <div
                v-for="device in filteredDevices"
                :key="device.id"
                class="checkbox-item"
              >
                <el-checkbox :label="device.id">
                  {{ device.deviceCode }} ({{ device.deviceName }}) - {{ device.deviceStatusName }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-scrollbar>
        </div>
      </el-col>

      <!-- 右侧设备状态 -->
      <el-col :span="12" class="col-wrapper">
        <div class="card">
          <h3>{{ t('configDevice.rp') }}</h3>
          <div class="dept-select">
            <el-select
              v-model="formData.deviceStatus"
              @change="handleStatusChange"
              :placeholder="t('deviceStatus.choose')"
              clearable
              :disabled="selectedDevices.length === 0"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_DEVICE_STATUS)"
                :key="dict.label"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>

          <el-input
            v-model="formData.reason"
            :placeholder="t('configDevice.rfaHolder')"
            :disabled="!formData.deviceStatus"
            class="reason-input"
            type="textarea"
            :rows="3"
            @input="handleReasonInput"
          />

          <div class="action-bar">

          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 暂存关联列表 -->
    <div class="temp-list card">
      <h3>{{ t('configPerson.adjustmentRecords') }}</h3>
      <el-table :data="tempRelations" style="width: 100%">
        <el-table-column prop="deviceNames" :label="t('deviceStatus.deviceName')" width="200" >
          <template #default="{ row }">
            {{ row.deviceNames }}
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="t('deviceStatus.status')" >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="reason" :label="t('configDevice.reasonForAdjustment')" />
        <el-table-column :label="t('deviceStatus.operation')" width="120">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="removeTempRelation(row.deviceId)"
            >
              {{ 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>
</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 {simpleUserList, UserVO} from "@/api/system/user";
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import { useRouter } from 'vue-router'
import { useTagsViewStore } from "@/store/modules/tagsView";
const router = useRouter()

const { t } = useI18n() // 国际化
defineOptions({ name: 'ConfigDeviceStatus' })

const simpleDevices = ref<IotDeviceVO[]>([])
const currentStatus = ref<string>('')
const adjustReason = ref<string>('')
const deptList = ref<Tree[]>([]) // 树形结构
const selectedDevices = ref<number[]>([]) // 改为数组存储多选
// 获取当前设备对象
const currentDevice = computed(() => {
  return simpleDevices.value.find(d => d.id === selectedDevice.value)
})

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,
  reason: '',
  assetProperty: undefined,
  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 selectedDept = ref('')
const tempRelations = ref<Array<{
  deviceId: number
  deviceNames: string
  status: string
  statusLabel: string
  reason: string
}>>([])

// 设备切换时清空状态
const handleDeviceChange = () => {
  currentStatus.value = ''
  adjustReason.value = ''
  // 尝试从暂存记录恢复数据
  const existRecord = tempRelations.value.find(r => r.deviceId === selectedDevice.value)
  if (existRecord) {
    currentStatus.value = existRecord.deviceStatus
    adjustReason.value = existRecord.reason
  }
}

// 修改watch监听
watch(selectedDevices, (newVal, oldVal) => {
  // 删除取消选择的设备
  const removedDevices = oldVal.filter(id => !newVal.includes(id))
  removedDevices.forEach(deviceId => {
    const index = tempRelations.value.findIndex(r => r.deviceId === deviceId)
    if (index > -1) tempRelations.value.splice(index, 1)
  })

  // 自动应用当前状态到新选设备
  if (formData.value.deviceStatus && formData.value.reason) {
    saveCurrentRelation()
  }
})

// 修改保存方法
const saveCurrentRelation = () => {
  if (!formData.value.deviceStatus /*|| !formData.value.reason*/) return

  const statusDict = getStrDictOptions(DICT_TYPE.PMS_DEVICE_STATUS)
    .find(d => d.value === formData.value.deviceStatus)

  selectedDevices.value.forEach(deviceId => {
    const device = simpleDevices.value.find(d => d.id === deviceId)
    if (!device) return

    const newRelation = {
      deviceId,
      deviceNames: `${device.deviceCode} (${device.deviceName})`,
      status: formData.value.deviceStatus!,
      statusLabel: statusDict?.label || '未知状态',
      reason: formData.value.reason
    }

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

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

/** 获得 部门下的设备 列表 */
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 isSaveDisabled = computed(() => {
  // 当没有调整记录或调整原因为空时禁用按钮
  return tempRelations.value.length === 0 || !formData.value.reason.trim();
});

// 添加状态变更处理
const handleStatusChange = () => {
  if (selectedDevices.value.length > 0) {
    saveCurrentRelation()
  }
}

// 新增输入处理方法
const handleReasonInput = (value: string) => {
  formData.value.reason = value
  if (selectedDevices.value.length > 0 && formData.value.deviceStatus) {
    saveCurrentRelation()
  }
}

// 添加多设备判断方法
const isMultiDevice = (row: any) => {
  return selectedDevices.value.includes(row.deviceId) && selectedDevices.value.length > 1
}

// 设备过滤文本
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 removeTempRelation = (deviceId: number) => {
  // 从暂存列表删除
  tempRelations.value = tempRelations.value.filter(r => r.deviceId !== deviceId)

  // 从选中设备中移除
  selectedDevices.value = selectedDevices.value.filter(id => id !== deviceId)

  // 如果当前表单状态为空，尝试恢复其他设备的状态
  if (!formData.value.deviceStatus && tempRelations.value.length > 0) {
    const firstRelation = tempRelations.value[0]
    formData.value.deviceStatus = firstRelation.status
    formData.value.reason = firstRelation.reason
  }
}

// 提交时处理数据
const submitRelations = async () => {
  try {
    // 检查是否有空的原因
    const hasEmptyReason = tempRelations.value.some(
      item => !item.reason?.trim()
    )
    if (hasEmptyReason) {
      ElMessage.error('请填写所有设备的调整原因')
      return
    }
    // 转换数据结构
    const submitData = tempRelations.value.map(r => ({
      deviceId: r.deviceId,
      status: r.status,
      reason: r.reason
    }))
    await IotDeviceApi.saveDeviceStatuses(submitData)
    ElMessage.success('提交成功')
    tempRelations.value = []
    delView(unref(router.currentRoute.value))
    router.back()
  } catch (error) {
    ElMessage.error('提交失败')
  }
}

/** 初始化 */
onMounted(async () => {
  // 初始化部门树 根据选择的部门 查询设备列表 部门人员列表
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // getList()
})

</script>

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

.card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  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;
}

.col-wrapper {
  display: flex;
  flex-direction: column;
}

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

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

.equal-height-row {
  display: flex;
  align-items: stretch;
}

.el-scrollbar {
  flex: 1;
}

.reason-input {
  margin-top: 20px;
}

/* 添加多设备标签样式 */
.el-tag {
  margin-left: 8px;
  vertical-align: middle;
}

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

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