<script lang="ts" setup>
import * as echarts from 'echarts'
import {
  ANIMATION,
  CHART_RENDERER,
  createLegend,
  createTooltip,
  FONT_FAMILY,
  THEME
} from '@/utils/kb'

type ActivePanel = 'category' | 'value'

type EquipmentCategoryItem = {
  project: string
  model: string
  total: number
  owned: number
}

const activePanel = ref<ActivePanel>('category')
const categoryChartRef = ref<HTMLDivElement>()
let categoryChart: echarts.ECharts | null = null

const panelOptions: Array<{ label: string; value: ActivePanel }> = [
  {
    label: '类别',
    value: 'category'
  },
  {
    label: '价值',
    value: 'value'
  }
]

const activeTitle = computed(() =>
  activePanel.value === 'category' ? '设备类别统计' : '设备价值统计'
)

const categoryData: EquipmentCategoryItem[] = [
  { project: 'SCP项目', model: '50L', total: 4, owned: 3 },
  { project: '紫金山项目', model: '40J', total: 2, owned: 1 },
  { project: '新疆修井项目', model: '650HP', total: 1, owned: 1 },
  { project: '新疆修井项目', model: '550HP', total: 7, owned: 7 },
  { project: '新疆修井项目', model: '450HP', total: 2, owned: 2 },
  { project: '伊拉克钻修项目', model: '750HP', total: 4, owned: 4 },
  { project: '伊拉克钻修项目', model: '1000HP', total: 2, owned: 2 },
  { project: '伊拉克钻修项目', model: '70D', total: 1, owned: 1 },
  { project: '伊拉克一体化钻井项目', model: '70D', total: 1, owned: 0 },
  { project: '阿根廷项目', model: '350HP', total: 3, owned: 3 },
  { project: '埃塞项目', model: '50D', total: 2, owned: 0 }
]

function formatProjectName(value: string) {
  return value.replace(/项目$/, '')
}

const categoryRows = computed(() =>
  categoryData.map((item, index) => {
    const nonOwned = Math.max(item.total - item.owned, 0)
    const displayProject = formatProjectName(item.project)
    const isFirstProjectRow = index === 0 || categoryData[index - 1].project !== item.project

    return {
      ...item,
      displayProject,
      projectLabel: isFirstProjectRow ? displayProject : '',
      nonOwned
    }
  })
)

function getCategoryChartLayout() {
  const { clientWidth = 0, clientHeight = 0 } = categoryChartRef.value ?? {}
  const compact = clientHeight > 0 && (clientHeight < 210 || clientWidth < 520)

  return {
    compact,
    gridTop: compact ? 26 : 34,
    gridRight: compact ? 24 : 92,
    gridBottom: compact ? 20 : 24,
    gridLeft: compact ? 154 : 200,
    legendLeft: compact ? 282 : 360,
    legendItemSize: compact ? 8 : 10,
    legendGap: compact ? 10 : 14,
    axisFontSize: compact ? 10 : 12,
    projectFontSize: compact ? 11 : 13,
    modelLabelWidth: compact ? 44 : 54,
    projectLabelWidth: compact ? 90 : 104,
    projectOffset: compact ? 58 : 70,
    barWidth: compact ? 9 : 13,
    summaryLabelDistance: compact ? 4 : 6,
    summaryLabelFontSize: compact ? 10 : 12
  }
}

