<template>
  <div class="right-data-box3">
    <LDBTitleBox title="质量管理" align="right" />
    <div class="quality-management-content">
      <div>
        <ul class=" quality-tab-menu">
          <li :class="currentTab === 0 ? 'ym-active1' : 'taba1'">
            <a href="" @click.prevent="switchTab(0)">SPC控制图</a>
          </li>
          <li :class="currentTab === 1 ? 'ym-active1' : 'taba1'">
            <a href="" @click.prevent="switchTab(1)">工序能力分析</a>
          </li>
          <li :class="currentTab === 2 ? 'ym-active1' : 'taba1'">
            <a href="" @click.prevent="switchTab(2)">均值极差图</a>
          </li>
        </ul>
      </div>

      <div class="quality-charts-container" @mouseenter="pauseTabRotation" @mouseleave="resumeTabRotation">
        <div id="quality-box2" class="quality-chart" :style="{ display: currentTab === 0 ? 'block' : 'none' }"></div>
        <div id="quality-box4" class="quality-chart" :style="{ display: currentTab === 1 ? 'block' : 'none' }"></div>
        <div id="quality-box6" class="quality-chart" :style="{ display: currentTab === 2 ? 'block' : 'none' }"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'


// ==================== 组件定义 ====================
defineOptions({
  name: 'QualityManagement',
})

// ==================== 数据定义 ====================
const qualityCharts = ref<echarts.ECharts[]>([])
const currentTab = ref(0)
const tabTimer = ref<ReturnType<typeof setInterval> | null>(null)
const isPaused = ref(false)

// ==================== 图表初始化 ====================
// 初始化质量管理图表
const initQualityCharts = () => {
  nextTick(() => {
    // SPC控制图
    const chartDom1 = document.getElementById('quality-box2')
    if (chartDom1) {
      const chart = echarts.init(chartDom1)
      const option = getSPCChartOption()
      chart.setOption(option)
      qualityCharts.value.push(chart)
    }

    // 工序能力分析图
    const chartDom2 = document.getElementById('quality-box4')
    if (chartDom2) {
      const chart = echarts.init(chartDom2)
      const option = getProcessCapabilityOption()
      chart.setOption(option)
      qualityCharts.value.push(chart)
    }

    // 均值极差图
    const chartDom3 = document.getElementById('quality-box6')
    if (chartDom3) {
      const chart = echarts.init(chartDom3)
      const option = getMeanRangeChartOption()
      chart.setOption(option)
      qualityCharts.value.push(chart)
    }
  })
}

// ==================== 图表配置 ====================
// SPC控制图配置
const getSPCChartOption = () => {
  // 计算SPC参数
  const data = [0.12, 0.15, 0.18, 0.14, 0.16, 0.13, 0.17, 0.19, 0.11, 0.15]
  const mean = data.reduce((a, b) => a + b, 0) / data.length
  const range = Math.max(...data) - Math.min(...data)
  const ucl = mean + 0.15 // 模拟计算的上控制限
  const lcl = Math.max(0, mean - 0.15) // 模拟计算的下控制限，确保不为负

  return {
    title: {
      text: `SPC控制图 (CL=${mean.toFixed(3)}, UCL=${ucl.toFixed(3)}, LCL=${lcl.toFixed(3)})`,
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 350
      },
      top: '5%'
    },
    color: ['#38b3f1'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      }
    },
    grid: {
      top: '30%',
      left: '5%',
      right: '15%',
      bottom: '0%',
      containLabel: true
    },
    xAxis: [{
      type: 'category',
      data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      axisLabel: {
        color: '#fff'
      },
      axisTick: {
        alignWithLabel: true
      }
    }],
    yAxis: [{
      type: 'value',
      axisLabel: {
        color: '#fff'
      },
      name: '质量特性',
      nameTextStyle: {
        color: '#fff',
        fontWeight: 300,
        fontSize: 12
      }
    }],
    series: [{
      name: 'SPC',
      type: 'line',
      barWidth: '60%',
      data: data,
      markLine: {
        data: [
          {
            name: 'UCL',
            yAxis: ucl,
            lineStyle: {
              color: '#F56C6C',
              type: 'dashed'
            },
            label: {
              formatter: 'UCL: {c}',
              position: 'end',
              color: '#F56C6C'
            }
          },
          {
            name: 'CL',
            yAxis: mean,
            lineStyle: {
              color: '#67C23A',
              type: 'solid'
            },
            label: {
              formatter: 'CL: {c}',
              position: 'end',
              color: '#67C23A'
            }
          },
          {
            name: 'LCL',
            yAxis: lcl,
            lineStyle: {
              color: '#F56C6C',
              type: 'dashed'
            },
            label: {
              formatter: 'LCL: {c}',
              position: 'end',
              color: '#F56C6C'
            }
          }
        ]
      },
      lineStyle: {
        color: '#38b3f1',
        width: 2
      },
      itemStyle: {
        color: '#38b3f1'
      },
      symbol: 'circle',
      symbolSize: 6
    }]
  }
}

