<template>
  <view class="gender-card" ref="cardRef">
    <view class="card-header">
      <text class="title">用户性别比例</text>
    </view>
    
    <view class="card-content">
      <!-- 上部/左部图例区 - 复刻新图样式 (stacked) -->
      <view class="legend-col">
        <view class="legend-item" v-for="(item, index) in (genderData as UTSJSONObject[])" :key="index">
          <view class="legend-dot" :style="{ backgroundColor: (item['itemStyle'] as UTSJSONObject)['color'] as string }"></view>
          <text class="legend-label">{{ item['name'] }}</text>
        </view>
      </view>

      <!-- 下部图表区 - 核心容器 -->
      <view class="chart-col" ref="chartWrapRef">
        <!-- 图表组件 -->
        <EChartsView :option="chartOption" class="donut-chart" />
        
        <!-- 中心文字：绝对居中 -->
        <view class="center-text">
          <text class="total-label">总用户数</text>
          <text class="total-value">{{ totalUsers }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="uts">
import EChartsView from '@/uni_modules/charts/EChartsView.vue'
import { showSubSider, isMainAsideCollapsed, layoutMode } from '@/layouts/admin/store/adminNavStore.uts'

/**
 * 用户性别比例 - CRMEB 1:1 复刻版 (响应式增强)
 * 解决了：<1200px 布局切换、Canvas 溢出、图表裁切、中心偏移问题
 */
export default {
  components: {
    EChartsView
  },
  data() {
    return {
      totalUsers: 789,
      genderData: [
        { value: 400, name: '男', itemStyle: { color: '#1890ff' } },
        { value: 300, name: '女', itemStyle: { color: '#febc2c' } },
        { value: 89, name: '未知', itemStyle: { color: '#919eab' } }
      ],
      chartOption: {} as any,
      resizeObserver: null as any | null
    }
  },
  computed: {
    navState(): string {
      return `${showSubSider.value}-${isMainAsideCollapsed.value}-${layoutMode.value}`
    }
  },
  watch: {
    navState() {
      // 侧边栏/断点状态变化时，强制触发 resize
      this.triggerRobustResize()
    }
  },
  mounted() {
    this.setupResizeSystem()
    
    // 📌 参考 AnalyticsPieChart 的延迟初始化策略，解决 H5 渲染 0 宽高问题
    setTimeout(() => {
      this.initChart()
    }, 300)
  },
  unmounted() {
    if (this.resizeObserver != null) {
      (this.resizeObserver as any).disconnect()
    }
    window.removeEventListener('resize', this.triggerRobustResize)
    
    const sidebar = document.querySelector('.admin-sidebar-container') || document.querySelector('.admin-main-aside')
    if (sidebar != null) {
      sidebar.removeEventListener('transitionend', this.triggerRobustResize)
    }
  },
  methods: {
    initChart() {
      // 📌 参考 AnalyticsPieChart 的数据映射和 PlainObject 处理
      const plainData = (this.genderData as Array<any>).map((it) => {
        const itemStyle = it['itemStyle'] ? this.toPlainObject(it['itemStyle']) : {} as any
        return {
          name: String(it['name']),
          value: Number(it['value']),
          itemStyle: itemStyle
        }
      })

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: '#fff',
          padding: [10, 15],
          textStyle: { color: '#333' },
          extraCssText: 'box-shadow: 0 2px 8px rgba(0,0,0,0.15); border-radius: 4px;'
        },
        legend: { show: false },
        series: [
          {
            name: '性别比例',
            type: 'pie',
            radius: ['58%', '75%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            label: { show: false },
            emphasis: {
              scale: true,
              scaleSize: 10,
              label: { show: false }
            },
            data: plainData
          }
        ]
      }
      this.chartOption = this.toPlainObject(option)
    },

    /**
     * 建立可靠 resize 闭环
     */
    setupResizeSystem() {
      // 1. ResizeObserver 监听容器真实尺寸变化 (节流处理)
      if (typeof ResizeObserver !== 'undefined') {
        let timer: any = null
        this.resizeObserver = new ResizeObserver(() => {
          if (timer) return
          timer = setTimeout(() => {
            this.triggerRobustResize()
            timer = null
          }, 100)
        })
        const wrap = (this.$refs['chartWrapRef'] as any).$el
        if (wrap != null) {
          (this.resizeObserver as any).observe(wrap)
        }
      }

      // 2. Window Resize 兜底
      window.addEventListener('resize', this.triggerRobustResize)

      // 3. 监听侧边栏动画结束 (transitionend)
      const sidebar = document.querySelector('.admin-sidebar-container') || document.querySelector('.admin-main-aside')
      if (sidebar != null) {
        sidebar.addEventListener('transitionend', this.triggerRobustResize)
      }
    },

    triggerRobustResize() {
      // 触发一次 layout 后的渲染
      requestAnimationFrame(() => {
        window.dispatchEvent(new Event('resize'))
        
        // 补充第二次 frame 针对重构动画的延迟校准
        setTimeout(() => {
          window.dispatchEvent(new Event('resize'))
        }, 30)
      })
    },

    toPlainObject(obj: any): any {
      if (obj == null) return null
      if (typeof obj !== 'object') return obj
      if (Array.isArray(obj)) {
        return obj.map((item: any): any => this.toPlainObject(item))
      }
      const plain: any = {}
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          const value = obj[key]
          if (typeof value === 'function' || key.startsWith('_') || key === 'toJSON') {
            continue
          }
          if (value != null && typeof value === 'object' && !Array.isArray(value)) {
            // 📌 参考 AnalyticsPieChart 的优化逻辑，处理普通对象拷贝
            let isSimple = true
            for (const k in value) {
              if (typeof value[k] === 'object' && value[k] !== null) {
                isSimple = false
                break
              }
            }
            plain[key] = isSimple ? { ...value } : this.toPlainObject(value)
          } else {
            plain[key] = value
          }
        }
      }
      return plain
    }
  }
}
</script>

