<template>
  <div class="fittingEquation-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">保存</el-button>
        <el-button style="margin-right:20px" type="primary" plain @click="$router.replace({
					path: '/fittingEquationList',
					query: $route.query
				})">取消</el-button>
				<span style="color: #666;">
						使用说明
					<el-tooltip
						effect="dark"
					>
						<div
							slot="content"
							v-html="useTip"
							style="line-height: 20px;width:350px"
						></div>
						<i class="el-icon-question" />
					</el-tooltip>
				</span>
      </div>
			<div class="left-min">
				<div class="section-item">
					<label style="display: block">时间:</label>
					<el-select
							style="width: 120px;margin: 10px 0"
							v-model="leftOption.DateType"
							placeholder="请选择"
							@change="leftOption.date=[]"
					>
						<el-option
								v-for="item in yearSelector"
								:key="item.value"
								:label="item.name"
								:value="item.value"
						/>
					</el-select>
					<date-picker
						v-model="leftOption.date"
						v-show="leftOption.DateType===5"
						style="width:120px;"
						type="date"
						range
						value-type="format"
						placeholder="请选择时间段"
					/>
				</div>
        
        <el-collapse v-model="activeNames" class="targetset-cont">
          <el-collapse-item  
            class="series-li"
            :name="0"
          >
            <template slot="title">
              <el-button type="text" size="small" style="font-size: 15px;">X值指标</el-button>
            </template>
            <div class="setting-wrapper">
              <selectTarget
								ref="xSelectRef"
                @select="chooseXEdbs"
              />

              <ul class="edb-list">
                <li v-for="(item,index) in leftOption.xEdbs" :key="item.id">
                  <div class="info">
										<el-popover
											placement="top-start"
											width="200"
											trigger="hover"
											:content="item.name">
											<div class="text_oneLine" slot="reference" style="max-width:200px;">
												<span>{{index+1}}:</span>
												<span>{{item.name}}</span>
											</div>
										</el-popover>
										<i class="el-icon-delete deletesty" @click="removeTarget('x',index)"></i>
                  </div>
                </li>
              </ul>
            </div>
          </el-collapse-item>
          <el-collapse-item  
            class="series-li"
            :name="1"
          >
            <template slot="title">
              <el-button type="text" size="small" style="font-size: 15px;">Y轴指标</el-button>
            </template>
            <div class="setting-wrapper">
              <selectTarget
								ref="ySelectRef"
                @select="chooseYEdbs"
              />

              <ul class="edb-list">
                <li v-for="(item,index) in leftOption.yEdbs" :key="item.id">
                  <div class="info">
										<el-popover
											placement="top-start"
											width="200"
											trigger="hover"
											:content="item.name">
											<div class="text_oneLine" slot="reference" style="max-width:200px;">
												<span>{{index+1}}:</span>
												<span>{{item.name}}</span>
											</div>
										</el-popover>
										<i class="el-icon-delete deletesty" @click="removeTarget('y',index)"></i>
                  </div>
                </li>
              </ul>
            </div>
          </el-collapse-item>
        </el-collapse>
        
        <el-button type="primary" @click="getPreviewData">确定</el-button>
			</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="chartBatchData.length">
				<div class="card-wrapper" v-for="(item,index) in chartBatchData" :key="index">
            <chartCard 
              :entryType="index+1"
              :ref="`chartCard${index+1}`"
              :data="item"
            />

				</div>
      </div>
			
			<div class="nodata" v-else>
				<tableNoData text="暂无信息"/>
			</div>
		</div>

    <!-- 保存弹窗 -->
    <fittingEquationSaveDia
      :isShow.sync="isSaveDialog"
			:initData="leftOption.ChartMappingList"
			@saveBack="editChartBackHandle"
    />

  </div>
</template>

