<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>{{ time }} <span style="color:#ff9829">智能产线</span> 每日产量</span>
          </div>
          <div class="body">
            <div class="chartsdom" id="chart_ptrend"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>{{ time }} <span style="color:#ff9829">智能产线</span> 每日产品合格率</span>
          </div>
          <div class="body">
            <div class="chartsdom" id="chart_arc"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getCountDay, getPassRate } from "@/api/index";
import { timeFormate } from "@/utils/timeFormate";
export default {
  name: "Index",
  data() {
    return {
      xData: ['星期一','星期二','星期三','星期四','星期五','星期六','星期日'],
      barList: [],
      lineList: [],
      time: ''
    };
  },
  mounted() {
    this.time = timeFormate(new Date());
    this.getData();
  },
  methods: {
    /** 获取并处理数据 */
    async getData() {
      try {
        // 获取产量数据
        const res1 = await getCountDay();
        if (res1.data) {
          this.barList = Object.keys(res1.data).map((lineName) => ({
            name: lineName,
            data: this.xData.map(week =>
              res1.data[lineName][week]?.['产量'] ?? 0
            )
          }));
          this.getEchart1();
        }

        // 获取合格率数据
        const res2 = await getPassRate();
        if (res2.data) {
          this.lineList = Object.keys(res2.data).map((lineName) => ({
            name: lineName,
            data: this.xData.map(week => {
              let rate = res2.data[lineName][week]?.['合格率'];
              if (typeof rate === 'string' && rate.includes('%')) {
                rate = parseFloat(rate.replace('%', ''));
              }
              return rate ? rate : null;
            })
          }));
          this.getEchart2();
        }
      } catch (e) {
      }
    },
    // 柱状图
    getEchart1() {
      const myChart = this.$echarts.init(document.getElementById('chart_ptrend'));
      const colorArr = ['#179bf1', '#ff9829', '#7adfa0', '#ff7b7b', '#a17bff', '#ffd700', '#00bfff'];
      const series = this.barList.map((item, idx) => ({
        name: item.name,
        type: 'bar',
        data: item.data,
        barWidth: 20,
        legendHoverLink: true,
        label: {
          show: false,
          position: 'top',
          color: '#000',
          fontSize: 14,
          fontWeight: 800
        },
        itemStyle: {
          barBorderRadius: [8, 0],
          color: colorArr[idx % colorArr.length]
        }
      }));

      myChart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: this.barList.map(item => item.name), top: 10 },
        grid: { top: '20%', bottom: '20%' },
        xAxis: [{
          type: 'category',
          axisLabel: { margin: 10, interval: 0, fontSize: 14, color: '#222' },
          data: this.xData,
          axisLine: { show: true, lineStyle: { color: '#222' } }
        }],
        yAxis: [{
          type: 'value',
          name: '双',
          nameTextStyle: { fontSize: 14 },
          axisLabel: { margin: 10, interval: 0, fontSize: 14, color: '#222' },
          axisLine: { show: true, lineStyle: { color: '#222' } }
        }],
        series
      }, true);

      window.addEventListener('resize', () => myChart.resize());
    },
    // 折线图
    getEchart2() {
      const chartDom = document.getElementById('chart_arc');
      if (this.myChart2) this.myChart2.dispose();
      this.myChart2 = this.$echarts.init(chartDom);

      const colorArr = ['#ffeb7b', '#5bc0eb', '#fa7921', '#6a4c93', '#17b978', '#e84545', '#f9dc5c'];
      const series = this.lineList.map((line, idx) => ({
        name: line.name,
        type: 'line',
        data: Array.isArray(line.data) ? line.data : [],
        symbolSize: 10,
        lineStyle: { width: 4 },
        itemStyle: { color: colorArr[idx % colorArr.length] },
        label: {
          show: false,
          color: '#222',
          fontSize: 14,
          position: 'top',
          formatter: params => params.value !== null ? `${params.value}%` : ''
        },
        smooth: true,
      }));

      this.myChart2.setOption({
        tooltip: {
          trigger: 'axis',
          showContent: true,
          formatter: params => {
            if (!params?.length) return '';
            return params[0].axisValue + '<br/>' +
              params.map(item => `${item.marker}${item.seriesName}：${item.data ?? '-'}%<br/>`).join('');
          }
        },
        color: colorArr,
        legend: { data: this.lineList.map(l => l.name), top: 40 },
        grid: { top: 100, left: 60, right: 60, bottom: 80, containLabel: true },
        xAxis: {
          type: 'category',
          data: this.xData,
          boundaryGap: true,
          axisTick: { show: false },
          axisLabel: { margin: 10, fontSize: 14, formatter: '{value}' },
          axisLine: { show: false, lineStyle: { color: '#222' } },
          splitLine: { show: true, lineStyle: { type: 'dashed' } }
        },
        yAxis: {
          type: 'value',
          max: 100,
          min: 60,
          axisLabel: { margin: 10, fontSize: 14, formatter: '{value} %' },
          axisTick: { show: true },
          axisLine: { show: false, lineStyle: { color: '#222' } }
        },
        series
      }, true);

      if (!this._echart2ResizeHandler) {
        this._echart2ResizeHandler = () => this.myChart2 && this.myChart2.resize();
        window.addEventListener('resize', this._echart2ResizeHandler);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }
  ul {
    padding: 0;
    margin: 0;
    list-style-type: none;
  }
  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;
  h4 {
    margin-top: 0px;
  }
  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }
  p {
    margin-top: 10px;
    b {
      font-weight: 700;
    }
  }
  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
    .chartsdom {
      width: 100%;
      height: 500px;
    }
  }
}
</style>
