<template>
  <div class="commodity-chart-editor-container" id="box">
    <span
      class="slide-icon slide-right"
      @click="isSlideLeft = !isSlideLeft"
      v-show="isSlideLeft"
    >
      <i class="el-icon-d-arrow-right"></i>
    </span>
    <div class="left-cont" v-show="!isSlideLeft" id="left">
      <div class="left-top">
        <el-button 
					type="primary" 
					@click="saveHandle"
					:disabled="chartInfo.ChartType === 5 && tableData.length !== 2"
				>保存</el-button>
        <el-button type="primary" plain @click="$router.back()">取消</el-button>
      </div>
			<div class="left-min">
				<div class="search-cont">
					<label>选择现货价格指标</label>
					<el-select
						v-model="search_txt"
						v-loadMore="searchLoad"
						ref="searchRef"
						:filterable="!search_txt"
						remote
						clearable
						placeholder="选择现货价格指标"
						style="width:90%;margin-top: 10px;display: block;"
						:remote-method="searchHandle"
						@click.native="inputFocusHandle"
						@change="selectTarget($event && searchOptions.find(_ => _.EdbInfoId === $event))"
					>
						<i slot="prefix" class="el-input__icon el-icon-search"></i>
						<el-option
							v-for="item in searchOptions"
							:key="item.EdbInfoId"
							:label="item.EdbName"
							:value="item.EdbInfoId"
						>
						</el-option>
					</el-select>
				</div>
				
				<!-- 盘面利润 -->
				<div class="profit-set" v-if="chartInfo.Source===5">
					<el-button type="text" @click="openProfitOption">盘面利润设置</el-button>
				</div>

				<el-form
					ref="diaForm"
					label-position="top"
					label-width="80px"
					:model="chartInfo"
					:rules="chartRules"
				>
					<el-form-item label="选择期货" prop="futures_id" v-if="chartInfo.Source===2">
						<el-cascader
							v-model="chartInfo.futures_id"
							:options="futuresOptions"
							:props="{
								label: 'FutureGoodEdbInfoName',
								value: 'FutureGoodEdbInfoId',
								children: 'Child',
								emitPath: false
							}"
							style="width: 90%"
							placeholder="请选择期货"
							@change="changeFuturesHandle"
						/>
					</el-form-item>
					<el-form-item label="图表名称" prop="ChartName">
						<el-input
							v-model="chartInfo.ChartName"
							style="width: 90%"
							placeholder="必填项"
							clearable
						/>
					</el-form-item>
					<el-form-item label="图表分类" prop="classify">
						<el-cascader
							v-model="chartInfo.classify"
							:options="classifyOptions"
							:props="{
								label: 'ChartClassifyName',
								value: 'ChartClassifyId',
								children: 'Children',
								emitPath: false
							}"
							style="width: 90%"
							placeholder="请选择所属分类"
						/>
					</el-form-item>
				</el-form>

				<div class="targetset-cont">
					
					<!-- 价格曲线日期配置 -->
					<bar-option
						v-if="!chart_code || (chart_code&&chartInfo.ChartType)"
						ref="BarOptRef"
						:edblist="tableData"
						:datedata="commodityChartData"
						:initData="initDateOptions"
						@getData="getPreviewData"
					/>
        </div>
			</div>
      <span
        class="move-btn resize"
        v-drag
        id="resize"
      ></span>
      <span class="slide-icon slide-left" @click="isSlideLeft = !isSlideLeft">
				<i class="el-icon-d-arrow-left"></i>
			</span>
    </div>
    <div class="right-cont" id="right" :style="isSlideLeft ? 'width:100%' : `width:80%`">
			<div class="chart-min-cont" v-if="tableData.length&&(chartInfo.futures_id||profitInfo.list.length)&&commodityChartData.length">
				<div class="cont-bottom">
					<div class="chart-show-cont" v-show="options.series">
						<div class="chartWrapper" id="chartWrapper">
							<h2 class="chart-title" v-show="chartInfo.ChartName">{{ chartInfo.ChartName }}</h2>
							<Chart :options="options" minHeight="440px" height="500px" ref="chartRef" />

							<!-- 上下限  -->
							<div class="range-cont left">
								<el-input
									style="width: 60px; display: block"
									size="mini"
									type="number"
									placeholder="上限"
									v-model="chartLimit.max"
									@change="setCommodityChart"
								/>
								<el-input
									class="min-data-input"
									size="mini"
									type="number"
									placeholder="下限"
									v-model="chartLimit.min"
									@change="setCommodityChart"
								/>
							</div>
						</div>
						<span class="chart-author"
							>作者:{{ chartInfo.SysUserRealName || roleName }}</span
						>
					</div>
				</div>
      </div>
			
			<div class="nodata" v-else>
				<tableNoData text="暂无信息"/>
			</div>
		</div>


	<!-- 盘面利润设置弹窗 -->
	<plateProfitDia
		:isShow.sync="isOpenPlateprofitDia"
		:options="futuresOptions"
		:data="profitInfo"
		@ensure="setProfitBack"
	/>
  </div>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import futuresInterface from '@/api/modules/futuresBaseApi';
