<template>
  <el-row :gutter="20">
    <!-- 左侧 设备分类 树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeviceCategoryTree @node-click="handleDeviceCategoryTreeNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <ContentWrap>
          <ContentWrap v-if="selectedNode">
            <div style="display: flex;flex-direction: row; justify-content: space-between; vertical-align: center">
              <div style="display: flex;flex-direction: row; ">
                <el-radio v-model="ifDevice" label="1" size="large" @input="handleClassifyRadio" border>分类告警区间设置</el-radio>
                <el-radio v-model="ifDevice" label="2" size="large" @input="handleDeviceRadio" border>设备告警区间设置</el-radio>
              </div>
<!--              <el-select-->
<!--                style="width: 200px;"-->
<!--                v-if="selectedNode&&ifDevice==='2'"-->
<!--                :placeholder="t('faultForm.choose')"-->
<!--                clearable-->
<!--                @change="handleDeviceSelected"-->
<!--                @clear="handleClear"-->
<!--              />-->
              <el-select style="width: 250px" v-model="selectedDeviceId" v-if="selectedNode&&ifDevice==='2'" :placeholder="t('iotMaintain.deviceHolder')"
                         @clear="handleClear" @change="handleDeviceSelected" :class="{ 'shake-highlight': isDeviceSelectShake }" filterable>
                <el-option
                  v-for="item in devices"
                  :key="item.id"
                  :label="item.deviceCode"
                  :value="item.id">
                  <span style="float: left">{{ item.deviceCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deviceName }}</span>
                </el-option>
              </el-select>
            </div>
          </ContentWrap>
          <!-- 选中项信息与操作 -->
          <div v-if="selectedNode" class="selected-info-bar">
            <div class="selected-info">
              <Icon icon="fa:foursquare" />
              <h2 class="selected-name">{{ifDevice==='1'?selectedName:selectedDeviceName }}</h2>
              <el-tag
                :type="ifDevice === '1' ? 'success' : 'primary'"
                class="node-type-tag"
              >
                {{ ifDevice === '1' ? '分类' : '设备' }}
              </el-tag>
            </div>

            <div class="action-buttons">
              <el-button
                type="warning"
                @click="handleQuery"
                class="add-property-btn"
                size="default"
              >
                <template #icon>
                  <Icon icon="ep:search" />
                </template>
                查询
              </el-button>
              <el-button
                type="primary"
                @click="openForm('create')"
                class="add-property-btn"
                size="default"
              >
                <template #icon>
                  <Plus />
                </template>
                添加属性
              </el-button>
              <el-button
                type="success"
                @click="saveAllProperties"
                :loading="saveLoading"
                size="default"
              >
                <template #icon>
                  <Check />
                </template>
                保存配置
              </el-button>
            </div>
          </div>
          <!-- 未选择任何项时的空状态 -->
          <div v-else class="empty-state">
            <el-empty description="请从左侧选择一个设备或分类" class="main-empty-state">
              <template #image>
                <div class="empty-image-container">
                  <Icon :size="40" icon="fa-solid:empty-set"/>
                </div>
              </template>
            </el-empty>
          </div>
        </ContentWrap>

        <ContentWrap>
          <el-row v-if="selectedNode&&list.length>0" :gutter="16">
            <el-col v-for="item in list" :key="item.id" :lg="6" :md="12" :sm="12" :xs="24" class="mb-4">
              <el-card v-loading="loading" :body-style="{ padding: '0' }" class="h-full transition-colors">
                <!-- 内容区域 -->
                <div class="p-4">
                  <!-- 标题区域 -->
                  <div class="flex items-center mb-3">
                    <div class="mr-2.5 flex items-center">
                      <el-image :src="defaultIconUrl" class="w-[35px] h-[35px]" />
                    </div>
                    <div class="text-[16px] font-600">{{ item.alarmProperty }}</div>
                  </div>

                  <!-- 信息区域 -->
                  <div class="flex items-center text-[14px]">
                    <div class="flex-1">
<!--                      <div class="mb-2.5 last:mb-0">-->
<!--                        <span class="text-[#717c8e] mr-2.5">属性标识</span>-->
<!--&lt;!&ndash;                        <div style="width: 300px;  padding: 0px;">&ndash;&gt;-->
<!--                          &lt;!&ndash; 为span添加换行样式类 &ndash;&gt;-->
<!--                          <span class="auto-wrap" style="color: dodgerblue; width: 200px">{{ item.propertyCode }}</span>-->
<!--&lt;!&ndash;                        </div>&ndash;&gt;-->
<!--                      </div>-->
                      <div class="mb-2.5 last:mb-0">
                        <span class="text-[#717c8e] mr-2.5">设备名称</span>
                          <el-tag><span class="auto-wrap" style="color: dodgerblue">{{ item.deviceName }}</span></el-tag>
                      </div>
                      <div class="mb-2.5 last:mb-0">
                        <span class="text-[#717c8e] mr-2">上限数值</span>
                        <el-input
                          v-model.number="item.maxValue"
                          type="number"
                          class="text-[#0070ff] inline-input"
                          style="width: 80px"
                          size="small"
                          step="any"
                        :min="item.minValue !== null ? item.minValue : -Infinity"
                        />
                        <span class="text-[#717c8e] mr-2 ml-2">下限数值</span>
                        <el-input
                          v-model.number="item.minValue"
                          type="number"
                          class="text-[#0070ff] inline-input"
                          style="width: 80px"
                          size="small"
                          step="any"
                          :max="item.maxValue !== null ? item.maxValue : Infinity"
                        />
                      </div>
                      <div class="mb-2.5 last:mb-0">

                      </div>
                    </div>