<script>
import { fittingEquationInterface } from '@/api/modules/chartRelevanceApi';
import { yearSelector } from '@/utils/defaultOptions';
import Chart from '@/views/dataEntry_manage/components/chart';
import selectTarget from './components/selectTarget.vue';
import fittingEquationSaveDia from './components/fittingEquationSaveDia.vue';
import chartCard from './components/chartCard.vue';
export default {
  components: { Chart,selectTarget,fittingEquationSaveDia,chartCard },
	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');
		}
	},
  data() {
    return {
			chart_code: this.$route.query.code || '',
			isSlideLeft: false,
			activeNames:[0],

			chartBatchData: [],
			yearSelector: [
        ...yearSelector,
        { name: '自定义',value: 5 }
      ],
			dateSelector: [
				{ name: '过去1年',value: 1 },
				{ name: '过去2年',value: 2 },
				{ name: '过去3年',value: 3 },
				{ name: '过去5年',value: 4 },
				{ name: '过去10年',value: 5 },
				{ name: '自定义',value: 6 },
				
			],

      leftOption: {
				MultipleGraphConfigId: 0,
				ChartMappingList:[],
        DateType: yearSelector[0].value,
				date: [],
        xEdbs: [],
        yEdbs: []
      },

			classifyOptions: [],//分类option

			isSaveDialog: false,

			useTip:`1、选择两组有相关性的指标<br>
					2、对两组在选定时间范围内的每一个时间节点,生成拟合方程Y=aX+b以及相关系数R²<br>
					3、分别画出弹性系数a,截距b,相关系数R²,在选定时间范围内的曲线图`

    };
  },
  methods: {

		/* 获取图表详情 */
		getChartInfo() {
			fittingEquationInterface.getConfigSetting({
				UniqueCode: this.chart_code,
			}).then((res) => {
				if (res.Ret !== 200) return;
				
				const { ChartMappingList,EdbInfoList,LineChartInfoConfig,MultipleGraphConfigId } = res.Data;
				this.leftOption = {
					MultipleGraphConfigId,
					ChartMappingList,
					DateType: LineChartInfoConfig.DateType,
					date: [LineChartInfoConfig.StartDate,LineChartInfoConfig.EndDate],
					xEdbs: LineChartInfoConfig.XEdbInfoIdList.map(_ => ({ id: _,name:EdbInfoList.find(_edb =>_edb.EdbInfoId===_).EdbName })),
					yEdbs: LineChartInfoConfig.YEdbInfoIdList.map(_ => ({ id: _,name:EdbInfoList.find(_edb =>_edb.EdbInfoId===_).EdbName })),
				}

				this.getPreviewData();
			});
		},

    /* 获取数据 */
		getPreviewData() {
			if(!this.leftOption.xEdbs.length || !this.leftOption.yEdbs.length) return this.$message.warning('请先选择指标');
			if(this.leftOption.xEdbs.length < 2 || this.leftOption.yEdbs.length < 2) return this.$message.warning('指标数量不得少于2组')
			if(this.leftOption.yEdbs.length !== this.leftOption.xEdbs.length) return this.$message.warning('X轴与Y轴指标数量不一致');

			const { DateType,date,xEdbs,yEdbs } = this.leftOption;
			let params = {
				DateType,
				StartDate: date[0]||'',
				EndDate: date[1]||'',
				XEdbInfoIdList: xEdbs.map(_ => _.id),
				YEdbInfoIdList: yEdbs.map(_ => _.id)
			}

			const chartNameMap = {
				1: this.leftOption.ChartMappingList.find(_ => _.Source===5) ? this.leftOption.ChartMappingList.find(_ => _.Source===5).ChartName : '',
				2: this.leftOption.ChartMappingList.find(_ => _.Source===6) ? this.leftOption.ChartMappingList.find(_ => _.Source===6).ChartName : '',
				3: this.leftOption.ChartMappingList.find(_ => _.Source===7) ? this.leftOption.ChartMappingList.find(_ => _.Source===7).ChartName : '',
			}

			fittingEquationInterface.previewData(params).then(res => {
				if(res.Ret !== 200) return

				this.chartBatchData = res.Data.List ? res.Data.List.map((_,index) =>({
					ChartInfo: { Source: 6,ChartName: chartNameMap[index+1] },
					EdbInfo: {
						..._,
						ChartColor:'#00f',
						ChartStyle:'spline',
						PredictChartColor: '#00f',
						ChartType:0,
						ChartWidth:3,
						EdbName:_.Name,
						EdbNameEn: _.NameEn,
						IsAxis:1
					}
				})) : [];
			})
		},

    // 选择指标
    chooseXEdbs(edb) {
			if(edb){
				this.leftOption.xEdbs.push({
					id: edb.EdbInfoId,
					name: edb.EdbName,
				})
				this.$refs.xSelectRef.search_txt = '';
			}
    },

    chooseYEdbs(edb) {
			if(edb) {
				if(this.leftOption.yEdbs)
				this.leftOption.yEdbs.push({
					id: edb.EdbInfoId,
					name: edb.EdbName,
				})
				this.$refs.ySelectRef.search_txt = '';
			}
    },

		/* 删除指标 */
    removeTarget(type,index) {
      type === 'x' ? this.leftOption.xEdbs.splice(index,1) : this.leftOption.yEdbs.splice(index,1);
    },

    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.leftOption.xEdbs.length || !this.leftOption.yEdbs.length) return this.$message.warning('请先选择指标');
			if(this.leftOption.xEdbs.length < 2 || this.leftOption.yEdbs.length < 2) return this.$message.warning('指标数量不得少于2组')
			if(this.leftOption.yEdbs.length !== this.leftOption.xEdbs.length) return this.$message.warning('X轴与Y轴指标数量不一致');
      this.isSaveDialog = true;

		},

		/* 保存成功跳列表 */
		editChartBackHandle(query) {
			this.$router.replace({
        path: '/fittingEquationList',
        query
      })
		}
	},
  mounted() {
		this.chart_code && this.getChartInfo();
		window.addEventListener('resize', this.reloadRightWid);
	},
	destroyed() {
		window.removeEventListener('resize', this.reloadRightWid);
	}
};
</script>
<style lang="scss">
.fittingEquation-chart-editor-container {
	$font-small: 12px; $font-normal: 14px;

  display: flex;
	*{ box-sizing: border-box; }
	.el-date-editor .el-range-separator {
		width: 10%;
	}
	.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;

			.targetset-cont {
        border: 1px solid #DCDFE6;
        margin: 20px 0;
        
				.el-collapse-item.is-disabled .el-collapse-item__header {
					color: #333;
				}
				.setting-wrapper {
					padding: 15px;
				}
				.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;
					}
				}
				.edb-list {
					margin: 10px 0;
					.info {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 10px;
						color: #666;
					}
				}
			}
		}
		.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;
      height: calc(100vh - 118px);
			border: 1px solid #ececec;
      overflow-y: auto;
			display: flex;
			flex-wrap: wrap;
			.card-wrapper {
				width: 50%;
        margin-bottom: 20px;
        min-height: 350px;
				.card-item {
					padding: 20px;
					.top {
						display: flex;
						justify-content: space-between;
						align-items: center;
					}
					.chartWrapper {
						.title {
							font-size: 15px;
							text-align: center;
							margin: 10px 0;
						}
					}
				}
			}
    }
    .nodata {
      height: calc(100vh - 120px);
			background-color: #fff;
      text-align: center;
      font-size: 16px;
      color: #666;
			padding: 100px 0;
    }
	}
}
</style>
<style lang="scss">
.edb-item-style .el-input__icon {
	line-height: 27px;
}
</style>
