<template>
  <div class="radarEditor" :class="{ disabled: props.disabled }">
    <DetectionAreaView :coordinates="coordinates" :direction="angle" mode="edit">
      <template #furnitures>
        <template v-if="showFurniture">
          <EditableFurniture
            v-for="item in roomStore.localFurnitureItems"
            :key="item.nanoid"
            :item="item"
            :angle="angle"
            :coordinates="coordinates"
            :canvas-size="500"
            :disabled="disabled"
            @update="handleFurnitureUpdate"
          />
        </template>
      </template>

      <template #subregion>
        <EditableSubregion
          v-if="showSubregion"
          ref="editableSubregionRef"
          :angle="angle"
          :canvas-size="500"
          :subRegions="roomStore.localSubRegions"
          :editable="!disabled"
          :has-bed="roomStore.localFurnitureItems.some((item) => item.type === 'bed')"
          @create="handleSubregionCreate"
          @update="handleSubregionUpdate"
        />
      </template>
    </DetectionAreaView>

    <div v-if="!disabled && showPanel" class="options">
      <div class="close" @click="showPanel = false">×</div>
      <div class="header">
        <a-radio-group
          v-model:value="modeRadio"
          button-style="solid"
          size="small"
          @change="modeRadioChange"
        >
          <a-radio-button :value="1">家具配置</a-radio-button>
          <a-radio-button :value="2">子区域配置</a-radio-button>
        </a-radio-group>
        <!-- <a-button type="link" size="small" @click="syncCoordinates">同步坐标</a-button> -->
      </div>

      <div v-if="modeRadio === 1" class="config">
        <div class="panel">
          <div class="panel-hd">家具</div>
          <div class="panel-ct">
            <div class="furnitureTool">
              <a-radio-group v-model:value="sideRadio" size="small">
                <a-radio :style="radioStyle" :value="1">客厅</a-radio>
                <a-radio :style="radioStyle" :value="2">餐厅</a-radio>
                <a-radio :style="radioStyle" :value="3">卧室</a-radio>
                <a-radio :style="radioStyle" :value="4">卫生间</a-radio>
              </a-radio-group>

              <furniture-list
                v-if="sideRadio === 1"
                :icons="livingroomIcons"
                @add="add"
              ></furniture-list>
              <furniture-list
                v-if="sideRadio === 2"
                :icons="diningroomIcons"
                @add="add"
              ></furniture-list>
              <furniture-list
                v-if="sideRadio === 3"
                :icons="bedroomIocns"
                @add="add"
              ></furniture-list>
              <furniture-list
                v-if="sideRadio === 4"
                :icons="bathroomIocns"
                @add="add"
              ></furniture-list>
            </div>
          </div>

          <div class="panel-hd">
            <div
              >已添加的家具
              <span v-if="roomStore.localFurnitureItems.length"
                >({{ roomStore.localFurnitureItems.length }})</span
              ></div
            >
            <a-space>
              <a-switch
                v-model:checked="showFurniture"
                size="small"
                checked-children="显示"
                un-checked-children="隐藏"
              />
              <a-popconfirm
                v-if="roomStore.localFurnitureItems.length"
                title="确定清空家具吗？"
                @confirm="clearFurniture"
              >
                <a-button size="small" type="link">清空</a-button>
              </a-popconfirm>
              <a-button size="small" type="link" @click="modeRadio = 1">添加</a-button>
            </a-space>
          </div>
          <div class="panel-ct">
            <template v-if="roomStore.localFurnitureItems.length">
              <div
                v-for="(furniture, index) in roomStore.localFurnitureItems"
                :key="index"
                class="list-item"
              >
                <a-collapse v-model:activeKey="furnitureActiveKey" ghost>
                  <a-collapse-panel :key="index + 1" :header="`${furniture.name} 属性`">
                    <div class="mapConfig">
                      <div class="mapConfig-item">
                        <label class="mapConfig-item-label">家具尺寸：</label>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-input-number
                              v-model:value="furniture.width"
                              :min="10"
                              size="small"
                              :style="inputStyle"
                            />
                            <a-input-number
                              v-model:value="furniture.length"
                              :min="10"
                              size="small"
                              :style="inputStyle"
                            />
                          </a-space>
                        </div>
                      </div>

                      <div class="mapConfig-item">
                        <label class="mapConfig-item-label">家具旋转：</label>
                        <div class="mapConfig-item-content">
                          <a-select
                            v-model:value="furniture.rotate"
                            size="small"
                            :style="inputStyle"
                          >
                            <a-select-option :value="0">0°</a-select-option>
                            <a-select-option :value="90">90°</a-select-option>
                            <a-select-option :value="180">180°</a-select-option>
                            <a-select-option :value="270">270°</a-select-option>
                          </a-select>
                        </div>
                      </div>

                      <!-- <div class="mapConfig-item">
                        <label class="mapConfig-item-label">位置微调：</label>
                        <div class="mapConfig-item-content"></div>
                        <a-space>
                          <ArrowLeftOutlined @click="nudge('left')" />
                          <ArrowUpOutlined @click="nudge('up')" />
                          <ArrowDownOutlined @click="nudge('down')" />
                          <ArrowRightOutlined @click="nudge('right')" />
                          <a-input-number
                            v-model:value="nudgeStep"
                            :min="1"
                            size="small"
                            style="width: 60px"
                          />
                        </a-space>
                      </div> -->

                      <!-- <div class="mapConfig-item">
                        <label class="mapConfig-item-label">left/top：</label>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-input-number
                              v-model:value="furniture.left"
                              disabled
                              size="small"
                              :style="inputStyle"
                            />
                            <a-input-number
                              v-model:value="furniture.top"
                              disabled
                              size="small"
                              :style="inputStyle"
                            />
                          </a-space>
                        </div>
                      </div> -->

                      <div class="mapConfig-item">
                        <label class="mapConfig-item-label">距离雷达：</label>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-input-number
                              v-model:value="furniture.x"
                              size="small"
                              :style="inputStyle"
                            />
                            <a-input-number
                              v-model:value="furniture.y"
                              size="small"
                              :style="inputStyle"
                            />
                          </a-space>
                        </div>
                      </div>

                      <div class="mapConfig-item">
                        <label class="mapConfig-item-label">操作：</label>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-popconfirm
                              title="确定删除家具吗？"
                              @confirm="deleteFurniture(furniture.nanoid!)"
                            >
                              <DeleteOutlined />
                            </a-popconfirm>
                          </a-space>
                        </div>
                      </div>
                    </div>
                  </a-collapse-panel>
                </a-collapse>
              </div>
            </template>
            <div v-else class="list-empty">暂无家具</div>
          </div>
        </div>
      </div>

      <div v-if="modeRadio === 2" class="info">
        <div class="panel">
          <div class="panel-hd">
            <div
              >已添加的子区域
              <span v-if="roomStore.localSubRegions.length"
                >({{ roomStore.localSubRegions.length }})</span
              ></div
            >
            <a-space>
              <a-switch
                v-model:checked="showSubregion"
                size="small"
                checked-children="显示"
                un-checked-children="隐藏"
              />
              <a-popconfirm
                v-if="roomStore.localSubRegions.length"
                title="确定清空子区域吗？"
                @confirm="clearSubregions"
              >
                <a-button size="small" type="link">清空</a-button>
              </a-popconfirm>
              <a-button size="small" type="link" @click="createSubregion">新建</a-button>
            </a-space>
          </div>
          <div class="panel-ct">
            <template v-if="roomStore.localSubRegions.length">
              <div
                v-for="(region, index) in roomStore.localSubRegions"
                :key="index"
                class="list-item"
              >
                <a-collapse v-model:activeKey="regionActiveKey" ghost>
                  <a-collapse-panel :key="index + 1" :header="`子区域 ${index + 1} 属性`">
                    <div class="mapConfig">
                      <div class="mapConfig-item">
                        <div class="mapConfig-item-label">X范围：</div>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-input
                              v-model:value.trim="region.startXx"
                              :style="inputStyle"
                              size="small"
                            />

                            <a-input
                              v-model:value.trim="region.stopXx"
                              :style="inputStyle"
                              size="small"
                            />
                          </a-space>
                        </div>
                      </div>

                      <div class="mapConfig-item">
                        <div class="mapConfig-item-label">Y范围：</div>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-input
                              v-model:value.trim="region.startYy"
                              :style="inputStyle"
                              size="small"
                            />

                            <a-input
                              v-model:value.trim="region.stopYy"
                              :style="inputStyle"
                              size="small"
                            />
                          </a-space>
                        </div>
                      </div>

                      <div class="mapConfig-item">
                        <div class="mapConfig-item-label">Z范围：</div>
                        <div class="mapConfig-item-content">
                          <a-space>
                            <a-input
                              v-model:value.trim="region.startZz"
                              :style="inputStyle"
                              size="small"
                            />

                            <a-input
                              v-model:value.trim="region.stopZz"
                              :style="inputStyle"
                              size="small"
                            />
                          </a-space>
                        </div>
                      </div>

                      <div class="mapConfig-item">
                        <div class="mapConfig-item-label">区域跟踪：</div>
                        <div class="mapConfig-item-content">
                          <a-switch v-model:checked="region.isTracking" size="small" />
                        </div>
                      </div>

                      <div class="mapConfig-item">
                        <div class="mapConfig-item-label">区域跌倒：</div>
                        <div class="mapConfig-item-content">
                          <a-switch v-model:checked="region.isFalling" size="small" />
                        </div>
                      </div>

                      <div v-if="region.isBed" class="mapConfig-item">
                        <div class="mapConfig-item-label">呼吸检测：</div>
                        <div class="mapConfig-item-content"> 默认开启 </div>
                      </div>

                      <div class="mapConfig-item">
                        <div class="mapConfig-item-label">删除区域：</div>
                        <div class="mapConfig-item-content">
                          <a-popconfirm
                            title="确定删除区域吗？"
                            @confirm="deleteBlockArea(region.nanoid || '')"
                          >
                            <DeleteOutlined />
                          </a-popconfirm>
                        </div>
                      </div>
                    </div>
                  </a-collapse-panel>
                </a-collapse>
              </div>
            </template>
            <div v-else class="list-empty">暂无子区域</div>
          </div>
        </div>
      </div>
    </div>

    <a-button v-else type="link" @click="showPanel = true">开始配置</a-button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted, reactive } from 'vue'
