<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :xs="24" :span="isLeftContentCollapsed ? 24 : 20">
      <ContentWrap style="border: 0">
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          @submit.prevent
          label-width="68px">
          <el-form-item label="成套名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入成套名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-200px" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> {{ t('devicePerson.search') }}</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('devicePerson.reset') }}</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表（卡片） -->
      <ContentWrap style="border: 0" class="h-[78vh] overflow-y-auto">
        <div v-loading="loading" class="h-[75vh] overflow-x-hidden">
          <el-row :gutter="20">
            <el-col
              v-for="(item, index) in list"
              :key="item.id || index"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="mt-2">
              <el-card shadow="hover" class="device-card hhh rounded-sm">
                <div class="card-header">
                  <div class="flex justify-between w-full">
                    <div>
                      <div class="card-title">{{ item.name }}</div>
                      <div class="card-dept">{{ item.deptName }}</div>
                    </div>
                    <el-tag
                      :type="getOnlineStatusTagType(item.ifOnline)"
                      size="small"
                      class="status-tag">
                      {{ item.ifOnline ? '在线' : '离线' }}
                    </el-tag>
                  </div>
                </div>
                <div class="card-body" style="margin-top: -20px">
                  <div class="card-row">
                    <span class="muted">成套类型:</span>
                    <span class="type-with-icon">
                      <dict-tag :type="DICT_TYPE.DEVICE_GROUP_TYPE" :value="item.type" />
                      <el-image
                        v-if="item.type === '1'"
                        :src="img1"
                        style="width: 30px; height: 30px; margin-left: 40px" />
                      <el-image
                        v-else
                        :src="img2"
                        style="width: 40px; height: 40px; margin-left: 40px" />
                    </span>
                  </div>
                  <div class="card-row"
                    ><span class="muted">设备数量:</span>
                    {{ (item.details && item.details.length) || 0 }}</div
                  >
                  <div class="card-row"
                    ><span class="muted">主设备:</span>
                    {{
                      item.details && item.details.filter((d) => d.ifMaster)[0]
                        ? item.details.filter((d) => d.ifMaster)[0].deviceName +
                          ' ' +
                          item.details.filter((d) => d.ifMaster)[0].deviceCode
                        : '无'
                    }}
                  </div>
                  <div class="card-row">
                    <span class="muted">在线状态:</span>
                    <el-tag :type="getOnlineStatusTagType(item.ifOnline)" size="small">
                      {{ item.ifOnline ? '在线' : '离线' }}
                    </el-tag>
                  </div>
                </div>
                <template #footer>
                  <el-button type="primary" link @click="handleEdit(item)"
                    ><Icon icon="ep:view" class="mr-5px" /> 查看详情
                  </el-button>
                </template>
              </el-card>
            </el-col>
          </el-row>

          <div style="margin-top: 16px">
            <Pagination
              :total="total"
              v-model:page="queryParams.pageNo"
              v-model:limit="queryParams.pageSize"
              @pagination="getList" />
          </div>
        </div>
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { IotDeviceApi } from '@/api/pms/device'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { DICT_TYPE } from '@/utils/dict'

import img1 from '../../../assets/imgs/300.png'
import img2 from '../../../assets/imgs/other.png'
const deptList = ref<Tree[]>([]) // 树形结构
import { useRouter } from 'vue-router'
const router = useRouter()

defineOptions({ name: 'IotDeviceMonitor' })

const loading = ref(true) // 列表的加载中

const { t } = useI18n()

const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
let isLeftContentCollapsed = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptName: undefined,
  name: undefined,
  deptId: undefined
})
const queryFormRef = ref(null) // 搜索的表单

const contentSpan = ref(20)
const treeShow = ref(true)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单相关
const formRef = ref()
const formData = ref({
  name: '',
  details: [],
  deptId: '',
  remark: ''
})