// 工序能力分析图配置
const getProcessCapabilityOption = () => {
  return {
    title: {
      text: '工序能力分析 (Cp=1.45, Cpk=1.32)',
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 500
      },
      top: '2%'
    },
    textStyle: {
      color: '#fff'
    },
    grid: {
      top: '30%',
      left: '5%',
      right: '20%',
      bottom: '0%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#fff'
        }
      },
      formatter: (params: any) => {
        let tooltipText = `数值: ${params[0].name}<br/>`
        params.forEach((param: any) => {
          if (param.seriesType === 'custom') {
            tooltipText += '概率密度: ' + param.value[1] + '<br/>'
          }
        })
        return tooltipText
      }
    },
    xAxis: [{
      type: 'value',
      min: 8,
      max: 12,
      interval: 0.5,
      axisLabel: {
        color: '#fff'
      },
      name: '质量特性值',
      nameTextStyle: {
        color: '#fff'
      }
    }],
    yAxis: [{
      type: 'value',
      name: '频率',
      min: 0,
      max: 0.25,
      interval: 0.05,
      axisLabel: {
        formatter: '{value}',
        color: '#fff'
      },
    }],
    series: [{
      name: '平滑直方图',
      type: 'custom',
      renderItem: function (params: any, api: any) {
        const xValue = api.value(0);
        const yValue = api.value(1);
        const barWidth = 0.3; // 柱状图宽度
        const smoothFactor = 0.1; // 平滑因子

        const points = [];

        // 左侧底部
        points.push([api.coord([xValue - barWidth / 2, 0])]);
        // 左侧顶部带圆弧
        points.push([api.coord([xValue - barWidth / 2, yValue * (1 - smoothFactor)])]);
        points.push([api.coord([xValue - barWidth / 4, yValue])]);
        points.push([api.coord([xValue, yValue])]);
        // 右侧顶部带圆弧
        points.push([api.coord([xValue + barWidth / 4, yValue])]);
        points.push([api.coord([xValue + barWidth / 2, yValue * (1 - smoothFactor)])]);
        // 右侧底部
        points.push([api.coord([xValue + barWidth / 2, 0])]);

        return {
          type: 'polygon',
          shape: {
            points: points
          },
          style: api.style()
        };
      },
      itemStyle: {
        color: '#F56C6C',
        opacity: 0.8
      },
      markLine: {
        data: [
          {
            name: 'LSL',
            xAxis: 8.5,
            lineStyle: {
              color: '#F56C6C',
              type: 'dashed'
            },
            label: {
              formatter: 'LSL',
              position: 'end',
              color: '#F56C6C',
            }
          },
          {
            name: '目标值',
            xAxis: 9.8,
            lineStyle: {
              color: '#67C23A',
              type: 'solid'
            },
            label: {
              formatter: '目标: 9.8',
              position: 'end',
              color: '#67C23A',
              offset: [0, -15]
            }
          },
          {
            name: 'USL',
            xAxis: 11.0,
            lineStyle: {
              color: '#F56C6C',
              type: 'dashed'
            },
            label: {
              formatter: 'USL',
              position: 'end',
              color: '#F56C6C'
            }
          },
          {
            name: '均值',
            xAxis: 9.5,
            lineStyle: {
              color: '#E6A23C',
              type: 'solid'
            },
            label: {
              formatter: '均值: 9.5',
              position: 'end',
              color: '#E6A23C'
            }
          }
        ],
        symbol: 'none'
      },
      // 使用更平滑的数据点
      data: [
        [8.0, 0.001], [8.2, 0.005], [8.4, 0.012],
        [8.6, 0.025], [8.8, 0.048], [9.0, 0.085],
        [9.1, 0.110], [9.2, 0.140], [9.3, 0.175],
        [9.4, 0.210], [9.45, 0.230], [9.5, 0.240],
        [9.55, 0.235], [9.6, 0.220], [9.7, 0.190],
        [9.8, 0.155], [9.9, 0.120], [10.0, 0.090],
        [10.2, 0.045], [10.4, 0.020], [10.6, 0.008],
        [10.8, 0.003], [11.0, 0.001]
      ]
    }, {
      name: '分布曲线',
      type: 'line',
      smooth: true,
      data: [
        [8.0, 0.001], [8.2, 0.005], [8.4, 0.012],
        [8.6, 0.025], [8.8, 0.048], [9.0, 0.085],
        [9.1, 0.110], [9.2, 0.140], [9.3, 0.175],
        [9.4, 0.210], [9.45, 0.230], [9.5, 0.240],
        [9.55, 0.235], [9.6, 0.220], [9.7, 0.190],
        [9.8, 0.155], [9.9, 0.120], [10.0, 0.090],
        [10.2, 0.045], [10.4, 0.020], [10.6, 0.008],
        [10.8, 0.003], [11.0, 0.001]
      ],
      lineStyle: {
        color: '#E6A23C',
        width: 2
      },
      symbol: 'none'
    }, {
      name: '分位线',
      type: 'line',
      markLine: {
        data: [
          {
            name: 'QL',
            xAxis: 8.8,
            lineStyle: {
              color: '#E6A23C',
              type: 'dotted'
            },
            label: {
              formatter: 'QL',
              position: 'end',
              color: '#E6A23C',
            },
          },
          {
            name: 'QU',
            xAxis: 10.2,
            lineStyle: {
              color: '#E6A23C',
              type: 'dotted'
            },
            label: {
              formatter: 'QU',
              position: 'end',
              color: '#E6A23C'
            }
          }
        ],
        symbol: 'none'
      },
      data: [],
      lineStyle: {
        width: 0
      }
    }]
  }
}