function getCategoryOption(data: any): echarts.EChartsOption {
  const modelLabels = data.map((item) => item.model)
  const projectLabels = data.map((item) => item.projectLabel)
  const totalData = data.map((item) => item.total)
  const ownedData = data.map((item) => item.owned)
  const nonOwnedData = data.map((item) => item.nonOwned)
  const maxTotal = Math.max(...totalData, 1)
  const layout = getCategoryChartLayout()
  const summaryLabel = {
    show: true,
    position: 'right' as any,
    distance: layout.summaryLabelDistance,
    color: THEME.text.strong,
    fontSize: layout.summaryLabelFontSize,
    fontWeight: 700,
    fontFamily: FONT_FAMILY,
    formatter(params: any) {
      const row = data[params.dataIndex]

      if (!row) return ''

      return `${row.owned} / ${row.nonOwned}`
    }
  }

  return {
    ...ANIMATION,
    grid: {
      ...THEME.grid,
      top: layout.gridTop,
      right: layout.gridRight,
      bottom: layout.gridBottom,
      left: layout.gridLeft,
      containLabel: false
    },
    color: [THEME.color.green.line, THEME.color.orange.line],
    legend: createLegend(
      {
        top: 0,
        right: 0,
        left: layout.legendLeft,
        itemWidth: layout.legendItemSize,
        itemHeight: layout.legendItemSize,
        itemGap: layout.legendGap,
        selectedMode: true
      },
      ['自有设备', '非自有设备']
    ),
    tooltip: createTooltip({
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: THEME.split
        }
      },
      formatter(params: any[]) {
        const first = params[0]
        const row = data[first?.dataIndex ?? 0]
        if (!row) return ''

        const ownedMarker =
          '<span style="display:inline-block;width:8px;height:8px;margin-right:6px;border-radius:2px;background:#2e9a5b;"></span>'
        const nonOwnedMarker =
          '<span style="display:inline-block;width:8px;height:8px;margin-right:6px;border-radius:2px;background:#f08c2e;"></span>'

        return [
          `<div style="min-width:132px;font-weight:700;color:#24364f;margin-bottom:6px;">${row.displayProject} / ${row.model}</div>`,
          `<div style="display:flex;justify-content:space-between;gap:18px;line-height:22px;"><span>${ownedMarker}自有设备</span><b style="color:#2e9a5b;">${row.owned}</b></div>`,
          `<div style="display:flex;justify-content:space-between;gap:18px;line-height:22px;"><span>${nonOwnedMarker}非自有设备</span><b style="color:#f08c2e;">${row.nonOwned}</b></div>`,
          `<div style="margin-top:4px;padding-top:4px;border-top:1px solid rgba(31,91,184,.12);display:flex;justify-content:space-between;gap:18px;line-height:22px;"><span>设备合计</span><b style="color:#1f5bb8;">${row.total}</b></div>`
        ].join('')
      }
    }),
    xAxis: {
      type: 'value',
      max: Math.max(10, Math.ceil(maxTotal + 1)),
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      },
      axisLabel: {
        show: true,
        color: THEME.text.regular,
        fontSize: layout.axisFontSize,
        fontWeight: 500,
        fontFamily: FONT_FAMILY
      },
      splitLine: {
        lineStyle: {
          color: THEME.split,
          type: 'dashed'
        }
      }
    },
    yAxis: [
      {
        type: 'category',
        data: modelLabels,
        inverse: true,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: THEME.text.regular,
          fontSize: layout.axisFontSize,
          fontWeight: 500,
          fontFamily: FONT_FAMILY,
          margin: layout.compact ? 6 : 10,
          width: layout.modelLabelWidth,
          overflow: 'truncate',
          align: 'right'
        }
      },
      {
        type: 'category',
        data: projectLabels,
        inverse: true,
        position: 'left',
        offset: layout.projectOffset,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: THEME.text.strong,
          fontSize: layout.projectFontSize,
          fontWeight: 700,
          fontFamily: FONT_FAMILY,
          margin: layout.compact ? 6 : 10,
          width: layout.projectLabelWidth,
          overflow: 'break',
          align: 'right'
        }
      }
    ],
    series: [
      {
        name: '设备数量',
        type: 'bar',
        data: totalData,
        barWidth: layout.barWidth,
        silent: true,
        z: 1,
        label: summaryLabel,
        labelLayout: {
          hideOverlap: false
        },
        itemStyle: {
          borderRadius: 999,
          color: THEME.split
        },
        tooltip: {
          show: false
        }
      },
      {
        name: '自有设备',
        type: 'bar',
        stack: 'device',
        data: ownedData,
        barWidth: layout.barWidth,
        barGap: '-100%',
        z: 3,
        itemStyle: {
          // borderRadius: [999, 0, 0, 999],
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: THEME.color.green.light },
            { offset: 0.55, color: THEME.color.green.mid },
            { offset: 1, color: THEME.color.green.line }
          ])
        }
      },
      {
        name: '非自有设备',
        type: 'bar',
        stack: 'device',
        data: nonOwnedData,
        barWidth: layout.barWidth,
        z: 3,
        itemStyle: {
          // borderRadius: [0, 999, 999, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: THEME.color.orange.light },
            { offset: 0.55, color: THEME.color.orange.mid },
            { offset: 1, color: THEME.color.orange.line }
          ])
        }
      }
    ]
  }
}

function initCategoryChart() {
  if (!categoryChartRef.value) return

  if (categoryChart) {
    categoryChart.dispose()
  }

  categoryChart = echarts.init(categoryChartRef.value, undefined, {
    renderer: CHART_RENDERER
  })
  renderCategoryChart()
}

function renderCategoryChart() {
  categoryChart?.setOption(getCategoryOption(categoryRows.value), true)
}

function resizeCategoryChart() {
  categoryChart?.resize()
  renderCategoryChart()
}

function destroyCategoryChart() {
  if (categoryChart) {
    categoryChart.dispose()
    categoryChart = null
  }
}

watch(activePanel, (value) => {
  if (value !== 'category') return

  nextTick(() => {
    resizeCategoryChart()
  })
})

onMounted(() => {
  initCategoryChart()
  window.addEventListener('resize', resizeCategoryChart)
  window.addEventListener('rykb:resize', resizeCategoryChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeCategoryChart)
  window.removeEventListener('rykb:resize', resizeCategoryChart)
  destroyCategoryChart()
})
</script>

<template>
  <div class="panel flex flex-col">
    <div class="panel-title flex items-center justify-between">
      <div class="kb-panel-title-text flex items-center">
        <div class="icon-decorator">
          <span></span>
          <span></span>
        </div>
        {{ activeTitle }}
      </div>
      <el-segmented
        v-model="activePanel"
        :options="panelOptions"
        size="small"
        class="equipment-category-switch" />
    </div>
    <div class="flex-1 min-h-0">
      <div v-show="activePanel === 'category'" ref="categoryChartRef" class="category-chart"></div>
      <div v-show="activePanel === 'value'" class="h-full"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url('@/styles/kb.scss');

.equipment-category-switch {
  --el-segmented-item-selected-color: #03409b;
  --el-segmented-item-selected-bg-color: rgb(255 255 255 / 86%);
  --el-segmented-bg-color: rgb(31 91 184 / 10%);
  --el-segmented-item-hover-bg-color: rgb(255 255 255 / 56%);

  min-height: calc(26px * var(--kb-scale, 1));
  padding: calc(2px * var(--kb-scale, 1));
  border: 1px solid rgb(31 91 184 / 12%);
  transform: translateY(calc(-2px * var(--kb-scale, 1)));

  :deep(.el-segmented__item) {
    min-height: calc(22px * var(--kb-scale, 1));
    padding: 0 calc(8px * var(--kb-scale, 1));
    font-size: calc(13px * var(--kb-scale, 1));
    font-weight: 600;
    color: #29527f;
  }
}

.category-chart {
  width: 100%;
  height: 100%;
  min-height: 0;
}
</style>