<!--                    <div class="w-[100px] h-[80px]">-->
<!--                      <el-image :src="defaultPicUrl" class="w-full h-full" />-->
<!--                    </div>-->
                  </div>

                  <!-- 分隔线 -->
                  <el-divider class="!my-3" />

                  <!-- 按钮组 -->
                  <div class="flex items-center px-0">
                    <el-button
                      class="flex-1 !px-2 !h-[32px] text-[13px]"
                      plain
                      type="primary"
                      @click="openUpdateForm('update', item)"
                    >
                      <Icon class="mr-1" icon="ep:edit-pen" />
                      编辑
                    </el-button>
<!--                    <el-button-->
<!--                      class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]"-->
<!--                      plain-->
<!--                      type="warning"-->
<!--                      @click="openDetail(item.id)"-->
<!--                    >-->
<!--                      <Icon class="mr-1" icon="ep:view" />-->
<!--                      详情-->
<!--                    </el-button>-->
<!--                    <el-button-->
<!--                      class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]"-->
<!--                      plain-->
<!--                      type="success"-->
<!--                      @click="openObjectModel(item)"-->
<!--                    >-->
<!--                      <Icon class="mr-1" icon="ep:scale-to-original" />-->
<!--                      物模型-->
<!--                    </el-button>-->
                    <el-button
                      class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]"
                      plain
                      type="danger"
                      @click="handleDelete(item.id)"
                    >
                      <Icon icon="ep:delete" />删除
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <Pagination
            v-if="selectedNode&&list.length>0"
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="getList"
          />
        </ContentWrap>
        <!-- 有选中项但无属性时的空状态 -->
        <div v-if="selectedNode && list.length === 0" class="no-properties-state">
          <el-empty description="暂无属性，请点击添加属性按钮创建">
            <template #image>
              <div class="no-properties-image">
                <el-icon class="no-properties-icon"><Icon icon="ep:add" /></el-icon>
              </div>
            </template>
            <template #bottom>
              <el-button type="primary" @click="showAddPropertyDialog" size="default">
                <template #icon>
                  <Plus />
                </template>
                添加第一个属性
              </el-button>
            </template>
          </el-empty>
        </div>
      </ContentWrap>
    </el-col>
  </el-row>
  <IotAlarmSettingForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { CommonStatusEnum } from '@/utils/constants'
import * as DeviceTemplateApi from '@/api/pms/devicetemplate'
import DeviceCategoryTree from '../../bom/DeviceCategoryTree.vue'
import { useTreeStore } from '@/store/modules/attrTemplateTreeStore'
import { Check, Plus } from '@element-plus/icons-vue'
import { nextTick, reactive, ref } from 'vue'
import { IotAlarmSettingApi } from '@/api/pms/alarm'
import IotAlarmSettingForm from "@/views/pms/device/monitor/IotAlarmSettingForm.vue";
import defaultIconUrl from '@/assets/svgs/iot/cube.svg'
import defaultPicUrl from '@/assets/svgs/iot/arrange.svg'
import {IotDeviceApi} from "@/api/pms/device";

defineOptions({ name: 'IotAlarmSet' })

const treeStore = useTreeStore()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { push } = useRouter()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const saveLoading = ref(false) // 保存的加载状态
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  status: undefined,
  classifyId: undefined,
  deviceId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

// 从 Store 中获取左侧 设备分类树 选中的 节点ID
const selectedId = ref<string>()
const selectedDeviceId = ref<string>()
const selectedName = ref<string>()
const selectedDeviceName = ref<string>()
const selectedNode = ref(null)
const ifDevice = ref('')
const devices = ref([])
const isDeviceSelectShake = ref(false)

