<!--
  @description: 报表统计-设备/物资价格走势图
  @Modifier：肖文龙
  @routerPath:
  @date：  2021/01/29
-->
<template>
  <dl
    class="reportChart_crud"
    :style="{'height':height}"
  >
    <dt>
      设备/物资价格走势图
      <p class="right">
        <i class="iconfont icon-xiazai1" @click="dowloadClick" />
        <!--statisticalMonth 是否有值 有值时则为查询的月份  为空时则是查询的年 -->
        <!-- <el-date-picker
          v-show="searchData.statisticalMonth"
          v-model="searchData.statisticalMonth"
          :value-format="elValueYearMonth"
          popper-class="el-date-picker-month el-date-picker_header_none"
          type="month"
          style="margin-right:2.5rem"
          placeholder="请选择月份"
        />
        <span @click="handChange('d')">日</span>
        <span class="lin not-select">｜</span>
        <span @click="handChange('m')">月</span> -->
      </p>
    </dt>
    <dd>
      <ul class="materiel-tabs">
        <li
          v-for="(item, index) in purchaseTabs"
          :key="index"
          :class="{'active':searchData.purchaseName===item.purchaseName}"
          @click="tabClick(index,item)"
        >
          <p class="tabs-name">
            {{ item.purchaseName }}
            <!-- purchaseName -->
          </p>
          <p class="tabs-bg" />
        </li>
      </ul>
      <MyEcharts
        :id="'priceTrendChart'"
        height="calc(100% - 50px)"
        class="echart-dom"
        :option="chartOption"
      />
    </dd>
  </dl>
</template>