// 均值极差图配置
const getMeanRangeChartOption = () => {
  // 计算均值图参数
  const meanData = [92, 90, 87, 100, 78, 72, 89, 75, 88, 74, 89, 91, 92, 89, 78, 84, 82, 83, 81, 92, 94, 91, 92, 80]
  const meanAvg = meanData.reduce((a, b) => a + b, 0) / meanData.length
  const meanUcl = meanAvg + 15 // 模拟计算
  const meanLcl = meanAvg - 15 // 模拟计算

  // 计算极差图参数
  const rangeData = [14, 12, 12, 11, 13, 13, 14, 12, 13, 16, 11, 14, 13, 12, 12, 13, 15, 12, 11, 15, 16, 14, 12, 14]
  const rangeAvg = rangeData.reduce((a, b) => a + b, 0) / rangeData.length
  const rangeUcl = rangeAvg * 2.114 // 使用D4系数(n=5)
  const rangeLcl = 0 // 对于n=5, D3=0

  return {
    title: {
      text: `(X̄: CL=${meanAvg.toFixed(1)}, UCL=${meanUcl.toFixed(1)}, LCL=${meanLcl.toFixed(1)} \n R: CL=${rangeAvg.toFixed(1)}, UCL=${rangeUcl.toFixed(1)}, LCL=${rangeLcl.toFixed(1)})`,
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 12,
        fontWeight: 500
      },
      top: '8%',
    },
    color: ['#fc0000', '#ff7d4e'],
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['极差控制图(R)', '均值控制图(X̄)'],
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      top: '0%',
    },
    textStyle: {
      color: '#fff'
    },
    grid: {
      top: '30%',
      left: '1%',
      right: '30%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
      axisLabel: {
        color: '#fff'
      },
      name: '子组序号',
      nameGap: 50,
      nameTextStyle: {
        color: '#fff'
      },

    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#fff'
      },
      name: '质量特性值',
      nameTextStyle: {
        color: '#fff',

      }
    },
    series: [
      {
        name: '极差控制图(R)',
        type: 'line',
        data: rangeData,
        itemStyle: {
          color: "#fc0000"
        },
        lineStyle: {
          color: "#fc0000",
          width: 2
        },
        markLine: {
          data: [
            {
              name: 'UCL',
              yAxis: rangeUcl,
              lineStyle: {
                color: '#F56C6C',
                type: 'dashed'
              },
              label: {
                formatter: 'UCL-R:{c}',
                position: 'end',
                color: '#F56C6C'
              }
            },
            {
              name: 'CL',
              yAxis: rangeAvg,
              lineStyle: {
                color: '#67C23A',
                type: 'solid'
              },
              label: {
                formatter: 'CL-R:{c}',
                position: 'end',
                color: '#67C23A'
              }
            },
            {
              name: 'LCL',
              yAxis: rangeLcl,
              lineStyle: {
                color: '#F56C6C',
                type: 'dashed'
              },
              label: {
                formatter: 'LCL-R:{c}',
                position: 'end',
                color: '#F56C6C'
              }
            }
          ]
        },
        symbol: 'circle',
        symbolSize: 4,
        smooth: true
      },
      {
        name: '均值控制图(X̄)',
        type: 'line',
        data: meanData,
        itemStyle: {
          color: "#ff7d4e"
        },
        lineStyle: {
          color: "#ff7d4e",
          width: 2
        },
        markLine: {
          data: [
            {
              name: 'UCL',
              yAxis: meanUcl,
              lineStyle: {
                color: '#F56C6C',
                type: 'dashed'
              },
              label: {
                formatter: 'UCL-X̄:{c}',
                position: 'end',
                color: '#F56C6C'
              }
            },
            {
              name: 'CL',
              yAxis: meanAvg,
              lineStyle: {
                color: '#67C23A',
                type: 'solid'
              },
              label: {
                formatter: 'CL-X̄:{c}',
                position: 'end',
                color: '#67C23A'
              }
            },
            {
              name: 'LCL',
              yAxis: meanLcl,
              lineStyle: {
                color: '#F56C6C',
                type: 'dashed'
              },
              label: {
                formatter: 'LCL-X̄:{c}',
                position: 'end',
                color: '#F56C6C'
              }
            }
          ]
        },
        symbol: 'circle',
        symbolSize: 4
      },

    ]
  }
}