// 获取在线状态的标签类型
const getOnlineStatusTagType = (ifOnline: boolean) => {
  return ifOnline ? 'success' : 'info'
}

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '成套名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '成套编码不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  devices: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (selectedDeviceIds.value.length === 0) {
          callback(new Error('请至少选择一个设备'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  mainDevice: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!mainDeviceId.value) {
          callback(new Error('请选择主设备'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 部门树数据
const selectedDeptId = ref<number | string>('')

// 新增时部门改变时获取设备列表
const handleDeptChange = async (deptId) => {
  if (deptId) {
    selectedDeptId.value = deptId
    getDeviceList(deptId)
  }

  // 清空主设备she 设备列表
  selectedDevices.value = []
  mainDeviceId.value = ''
  selectedDeviceIds.value = []
}
// 获取设备列表
const getDeviceList = async (deptId) => {
  try {
    const res = await IotDeviceApi.getIotDeviceSetOptions(deptId)
    deviceOptions.value = res.map((item) => ({
      key: item.id, // 始终使用id作为key
      label: `${item.deviceName} (${item.deviceCode})`,
      ...item
    }))
  } catch (err) {
    console.error(err)
  }
}

// 设备选择相关
const deviceOptions = ref<any[]>([])
const selectedDeviceIds = ref([])
const selectedDevices = ref([])
const mainDeviceId = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotDeviceApi.getIotDeviceSetList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 首页处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 设备过滤方法
const filterDeviceMethod = (query, item) => {
  return item.label.toLowerCase().includes(query.toLowerCase())
}

// 更新已选择的设备列表
const updateSelectedDevices = () => {
  // 根据 selectedDeviceIds 从 deviceOptions 中找到对应的设备
  selectedDevices.value = deviceOptions.value.filter((item) =>
    selectedDeviceIds.value.includes(item.key)
  )

  console.log('selectedDevices>>>>>>>>>>>>>>>>', selectedDevices.value)

  // 构建 details 数据
  formData.value.details = selectedDevices.value.map((item) => ({
    deviceId: item.id,
    deviceName: item.deviceName,
    deviceCode: item.deviceCode,
    deptId: item.deptId,
    ifMaster: item.id === mainDeviceId.value ? true : false
  }))

  // 如果主设备不在当前选择中，则清空主设备
  if (
    mainDeviceId.value &&
    !selectedDevices.value.some((device) => device.id === mainDeviceId.value)
  ) {
    mainDeviceId.value = ''
  }
}

const rightDeviceChange = (val) => {
  selectedDeviceIds.value = val
  updateSelectedDevices()

  // 手动触发验证
  if (formRef.value) {
    formRef.value.validateField('devices')
    if (val.length > 0) {
      formRef.value.validateField('mainDevice')
    }
  }
}

// 设置主设备
const setMainDevice = (val) => {
  mainDeviceId.value = val
  // 更新 details 中的 ifMaster 字段
  console.log('selectedDevices.value>>>>>>>>>>>>>>>>', selectedDevices.value)

  formData.value.details = selectedDevices.value.map((item) => ({
    deviceId: item.id,
    deviceName: item.deviceName,
    deviceCode: item.deviceCode,
    deptId: item.deptId,
    ifMaster: item.id === mainDeviceId.value ? true : false
  }))

  console.log('formData.value.details>>>>>>>>>>>>>>>>', formData.value.details)

  // 手动触发验证
  if (formRef.value) {
    formRef.value.validateField('mainDevice')
  }
}

// 显示新增对话框
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增成套设备'
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const handleEdit = (row) => {
  if (row.type === '1') {
    router.push({ path: '/kanban/monitor/kanban', query: { deviceSetId: row.id } })
  } else {
    router.push({ path: '/kanban/monitor/kanbanOther', query: { deviceSetId: row.id } })
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    details: [],
    deptId: '',
    remark: ''
  }
  selectedDeviceIds.value = []
  selectedDevices.value = []
  deviceOptions.value = []
  mainDeviceId.value = ''
}

// 取消操作
const cancel = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const submit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const data = {
        ...formData.value
      }

      console.log('提交数据:', data)

      if (isEdit.value) {
        await IotDeviceApi.updateIotDeviceSet(data)
        ElMessage.success('编辑成功')
      } else {
        await IotDeviceApi.createIotDeviceSet(data)
        ElMessage.success('新增成功')
      }

      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

onMounted(async () => {
  getList()

  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>

<style scoped lang="scss">
::v-deep .el-card {
  border-radius: 5px !important;
}

::v-deep .hhh.el-card {
  background-color: transparent !important;
  border-radius: 5px !important;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(28, 39, 63, 0.06);
}
.transfer-container {
  display: flex;
  flex-direction: column;
}

.transfer-footer {
  margin-top: 8px;
  text-align: right;
}

::deep(.el-transfer-panel) {
  width: 300px;
}

::deep(.el-tree--highlight-current) {
  height: 200px !important;
}

/* 调整穿梭框面板主体高度 */
::deep(.el-transfer-panel__body) {
  height: 850px !important;
}

/* 如果需要进一步调整，可以分别设置左右面板的高度 */
::deep(.el-transfer-panel .el-transfer-panel__list) {
  height: 850px !important; /* 调整列表区域高度 */
}

.el-transfer {
  --el-transfer-panel-body-height: 500px;
}

.device-card {
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(28, 39, 63, 0.06);
  /* 渐变蓝背景 */
  background: linear-gradient(to top, #fff 0%, #effaff 100%);
  color: #717e9d !important;
}

/* 移除 el-card 默认内边距，统一由子元素控制 */
.device-card ::v-deep .el-card__body {
  padding: 0;
  color: #717e9d !important;
}

.device-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 16px;
}

.device-card .card-title {
  font-weight: 700;
  font-size: 16px;
  line-height: 1.2;
  color: #34475c;
}

.device-card .card-dept {
  font-size: 12px;
  opacity: 0.95;
  margin-top: 6px;
  color: #34475c;
}

.device-card .status-tag {
  margin-bottom: 8px;
}

.device-card .card-status {
  background: rgba(255, 255, 255, 0.18);
  color: #fff;
  padding: 6px 10px;
  border-radius: 999px;
  font-size: 12px;
}

.device-card .card-body {
  background: transparent;
  padding: 14px 16px;
  font-size: 14px;
  color: #34475c;
}

.device-card .card-row {
  display: flex;
  align-items: center;
  padding: 2px 0;
}

.device-card .card-row:last-child {
  border-bottom: none;
}

.device-card .card-row .muted {
  color: #34475c;
  width: 86px;
  flex-shrink: 0;
}

.device-card .type-with-icon {
  display: inline-flex;
  align-items: center;
}

.device-card .card-row .value {
  color: #fff;
  flex: 1;
}

.device-card ::v-deep .el-card__footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 16px;
  background: transparent;
  color: #fff;
}

.device-card .detail-link {
  color: #fff;
  font-weight: 500;
}

.device-card .id-label {
  color: rgba(255, 255, 255, 0.85);
  font-size: 12px;
  font-size: 12px;
}

::-webkit-scrollbar {
  width: 5px; /* 设置滚动条宽度 */
}
::-webkit-scrollbar-thumb {
  background-color: darkgrey; /* 设置滚动条颜色 */
  border-radius: 10px; /* 设置圆角 */
}
::-webkit-scrollbar-track {
  background: transparent; /* 设置轨道颜色 */
}
</style>
