import { dataBaseInterface } from '@/api/api.js';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import { defaultOpts } from '@/utils/defaultOptions';
import { mapState } from 'vuex';

/* 新增编辑图表公用 */
export default {
	data() {
		return {
			edbFromType: 0,//指标数据来源 eta 和eta预测
			chartInfo: {
				ChartType: 1,
				Source:1,
				Unit: '',
				ChartName: ''
			},
			chartRules: {
				ChartType:[
					{ required: true, message: '生成样式不能为空', trigger: 'blur' },
				],
				ChartName:[
					{ required: true, message: '图表名称不能为空', trigger: 'blur' },
				],
				classify:[
					{ required: true, message: '图表分类不能为空', trigger: 'blur' },
				],
				Unit:[
					{ required: true, message: '图表单位不能为空', trigger: 'blur' },
				],
			},

			classifyOptions: [],//分类option
      levelProps: {
        label: 'ChartClassifyName',
        value: 'ChartClassifyId',
        children: 'Children',
      },

			styleArr: [
				{ label: '曲线图', key: 1 },
        { label: '季节性图', key: 2 },
        // { label: '堆积面积图', key: 3 },
        { label: '堆积柱状图', key: 4 },
        { label: '散点图', key: 5 },
        { label: '组合图', key: 6 },
				{ label: '柱形图',key: 7 },
				{ label: '截面散点图',key: 10 },
      ], //图表样式


			searchOptions: [],
			search_have_more: true,
			search_page: 1,
			current_search:'',
		}
	},
	computed: {
		...mapState({
			chart_lang: state => state.edb.chart_lang,	
		})
	},
	watch: {
		edbFromType() {
			this.search_txt = '';
		},
		'chartInfo.ChartType': {
			handler(newval, oldval) {
				console.log(this.needWatch)
				if(!this.needWatch) return
				this.activeNames = '';
				this.options = {};

				if(newval === 2 && this.tableData.length > 1) {
					this.chartInfo.ChartType = oldval;
					return this.$message.warning('您选择的图表样式为季节性图表，只支持单指标画图');
				} else if(newval === 5 && this.tableData.length > 2) {
					this.chartInfo.ChartType = oldval;
					return this.$message.warning('您选择的图表样式为散点图，最多支持2个指标');
				}else if(newval===10&&this.tableData.length) {
					this.$nextTick(() => {
						console.log(this.$refs.SectionScatterOptRef)
						this.$refs.SectionScatterOptRef.seriesArr = [
							{ 
								index:1,
								showTrendLine: false,
								showFitEquation: false,
								showRSquare: false,
								tagsAllShow: false,
								edbs: this.tableData.map(item => ({
									name: item.EdbName,
									is_show: false,
									x_target_id: item.EdbInfoId,
									x_target_name: item.EdbName,
									x_date_type: 1,
									x_date: item.LatestDate,
									x_date_value: 0,
									y_target_id: 0,
									y_target_name: '',
									y_date_type: 1,
									y_date: '',
									y_date_value: 0,
								}))
							}
						]
					})
				}

				//柱形图 截面散点切换到普通图 依赖的指标信息其实只有信息无数据 需清空
				if([7,10].includes(oldval)&&![7,10].includes(newval)) {
					this.tableData = [];
					this.chartInfo.LeftMax = '';
					this.chartInfo.LeftMin = '';
				}

				this.initStatus();

				//共用结构的类型切换可以直接画图
				if(![7,10].includes(newval)) {
					//单指标允许相互切换
					this.tableData.length===1 && this.selectTarget(this.tableData[0],'switch');
					this.tableData.length > 1 && this.setChartOptionHandle(this.tableData);
				}
      },
		}
	},

	methods: {
		/* 选择指标 获取指标详情并push到表格中*/
		selectTarget(item,type='') {
			if(!item) return

			/* 正常图获取指标数据 柱形图不获取 */
			if(this.chartInfo.ChartType !== 7) {
				let params = this.sameOptionType.includes(this.chartInfo.ChartType) 
					? {
						EdbInfoId: item.EdbInfoId,
						ChartType: this.chartInfo.ChartType,
						DateType: this.year_select,
						StartDate:
							this.year_select === 5 || this.year_select === 6
								? this.select_date[0]
								: '',
						EndDate: this.year_select === 5 ? this.select_date[1] : '',
					} 
					: {
						EdbInfoId: item.EdbInfoId,
						ChartType: this.chartInfo.ChartType,
						Calendar: this.calendar_type,
						SeasonStartDate: this.season_year ? this.season_year[0] : '',
						SeasonEndDate: this.season_year ? this.season_year[1] : '',
					};
				dataBaseInterface.chartInfo(params).then((res) => {
					if(res.Ret !== 200) return;
						let [ tableItem ] = res.Data.EdbInfoList;
	
						// 同一指标切换图表类型
						if(type) {
							this.tableData = [ tableItem ];
							return
						};
						//检查添加指标是否已存在
						let have_bol = this.tableData.every(item => item.EdbInfoId !== tableItem.EdbInfoId);
	
						if(have_bol) {
							this.search_txt = '';
							if(this.chartInfo.ChartType === 2 && this.tableData.length >= 1) return this.$message.warning('您选择的图表样式为季节性图表，只支持单指标画图')
							else if(this.chartInfo.ChartType === 5 && this.tableData.length >= 2) return this.$message.warning('您选择的图表样式为散点图，最多支持2个指标')
							this.tableData.push(tableItem);
							this.isSetExtremeValue = true;
							console.log(this.tableData)
						}else {
							this.$message.warning('录入指标已存在');
						}
				})
			}else {
				this.setBarEdbList(item);
			}

		},

		/* 添加柱形图表格 */
		setBarEdbList(edb) {
			let have_bol = this.tableData.some(item => item.EdbInfoId === edb.EdbInfoId);

			//新增属性用作别名
			this.$set(edb,'EdbAliasName',edb.EdbName)
			if(have_bol) return this.$message.warning('录入指标已存在');
			this.search_txt = '';
			this.tableData.push(edb)

		},

		/* 获取bar数据 */
		getBarPreviewData({sort,dateList}) {
			if(!this.tableData.length || !dateList.length) return

			let params = {
				EdbInfoIdList: this.tableData.map(_ => ({
					EdbInfoId: _.EdbInfoId,
					Name:_.EdbAliasName
				})),
				DateList: dateList,
				Sort: {
					Sort: sort.sort,
					DateIndex: Number(sort.sortIndex)
				}
			}

			dataBaseInterface.getBarData(params).then(res => {
				if(res.Ret !== 200) return

				const { EdbInfoList,XEdbIdValue,YDataList } = res.Data;

				let xData = XEdbIdValue.map(_ => EdbInfoList.find(edb => edb.EdbInfoId===_).EdbAliasName)

				this.barDateList = YDataList;
				this.barXData = xData;
				this.barEdbData = EdbInfoList;

				//初始状态设置上下限极值
				if(!this.chartInfo.LeftMin) {
					const value_arr = this.barDateList.map(_ => _.Value).flat(Infinity)
					console.log(value_arr)
					this.chartLimit = {
						min: Math.min(...value_arr),
						max: Math.max(...value_arr)
					}
				}
			})
		},

		/* 曲线图切换筛选项时请求数据 */
		async getPreviewSplineInfo() {
			let params = {
        ChartType: this.chartInfo.ChartType,
        DateType: this.year_select,
        StartDate: [5, 6].includes(this.year_select)
          ? this.select_date[0]
          : '',
        EndDate: this.year_select === 5 ? this.select_date[1] : '',
        Calendar: this.calendar_type,
        SeasonStartDate: this.season_year ? this.season_year[0] : '',
        SeasonEndDate: this.season_year ? this.season_year[1] : '',
        ChartEdbInfoList: this.tableData.map(_ => ({
          EdbInfoId: _.EdbInfoId,
          EdbInfoType: _.EdbInfoType,
          LeadValue: _.EdbInfoType ? 0 : Number(_.LeadValue),
          LeadUnit: _.EdbInfoType ? '' : _.LeadUnit,
        }))
      }

      const res = await dataBaseInterface.getSplinePreviewData(params)

      if(res.Ret !== 200) return

      const { EdbInfoList } = res.Data;

      this.tableData.forEach((item) => {
        let edbData = EdbInfoList.find(_ => _.EdbInfoId===item.EdbInfoId);
        item.DataList = edbData.DataList;
        if(edbData.EdbInfoCategoryType===1) item.MoveLatestDate = edbData.MoveLatestDate;
      });
		},

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

			this.getPreviewSplineInfo();
		},

		/* 打开时间段弹窗 */
		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];
			if (data.dateType === 5) {
				this.dateTip = `${data.start_date}~${data.end_date}`;
			} else {
				this.dateTip = `${data.start_date}~至今`;
			}
			this.getPreviewSplineInfo();
		},

			/* 季节图切换年份  保持当前配置 */
		seasonYearChange() {
			this.getPreviewSplineInfo();
		},

		/* 切换图重置状态 */
		initStatus() {
			this.year_select = 3;
			this.select_date = '';
			this.isSetExtremeValue = true;
			this.calendar_type = '公历';
			this.season_year = '';
			this.dateForm = {};
			this.dateTip = '请选择时间段';
			this.barDateList = [];
      this.chartLimit = {};
      this.sectionScatterData = {};
		},

		/* 添加指标时 配置默认颜色 线条等 */
		setAddChartDefault() {
			this.tableData.forEach((item,index) => {
				item.ChartColor = item.ChartColor || defaultOpts.colors[index];
				item.PredictChartColor = item.PredictChartColor || defaultOpts.colors[index];
				item.ChartStyle = item.ChartStyle || 'spline';
				if (index === 0)
					this.tableData[index].ChartWidth = this.tableData[index].ChartWidth || 3;
				if (index >= 1)
					this.tableData[index].ChartWidth = this.tableData[index].ChartWidth || 1;
			})
		},

		/* 搜索 */
		searchHandle(query) {
			this.search_page = 1;
			this.current_search = query;
			this.searchApi(this.current_search)
		},

		async searchApi(query,page=1) {
			let params = {
				KeyWord:query,
				CurrentIndex: page,
			}
			const res = this.edbFromType === 0
				? await dataBaseInterface.targetSearchByPage(params)
				: await preDictEdbInterface.edbSearch(params)

				if(res.Ret !== 200) return
				const { List,Paging } = res.Data;
				this.search_have_more = page < Paging.Pages;
				this.searchOptions = page === 1 ? List : this.searchOptions.concat(List);
		},

		/* 聚焦获取当前检索 */
		inputFocusHandle(e) {
			this.search_page = 1;
			this.current_search = e.target.value;
			this.searchApi(this.current_search);
		},

		searchLoad() {
			if(!this.search_have_more) return;
			this.searchApi(this.current_search,++this.search_page);
		},

		/* 获取分类目录结构 */
		getMenu() {
			dataBaseInterface.chartClassify().then(res => {
				if(res.Ret === 200) {
					this.filterNodes(res.Data.AllNodes);
					this.classifyOptions = res.Data.AllNodes || [];
				}
			})
		},

		// 递归改变第四级目录结构
		filterNodes(arr) {
			arr.length && arr.forEach(item => {
				item.Children.length && this.filterNodes(item.Children)
				if(item.Level === 3) {
					delete item.Children
				}
			})
		},

		/* 移除表格指标 */
		delTarget(item) {
			if(this.tableData.length) {
				let index = this.tableData.findIndex(obj => obj.EdbInfoId === item.EdbInfoId);
				this.tableData.splice(index, 1);
				this.$message.success('删除成功')
			}
		},

		reloadRightWid() {
			let total_wid = $('#box')[0].offsetWidth;
      let left = $('#left')[0].offsetWidth;
      let rigtWid = total_wid - left - 20 + 'px';
      $('#right')[0].style.width = rigtWid;
		},

		/* 时间截面散点图预览数据 */
		getSectionScatterData(series) {
			const { x_title,y_title,x_unit,y_unit } = series[0];

			let param_series = series.map(_ => ({
				Name: _.series_name,
				Color: _.color,
				ShowRSquare: _.showRSquare,
				ShowFitEquation: _.showFitEquation,
				ShowTrendLine: _.showTrendLine,
				EdbInfoList: _.edbs.map(edb=>({
					XEdbInfoId: edb.x_target_id,
					YEdbInfoId: edb.y_target_id,
					Name: edb.name,
					XDateType: edb.x_date_type,
					XDate: edb.x_date,
					XDateValue: edb.x_date_value,
					YDateType: edb.y_date_type,
					YDate: edb.y_date,
					YDateValue: edb.y_date_value,
					IsShow: edb.is_show
				}))
			}))
			let params = {
				XName: x_title,
				YName: y_title,
				XUnitName: x_unit,
				YUnitName: y_unit,
				XMinValue: String(this.chartLimit.x_min||''),
				XMaxValue: String(this.chartLimit.x_max||''),
				YMinValue: String(this.chartLimit.min||''),
				YMaxValue: String(this.chartLimit.max||''),
				SeriesList: param_series
			}
			dataBaseInterface.sectionScatterPreviewData({
				ExtraConfig: JSON.stringify(params)
			}).then(res => {
				if(res.Ret !== 200) return
				
				const { EdbInfoList,DataResp } = res.Data;

				this.sectionScatterData = DataResp;
				this.tableData = EdbInfoList;
				
				//初始状态设置上下限极值
				if(!this.sectionScatterData.XMaxValue) {
					const x_value_arr = this.sectionScatterData.DataList.map(_ => _.EdbInfoList.map(point => point.XValue)).flat(Infinity)
					const y_value_arr = this.sectionScatterData.DataList.map(_ => _.EdbInfoList.map(point => point.YValue)).flat(Infinity)
					this.chartLimit = {
						min: Math.min(...y_value_arr),
						max: Math.max(...y_value_arr),
						x_min: Math.min(...x_value_arr),
						x_max: Math.max(...x_value_arr)
					}
				}
			})
		},

		/* 添加图表参数 */
		getSaveParamsByChartType(public_param) {
			switch(this.chartInfo.ChartType) {
				case 2: 
					return {
						...public_param,
						Calendar: this.calendar_type,
						SeasonStartDate: this.season_year ? this.season_year[0] : '',
						SeasonEndDate: this.season_year ? this.season_year[1] : '',
					}
				case 7:
					return {
						...public_param,
						DateType: 6,
						LeftMin: String(this.chartLimit.min),
						LeftMax: String(this.chartLimit.max),
						BarChartInfo: {
							EdbInfoIdList: this.barEdbData.map(item => ({ EdbInfoId: item.EdbInfoId,Name: item.EdbAliasName })),
							DateList: this.$refs.BarOptRef.dateList.map(item => ({
								Type: item.Type,
								Date: item.Date,
								Value: item.Value,
								Name: item.Name,
								Color: item.Color
							})),
							Sort: {
								Sort: this.$refs.BarOptRef.sortObj.sort,
								DateIndex: Number(this.$refs.BarOptRef.sortObj.sortIndex)
							},
							Unit: this.chartInfo.Unit
						}
					}
				case 10: 
					return {
						...public_param,
						DateType: 6,
						StartDate: "",
						EndDate: "",
						Calendar: "公历",
						SeasonStartDate: "",
						SeasonEndDate: "",
						ExtraConfig: JSON.stringify({
							XName: this.$refs.SectionScatterOptRef.seriesArr[0].x_title,
							YName: this.$refs.SectionScatterOptRef.seriesArr[0].y_title,
							XUnitName: this.$refs.SectionScatterOptRef.seriesArr[0].x_unit,
							YUnitName: this.$refs.SectionScatterOptRef.seriesArr[0].y_unit,
							XNameEn: this.$refs.SectionScatterOptRef.seriesArr[0].x_title_en || '',
							YNameEn: this.$refs.SectionScatterOptRef.seriesArr[0].y_title_en || '',
							XUnitNameEn: this.$refs.SectionScatterOptRef.seriesArr[0].x_unit_en || '',
							YUnitNameEn: this.$refs.SectionScatterOptRef.seriesArr[0].y_unit_en || '',
							XMinValue: String(this.chartLimit.x_min),
							XMaxValue: String(this.chartLimit.x_max),
							YMinValue: String(this.chartLimit.min),
							YMaxValue: String(this.chartLimit.max),
							SeriesList: this.$refs.SectionScatterOptRef.seriesArr.map(_ => ({
								Name: _.series_name,
								NameEn: _.series_name_en || '',
								Color: _.color,
								ShowRSquare: _.showRSquare,
								ShowFitEquation: _.showFitEquation,
								ShowTrendLine: _.showTrendLine,
								EdbInfoList: _.edbs.map(edb=>({
									XEdbInfoId: edb.x_target_id,
									YEdbInfoId: edb.y_target_id,
									Name: edb.name,
									NameEn: edb.name_en || '',
									XDateType: edb.x_date_type,
									XDate: edb.x_date,
									XDateValue: edb.x_date_value,
									YDateType: edb.y_date_type,
									YDate: edb.y_date,
									YDateValue: edb.y_date_value,
									IsShow: edb.is_show
								}))
							}))
						})
					}	
			}
		},

		/* 奇怪柱形图更新单位 */
		changeUnit(val) {
			if(!this.options.series) return

			this.options.yAxis[0].title.text = val;
		}
	}
}