// ==================== 标签页控制 ====================
// 切换标签页
const switchTab = (index: number) => {
  currentTab.value = index
  nextTick(() => {
    const chart = qualityCharts.value[index]
    if (chart) {
      setTimeout(() => {
        chart.resize()
      }, 100)
    }
  })
}

// 开始标签页轮播
const startTabRotation = () => {
  const interval = window.dt_Config?.QualityManagementRefreshInterval
  if (isPaused.value) return
  tabTimer.value = setInterval(() => {
    const nextTab = (currentTab.value + 1) % 3
    switchTab(nextTab)
  }, interval)
}

// 暂停标签页轮播
const pauseTabRotation = () => {
  isPaused.value = true
  stopTabRotation()
}

// 恢复标签页轮播
const resumeTabRotation = () => {
  isPaused.value = false
  startTabRotation()
}

// 停止标签页轮播
const stopTabRotation = () => {
  if (tabTimer.value) {
    clearInterval(tabTimer.value)
    tabTimer.value = null
  }
}

// ==================== 窗口处理 ====================
// 处理窗口大小变化
const handleResize = () => {
  qualityCharts.value.forEach(chart => {
    if (chart) {
      chart.resize()
    }
  })
}

// ==================== 生命周期 ====================
onMounted(() => {
  initQualityCharts()
  startTabRotation()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  stopTabRotation()
  window.removeEventListener('resize', handleResize)
  qualityCharts.value.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
})
</script>

<style scoped>
.quality-management-content {
  width: 100%;
  height: calc(100% - 40px);
  padding: 10px;
  box-sizing: border-box;
}

.quality-tab-menu {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
}

.quality-tab-menu li {
  margin: 0 5px;
}

.quality-tab-menu li a {
  color: #38b3f1;
  text-decoration: none;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 3px;
  transition: all 0.3s;
  display: block;
  text-align: center;
  min-width: 80px;
}

.quality-tab-menu .ym-active1 a {
  background-color: rgba(56, 179, 241, 0.3);
  color: #38b3f1;
  border: 1px solid #38b3f1;
}

.quality-tab-menu .taba1 a {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(56, 179, 241, 0.5);
}

.quality-tab-menu li a:hover {
  background-color: rgba(56, 179, 241, 0.5);
  color: #fff;
}

.quality-charts-container {
  height: 220px;
  position: relative;
}

.quality-chart {
  height: 100%;
  width: 100%;
  background-color: transparent;
}
</style>

<script lang="ts">
export default {
  name: 'QualityManagement',
}
</script>