<style scoped lang="scss">
.gender-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  box-sizing: border-box;
  width: 100%;
  height: 100%; /* 确保沾满父级格子 */
}

.card-header {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.title {
  font-size: 16px;
  font-weight: bold; /* 同步地图 bold */
  color: #333;
}

.card-content {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  min-height: 0;
}

/* 图例区 (横向排列) 对齐图片 */
.legend-col {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.legend-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-label {
  font-size: 14px;
  color: #333;
}

/* 核心图表列 (centered) */
.chart-col {
  flex: 1;
  width: 100%;
  position: relative;
  min-height: 0; /* 允许 flex 压缩 */
  overflow: visible !important;
  display: flex;
  justify-content: center;
}

/* 响应式断点 - 维持垂直布局并增加空间 */
@media (max-width: 1199.98px) {
  .chart-col {
    height: 400px; /* 增加高度，给图表更多空间 */
    min-height: 400px;
  }
  
  .gender-card {
    height: auto; /* 在单列模式下允许高度自适应 */
    min-height: 480px; /* 确保整体卡片有足够高度 */
  }
}

/* 强制覆盖 EChartsView 样式 (确保完整铺满并通过 ECharts 配置居中) */
:deep(.donut-chart) {
  width: 100% !important;
  height: 100% !important;
  
  .ec-wrap {
    position: relative !important;
    width: 100% !important;
    height: 100% !important;
    overflow: visible !important;
  }
  
  .ec-canvas {
    position: absolute !important;
    inset: 0 !important;
    width: 100% !important;
    height: 100% !important;
  }
}

/* 图表中心文字 (必须绝对居中于容器，微调位置垂直视觉居中) */
.center-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  pointer-events: none;
  user-select: none;
  z-index: 10;
}

.total-label {
  font-size: 15px;
  color: #666;
  margin-bottom: 0;
  font-weight: 700;
}

.total-value {
  font-size: 48px;
  font-weight: 700;
  color: #333;
  line-height: 1.1;
}
</style>