import DetectionAreaView from '../DetectionAreaView/index.vue'
import EditableFurniture from '../EditableFurniture/index.vue'
import EditableSubregion from '../EditableSubregion/index.vue'
import type { FurnitureIconType } from '@/types/furniture'
// import { message } from 'ant-design-vue'
import { nanoid } from 'nanoid'
import { furnitureIconNameMap, furnitureIconSizeMap } from '@/const/furniture'
import type { LocalFurnitureItem, LocalSubRegionItem } from '@/api/room/types'
import {
  DeleteOutlined,
  // ArrowLeftOutlined,
  // ArrowUpOutlined,
  // ArrowDownOutlined,
  // ArrowRightOutlined,
} from '@ant-design/icons-vue'
import { useRoomStore } from '@/stores/room'

defineOptions({ name: 'RadarEditor' })

interface Props {
  coordinates: [number, number, number, number]
  angle: number
  disabled?: boolean
}
const props = defineProps<Props>()

const roomStore = useRoomStore()

console.log('props', props)

const inputStyle = computed(() => ({ width: '70px' }))
// const pixelPosition = reactive({ left: 0, top: 0 })
// const nudgeStep = ref(5)
// 微调功能
// const nudge = (direction: 'left' | 'right' | 'up' | 'down') => {
//   const step = nudgeStep.value
//   switch (direction) {
//     case 'left':
//       pixelPosition.left -= step
//       break
//     case 'right':
//       pixelPosition.left += step
//       break
//     case 'up':
//       pixelPosition.top -= step
//       break
//     case 'down':
//       pixelPosition.top += step
//       break
//   }
// }

