<template>
	<div>
		<el-dialog
		:visible.sync="isCreateChart"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="close"
		custom-class="create-chart-container"
		top="10vh"
		center
		width="80%"
		v-dialogDrag>
		<div slot="title" style="display: flex; align-items: center">
			<span style="font-size: 16px;cursor: pointer;" @click="editEnName" v-if="chartLang=='en'">{{chartInfo.EdbNameEn || '点击输入英文图表名称' }}</span>
			<span style="font-size: 16px;" v-else>{{chartInfo.EdbName || ''}}</span>
		</div>
		<h2 style="margin-bottom: 15px" v-if="!isOnlyShowBaseChart">{{chart_type===1 ? '曲线图' : '季节性图'}}</h2>
		<div class="header">
			<template v-if="chart_type===1">
				<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>
				<el-button type="text" class="btn-sty" @click="showOnChart('toggle')" v-if="!isOnlyShowBaseChart">{{ isShowOnyearData ? '隐藏同比图' : '展示同比图'}}</el-button>
			</template>
			<!-- 季节图时间选择 -->
			<template v-else-if="chart_type===2">
				<date-picker
						v-model="season_year"
						type="month"
						value-type="format"
						range
						placeholder="年份日期选择"
						@change="getDataByPath"
				/>
			</template>

			<span class="change-chart-btn" @click="chartTypeChange" v-if="!isOnlyShowBaseChart">切换{{chart_type==1?'季节性图':'曲线图'}}</span>
		</div>
		<div class="min-wrapper">
			<div class="chartWrapper" id="chartWrapper" v-if="showChart">
				<Chart :options="options" ref="chartRef" inset="true" @clickYAxisTitle="clickYAxisTitle" />
				<div class="range-cont left" v-if="leftIndex != -1">
					<el-input
						style="width: 80px; display: block"
						size="mini"
						type="number"
						placeholder="上限"
						v-model="chartInfo.MaxValue"
						@change="() => { chart_type===1?setOptions():setSeasonOptions() }"
					/>
					<el-input
						class="min-data-input"
						size="mini"
						type="number"
						placeholder="下限"
						v-model="chartInfo.MinValue"
						@change="() => { chart_type===1?setOptions():setSeasonOptions() }"
					/>
				</div>
				<div class="range-cont right" v-if="isShowOnyearData">
					<el-input
						style="width: 80px; display: block"
						size="mini"
						type="number"
						placeholder="上限"
						v-model="limitData.rightMax"
						@change="changeLimit"
					/>
					<el-input
						class="min-data-input"
						size="mini"
						type="number"
						placeholder="下限"
						v-model="limitData.rightMin"
						@change="changeLimit"
					/>
				</div>
				<!-- 公历农历切换 只用于季节性图 -->
				<div style="text-align:center;">
					<el-radio-group
							v-model="calendar_type"
							class="calendar-cont"
							v-if="chart_type===2"
							@change="getDataByPath"
					>
							<el-radio-button label="公历" />
							<el-radio-button label="农历" />
					</el-radio-group>
				</div>
			</div>
		</div>
		</el-dialog>
		
		<!-- 自定义时间段选择弹窗 -->
		<DateChooseDia
			:isDateDia="isDateDia"
			:dateForm="dateForm"
			@cancel="isDateDia = false"
			@dateBack="dataChangeBack"
		/>
	</div>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import * as supplyApi from '@/api/modules/supplyApi.js';
