<template>
  <div>
    <a-form :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
      <a-form-item :label="$t('functional-analysis.top-btn.data-type')">
        <a-select @change="dataTypeChange" :value="dataType">
          <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>
    <a-spin :spinning="loading">
      <div id="eCharts2" style="height:650px;"/>
    </a-spin>
  </div>
</template>
<script>

import * as echarts from 'echarts';

export default {
  name: "ParetoAnalysis",
  data() {
    return {
      formItemLayout: {
        // xxl: '1600px',
        // xl: '1200px',
        // lg: '992px',
        // md: '768px',
        // sm: '576px',
        // xs: '480px',
        labelCol: {
          xxl: {span: 2},
          xl: {span: 2},
          lg: {span: 2},
          md: {span: 24},
          xs: {span: 24},
          sm: {span: 24}
        },
        wrapperCol: {
          xxl: {span: 10},
          xl: {span: 10},
          lg: {span: 10},
          md: {span: 24},
          xs: {span: 24},
          sm: {span: 24}
        }
      },
      /** 数据类型 */
      dataType: '01',
      /** 数据类型字典 */
      dataTypeDict: [
        {value: "01", name: 'RPN'},
        {value: "02", name: 'SO'},
        {value: "03", name: 'SD'},
        {value: "04", name: 'OD'},
      ],
      /** 响应Data数据 */
      resData: {},
      /** 图表Loading */
      loading: false,
      /** X轴tooltip显示的内容 */
      xLabel: "",
      myChart: undefined,
    };
  },
  mounted() {
    this.list();
  },
  methods: {
    /**
     * 节点类型
     * @param val 下拉key
     */
    dataTypeChange(val) {
      this.dataType = val;

      /** RPN */
      let rpnCauses = this.resData.rpnVos.map(item => item.frCauseName);
      let rpnBeforeOptimizationData = this.resData.rpnVos.map(item => item.rpnValBefore);
      let rpnAfterOptimizationData = this.resData.rpnVos.map(item => item.rpnValAfter);
      let rpnCumulativePercentData = this.resData.rpnVos.map(item => item.rpnCumulativePercent);

      /** SO */
      let soCauses = this.resData.soVos.map(item => item.frCauseName);
      let soBeforeOptimizationData = this.resData.soVos.map(item => item.soValBefore);
      let soAfterOptimizationData = this.resData.soVos.map(item => item.soValAfter);
      let soCumulativePercentData = this.resData.soVos.map(item => item.soCumulativePercent);

      /** SD */
      let sdCauses = this.resData.sdVos.map(item => item.frCauseName);
      let sdBeforeOptimizationData = this.resData.sdVos.map(item => item.sdValBefore);
      let sdAfterOptimizationData = this.resData.sdVos.map(item => item.sdValAfter);
      let sdCumulativePercentData = this.resData.sdVos.map(item => item.sdCumulativePercent);

      /** OD */
      let odCauses = this.resData.odVos.map(item => item.frCauseName);
      let odBeforeOptimizationData = this.resData.odVos.map(item => item.odValBefore);
      let odAfterOptimizationData = this.resData.odVos.map(item => item.odValAfter);
      let odCumulativePercentData = this.resData.odVos.map(item => item.odCumulativePercent);

      // 初始化图表
      switch (val) {
        case '01':
          this.initChart(parseInt(this.resData.rpnVos.length), 'RPN', rpnCauses, rpnBeforeOptimizationData,
              rpnAfterOptimizationData, rpnCumulativePercentData);
          break;
        case '02':
          this.initChart(parseInt(this.resData.soVos.length), 'SO', soCauses, soBeforeOptimizationData,
              soAfterOptimizationData, soCumulativePercentData);
          break;
        case '03':
          this.initChart(parseInt(this.resData.sdVos.length), 'SD', sdCauses, sdBeforeOptimizationData,
              sdAfterOptimizationData, sdCumulativePercentData);
          break;
        case '04':
          this.initChart(parseInt(this.resData.odVos.length), 'OD', odCauses, odBeforeOptimizationData,
              odAfterOptimizationData, odCumulativePercentData);
          break;
      }
    },
    /**
     * 列表
     */
    list(struId = undefined) {
      let _that = this;
      _that.loading = true;
      _that.$api.getParetoAnalysis({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: struId
      }).then(res => {
        if (res.flag) {
          _that.resData = res.data;
          // 初始化图表
          _that.dataTypeChange(_that.dataType);
        } else {
          _that.$message.error(res.message, 1);
        }
      }).finally(() => {
        _that.loading = false;
      });
    },
    /**
     * 初始化图表
     * @param size 总数
     * @param yTitle Y轴标题
     * @param causes 刻度
     * @param beforeOptimization 优化前数据
     * @param afterOptimization 优化后数据
     * @param cumulativePercent 累计百分比
     */
    initChart(size, yTitle, causes, beforeOptimization, afterOptimization, cumulativePercent) {

      // 计算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.myChart = echarts.init(document.getElementById('eCharts2'), null, {locale: lang});
      // 绑定鼠标移入/移出事件
      this.myChart.on('mouseover', this.xAxisOver)
      this.myChart.on('mouseout', this.xAxisout)
      this.myChart.hideLoading();
      let option = {
        title: {
          text: this.$t('functional-analysis.top-btn.pareto-analysis'),
          x: 'center'
        },
        toolbox: {
          feature: {
            dataView: {show: true, readOnly: false},
            // restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        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: '10%',
          right: '10%',
          bottom: '15%'  // 网格线距离底部的距离
        },
        xAxis: [
          {
            type: 'category',
            data: causes,
            axisPointer: {
              type: 'shadow'
            },
            axisLabel: {
              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',
            name: yTitle,
// 				min: 0,
// 				max: 200,
            interval: 20,
            axisLabel: {
              formatter: '{value}'
            },
            // 网格线样式
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#B0C4DE'],
                width: 1,
                type: 'solid'
              }
            },
            // y轴线颜色修改
            /*axisLine:{
              lineStyle:{
                color:'#B0C4DE',
                width:1
              }
            }*/
          },
          {
            type: 'value',
            name: this.$t('functional-analysis.top-btn.cumulative-percentage'),
            min: 0,
            max: 100,
            interval: 20,
            axisLabel: {
              formatter: '{value}%'
            },
            // 网格线样式
            // splitLine: {
            //   show: true,
            //   lineStyle: {
            //     color: ['#ccc'],
            //     width: 1,
            //     type: 'solid'
            //   }
            // }
          }
        ],
        series: [
          {
            name: this.$t('functional-analysis.top-btn.initial'),
            type: 'bar',
            itemStyle: {
              color: '#08c'
              /*color:function (params) {
                // 将图形前20%的颜色修改为红色
                if (params.dataIndex > beforeTotal-1 || beforeTotal==1) {
                  return "#4F81BD";
                } else {
                  return "red";
                }
              }*/
            },
            data: beforeOptimization
          },
          {
            name: this.$t('functional-analysis.top-btn.revised'),
            type: 'bar',
            itemStyle: {
              color: '#42a75e'
              /*color:function (params) {
                // 将图形前20%的颜色修改为红色
                if (params.dataIndex > beforeTotal-1 || beforeTotal==1) {
                  return "#9BBB59";
                } else {
                  return "red";
                }
              }*/
            },
            data: afterOptimization
          },
          {
            name: this.$t('functional-analysis.top-btn.cumulative-percentage'),
            type: 'line',
            itemStyle: {
              color: '#FF8C00'
            },
            yAxisIndex: 1,
            data: cumulativePercent
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(option);
    },
    /**
     * 保留指定位数的数值并且四舍五入
     * @param number
     * @param digit
     * @return {string}
     */
    toFixed(number, digit) {
      let v = parseFloat(number);
      return v.toFixed(digit);
    },
    /**
     * 鼠标移入显示文字设置
     * @param params
     * @returns {string|*}
     */
    formateTooltip(params) {
      return this.xLabel
    },
    /**
     * echart图鼠标移入事件
     * @param params
     */
    xAxisOver (params) {
      //因为进入柱形图区域也会触发事件，需要对参数的值判断，只响应坐标轴触发事件
      if (params.componentType === 'xAxis') {
        //保存标签值
        let strs = params.value.split('^');
        this.xLabel = strs[2];
        let offsetX = params.event.offsetX + 10;
        let offsetY = params.event.offsetY + 10;
        let dataIndex = params.dataIndex;
        this.myChart.setOption({tooltip: {
            formatter: this.formateTooltip,
            alwaysShowContent: true
          }})
        //显示提示框
        this.myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: dataIndex,
          position: [offsetX, offsetY]
        })
      } else if (params.componentType === 'series') {
        this.myChart.setOption({
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              let optimizeBefore = this.$t('functional-analysis.top-btn.initial');
              let optimizeAfter = this.$t('functional-analysis.top-btn.revised');
              let accumulativePercentage = this.$t('functional-analysis.top-btn.cumulative-percentage');
              let strs = params[0].name.split('^');
              // 结构
              let strStructure = this.$t('global-dict.structure') + " : " + strs[0] + "</br>";
              // 功能
              let strFunction = this.$t('global-dict.function') + " : " + strs[1] + "</br>";
              // 失效原因
              let strCause = this.$t('global-dict.failure') + " : " + strs[2] + "</br>";
              if (params[0] && params[0].seriesName === optimizeBefore && !params[1] && !params[2]) {
                // 优化前
                let strBefore = params[0].marker + " " + params[0].seriesName + " : " + params[0].value + "</br>";
                return strStructure + strFunction + strCause + strBefore;
              } else if (params[0] && params[0].seriesName === optimizeAfter && !params[1] && !params[2]) {
                let afterValue = params[0].value;
                // 如果优化后的值为0，则显示空
                if (afterValue === 0) {
                  afterValue = "";
                }
                // 优化后
                let strAfter = params[0].marker + " " + params[0].seriesName + " : " + afterValue + "</br>";
                return strStructure + strFunction + strCause + strAfter;
              } else if (params[0] && params[0].seriesName === accumulativePercentage && !params[1] && !params[2]) {
                // 失效百分比
                let strPercent = params[0].marker + " " + params[0].seriesName + " : " + this.toFixed(params[0].value, 2)
                    + "%" + "</br>";
                return strStructure + strFunction + strCause + strPercent;
              } else if (params[0] && params[0].seriesName === optimizeBefore && !params[1]
                  && params[1].seriesName === optimizeAfter && !params[2]) {
                let afterValue = params[1].value;
                // 如果优化后的值为0，则显示空
                if (afterValue === 0) {
                  afterValue = "";
                }
                // 优化前
                let strBefore = params[0].marker + " " + params[0].seriesName + " : " + params[0].value + "</br>";
                // 优化后
                let strAfter = params[1].marker + " " + params[1].seriesName + " : " + afterValue + "</br>";
                return strStructure + strFunction + strCause + strBefore + strAfter;
              } else if (params[0] && params[0].seriesName === optimizeBefore && !params[1]
                  && params[1].seriesName === accumulativePercentage && !params[2]) {
                // 优化前
                let strBefore = params[0].marker + " " + params[0].seriesName + " : " + params[0].value + "</br>";
                // 失效百分比
                let strPercent = params[1].marker + " " + params[1].seriesName + " : " + this.toFixed(params[1].value, 2)
                    + "%" + "</br>";
                return strStructure + strFunction + strCause + strBefore + strPercent;
              } else if (params[0] && params[0].seriesName === optimizeAfter && !params[1]
                  && params[1].seriesName === accumulativePercentage && !params[2]) {
                let afterValue = params[0].value;
                // 如果优化后的值为0，则显示空
                if (afterValue === 0) {
                  afterValue = "";
                }
                // 优化后
                let strAfter = params[0].marker + " " + params[0].seriesName + " : " + afterValue + "</br>";
                // 失效百分比
                let strPercent = params[1].marker + " " + params[1].seriesName + " : " + this.toFixed(params[1].value, 2) + "%" + "</br>";
                return strStructure + strFunction + strCause + strAfter + strPercent;
              } else {
                let afterValue = params[1].value;
                // 如果优化后的值为0，则显示空
                if (afterValue === 0) {
                  afterValue = "";
                }
                // 优化前
                let strBefore = params[0].marker + " " + params[0].seriesName + " : " + params[0].value + "</br>";
                // 优化后
                let strAfter = params[1].marker + " " + params[1].seriesName + " : " + afterValue + "</br>";
                // 失效百分比
                let strPercent = params[2].marker + " " + params[2].seriesName + " : " + this.toFixed(params[2].value, 2) + "%" + "</br>";
                /*params.forEach(function (item) {
                  result += item.marker + "--- " + item.seriesName + " : " + toFixed(item.value, 2) +"%"+"</br>";
                });*/
                return strStructure + strFunction + strCause + strBefore + strAfter + strPercent;
              }
            }
          },
        })
      }
    },
    /**
     * echart图鼠标移出事件
     * @param params
     */
    xAxisout (params) {
      if (params.componentType === 'xAxis') {
        this.xLabel = ''
        this.myChart.setOption({
          tooltip: {
            formatter: this.formateTooltip,
            alwaysShowContent: false
          }
        })
      }
    }
  },
};
</script>
<style lang="less" scoped>
/** 表格头部自动换行 */
/deep/ .ant-table-thead {
  .ant-table-row-cell-ellipsis .ant-table-column-title {
    white-space: normal;
  }
}

/*/deep/ .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
  overflow-y: auto !important;
}*/
</style>

