<template>
  <div style="background-color:#f0f2f5;padding:12px;">
    <a-spin :spinning="loading">
      <a-card :title="$t('functional-analysis.top-btn.pareto-analysis')">
        <template slot="extra">
          <a-form layout="inline" style="margin-right: -24px;">
            <a-form-item :label="$t('functional-analysis.top-btn.data-type')">
              <a-select @change="dataTypeChange" :value="dataType" style="width: 120px;">
                <a-select-option v-for="(item, index) in dataTypeDict" :key="index" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </template>
        <div id="eCharts2" :style="{ height: chartHeight }" />
      </a-card>
    </a-spin>
  </div>
</template>
<script>

import * as echarts from 'echarts';

export default {
  name: "ParetoAnalysis",
  data() {
    return {
      /** 数据类型 */
      dataType: '01',
      /** 数据类型字典 */
      dataTypeDict: [
        { value: "01", name: 'RPN' },
        { value: "02", name: 'SO' },
        { value: "03", name: 'SD' },
        { value: "04", name: 'OD' },
      ],
      /** 图表Loading */
      loading: true,
      paretoChart: undefined,
      // 图表X轴数据
      xAxisData4RPN: [],
      // 图表结构名称数据
      struNames4RPN: [],
      // 图表功能名称数据
      functionNames4RPN: [],
      // 图表X轴数据
      xAxisData4SO: [],
      // 图表结构名称数据
      struNames4SO: [],
      // 图表功能名称数据
      functionNames4SO: [],
      // 图表X轴数据
      xAxisData4SD: [],
      // 图表结构名称数据
      struNames4SD: [],
      // 图表功能名称数据
      functionNames4SD: [],
      // 图表X轴数据
      xAxisData4OD: [],
      // 图表结构名称数据
      struNames4OD: [],
      // 图表功能名称数据
      functionNames4OD: [],
      // RPN数据
      beforeRPNSeriesData: [],
      afterRPNSeriesData: [],
      beforeRPNPercentData: [],
      // SO数据
      beforeSOSeriesData: [],
      afterSOSeriesData: [],
      beforeSOPercentData: [],
      // SD数据
      beforeSDSeriesData: [],
      afterSDSeriesData: [],
      beforeSDPercentData: [],
      // OD数据
      beforeODSeriesData: [],
      afterODSeriesData: [],
      beforeODPercentData: [],
      chartHeight: window.innerHeight - 230 + 'px'
    };
  },
  mounted() {
    this.initAllDatas();
    window.onresize = () => {
      this.chartHeight = window.innerHeight - 230 + 'px';
      this.paretoChart.resize();
    };
  },
  methods: {
    /**
     * 节点类型
     * @param val 下拉key
     */
    dataTypeChange(val) {
      this.dataType = val;
      // 初始化图表
      switch (val) {
        case '01':
          this.initChart(this.xAxisData4RPN.length, 1000, 200, this.xAxisData4RPN, this.struNames4RPN, this.functionNames4RPN,
              this.beforeRPNSeriesData, this.afterRPNSeriesData, this.beforeRPNPercentData);
          break;
        case '02':
          this.initChart(this.xAxisData4SO.length, 100, 20, this.xAxisData4SO, this.struNames4SO, this.functionNames4SO,
              this.beforeSOSeriesData, this.afterSOSeriesData, this.beforeSOPercentData);
          break;
        case '03':
          this.initChart(this.xAxisData4SD.length, 100, 20, this.xAxisData4SD, this.struNames4SD, this.functionNames4SD,
              this.beforeSDSeriesData, this.afterSDSeriesData, this.beforeSDPercentData);
          break;
        case '04':
          this.initChart(this.xAxisData4OD.length, 100, 20, this.xAxisData4OD, this.struNames4OD, this.functionNames4OD,
              this.beforeODSeriesData, this.afterODSeriesData, this.beforeODPercentData);
          break;
        default:
          this.initChart(this.xAxisData4RPN.length, 1000, 200, this.xAxisData4RPN, this.struNames4RPN, this.functionNames4RPN,
              this.beforeRPNSeriesData, this.afterRPNSeriesData, this.beforeRPNPercentData);
      }
    },
    sortByObject(name) {
      return function (obj1, obj2) {
        return obj2[name] - obj1[name];
      }
    },
    /**
     * 初始化所有数据
     */
    async initAllDatas() {
      let _that = this;
      this.loading = true;
      await this.$api.getParetoAnalysis({
        fmeaId: _that.$store.getters.rfmeaId,
      }).then(res => {
        if (res.flag) {
          let resDatas = res.data.faultAnalysisResult;
          let beforeTotalRPN = 0;
          let beforeTotalSO = 0;
          let beforeTotalSD = 0;
          let beforeTotalOD = 0;
          resDatas.forEach(item => {
            item.beforeRPN = item.beforeOptS * item.beforeOptO * item.beforeOptD;
            item.beforeSO = item.beforeOptS * item.beforeOptO;
            item.beforeSD = item.beforeOptS * item.beforeOptD;
            item.beforeOD = item.beforeOptO * item.beforeOptD;
          });
          // 按照RPN大小排序
          let sortByRPNDatas = resDatas.sort(this.sortByObject('beforeRPN'));
          sortByRPNDatas.forEach((resData, index) => {
            let afterRPN = resData.afterOptD * resData.afterOptO * resData.afterOptS;
            let beforeRPN = resData.beforeOptD * resData.beforeOptO * resData.beforeOptS;
            // 以失效名称为X轴数据
            _that.xAxisData4RPN.push({
              value: resData.faultName,
            });
            // 结构名数组（tooltip显示）
            _that.struNames4RPN.push(resData.struName);
            // 功能名数组（tooltip显示）
            _that.functionNames4RPN.push(resData.functionName);
            // 系列1：优化前的值
            _that.beforeRPNSeriesData.push({ value: beforeRPN });
            // 系列2：优化后的值
            _that.afterRPNSeriesData.push({ value: afterRPN });
            // 系列3：优化前的值百分比（当前失效之前的值之和/所有失效值之和）
            beforeTotalRPN += beforeRPN;
            _that.beforeRPNPercentData.push({ value: beforeTotalRPN })
          });
          // 计算RPN大小排序系列3的百分比占比
          _that.beforeRPNPercentData.forEach(item => {
            item.value = (item.value / beforeTotalRPN) * 100;
          });

          // 按照SO值大小排序
          let sortBySODatas = resDatas.sort(this.sortByObject('beforeSO'));
          sortBySODatas.forEach((resData, index) => {
            let afterSO = resData.afterOptO * resData.afterOptS;
            let beforeSO = resData.beforeOptO * resData.beforeOptS;
            // 以失效名称为X轴数据
            _that.xAxisData4SO.push({
              value: resData.faultName,
            });
            // 结构名数组（tooltip显示）
            _that.struNames4SO.push(resData.struName);
            // 功能名数组（tooltip显示）
            _that.functionNames4SO.push(resData.functionName);
            // 系列1：优化前的值
            _that.beforeSOSeriesData.push({ value: beforeSO });
            // 系列2：优化后的值
            _that.afterSOSeriesData.push({ value: afterSO });
            // 系列3：优化前的值百分比（当前失效之前的值之和/所有失效值之和）
            beforeTotalSO += beforeSO;
            _that.beforeSOPercentData.push({ value: beforeTotalSO })
          });
          // 计算SO大小排序系列3的百分比占比
          _that.beforeSOPercentData.forEach(item => {
            item.value = (item.value / beforeTotalSO) * 100;
          });

          // 按照SD值大小排序
          let sortBySDDatas = resDatas.sort(this.sortByObject('beforeSD'));
          sortBySDDatas.forEach((resData, index) => {
            let afterSD = resData.afterOptD * resData.afterOptS;
            let beforeSD = resData.beforeOptD * resData.beforeOptS;
            // 以失效名称为X轴数据
            _that.xAxisData4SD.push({
              value: resData.faultName,
            });
            // 结构名数组（tooltip显示）
            _that.struNames4SD.push(resData.struName);
            // 功能名数组（tooltip显示）
            _that.functionNames4SD.push(resData.functionName);
            // 系列1：优化前的值
            _that.beforeSDSeriesData.push({ value: beforeSD });
            // 系列2：优化后的值
            _that.afterSDSeriesData.push({ value: afterSD });
            // 系列3：优化前的值百分比（当前失效之前的值之和/所有失效值之和）
            beforeTotalSD += beforeSD;
            _that.beforeSDPercentData.push({ value: beforeTotalSD });
          });
          // 计算SD大小排序系列3的百分比占比
          _that.beforeSDPercentData.forEach(item => {
            item.value = (item.value / beforeTotalSD) * 100;
          });

          // 按照OD值大小排序
          let sortByODDatas = resDatas.sort(this.sortByObject('beforeOD'));
          sortByODDatas.forEach((resData, index) => {
            let afterOD = resData.afterOptD * resData.afterOptO;
            let beforeOD = resData.beforeOptD * resData.beforeOptO;
            // 以失效名称为X轴数据
            _that.xAxisData4OD.push({
              value: resData.faultName,
            });
            // 结构名数组（tooltip显示）
            _that.struNames4OD.push(resData.struName);
            // 功能名数组（tooltip显示）
            _that.functionNames4OD.push(resData.functionName);
            // 系列1：优化前的值
            _that.beforeODSeriesData.push({ value: beforeOD });
            // 系列2：优化后的值
            _that.afterODSeriesData.push({ value: afterOD });
            // 系列3：优化前的值百分比（当前失效之前的值之和/所有失效值之和）
            beforeTotalOD += beforeOD;
            _that.beforeODPercentData.push({ value: beforeTotalOD });
          });
          // 计算OD大小排序系列3的百分比占比
          _that.beforeODPercentData.forEach(item => {
            item.value = (item.value / beforeTotalOD) * 100;
          });
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.loading = false;
      });
      // 第一次初始化默认加载RPN数据
      this.dataTypeChange('01');
    },
    /**
     * 初始化图表
     * @param size 总数
     * @param xAxisData x轴数据
     * @param struNames 结构名称
     * @param functionNames 功能名称
     * @param beforeSeriesData 优化前数据
     * @param afterSeriesData 优化后数据
     * @param afterPercentData 优化后百分比数据
     */
    initChart(size, yMax, interval, xAxisData, struNames, functionNames, beforeSeriesData, afterSeriesData, beforePercentData) {
      // 计算dataZoom的结束数值
      let dataZoomEnd = 0;
      if (size >= 7) {
        dataZoomEnd = Math.ceil(7 / size * 100);
      } else {
        dataZoomEnd = 100;
      }
      // 基于准备好的dom，初始化echarts实例
      // 语言
      let lang = this.$store.getters.lang.split('-')[0].toUpperCase();
      this.paretoChart = echarts.init(document.getElementById('eCharts2'), null, { locale: lang });
      let option = {
        toolbox: {
          feature: {
            saveAsImage: { show: true }
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let dataIndex = params[0].dataIndex;
            let name = params[0].name;
            return "结构：" + struNames[dataIndex] +
                "<br>功能：" + functionNames[dataIndex] +
                "<br>失效：" + name + "<br>" +
                params[0].marker + "优化前：" + params[0].data.value + "<br>" +
                params[1].marker + "优化后：" + params[1].data.value + "<br>" +
                params[2].marker + "累计百分比：" + params[2].data.value.toFixed(2) + '%';
          }
        },
        legend: {
          data: [
            this.$t('functional-analysis.top-btn.initial'),
            this.$t('functional-analysis.top-btn.revised'),
            this.$t('functional-analysis.top-btn.cumulative-percentage')
          ],
          top: '5%'
        },
        grid: {
          top: '15%',
          left: '5%',
          right: '5%',
          bottom: '10%'  // 网格线距离底部的距离
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisPointer: {
              type: 'shadow'
            },
            axisLabel: {
              show: false,
              interval: 0,
              rotate: 20,
              margin: 8,
              // formatter: (value, index) => {
              //   let strs = value.split('^');
              //   return (strs[2].length > 10 ? (strs[2].slice(0, 10) + "...") : strs[2]);
              // }
            },
            triggerEvent: true,
          }
        ],
        dataZoom: [
          {
            type: 'slider',
            textStyle: false,// 隐藏dataZoom上显示的名称
            show: true,
            inverse: true,
            start: 0,
            end: dataZoomEnd
          },
          {
            type: 'inside',
            start: 90,
            end: 100,
            top: 200
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
            max: yMax,
            interval: interval,
          },
          {
            type: 'value',
            name: this.$t('functional-analysis.top-btn.cumulative-percentage'),
            min: 0,
            max: 100,
            interval: 20,
          }
        ],
        series: [
          {
            name: this.$t('functional-analysis.top-btn.initial'),
            type: 'bar',
            itemStyle: {
              color: '#08c'
            },
            label: {
              show: true,
              position: 'top', // 将标签放在柱子的顶部
              distance: 15,
              align: 'middle', // 显示标签水平居中
              verticalAlign: 'middle',
              rotate: 0, // 确保标签是水平显示的（这实际上是默认值）
              // formatter: '{c}  {name|{a}}',
              fontSize: 12,
            },
            data: beforeSeriesData
          },
          {
            name: this.$t('functional-analysis.top-btn.revised'),
            type: 'bar',
            itemStyle: {
              color: '#42a75e'
            },
            label: {
              show: true,
              position: 'top', // 将标签放在柱子的顶部
              distance: 15,
              align: 'middle', // 显示标签水平居中
              verticalAlign: 'middle',
              rotate: 0, // 确保标签是水平显示的（这实际上是默认值）
              // formatter: '{c}  {name|{a}}',
              fontSize: 12,
            },
            data: afterSeriesData
          },
          {
            name: this.$t('functional-analysis.top-btn.cumulative-percentage'),
            type: 'line',
            itemStyle: {
              color: '#FF8C00'
            },
            label: {
              show: false,
              position: 'insideBottom',
              distance: 15,
              align: 'left',
              verticalAlign: 'middle',
              rotate: 90,
              formatter: function (params) {
                // return params.name;
              },
              fontSize: 12,
            },
            yAxisIndex: 1,
            data: beforePercentData
          }
        ]
      };
      this.paretoChart.setOption(option);
    },
  },
};
</script>
<style lang="less" scoped>
/** 表格头部自动换行 */
/deep/ .ant-table-thead {
  .ant-table-row-cell-ellipsis .ant-table-column-title {
    white-space: normal;
  }
}

/deep/ .ant-card-extra {
  padding: 0px 0;
}
</style>