import { yearSelector,defaultOpts,seasonOptions } from '@/utils/defaultOptions'
import Chart from '../components/chart'
import DateChooseDia from '../components/DateChooseDia';
import Highcharts from 'highcharts'
export default {
	components: { Chart,DateChooseDia },
	props: {
		isCreateChart: {
			type: Boolean,
		},
		edbid: {
			type: Number,
		},
		// 语言 ch/en
		chartLang:{
			type: String,
			default:()=> 'ch'
		}
	},
	computed: {

		// 同比，环比，环差，超季节性、 残差展示基础图
		isOnlyShowBaseChart() {
			return [6,12,13,35,37].includes(this.chartInfo.Source)
		}
	},
	watch: {
		isCreateChart(newval) {

			newval && this.getDataByPath()
		},
	},
	data () {
		return {
			year_select: 10, //年份选择项 默认全部
      yearSelector: [
				{
					name: '全部',
					value: 10,
				},
				...yearSelector,
			],
			select_date: [], // 自定义时间段项

			options: {},
			showChart: false,
			chart_type: 1,// 1曲线 2季节
			isShowOnyearData: false, //是否展示同比
			chartInfo: {},
			dataList: [],
			leftIndex: 0,

			season_year:[],//季节图日期选择
			calendar_type:'公历',

			/* 日期弹窗 */
      isDateDia: false, // 时间段弹窗
      dateForm: {},
      dateTip: '请选择时间段',
			limitData: {
				letMin: 0,
				leftMax: 0,
				rightMin: 0,
				rightMax: 0,
			},
			oldOptions: {
				MinValue: 0,
				MaxValue: 0
			},
		};
	},
	methods: {
		
		getDataByPath() {
			const apiMap = {
				'/database': this.getEdbData,
				'/analyseVariety': this.getPlantEdbData
			}

			apiMap[this.$route.path]()
		},

		/* 获取指标所有数据 */
		async getEdbData() {
			let params = {
				EdbInfoId: this.edbid,
				DateType: this.year_select,
				StartDate: this.select_date[0] || '',
				EndDate: this.select_date[1] || ''
			}

			const res = this.chart_type === 1 
				? await dataBaseInterface.ebd_data(params)
				: await dataBaseInterface.ebdSeasonData({
						EdbInfoId: this.edbid,
						Calendar: this.calendar_type,
						StartDate: this.season_year[0] || '',
						EndDate: this.season_year[1] || '',
					})
				
				if(res.Ret !== 200) return
					const { DataList,EdbInfo } = res.Data;
					// DataList 表格数据列表
					this.chartInfo = (this.oldOptions.MinValue || this.oldOptions.MinValue) ? {
						...EdbInfo,
						...this.oldOptions
					} : EdbInfo;
					this.tableData = DataList || [];

					this.chart_type === 1 ? this.setOptions() : this.setSeasonOptions();
					this.showChart = true;
		},

		/* 获取装置指标数据 */
		async getPlantEdbData() {
			let params = {
				VarietyEdbId: this.edbid,
				DateType: this.year_select,
				StartDate: this.select_date[0] || '',
				EndDate: this.select_date[1] || ''
			}

			const res = this.chart_type === 1 
				? await supplyApi.getEdbDetailData(params)
				: await supplyApi.getEdbSeasonData({
						VarietyEdbId: this.edbid,
						Calendar: this.calendar_type,
						StartDate: this.season_year[0] || '',
						EndDate: this.season_year[1] || '',
					})
				
				if(res.Ret !== 200) return
					const { DataList,EdbInfo } = res.Data;
					// DataList 表格数据列表
					this.chartInfo = (this.oldOptions.MinValue || this.oldOptions.MinValue) ? {
						...EdbInfo,
						...this.oldOptions
					} : EdbInfo;
					this.tableData = DataList || [];

					this.chart_type === 1 ? this.setOptions() : this.setSeasonOptions();
					this.showChart = true;
		},

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

			const { MinValue,MaxValue } = this.chartInfo;
			this.oldOptions = {
				MinValue: Number(MinValue),
				MaxValue: Number(MaxValue)
			}
      this.getDataByPath()
    },

		/* 打开时间段弹窗 */
    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;
    },

    /* 保存完自定义日期 刷新数据 保存当前的图表配置和上下限 只改变图表*/
    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}~至今`;

			const { MinValue,MaxValue } = this.chartInfo;
			this.oldOptions = {
				MinValue,
				MaxValue
			}
      this.getDataByPath();
    },

		chartTypeChange() {
			this.chart_type = this.chart_type===1 ? 2 : 1;
			this.init('no_reset')
			this.getDataByPath();
		},

		// 展示同比图
		async showOnChart(scene='') {
			if(scene==='toggle') {
				this.isShowOnyearData = this.isShowOnyearData ? false : true;
				if(!this.isShowOnyearData){
					const { MinValue,MaxValue } = this.chartInfo;
					this.oldOptions = {
						MinValue: Number(MinValue),
						MaxValue: Number(MaxValue)
					}
					this.getDataByPath();
				}  
			}
			if(!this.isShowOnyearData) return;

			let params = {
				DateType: this.year_select,
				StartDate: this.select_date[0] || '',
				EndDate: this.select_date[1] || ''
			}
			const res = this.$route.path === '/analyseVariety' 
				? await supplyApi.getEdbOnyearData({VarietyEdbId:this.edbid,...params})
				: await dataBaseInterface.edbOnyearData({EdbInfoId: this.edbid,...params});

			if(res.Ret !== 200) return

			const { EdbInfo,DataList } = res.Data;

			if(!this.limitData.rightMin && !this.limitData.rightMax) {
				this.limitData.rightMin = Number(EdbInfo.MinValue);
				this.limitData.rightMax = Number(EdbInfo.MaxValue);
			}

			this.options.yAxis.push({
				title: {
					text: '',
					align: 'high',
					rotation: 0,
					y: -15,
					offset: 0
				},
				labels: {
					formatter: function (ctx) {
						return ctx.value;
					},
					align: 'center',
				},
				min: Number(this.limitData.rightMin),
				max: Number(this.limitData.rightMax),
				...seasonOptions.yAxis,
				opposite: true,
			})

			this.options.series.push({
				data: DataList.map(item=>([item.DataTimestamp, item.Value])),
				type: 'spline',
				yAxis: 1,
				name: this.chartLang=='ch'?`${EdbInfo.EdbName}同比`:EdbInfo.EdbNameEn?`${EdbInfo.EdbNameEn}同比`:'无英文名称',
				lineWidth: 1
			})
			console.log(this.options.series)
		},

		changeLimit() {
			const { rightMax,rightMin } = this.limitData;
			this.options.yAxis[1].max = Number(rightMax);
			this.options.yAxis[1].min = Number(rightMin);

		},

		/* 图表配置 曲线*/
		setOptions() {
			const chartData = _.cloneDeep(this.tableData);

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

			//y轴

			// 单位 中文时 为无不显示   英文时 为空提示点击输入
			// 中文不存在或等于无时 英文显示为空  中文存在且英文不存在时 显示'英文单位'
			let yTitleText = this.chartLang=='ch'?
			(this.chartInfo.Unit && this.chartInfo.Unit!='无') ? this.chartInfo.Unit:'':
			!this.chartInfo.UnitEn && this.chartInfo.Unit && this.chartInfo.Unit!='无' ? '英文单位':this.chartInfo.UnitEn
			// title样式  英文为空时，提示文字样式  英文可以点击设置
			let yTitleStyle = {}
			if(this.chartLang=='en'){
				yTitleStyle.cursor='pointer'
				if(yTitleText=='英文单位'){
					yTitleStyle.color="#999"
				}
			}
			let yItem = {
				title: {
					text: yTitleText,
					align: 'high',
					rotation: 0,
					y: -15,
					offset: 0,
					style:yTitleStyle
				},
				labels: {
					formatter: function (ctx) {
						return ctx.value;
					},
					align: 'center',
				},
				min: Number(this.chartInfo.MinValue),
				max: Number(this.chartInfo.MaxValue),
				...seasonOptions.yAxis,
			};
			// 图例名称和图例文字样式
			let dataName = this.chartLang=='ch'?this.chartInfo.EdbName:this.chartInfo.EdbNameEn?this.chartInfo.EdbNameEn:'无英文名称'
			let color = this.chartLang=='en'&&(!this.chartInfo.EdbNameEn)?'#999':'#333'
			let legend={
				...defaultOpts.legend,
				itemStyle: {
					color
				},
			}
			//数据列
			let obj = {
				data: [],
				type: 'spline',
				yAxis: 0,
				name: dataName,
				lineWidth: 3
			};
			chartData.forEach((item, index) => {
				obj.data.push([item.DataTimestamp, item.Value]);
			});
			
			data.push(obj);
			ydata.push(yItem);

      // 范围为1年内 x轴显示为月/日 否则默认年/月
      let xAxis = {};
      const bool_time = this.xTimeDiffer();
      xAxis = bool_time
        ? {
            ...defaultOpts.xAxis,
            labels: {
              formatter: function (ctx) {
                return Highcharts.dateFormat('%m/%d', ctx.value);
              },
            },
          }
        : {
            ...defaultOpts.xAxis,
						labels: {
              formatter: function (ctx) {
                return Highcharts.dateFormat('%y/%m', ctx.value);
              },
            },
          };
      this.options = {
        series: data,
        yAxis: ydata,
        xAxis,
				legend
      };

			this.showOnChart();
		},

		/* 季节图 */
		setSeasonOptions() {
			console.log(this.tableData)
      const chartData = _.cloneDeep(this.tableData);
      let seasonYdata = [],
        seasonData = [];

        /* 公历数据处理 处理数据列 y轴 */
        if (this.calendar_type === '公历')
        for (let j of chartData) {
          
          let serie_item = {
            data: [],
            type: 'spline',
            yAxis: 0,
            name: j.Year,
          };
          const data_array = _.cloneDeep(j.DataList);
          data_array &&
            data_array.forEach((item) => {
              serie_item.data.push([item.DataTimestamp, item.Value]);
            });
          const index = chartData.findIndex(
            (item) => item.Year === j.Year
          );
          const s_yItem = {
            labels: {
              formatter: function () {
                let val = this.value;
                return index !== 0 ? '' : val;
              },
              align: 'center',
            },
            title: {
              text:  this.chartLang=='ch'?this.chartInfo.Unit:
							!this.chartInfo.UnitEn && this.chartInfo.Unit && this.chartInfo.Unit!='无' ? '英文单位':this.chartInfo.UnitEn,
              align: 'high',
              rotation: 0,
              y: -15,
              offset: -(12 * this.chartInfo.Unit.length),
            },
            max: Number(this.chartInfo.MaxValue),
            min: Number(this.chartInfo.MinValue),
            ...seasonOptions.yAxis,
          };
          seasonData.push(serie_item);
          seasonYdata.push(s_yItem);
        }

      /* 农历数据处理  */
      let filterArr =
        this.calendar_type === '农历'
          ? chartData.List.filter((item, index) => index > 0)
          : [];
      if (this.calendar_type === '农历')
        for (let j of filterArr) {

          let serie_item = {
            data: [],
            type: 'spline',
            yAxis: 0,
            name: j.Year
          };
          const data_array = _.cloneDeep(j.Items);
          data_array &&
            data_array.forEach((item) => {
              serie_item.data.push([item.DataTimestamp, item.Value]);
            });
          const index = filterArr.findIndex((item) => item.Year === j.Year);
          const s_yItem = {
            labels: {
              formatter: function () {
                let val = this.value;
                return index !== 0 ? '' : val;
              },
              align: 'center',
            },
            title: {
              text:  this.chartLang=='ch'?this.chartInfo.Unit:
							!this.chartInfo.UnitEn && this.chartInfo.Unit && this.chartInfo.Unit!='无' ? '英文单位':this.chartInfo.UnitEn,
              align: 'high',
              rotation: 0,
              y: -15,
              offset: -(12 * this.chartInfo.Unit.length),
            },
            max: Number(this.chartInfo.MaxValue),
            min: Number(this.chartInfo.MinValue),
            ...seasonOptions.yAxis,
          };
          seasonData.push(serie_item);
          seasonYdata.push(s_yItem);
        }

      /* x轴显示月日  提示框显示月日*/
      defaultOpts.xAxis.labels = {
        formatter: function () {
          return Highcharts.dateFormat('%m/%d', this.value);
        },
      };
      
      const tooltip = {
        ...defaultOpts.tooltip,
        dateTimeLabelFormats: {
          // 时间格式化字符
          day: '%m/%d',
          week: '%m/%d',
          month: '%m/%d',
          year: '%m/%d',
        },
        xDateFormat: '%m/%d',
      }
      let rangeSelector =
        this.calendar_type === '农历'
          ? {
              enabled: true,
              selected: 0,
              inputStyle: {
                display: 'none',
              },
              labelStyle: {
                display: 'none',
              },
              buttonTheme: {
                style: {
                  display: 'none',
                },
              },
              buttons: [
                {
                  type: 'month',
                  count: 12,
                  text: '12月',
                },
                {
                  type: 'month',
                  count: 15,
                  text: '15月',
                },
                {
                  type: 'all',
                  text: '全部',
                  type: 'all',
                },
              ],
            }
          : {
              enabled: false,
            };

      this.options = {
        colors:
          this.calendar_type === '公历'
            ? seasonOptions.colors.slice(-chartData.length)
            : seasonOptions.colors.slice(-filterArr.length),
        series: seasonData,
        yAxis: seasonYdata,
        rangeSelector,
        tooltip
      };
			console.log(this.options)
		},

	  /* 查询范围为1年内 x轴显示为月/日 否则默认年/月 */
    xTimeDiffer() {
      const end_date =
        this.year_select === 5
          ? this.select_date[1]
          : this.year_select === 6
          ? new Date()
          : '';
      //年限差
      const year_differ = this.$moment(end_date).diff(
        this.$moment(this.select_date[0]),
        'years',
        true
      );
      // console.log(year_differ)
      if ([5, 6].includes(this.year_select) && year_differ <= 1) {
        return true;
      } else {
        return false;
      }
    },

		init(type='') {
			if(type!=='no_reset') this.chart_type = 1;
			this.isShowOnyearData = false;
			this.year_select = 10;
			this.select_date = [];
			this.options = {};
			this.dateTip = '请选择时间段';
			this.oldOptions = {};
			this.calendar_type = '公历';
			this.season_year = [];
			this.limitData = {
				letMin: 0,
				leftMax: 0,
				rightMin: 0,
				rightMax: 0,
			}
		},

		close() {
			this.init()
			this.$emit('close')
		},
		// 编辑英文信息弹窗
		editEnName(){
			this.$emit('editEnName','chart')
		},
		// 竖轴标题点击事件
		clickYAxisTitle(){
			console.log(this.chartLang);
			if(this.chartLang == 'en') this.editEnName()
		}
	},
	created() {},
	mounted() {},
}
</script>
<style lang='scss'>
.create-chart-container {
	min-width: 1200px;
	/* .el-dialog__header {
		background-color: #fff;
		.el-dialog__close {
			color: #333;
		}
	} */

	@media screen and (max-width: 1710px) {
		.min-data-input {
			margin-top: 220px;
		}
	}

	@media screen and (min-width: 1711px) {
		
		.min-data-input {
			margin-top: 308px;
		}
	}
	.el-dialog__body {
		padding: 20px 50px 30px;
	}

	.header {
		position: relative;
		.close {
			font-size: 26px;
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
			cursor: pointer;
		}
		.year-btn {
			min-width: 98px;
			font-size: 14px;
			margin-right: 5px;
			margin-bottom: 5px;
		}
		.btn-sty {
			font-size: 16px;
			padding: 10px;
			border: 1px solid #409eff;
		}
		.change-chart-btn{
				float: right;
				color: #409eff;
				font-size: 16px;
				cursor: pointer;
				&::before{
						content:'';
						display: inline-block;
						width: 18px;
						height: 18px;
						background-image: url('~@/assets/img/chart_m/change.png');
						background-size: cover;
						position: relative;
						top: 4px;
						right: 4px;
				}
		}
	}
	.min-wrapper {
		.el-input__inner {
			padding: 0 0 0 5px;
		}
		margin: 40px 0;
		min-height: 400px;
		.chartWrapper {
			position: relative;
			padding: 0 100px;
			.range-cont {
				position: absolute;
				top: 8%;
				.min-data-input {
					width: 80px;
					display: block;
				}
				&.left {
					left: 0px;
				}
				&.right {
					right: 0;
				}
			}
		}
	}
}
</style>