<script>
/* api */
import { getMaterialsPriceTrendsInfoChart, exportMaterialsPriceTrendsInfoChart } from '@api/statisticalAnalysis/reportChart.js'
/* 公共方法*/
import { download } from '@/assets/js/utils'
/* 組件 */
import MyEcharts from '@/components/common/echarts/myEcharts.vue'// 图表
export default {
  name: 'PriceTrendChart',
  components: {
    MyEcharts// 图表
  },
  inject: ['chartData'],
  props: {
    height: {
      type: String,
      default: '100%'
    },
    purchaseData: {
      type: Array,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 查询条件
      searchData: {
        purchaseName: ''
      },
      // 图表配置
      chartOption: {},
      // 物料tab
      purchaseTabs: []
    }
  },
  watch: {
    purchaseData: {
      handler(val) {
        if (val) {
          this.purchaseTabs = []
          val.forEach((item) => {
            this.purchaseTabs.push({
              purchaseKey: item.purchaseCode,
              purchaseName: item.purchaseName + item.purchaseSpecification
            })
          })
          this.$nextTick(() => {
            this.initChart()
          })
        } else {
          this.purchaseTabs = []
          this.searchData.purchaseName = ''
          this.initChart()
        }
      },
      deep: true
    }
  },
  created() {
    // 日/月变更时
    // this.handChange('d')
  },
  methods: {
    /**
    * 日/月变更时
    *  @param {type} String  d 日 m 月
    */
    handChange(type) {
      if (type === 'd') {
        this.searchData.statisticalMonth = this.$Moment(this.currentTimeFn()).format(this.momentYearMonth)
      }
      if (type === 'm') {
        this.searchData.statisticalMonth = ''
      }
      // 获取数据
      this.initChart()
    },
    /**
     * 获取数据
     *  @param {searchData} Object 查询条件
    */
    initChart(searchData) {
      if (searchData) {
        this.searchData = {
          ...this.searchData,
          ...searchData
        }
      }
      // 首次进来 只显示第一个的数据
      if (this.purchaseTabs.length && searchData) {
        this.searchData.purchaseName = this.purchaseTabs[0].purchaseName
        this.searchData.productNo = this.purchaseTabs[0].purchaseKey
      }
      const data = {
        ...this.searchData
      }
      // delete data.

      getMaterialsPriceTrendsInfoChart(data).then(res => {
        this.init(res.data.data)
      })
    },
    /**
      * 渲染echarts
      * @param {fromData} Array
      */
    init(fromData) {
      const borderColor = this.chartData.borderColor // 边框颜色
      const textColor = this.chartData.textColor // 文本颜色
      /* ------------------------------------------------- */
      // seriesData
      fromData = JSON.parse(fromData)[0]
      let xAxisValue = []
      const seriesData = []
      for (const key in fromData) {
        const seriesItemData = {
          name: key,
          yuanLineColor: this.getRandomColor(),
          data: []
        }
        xAxisValue = []
        fromData[key].forEach(item => {
          seriesItemData.data.push(Number(item.materialPrice))
          xAxisValue.push(item.purchaseTime.split('/')[0] + '年' + item.purchaseTime.split('/')[1] + '月')
        })
        seriesData.push(seriesItemData)
      }
      /* ----------------*/
      // 数据
      const data = {
        title: {
          subtext: '价格（元）'
        },
        xAxis: {
          data: xAxisValue
        },
        seriesData
      }
      /* ------------------------------------------------- */
      this.chartOption = {
        title: {
          subtext: data.title.subtext,
          subtextStyle: { // 对应样式
            color: textColor
          }
        },
        // 提示框
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          // 距离 上右下左 的距离
          top: '10%',
          right: '5%',
          bottom: '20px',
          left: '5%',
          // 是否包含文本
          containLabel: true,
          // 显示边框
          show: false
        },
        // 图例
        legend: {
          selectedMode: false, // 取消图例上的点击事件
          textStyle: {
            color: textColor // 图例文字颜色
          }
        },
        xAxis: [
          {
            // 使用类目，必须有data属性
            type: 'category',
            // 使用 data 中的数据设为刻度文字
            ...data.xAxis,
            axisLine: {
              lineStyle: {
                opacity: 0 // 边框是否显引
              }
            },
            // 文字
            axisLabel: {
              color: textColor
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
            axisLine: {
              lineStyle: {
                opacity: 0// 边框是否显引
              }
            },
            // 文字
            axisLabel: {
              color: textColor
            },
            nameTextStyle: {
              // 标题文字
              color: textColor
            },
            splitLine: {
              lineStyle: {
                color: borderColor
              }
            }
          }
        ],
        series: data.seriesData.map(row => {
          return {
            name: row.name,
            type: 'line',
            smooth: false,
            symbolSize: 8, // 点的大小
            itemStyle: {
              // normal: {
              color: row.yuanLineColor, // 线颜色
              lineStyle: {
                width: 2.5// 设置线条粗细
              }
              // }
            },
            data: row.data
          }
        })
      }
    },
    getRandomColor() {
      const r = Math.floor(Math.random() * 256)
      const g = Math.floor(Math.random() * 256)
      const b = Math.floor(Math.random() * 256)
      return 'rgb(' + r + ',' + g + ',' + b + ')'
    },
    // tab点击
    tabClick(index, item) {
      // 判断是否切换tab
      if (this.searchData.purchaseName !== item.purchaseName) {
        this.searchData.purchaseName = this.purchaseTabs[index].purchaseName
        this.searchData.productNo = this.purchaseTabs[index].purchaseKey
        this.initChart()
      }
    },
    // 下载
    dowloadClick() {
      const data = this.searchData
      exportMaterialsPriceTrendsInfoChart(data).then(res => {
        download(res, '设备/物资价格走势图信息表.xls')
      })
    }
  }
}
</script>
<style lang="less" scoped>
// 引入变量
@import "../../reportChart.public.less";
@header-color:#ffeb7b; //header头部-文字高亮的颜色
@tab-ighlight:@text-ighlight; //当前tab选项高亮
@tab-H: 2.5rem; //tab高度
.reportChart_crud{
  .materiel-tabs {
    overflow: hidden;
    float: left;
    li {
      float: left;
      position: relative;
      height: @tab-H;
      line-height: @tab-H;
      margin-right: 10px;
      margin-top: 10px;
      cursor: pointer;
      .tabs-bg,
      .tabs-name {
        padding: 0 1.875rem;
      }
      .tabs-name {
        position: relative;
        z-index: 1;
      }
      .tabs-bg {
        border: 1px solid #ececec;
        box-sizing: border-box;
        z-index: 0;
        position: absolute;
        top: 0px;
        right: 0px;
        bottom: 0px;
        left: 0px;
        background: @highlight-bg;
        height: 100%;
      }
    }
    li.active {
      color: @tab-ighlight;
      .tabs-bg {
        border: 1px solid @tab-ighlight;
      }
    }
  }
  .echart-dom{
    clear: both;
  }
}
</style>