function deleteFurniture(nanoid: string) {
  roomStore.localFurnitureItems = roomStore.localFurnitureItems.filter((i) => i.nanoid !== nanoid)
}

// function addFurniture(item: FurnitureItem) {
//   // localFurniture.value.push(item)
//   roomStore.localFurnitureItems.push(item)
//   // emit('update:furnitureItems', [...roomStore.localFurnitureItems])
// }

// defineExpose({ addFurniture })

const modeRadio = ref<1 | 2 | 3>(1)
const sideRadio = ref<1 | 2 | 3 | 4>(1)
const editableSubregionRef = ref<InstanceType<typeof EditableSubregion>>()

const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
})

// 客厅图标
const livingroomIcons = [
  'living_sofa',
  'living_sofa_single',
  'living_tea_table',
  'living_bookcase',
  'living_tv_stand',
]

// 餐厅图标
const diningroomIcons = [
  'dining_table',
  'dining_table_rect',
  'dining_fridge',
  'dining_chair',
  'bath_door',
]

// 卧室图标
const bedroomIocns = [
  'bed',
  'bed_table',
  'bed_dressing_chair',
  'bed_dressing_mirror',
  'bed_cabinet',
]

// 卫生间图标
const bathroomIocns = ['bath_basin', 'bath_shower', 'bath_toilet', 'bath_floor']

// 添加家具
const add = (icon: FurnitureIconType) => {
  const originWidth = furnitureIconSizeMap[icon].width || 30
  const originHeight = furnitureIconSizeMap[icon].height || 30

  const newItem: LocalFurnitureItem = {
    name: furnitureIconNameMap[icon],
    type: icon,
    width: originWidth,
    length: originHeight,
    // top: 0,
    // left: 0,
    rotate: 0,
    x: 0,
    y: 0,
    nanoid: nanoid(),
  }

  roomStore.localFurnitureItems.push(newItem)
  // message.success('已添加家具')
}

