<template>
	<view>
		<follow :redirectUrl="'sfp/pages/childEdu/childEdu'" @getFollowData="getFollowData"
		v-show="isNeedOfficialAccountQrcode"></follow>
		<view class="wrapper" v-show="!isNeedOfficialAccountQrcode">
			<view class="banner">
				<!--头部技术支持组件-->
				<commonHead></commonHead>
				<img src="../../static/images/childEduBanner.jpg" alt="banner" srcset="">
			</view>	
			<scroll-view scroll-y="true" class="formInfoContainer" id="formInfoContainer">
				<view class="title"><view>小孩信息</view></view>
				<view class="listContent">
					<ul>
						<li>
							<div>昵称:</div>
							<div><input class="uni-input" v-model="eduPlanParam.name" maxlength="10" placeholder="昵称长度不超过10" /></div>
						</li>
						<li>
							<div>年龄：</div>
							<div><input class="uni-input" v-model="eduPlanParam.age" type="number" maxlength="2" placeholder="请输入周岁年龄" /></div>
						</li>
						<li class="multiline">
							<div class="multilineItem">
								<div>是否已上学：</div>
								<div class="selectBtnContent">
									<text :class="{'actived':haveAcceptEduFlag}" @click="haveAcceptEduFlag=true;eduPlanParam.ngoLearn=null">是</text>
									<text :class="{'actived':!haveAcceptEduFlag}" @click="haveAcceptEduFlag=false;eduPlanParam.maxGrade=null">否</text>
								</div>
							</div>
							<div class="multilineItem" v-if="haveAcceptEduFlag">
								<div>最高学历：</div>
								<div>
									<uni-data-picker placeholder="请选择最高学历" popup-title="请选择最高学历" :localdata="dataTree" v-model="eduPlanParam.maxGrade"
										@change="onchange" @nodeclick="onnodeclick">
									</uni-data-picker>
								</div>
							</div>
							<div class="multilineItem" v-if="!haveAcceptEduFlag">
								<div>几年后上学：</div>
								<div><input class="uni-input" v-model="eduPlanParam.ngoLearn" type="number" maxlength="1" placeholder="请输入整数" /></div>
							</div>
						</li>
						<li class="planGradeRange">
							<div>规划阶段</div>
							<div>
								<uni-data-picker placeholder="规划开始" popup-title="请选择规划开始阶段" :localdata="dataTree" v-model="eduPlanParam.startPlan"
									@change="onchange" @nodeclick="onnodeclick">
								</uni-data-picker>
								<text></text>
								<uni-data-picker placeholder="规划结束" popup-title="请选择规划结束阶段" :localdata="dataTree" v-model="eduPlanParam.endPlan"
									@change="onchange" @nodeclick="onnodeclick">
								</uni-data-picker>
							</div>
						</li>
					</ul>
				</view>
				<view class="title"><view>资源信息</view></view>
				<view class="listContent">
					<ul>
						<li>
							<div>已备教育资金总额：</div>
							<div><input class="uni-input" type="digit" maxlength="15" v-model="eduPlanParam.initEducationFund" placeholder="最高保留两位小数" />万元</div>
						</li>
						<li>
							<div>每年预备投入教育资金总额：</div>
							<div><input class="uni-input" type="digit" maxlength="15" v-model="eduPlanParam.educationDeposit" placeholder="最高保留两位小数" />万元</div>
						</li>
					</ul>
				</view>
				<view class="title"><view>参数</view></view>
				<view class="listContent">
					<ul>
						<li>
							<div>学费增长率：</div>
							<div><input class="uni-input" type="digit" maxlength="5" v-model="eduPlanParam.tuitionAddRate" placeholder="最高保留两位小数" />%</div>
						</li>
						<li>
							<div>资产投资回报率：</div>
							<div><input class="uni-input" type="digit" maxlength="5" v-model="eduPlanParam.investmentRate" placeholder="最高保留两位小数" />%</div>
						</li>
					</ul>
				</view>
				<!-- 学费设定 -->
				<view class="schoolingContent">
					<ul>
						<li>
							<div>学历</div>
							<div>学制（年）</div>
							<div style="flex-direction: column;">
								<view>首年预估费用</view>
								<view>(元)</view>
							</div>
							<div><view style="color: #ff5500;border-bottom: 1px solid #ff5500;" @click="schoolingLists=JSON.parse(JSON.stringify(dataTree))">恢复默认值</view></div>
						</li>
						<li v-for="item in schoolingLists" :key="item.value">
							<div>{{item.text}}</div>
							<div><input class="uni-input" maxlength="1" type="number" placeholder="最高不超过10" v-model="item.commonYears" @blur="updateSchoolingLists(item)"/></div>
							<div><input class="uni-input" maxlength="10" type="digit"  v-model="item.publicTuition" @blur="updateSchoolingLists(item)"/></div>
							<div><view class="settingButton" @click="settingYBY(item)">逐年设定</view></div>
						</li>
					</ul>
				</view>
				<!-- 测算结果及建议 -->
				<view class="title"><view>测算结果及建议</view></view>
				<!-- 图表 -->
				<!-- 为 ECharts 准备一个定义了宽高的 DOM -->
				<div id="main" style="width:96vw;height:400px" v-if="resultInfo"></div>
				<view class="summaryContent" v-if="resultInfo">
					<view class="successInfo" v-if="resultInfo.code=='B001'">
						<strong>恭喜您！</strong>
						<text>经过测算，您的资金可以负担{{eduPlanParam.name}}同学从{{getClassesInfo(getEducationNo(eduPlanParam.startPlan))}}到{{getClassesInfo(getEducationNo(eduPlanParam.endPlan))}}阶段的上学费用。</text>
					</view>
					<view class="failInfo" v-if="resultInfo.code=='A001'">
						<strong>很遗憾！</strong>
						<text v-if="resultInfo.educationNo>0">经过测算，您的资金只能负担到{{eduPlanParam.name}}同学到{{getClassesInfo(resultInfo.educationNo)}}。</text>
						<text v-if="resultInfo.educationNo<=0">经过测算，您的资金不足以负担{{eduPlanParam.name}}同学的教育目标。</text>
					</view>
					<view class="suggestionInfo" v-if="resultInfo.code=='A001'">
						<view>您可以这样做来实现：</view>
						<view>
							<ul>
								<li>1.提高已备教育资金总额到{{Math.abs(formatFloat(resultInfo.retEducationDeposit/10000))}}万元</li>
								<li>2.提高每年预备投入教育资金总额到{{Math.abs(formatFloat(resultInfo.retInitEducationFund/10000))}}万元</li>
							</ul>
						</view>
					</view>
				</view>
				<!-- 操作 -->
				<view class="optionContent">
					<button type="default" plain="true" form-type="reset"
					@click="resetData()" >全部清空</button>
					<button type="default" plain="true"
					class="btn" @click="educationEstimate()">开始计算</button>
				</view>
			
			</scroll-view>
		</view>
		<!--底部技术支持组件-->
		<foot></foot>
		<!-- 逐年设定弹窗 -->
		<view class="dialogContainer" v-if="settingYBYFlag">
			<view class="dialogContent">
				<view class="closeBtn" @click="closeDialog()">×</view>
				<ul>
					<li>
						<div>{{settingItem.text}}</div>
						<div>预估学费</div>
					</li>
					<li v-for="(item,index) in settingItem.children">
						<div>{{item.text}}</div>
						<div><input class="uni-input" type="digit" placeholder="最高保留两位小数" v-model="item.tuition"/></div>
					</li>
				</ul>
				<button type="default" plain="true" @click="confirmOption()">确定</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {ref} from "vue";
	import commonHead from '../header/header.vue';
	import follow from '../follow/follow.vue';
	import foot from "../footer/footer.vue";
	import {eduGradeLists} from "../../util/mock-data";
	import * as echarts from 'echarts';
	import api from "../../api/api";
	import common from "../../common/common";
	import dataHandling from "../../util/dataHandling";
	
	export default {
		data() {
			return {
				accountBalanceEnd:[],
				currentYearExpenditure:[],
				xAxisLists:[],
				settingItem:{},
				haveAcceptEduFlag:true,
				eduPlanParam:{
					name:'大宝',
					age:null,
					ngoLearn:null,
					maxGrade:null,
					startPlan:null,
					endPlan:null,
					initEducationFund:null,
					educationDeposit:null,
					tuitionAddRate:2.1,
					investmentRate:3.74,
					incomeAddRate:0,
					decimal:5
				},
				resultInfo:null,
				settingYBYFlag:false,
				isNeedOfficialAccountQrcode:true,
				classes:'1-1',
				dataTree: [],
				schoolingLists:eduGradeLists,
				flatEduGradeLists:[],
			}
		},
		methods: {
			getEducationNo(val){
				if(val){
					return this.flatEduGradeLists.filter(item=>item.value==val)[0].educationNo;
				}else{
					return null;
				}
				
			},
			getClassesInfo(val){
				if(val){
					const value = this.flatEduGradeLists.filter(item=>item.educationNo==val)[0].value;
					if(value){
						const schooling = value.split('-')[0];
						const grade = value.split('-')[1];
						let schoolingName = '';
						switch(schooling){
							case '1': 
								schoolingName = '幼儿园';
								break;
							case '2':
								schoolingName = '小学';
								break;
							case '3':
								schoolingName = '初中';
								break;
							case '4':
								schoolingName = '高中';
								break;
							case '5':
								schoolingName = '大学';
								break;
							case '6':
								schoolingName = '硕士';
								break;
							case '7':
								schoolingName = '博士';
								break;
							default:
								schoolingName = '幼儿园';
								break;
						}
						return (schoolingName + grade + '年级');
					}else{
						return val;
					}
					
				}
			},
			getFollowData(e){
				this.isNeedOfficialAccountQrcode= ref(e);
			},
			onnodeclick(e) {
				console.log(e);
			},
			onchange(e) {
				// console.log('onchange:', e);
			},
			drawLine(){
				  // 基于准备好的dom，初始化echarts实例
				      var myChart = echarts.init(document.getElementById('main'));
				      // 指定图表的配置项和数据
				      var option = {
						   title: {},
						   tooltip: {
						     trigger: 'axis',
						     axisPointer: {
						       type: 'cross',
						       label: {
						         backgroundColor: '#6a7985'
						       }
						     }
						   },
						   legend: {
						     data: ['教育金账户', '学费现金流'],
							 left:'1%'
						   },
						   grid: {
						     left: '2%',
						     containLabel: true
						   },
						   xAxis: [
						     {
						       type: 'category',
						       boundaryGap: false,
							   axisLabel:{
								   interval:0,
								   rotate:60
								},
								textStyle:{
									fontSize:10
								},
								data: this.xAxisLists
						     }
						   ],
						   yAxis: [
						     {
						       type: 'value'
						     }
						   ],
						   series: [
						     {
						       name: '教育金账户',
						       type: 'line',
							   itemStyle:{
								   color:'#2E9200'
							   },
							   lineStyle:{
								    color:'#46B700'
							   },
						       areaStyle: {
								   color:'#A5D58F'
							   },
						       emphasis: {
						         focus: 'series'
						       },
							   data:this.accountBalanceEnd,
						     },
						     {
						       name: '学费现金流',
						       type: 'line',
						       stack: 'Total',
							   itemStyle:{
								   color:'#C58906'
							   },
							   lineStyle:{
							   		color:'#E39C00'
							   },
						       areaStyle: {
								   color:'#FFAF00'
							   },
						       emphasis: {
						         focus: 'series'
						       },
							   data:this.currentYearExpenditure,
						     }
						   ]
				      };
				
				      // 使用刚指定的配置项和数据显示图表。
				      myChart.setOption(option);
			},
			settingYBY(item){
				// 逐年设定
				this.settingYBYFlag = true;
				this.settingItem = item;
			},
			updateSchoolingLists(val){
				if(Number(val.commonYears) != val.children.length){
					if(Number(val.commonYears) > 0){
						const arr = [];
						for(let i=0;i< Number(val.commonYears);i++){
							arr.push({text:`${i+1}年级`,value:`${val.value}-${i+1}`,tuition:null})
						}
						val.children = arr;
					}
				}
				if(val.publicTuition){
					val.children[0].tuition = val.publicTuition;
				}
			},
			closeDialog(){
				this.settingYBYFlag = false;
			},
			confirmOption(){
				this.settingYBYFlag = false;
				this.schoolingLists.filter(item=>item.value==this.settingItem.value)[0].publicTuition = this.settingItem.children[0].tuition;
			},
			objFlat(Data){
				// 对象数组拍平
			  const flatData = (data, parentId = undefined) => {
			        return data.reduce((prev, curr) => {
			          if (parentId != undefined) {
			            Object.assign(curr, {
			              parentId: parentId,
			            });
			          }
					  if(parentId){
						prev.push(curr);
					  }
			         
			          if (curr.children && curr.children.length > 0) {
			            prev.push(...flatData(curr.children,curr.value));
			          }
			          return prev;
			        }, []);
			      };
				  
				let flated = flatData(Data);
				return flated;
			},
			educationEstimate(){
				// 数据校验
				if(this.eduPlanParam.age && this.eduPlanParam.age > 50){
					common.errorDialog(2,'子女教育规划一般年龄不会超过40岁');
					return false;
				}else if(this.haveAcceptEduFlag && !this.eduPlanParam.maxGrade){
						common.errorDialog(1,'为了精准测算,请选择小孩的最高学历');
						return false;	
				}else if(!this.haveAcceptEduFlag && !this.eduPlanParam.ngoLearn && this.eduPlanParam.ngoLearn!=0){
						common.errorDialog(1,'为了精准测算,请填写小孩几年后上学');
						return false;	
				}else if(!this.eduPlanParam.startPlan || !this.eduPlanParam.endPlan){
					common.errorDialog(1,'为了精准测算,请选择规划阶段');
					return false;
				}else if(this.getEducationNo(this.eduPlanParam.startPlan) >= this.getEducationNo(this.eduPlanParam.endPlan)){
					common.errorDialog(1,'您的规划起始阶段应小于结束阶段');
					return false;
				}else if((!this.eduPlanParam.initEducationFund && this.eduPlanParam.initEducationFund!=0) || this.eduPlanParam.initEducationFund < 0){
					common.errorDialog(1,'请输入目前您已备教育资金总额');
					return false;
				}else if(!this.eduPlanParam.educationDeposit && this.eduPlanParam.educationDeposit!=0){
					common.errorDialog(1,'请输入您每年预备投入教育资金总额');
					return false;
				}
				const flatSchoolingLists = JSON.parse(JSON.stringify(this.objFlat(this.schoolingLists)));
				for(let i=0;i<flatSchoolingLists.length;i++){
					flatSchoolingLists[i]['educationNo']=i+1;
					flatSchoolingLists[i]['educationGrade']=flatSchoolingLists[i].value ? flatSchoolingLists[i].value.split('-')[0] : null;
					flatSchoolingLists[i]['gradeNo']=flatSchoolingLists[i].value ? flatSchoolingLists[i].value.split('-')[1] : null;
					flatSchoolingLists[i]['tuition']=flatSchoolingLists[i].tuition ? flatSchoolingLists[i].tuition : null;
					flatSchoolingLists[i]['text']=flatSchoolingLists[i]['parentId']=flatSchoolingLists[i]['value']=undefined;
				}
				const param = {
					...this.eduPlanParam,
					businessNo:uni.getStorageSync('businessNo'),
					wechat_openid:uni.getStorageSync('openId') || '',
					tuitionAddRate:(this.eduPlanParam.tuitionAddRate/100).toFixed(4),
					investmentRate:(this.eduPlanParam.investmentRate/100).toFixed(4),
					maxGrade:this.getEducationNo(this.eduPlanParam.maxGrade),
					startPlan:this.getEducationNo(this.eduPlanParam.startPlan),
					endPlan:this.getEducationNo(this.eduPlanParam.endPlan),
					educationTuitionInfos:flatSchoolingLists,
					initEducationFund:this.eduPlanParam.initEducationFund * Math.pow(10,4),
					educationDeposit:this.eduPlanParam.educationDeposit * Math.pow(10,4)
				}
				api.educationEstimate(param).then(res=>{
					this.resultInfo = res['data'];
					if(res['success']){
						this.currentYearExpenditure = [];
						 this.accountBalanceEnd = [];
						 this.xAxisLists = [];
						 const result = this.resultInfo.educationEstimateResInfos;
						for(let i=0;i<result.length;i++){
							this.currentYearExpenditure.push(Math.abs(result[i]['currentYearExpenditure']));
							this.accountBalanceEnd.push(result[i]['accountBalanceEnd']);
							this.xAxisLists.push(result[i]['educationNo'] ? this.getClassesInfo(result[i]['educationNo']) : result[i]['planyear'])
						}
						setTimeout(()=>{this.drawLine()},0)
					}else{
						this.currentYearExpenditure = [];
						 this.accountBalanceEnd = [];
						 this.xAxisLists = [];
						 common.errorDialog(2,res['message']);
						 return false;
					}
				})
			},
			resetData(){
				this.eduPlanParam = {
					name:'',
					age:null,
					ngoLearn:null,
					maxGrade:null,
					startPlan:null,
					endPlan:null,
					initEducationFund:null,
					educationDeposit:null,
					tuitionAddRate:2.1,
					investmentRate:3.74,
					incomeAddRate:0,
					decimal:5
				}
				this.schoolingLists.map(item=>{
					item.publicTuition=null;
					item.children.map(val=>val.tuition=null)
				})
			},
			/*
			num:源数据
			digitNum:保留几位小数
			type:向上(1)取还是向下(2)取
			*/
			formatFloat(num,digitNum=2,type=1){
				return common.formatFloat(num,digitNum=2,type=1)
			}
			
		},
		mounted() {
			this.dataTree = JSON.parse(JSON.stringify(eduGradeLists));
			this.flatEduGradeLists = JSON.parse(JSON.stringify(this.objFlat(this.schoolingLists)))
			this.flatEduGradeLists.map((val,idx)=>{
				val['educationNo'] = idx + 1;
			});
		},
		components:{
			follow,
			commonHead,
			foot
		}
	}
</script>

<style>
	@import url("childEdu.css");
</style>