import { chartSetMixin } from '@/views/dataEntry_manage/mixins/chartPublic';
import Chart from '@/views/dataEntry_manage/components/chart';
import barOption from '@/views/dataEntry_manage/components/barOptionSection.vue';
import plateProfitDia from './components/plateProfitDia.vue';
export default {
  components: { Chart,barOption,plateProfitDia },
	directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var init = e.clientX;
        // console.log(init);
        var box = $('#box')[0];
        // console.log(box.clientWidth)
        let total_wid = box.offsetWidth;
        var left = $('#left')[0];
        var right = $('#right')[0];
        var initWidth = left.offsetWidth;
        document.onmousemove = function (e) {
          var end = e.clientX;
          var newWidth = end - init + initWidth;
          left.style.width = newWidth + 'px';
          right.style.width = newWidth > 300 ? total_wid - newWidth + 'px' : total_wid - 320 + 'px';
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
          e.releaseCapture && e.releaseCapture();
        };
        e.setCapture && e.setCapture();
        return false;
      };
    },
  },
	computed: {
		roleName() {
			return localStorage.getItem('userName');
		}
	},
	mixins: [chartSetMixin],
  data() {
    return {
			chart_code: this.$route.query.code || '',
			isSlideLeft: false,
			search_txt: '',
			activeNames:'',

			chartInfo: {
				ChartName: '',
				futures_id: '',
				classify: '',
				Source: this.$route.query.scence==='profit' ? 5 : 2,
			},
			chartRules: {
				futures_id:[
					{ required: true, message: '暂未选择期货', trigger: 'blur' },
				],
				ChartName:[
					{ required: true, message: '图表名称不能为空', trigger: 'blur' },
				],
				classify:[
					{ required: true, message: '图表分类不能为空', trigger: 'blur' },
				],
			},

			classifyOptions: [],//分类option
			futuresOptions: [],//期货种类
			initDateOptions: null,

			searchOptions: [],
			search_have_more: true,
			search_page: 1,
			current_search:'',

			//盘面利润设置
			isOpenPlateprofitDia: false,
			profitInfo: {
				list: [],
				formula: ''
			}

    };
  },
  methods: {

		/* 获取图表详情 */
		getChartInfo() {
			dataBaseInterface.getChartByCode({
          UniqueCode: this.chart_code,
        })
        .then((res) => {
          if (res.Ret !== 200) return;
					const { ChartInfo,BarChartInfo,EdbInfoList,DataResp } = res.Data;

          this.chartInfo = ChartInfo.Source===5 ? {
						...ChartInfo,
						classify: ChartInfo.ChartClassifyId,
						ProfitNameEn: DataResp.ProfitNameEn,
						ProfitName: DataResp.ProfitName,
					} : {
						...ChartInfo, 
						classify: ChartInfo.ChartClassifyId,
						futures_id: BarChartInfo.EdbInfoIdList.find(_ => _.Source===2).EdbInfoId
					};

					this.search_txt = EdbInfoList[0].EdbInfoId;
					this.tableData = [EdbInfoList[0]];
					this.searchOptions = this.tableData;

					this.initDateOptions = ChartInfo.Source===5 ? {
						DateList: DataResp.Extra.DateList,
						Sort: {
							DateIndex: 0,
							Sort: 0
						}
					} : BarChartInfo;
					this.profitInfo =  ChartInfo.Source===5 ? {
						list: DataResp.Extra.FutureGoodEdbInfoIdList,
						formula: DataResp.Extra.CalculateFormula
					} :  {}
					this.initCommodityData(res.Data)
        });
		},

    /* 选择指标 获取指标详情并push到表格中*/
		selectTarget(edb) {
			if(!edb){
				this.tableData = [];
				return
			} 

			this.tableData = [edb];
			this.commodityChartData.length && this.chartInfo.futures_id && this.$refs.BarOptRef.getBarData();
		},

		/* 选择期货 */
		changeFuturesHandle(val) {
			if(!val) return
			this.commodityChartData.length && this.tableData.length && this.$refs.BarOptRef.getBarData();
		},

    /* 获取数据 */
		async getPreviewData({sort,dateList}) {
			if(!dateList.length) this.commodityChartData = [];
			if(!this.tableData.length || !dateList.length) return

			this.chartInfo.Source===2
				? await this.getCommodityPreview(dateList)
				: await this.getProfitPreview(dateList);
			
		},

		/* 价格曲线预览 */
		async getCommodityPreview(dateList) {
			let params = {
				EdbInfoIdList: [
					...this.tableData.map(_ => ({EdbInfoId: _.EdbInfoId,Name:'',Source: 1})),
					{ EdbInfoId: this.chartInfo.futures_id,Name: '',Source: 2 }
				],
				DateList: dateList.map(_ => ({
					Type: _.Type,
					Date: _.Date,
					Value: _.Value,
					Name: '',
					Color: _.Color
				})),
			}

			const res = await futuresInterface.getChartData(params);
			if(res.Ret !== 200) return
			const { EdbInfoList,XDataList,YDataList } = res.Data;
			
			this.commodityEdbList = EdbInfoList;
			this.commodityChartData = YDataList;
			this.commodityXData = XDataList;

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

		/* 利润曲线预览 */
		async getProfitPreview(dateList) {
			if(!this.profitInfo.list.length) return this.$message.warning('请先设置盘面利润配置')

			const { list,formula } = this.profitInfo;
			let params = {
				FutureGoodEdbInfoIdList: list,
				CalculateFormula: formula,
				BaseEdbInfoId: this.tableData[0].EdbInfoId,
				DateList: dateList.map(_ => ({
					Type: _.Type,
					Date: _.Date,
					Value: _.Value,
					Name: '',
					Color: _.Color
				})),
			}

			const res = await futuresInterface.previewProfitData(params);
			if(res.Ret !== 200) return

			const { XDataList,YDataList,ProfitNameEn,ProfitName } = res.Data.DataResp;
			const { EdbInfoList } = res.Data;
			
			this.commodityEdbList = EdbInfoList;
			this.commodityChartData = YDataList;
			this.commodityXData = XDataList;
			this.chartInfo = {
				...this.chartInfo,
				ProfitName,
				ProfitNameEn
			}

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

    /* 搜索 */
		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 = await dataBaseInterface.targetSearchByPage(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() {
			futuresInterface.classifyOne().then(res => {
				if(res.Ret !== 200) return
				this.classifyOptions = res.Data.AllNodes || [];
			})
		},

		/* 获取期货数据分类option */
		getFuturesOptions() {
			futuresInterface.futuresTargetClassify().then(res => {
				if(res.Ret !== 200) return
				res.Data = res.Data || [];
				this.futuresOptions = res.Data || [];
			})
		},

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

		/* 保存 */
		async saveHandle() {
			if(!this.tableData.length) return this.$message.warning('暂未选择指标');
			await this.$refs.diaForm.validate();

			if(!this.$refs.BarOptRef.dateList.length)  return this.$message.warning('请添加日期');

			let public_param = {
				ChartClassifyId: this.chartInfo.classify || 0,
				ChartName: this.chartInfo.ChartName,
				ChartType:8,
				DateType: 6,
			}
			
			this.chartInfo.Source === 2 ? this.handleSaveCommodity(public_param) : this.handleSaveProfit(public_param);
		},
		
		/* 商品价格曲线保存 */
		async handleSaveCommodity(public_param) {
			let params =  {
				...public_param,
				LeftMin: String(this.chartLimit.min),
				LeftMax: String(this.chartLimit.max),
				BarChartInfo: {
					EdbInfoIdList: [
						...this.tableData.map(_ => ({EdbInfoId: _.EdbInfoId,Name:'',Source: 1})),
						{ EdbInfoId: this.chartInfo.futures_id,Name: '',Source: 2 }
					],
					DateList: this.$refs.BarOptRef.dateList.map(item => ({
						Type: item.Type,
						Date: item.Date,
						Value: item.Value,
						Name: '',
						Color: item.Color
					}))
				}
			}

			const { Ret,Data } = this.chart_code
				? await futuresInterface.chartEdit({...params,ChartInfoId: this.chartInfo.ChartInfoId })
				:	await futuresInterface.chartAdd(params)

				if(Ret !== 200) return;
				this.setChartImage(Data);
		},

		/* 利润曲线保存 */
		async handleSaveProfit(public_param) {
			if(!this.profitInfo.list.length)  return this.$message.warning('请先设置盘面利润配置');
			const { list,formula } = this.profitInfo;
			let params = {
				...public_param,
				LeftMin: String(this.chartLimit.min),
				LeftMax: String(this.chartLimit.max),
				Extra: {
					FutureGoodEdbInfoIdList: list,
					CalculateFormula: formula,
					BaseEdbInfoId: this.tableData[0].EdbInfoId,
					DateList: this.$refs.BarOptRef.dateList.map(_ => ({
						Type: _.Type,
						Date: _.Date,
						Value: _.Value,
						Name: '',
						Color: _.Color
					})),
				}
			}

			const { Ret,Data } = this.chart_code
				? await futuresInterface.profitChartEdit({...params,ChartInfoId: this.chartInfo.ChartInfoId })
				:	await futuresInterface.profitChartAdd(params)

				if(Ret !== 200) return;
				this.setChartImage(Data);
		},

		 /* 设置图表封面图片 */
    setChartImage(data) {
      let svg = this.$refs.chartRef.chart.getSVG({
        chart: {
          width: 340,
          height: 230,
        }
      });
      let form = new FormData();
      form.append('Img', svg);
      this.setImageHandle(form,data);
    },
    
    async setImageHandle(form,{ UniqueCode,ChartInfoId }) {
      let { Data } = await dataBaseInterface.uploadImgSvg(form);
      await dataBaseInterface.setChartImage({
        ChartInfoId: ChartInfoId,
        ImageUrl: Data.ResourceUrl,
      });

			this.$message.success(this.chart_code ? '添加成功' : '保存成功');
			this.$router.replace({
				path: '/commordityChartBase',
				query: {
					code: UniqueCode,
					id: ChartInfoId
				}
			})

    },
	
		openProfitOption() {
			this.isOpenPlateprofitDia = true;
		},

		/* 盘面利润数据 */
		setProfitBack(obj) {
			this.profitInfo = obj;
			this.tableData.length && this.$refs.BarOptRef.dateList.length && this.getPreviewData({sort:null,dateList:this.$refs.BarOptRef.dateList});
		},
	},
  mounted() {
		this.getMenu();
		this.getFuturesOptions();
		this.chart_code && this.getChartInfo();
		window.addEventListener('resize', this.reloadRightWid);
	},
	destroyed() {
		window.removeEventListener('resize', this.reloadRightWid);
	}
};
</script>
<style lang="scss">
.commodity-chart-editor-container {
	$font-small: 12px; $font-normal: 14px;

  display: flex;
	*{ box-sizing: border-box; }
	.el-form--label-top .el-form-item__label {
		padding: 0;
	}
	.el-form-item {
		margin-bottom: 8px;
	}
	.el-input-number .el-input__inner {
		padding: 0 34px 0 4px;
	}
	.target-other-name .el-input__inner {
		padding: 0 30px 0 5px !important;
		height: 40px !important;
		line-height: 40px !important;
	}
	.el-color-picker--mini .el-color-picker__trigger {
		width: 60px;
		height: 25px;
		padding: 0;
	}
	.el-color-picker--mini .el-color-picker__mask {
		width: 60px;
		height: 25px;
	}

	.slide-icon {
		padding: 20px 0;
		/* display: block; */
		box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
		border-radius: 5px;
		cursor: pointer;
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		z-index: 99;
		&:hover {
			background-color: rgba(0, 0, 0, 0.05);
		}
		&.slide-left {
			right: 0;
		}
		&.slide-right {
			left: 0;
		}
	}
  .left-cont {
    width: 400px;
    min-width: 300px;
    background: #fff;
    margin-right: 20px;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    height: calc(100vh - 113px);
    overflow: hidden;
    position: relative;
    box-sizing: border-box;
    .left-top {
      padding: 15px 20px;
      border: 1px solid #ececec;
      box-shadow: 0px 3px 6px rgba(167, 167, 167, 0.09);
    }
		.left-min {
			padding: 30px 20px;
			max-height: calc(100vh - 194px);
			overflow-y: auto;
			.search-cont {
				color: #606266;
				margin-bottom: 10px;
			}
			.targetset-cont {
				padding: 30px 0 20px;
				.el-input__inner {
					height: 27px;
					line-height: 27px;
					padding: 0 4px;
				}
				.el-collapse-item.is-disabled .el-collapse-item__header {
					color: #333;
				}
				.target-list {
					border: 1px solid #DCDFE6;
					.del-icon {
						position: absolute;
						right: 10px;
						font-size: 16px;
						color: #f00;
						cursor: pointer;
					}
					.setting-cont {
						padding: 20px 20px 0;
						li {
							padding-bottom: 20px;
							margin-bottom: 20px;
							border-bottom: 1px solid #DCDFE6;
							&:last-child {
								padding-bottom: 0;
								margin-bottom: 0;
								border-bottom: none;
							}
						}
					}
				}
				.el-collapse-item__header {
					background-color: #F0F2F5;
					margin-bottom: 0;
					border-bottom: 1px solid #DCDFE6;
					padding: 0 30px;
					.el-collapse-item__arrow {
						position: absolute;
						left: 8px;
					}
				}

				.scatter-setting {
					display: flex;
					margin-bottom: 20px;
				}
			}
		}
		.move-btn {
			height: 100%;
			width: 4px;
			position: absolute;
			right: 0px;
			top: 0;
			&:hover {
				cursor: col-resize;
			}
		}
  }
	.right-cont {
		width: 80%;
    .mx-datepicker {
      width: 220px !important;
    }
		 /* =================== */
		.chart-min-cont {
			background: #fff;
			border: 1px solid #ececec;
			height: calc(100vh - 118px);
			overflow: auto;
			/* overflow: hidden; */
			border-radius: 4px;
			box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
			.cont-top {
				padding: 12px 30px;
				border-bottom: 1px solid #ececec;
				display: flex;
				justify-content: space-between;
				align-items: center;
				box-shadow: 0px 3px 6px rgba(167, 167, 167, 0.09);
				.top-left {
					.year-btn {
						margin-right: 5px;
						margin-bottom: 5px;
					}
					.btn-sty {
						border: 1px solid #409eff;
					}
				}
				.top-right {
					font-size: 16px;
					.join_txt {
						color: #409eff;
						cursor: pointer;
						&:hover {
							text-decoration: underline;
						}
					}
					.collected {
						color: #f00;
						cursor: pointer;
						&:hover {
							text-decoration: underline;
						}
					}
					.span-item {
						color: #409eff;
						cursor: pointer;
						&:hover {
							text-decoration: underline;
						}
						.el-icon-collection,
						.el-icon-document-copy {
							color: #409eff;
						}
					}
				}
			}
			.cont-bottom {
				padding: 30px;
				/* height: calc(100vh - 250px);
				overflow: auto; */
				.el-input__inner {
					height: 27px;
					line-height: 27px;
					padding: 0 4px;
				}
				.el-input-number .el-input__inner {
					padding: 0 34px 0 4px;
				}
				.highcharts-range-selector-group {
					display: none;
					.highcharts-input-group {
						display: none;
					}
				}
				.highcharts-axis-title {
					display: block;
				}
				.calendar-cont {
					display: block;
					margin: 10px auto 0;
					text-align: center;
				}
				/* =================== */
				.chart-show-cont {
					min-height: 400px;
					padding: 0 150px 20px 120px;
					position: relative;
					.chart-title {
						font-size: 16px;
						font-weight: normal;
						text-align: center;
						margin-bottom: 10px;
					}
					.chart-author {
						font-size: 14px;
						color: #333;
						position: absolute;
						bottom: 20px;
						right: 50px;
					}
					.chartWrapper {
						position: relative;
						.range-cont {
							position: absolute;
							top: 15%;
							.min-data-input {
								width: 60px;
								display: block;
							}
							&.left {
								left: -80px;
							}
							&.right {
								right: -65px;
							}
							&.rightTwo {
								right: -130px;
							}
						}
					}
				}
				.options-cont {
					display: flex;
					flex-wrap: wrap;
					justify-content: space-between;
				}
			}

		}
    .nodata {
      height: calc(100vh - 120px);
			background-color: #fff;
      text-align: center;
      font-size: 16px;
      color: #666;
			padding: 100px 0;
    }
		@media screen and (min-width: 1711px){
			.min-data-input {
				margin-top: 360px;
			}
			.btn-sty {
				padding: 10px;
			}
			.year-btn,.btn-sty {
				font-size: $font-normal;
			}
		}

		@media screen and (max-width: 1710px){
			.min-data-input {
				margin-top: 290px;
			}
			.year-btn {
				font-size: $font-small;
				margin-left: 5px;
				margin-right: 5px;
				margin-bottom: 5px;
				padding: 6px 12px;
			}
			.btn-sty {
				font-size: $font-small;
				margin-left: 5px;
				padding: 6px;
				border: 1px solid #409eff;
			}
		}
	}
}
</style>
<style lang="scss">
.edb-item-style .el-input__icon {
	line-height: 27px;
}
</style>
