<template>
  <div>
    <div class="header">
				<el-button
					type="primary"
					v-for="item in yearSelector"
					:key="item.value"
					size="medium"
					:plain="item.value !== year_select"
					class="year-btn"
					@click.native="changeYear(item)"
					>{{ item.name }}</el-button
				>
				<el-button type="text" class="btn-sty" @click="openDateDia">{{
					dateTip
				}}</el-button>
    </div>
    <div class="min-wrapper">
      <div class="chartWrapper">
        <Chart :options="options" ref="chartRef" height="500px" @clickYAxisTitle="changeEnOptions"/>
        <div class="author">添加人：{{edbInfo.SysUserRealName}}</div>
      </div>
    </div>

    <!-- 自定义时间段选择弹窗 -->
		<DateChooseDia
			:isDateDia="isDateDia"
			:dateForm="dateForm"
			@cancel="isDateDia = false"
			@dateBack="dataChangeBack"
		/>
  </div>
</template>

<script>
import { yearSelector,defaultOpts,seasonOptions } from '@/utils/defaultOptions';
import Chart from '@/views/dataEntry_manage/components/chart.vue';
import DateChooseDia from '@/views/dataEntry_manage/components/DateChooseDia';
import Highcharts from 'highcharts'
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import { dataBaseInterface } from '@/api/api.js';
export default {
  props: {
    id: Number,
    lang: String
  },
  watch: {
    id(newval) {
      this.initStatus();
      this.getChartDetailHandle()
    },
    lang(newval) {
      this.$emit('updateTit',{edb_name: newval === 'ch' ? this.edbInfo.EdbName : this.edbInfo.EdbNameEn,userid: this.edbInfo.SysUserId})
      this.setOptions();
    }
  },
  components: { Chart,DateChooseDia },
  data() {
    return {
      year_select: 10, //年份选择项 默认全部
      yearSelector: [
				{
					name: '全部',
					value: 10,
				},
				...yearSelector,
			],
			select_date: [], // 自定义时间段项

      options: {},
			showChart: false,
			edbInfo: {},
			dataList: [],
			leftIndex: 0,

			/* 日期弹窗 */
      isDateDia: false, // 时间段弹窗
      dateForm: {},
      dateTip: '请选择时间段',
    }
  },
  methods: {
    /* 获取图表数据 */
		getChartDetailHandle(type='') {
			preDictEdbInterface.edbChartInfo({
				EdbInfoId: this.id,
        DateType: this.year_select,
				StartDate: this.select_date[0] || '',
				EndDate: this.select_date[1] || ''
			}).then(res => {
				if(res.Ret !== 200) return

        const { DataList,EdbInfo } = res.Data;
				this.edbInfo = EdbInfo;
        this.dataList = DataList;
        
        this.setOptions();
        this.$emit('updateTit',{edb_name: this.lang === 'ch' ? EdbInfo.EdbName : EdbInfo.EdbNameEn,userid: EdbInfo.SysUserId})
        
        //更新图片
        if(type==='updateImg' || !EdbInfo.ChartImage) {
          this.$nextTick(() => {
            this.setChartImage()
          })
        }
			})
		},

    /* 关联图片 */
    setChartImage() {
      let svg = this.$refs.chartRef.chart.getSVG({
        chart:{
        width: 340,
        height: 230,
        }
      });
      let form = new FormData();
      form.append('Img', svg);
      this.setImageHandle(form);
    },

    async setImageHandle(form) {
      let { Data } = await dataBaseInterface.uploadImgSvg(form);
      await preDictEdbInterface.setImg({
        EdbInfoId: this.id,
        ImageUrl: Data.ResourceUrl,
      });
    },

     /* 年份改变 重新刷新图表接口  保存当前的图表配置和上下限 只改变图表 */
    changeYear(item) {
      this.year_select = item.value;
      this.select_date = [];
      this.dateTip = '请选择时间段';

      this.getChartDetailHandle();
    },

    /* 保存完自定义日期 刷新数据 保存当前的图表配置和上下限 只改变图表*/
    dataChangeBack(data) {
      this.year_select = data.dateType;
      this.isDateDia = false;
      this.select_date = [data.start_date, data.end_date];

      this.dateTip =
        data.dateType === 5
          ? `${data.start_date}~${data.end_date}`
          : `${data.start_date}~至今`;

      this.getChartDetailHandle();
    },

    /* 打开时间段弹窗 */
    openDateDia() {
      // 自定义时间段回显
      this.dateForm = {
        date_type: this.year_select,
        start_date:
          this.year_select === 5 || this.year_select === 6
            ? this.select_date[0]
            : '',
        end_date: this.year_select === 5 ? this.select_date[1] : '',
      };
      this.isDateDia = true;
    },

    /* 重置状态 */
    initStatus() {
			this.year_select = 10;
			this.select_date = [];
			this.options = {};
			this.dateTip = '请选择时间段';
		},

    	/* 查询范围为1年内 x轴显示为月/日 否则默认年/月 */
		xLabelDealHandle() {
			const end =
				this.year_select === 5
					? this.select_date[1]
					: this.year_select === 6
					? new Date()
					: '';
			const year_differ = this.$moment(end).diff(
				this.$moment(this.select_date[0]),
				'years',
				true
			);
			// console.log(year_differ)
			if ([5, 6].includes(this.year_select) && year_differ <= 1) {
				defaultOpts.xAxis.labels = {
					formatter: function () {
						return Highcharts.dateFormat('%m/%d', this.value);
					},
				};
			} else {
				defaultOpts.xAxis.labels = {};
			}
		},

    /* 一个指标曲线图配置  写死配置*/
    setOptions() {
      const chartData = _.cloneDeep(this.dataList);

      //拼接标题 数据列
      let data = [],
        ydata = [];

      const { Unit,MinValue,MaxValue,EdbName,LatestDate,UnitEn,EdbNameEn } = this.edbInfo;

      //y轴
      let yItem = {
        ...seasonOptions.yAxis,
        title: {
          text: this.lang === 'ch' ? Unit : (UnitEn || '无英文单位'),
          align: 'high',
          rotation: 0,
          y: -15,
          textAlign:'left',
          reserveSpace: false
        },
        labels: {
          formatter: function (ctx) {
            return ctx.value;
          },
          align: 'center',
          x: -5
        },
        min: Number(MinValue),
        max: Number(MaxValue),
        tickWidth: 1,
      };
        
      //数据列
      let obj = {
        data: [],
        type: 'spline',
        yAxis: 0,
        name: this.lang === 'ch' ? EdbName : (EdbNameEn || '无英文名称'),
        lineWidth: 3,
        zoneAxis: 'x',
        zones: [{
          value: new Date(LatestDate).getTime()+1
        }, {
          dashStyle: 'ShortDot',
          color: '#f00'
        }]
      };
      chartData.forEach(item => {
        obj.data.push([item.DataTimestamp, item.Value]);
      });
		
      data.push(obj);
      ydata.push(yItem);

      this.xLabelDealHandle();
      this.options = {
        series: data,
        yAxis: ydata,
      };
    },

    changeEnOptions() {
      this.$emit('openEnNameDia',this.edbInfo)
    }
  },
  mounted() {
    this.initStatus();
    this.id && this.getChartDetailHandle()
  },
}
</script>
<style scoped lang='scss'>
.header {
  position: relative;
  padding-right: 70px;
  .year-btn {
    min-width: 90px;
    font-size: 14px;
    margin-right: 5px;
    margin-bottom: 5px;
  }
  .btn-sty {
    font-size: 16px;
    padding: 9px;
    border: 1px solid #409eff;
  }
}
.min-wrapper {
  margin-top: 30px;
  .author {
    margin-top: 10px;
    text-align: right;
  }
}
</style>