const handleDeviceSelected = async (row) =>{
  debugger
  // selectedDeviceId.value = row.id
  const device = devices.value.find(item => item.id === row)
  if (device) {
    selectedDeviceName.value = device.deviceCode+device.deviceName
  }
  queryParams.deviceId = row
  await getList("2");
}
const handleClear = () =>{
  selectedDeviceId.value = ''
  selectedDeviceName.value = ''
}
const handleDeviceRadio = async () =>{
  selectedDeviceName.value = ''
  //置空分类名称
  // selectedName.value = ''
  const deviceParams = {
    assetClass: selectedId.value,
    pageNo:1,
  }
  // queryParams.deviceId  = selectedDeviceId.value
  const data = await IotDeviceApi.getAllDeviceParams(deviceParams)
  debugger
  devices.value = data;
  // if (selectedDeviceId.value===''||selectedDeviceId.value===undefined) {
  //   list.value = []
  // } else {
    await getList("2")
  // }
};
const handleClassifyRadio = async () =>{
  queryParams.classifyId = selectedId.value
  queryParams.deviceId = null
  selectedDeviceId.value = ''
  await getList("1")
};
/** 查询 设备属性模板 列表 */
const getList = async (ifdevice:string) => {
  loading.value = true
  try {
    debugger
    const data = await IotAlarmSettingApi.getIotAlarmSettingPage(queryParams, ifdevice)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

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

/** 处理 设备分类树 被点击 */
const handleDeviceCategoryTreeNodeClick = async (row) => {
  selectedNode.value = row
  selectedId.value = row.id
  selectedName.value = row.name
  queryParams.classifyId = row.id
  ifDevice.value = '1'
  await getList("1")
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (ifDevice.value === '2'&&(selectedDeviceId.value === ''||selectedDeviceId.value === null||selectedDeviceId.value === undefined)) {
    message.error('请先选择设备');
    // 触发抖动效果
    isDeviceSelectShake.value = true
    // 1秒后移除抖动类名，以便下次可以重新触发
    setTimeout(() => {
      isDeviceSelectShake.value = false
    }, 1000)
    return
  }
  formRef.value.open(type, id, selectedId.value, selectedName.value, selectedDeviceId.value, selectedDeviceName.value)
}

const openUpdateForm = (type: string, item?: any) => {
  debugger
  selectedDeviceId.value = item.deviceId
  selectedDeviceName.value = item.deviceName
  formRef.value.open(type, item.id, selectedId.value, selectedName.value, selectedDeviceId.value, selectedDeviceName.value)
}
/** 打开详情 */
const openDetail = (row) => {
  push({
    name: 'DeviceAttrTemplateModel',
    params: {
      id: row.deviceCategoryId,
      // 添加额外参数
      templateName: row.name,
      categoryName: row.deviceCategoryName
    }
  })
}

/** 修改 设备属性模板 状态 */
const handleStatusChange = async (row: DeviceTemplateApi.DeviceAttrTemplateVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.name + '"属性模板吗?')
    // 发起修改状态
    await DeviceTemplateApi.updateDeviceTemplateStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: DeviceTemplateApi.DeviceAttrTemplateVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await IotAlarmSettingApi.deleteIotAlarmSetting(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList(ifDevice.value)
  } catch {}
}

/** 保存所有属性配置 */
const saveAllProperties = async () => {
  if (!selectedNode.value) {
    message.warning('请先选择设备或分类')
    return
  }

  // 筛选出有修改的属性
  const modifiedItems = list.value.filter(item =>
    item.maxValue !== undefined || item.minValue !== undefined
  )

  if (modifiedItems.length === 0) {
    message.info('没有需要保存的修改')
    return
  }

  saveLoading.value = true
  try {
    debugger
    // 调用保存接口
    await IotAlarmSettingApi.batchUpdateAlarmSettings(modifiedItems)
    message.success('保存成功')
    // 重新获取列表刷新数据
    await getList(ifDevice.value)
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

/** 初始化 */
onMounted(() => {
  //一进来先查询分类的属性
  getList("1")
})
</script>
<style scoped>
.property-config-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.selected-info-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.selected-info {
  display: flex;
  align-items: center;
  gap: 12px;
}
.selected-name {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #1d2129;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.empty-image-container {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}

/* 新增样式：调整输入框显示效果 */
.inline-input {
  width: 100px;
  display: inline-block;
  vertical-align: middle;
}
.shake-highlight {
  animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
  background-color: red !important;
  box-shadow: 0 0 0 1px rgba(245, 108, 108, 0.2) !important;
}

@keyframes shake {
  10%, 90% { transform: translateX(-1px); }
  20%, 80% { transform: translateX(2px); }
  30%, 50%, 70% { transform: translateX(-3px); }
  40%, 60% { transform: translateX(3px); }
}
:deep(.el-select__selection) {
  height: 32px; /* 自定义高度 */
}
:deep(.el-select__placeholder.is-transparent){
  color: #409EFF;
}
.auto-wrap {
  /* 关键样式：确保文本能在容器内自动换行 */
  white-space: normal;
  word-break: break-all; /* 处理长单词或连续字符的换行 */
  display: inline-block; /* 确保span能正确应用宽度约束 */
  width: 100%; /* 让span占满父容器宽度 */
}
</style>