const handleFurnitureUpdate = (item: LocalFurnitureItem) => {
  roomStore.localFurnitureItems = roomStore.localFurnitureItems.map((i) =>
    i.nanoid === item.nanoid ? item : i
  )
}

// 创建子区域
const createSubregion = () => {
  if (editableSubregionRef.value) {
    editableSubregionRef.value?.createNewBlock()
  }
}

// 处理子区域创建事件
const handleSubregionCreate = () => {
  // message.success('已创建子区域')
}

// 处理子区域更新事件
const handleSubregionUpdate = (item: LocalSubRegionItem[]) => {
  // 可以在这里添加更新后的逻辑
  const hasBed = roomStore.localFurnitureItems.some((furniture) => furniture.type === 'bed')
  console.log('子区域更新', item, hasBed)
  if (hasBed) {
    roomStore.localSubRegions = item.map((region, index) => ({
      ...region,
      isBed: index === 0,
    }))
  } else {
    roomStore.localSubRegions = item
  }
}

const showPanel = ref(true)
const showSubregion = ref(false)
const showFurniture = ref(true)

setTimeout(() => {
  showSubregion.value = true
}, 500)

onUnmounted(() => {
  // 组件销毁时清除缓存
  localStorage.removeItem('subRegions')
})

const regionActiveKey = ref<number[]>([])
const furnitureActiveKey = ref<number[]>([])

const deleteBlockArea = (id: string) => {
  if (id) {
    roomStore.localSubRegions = roomStore.localSubRegions.filter((item) => item.nanoid !== id)
  }
}

const modeRadioChange = () => {
  regionActiveKey.value = []
  furnitureActiveKey.value = []
}

// const syncCoordinates = () => {
//   console.log('同步坐标', localFurniture.value, localSubRegions.value)
// }

const clearSubregions = () => {
  roomStore.localSubRegions = []
}

const clearFurniture = () => {
  roomStore.localFurnitureItems = []
}
</script>

<style scoped lang="less">
.radarEditor.disabled {
  cursor: no-drop;
  :deep(*) {
    pointer-events: none;
    user-select: none;
    opacity: 0.85;
  }
}

.radarEditor {
  position: relative;
  display: flex;
  gap: 8px;

  .radar-view {
    flex-shrink: 0;
  }

  .options {
    width: 280px;
    background-color: #fefefe;
    border-radius: 10px;
    padding: 12px;
    position: relative;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

    .close {
      position: absolute;
      top: 8px;
      right: 12px;
      font-size: 22px;
      font-weight: 600;
      line-height: 1;
      color: #999;
      cursor: pointer;
      transition: color 0.2s;
    }

    .header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
    }
  }
}

.panel {
  margin-bottom: 12px;
  &-hd {
    font-size: 12px;
    font-weight: 600;
    color: #666;
    line-height: 1.5;
    padding: 5px 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .ant-btn-link {
      font-size: 12px;
      line-height: 1.5;
      padding: 0;
    }
  }
  &-ct {
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-height: 30px;
    max-height: 300px;
    overflow-y: auto;

    // 滚动条不遮挡内容
    ::-webkit-scrollbar {
      width: 4px;
      height: 4px;
    }
    ::-webkit-scrollbar-track {
      background-color: transparent;
    }
    ::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 2px;
    }

    .furnitureTool {
      display: flex;
      justify-content: space-between;
      background-color: #f5f5f5;
      padding: 8px;
      border-radius: 8px;

      .furnitureList {
        flex-grow: 1;
      }
    }

    .subregionTool {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      padding: 10px 12px;
      border-radius: 8px;
      font-size: 14px;
      color: #333;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }

  .list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 8px;
    background-color: #f5f5f5;
    cursor: pointer;
  }

  .list-empty {
    padding: 8px 12px;
    font-size: 14px;
    color: #999;
    border-radius: 8px;
    background-color: #f5f5f5;
  }
}

.mapConfig {
  background-color: #f5f5f5;
  border-radius: 10px;
  padding: 0 12px;
  &-header {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-size: 14px;
      font-weight: 600;
      line-height: 24px;
    }
    .close {
      font-size: 14px;
      color: #666;
      cursor: pointer;
      position: relative;
      top: -5px;
    }
  }

  &-item {
    display: flex;
    line-height: 30px;
    &-label {
      color: #888;
      min-width: 80px;
    }
    &-content {
      color: #555;
    }
  }
}
:deep(.ant-collapse) {
  width: 100%;
}
:deep(.ant-collapse .ant-collapse-content > .ant-collapse-content-box) {
  padding: 0;
}
:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
  padding: 5px;
  user-select: none;
}
</style>
