<template>
	<view>
		<view class="wrapper">
			<text class="iconfont icon-youjiantou zuojiantou" @click="goBack()" style="top: 30rpx;"></text>
			<view class="banner">
				<!--头部技术支持组件-->
				<!-- <commonHead></commonHead> -->
				<image src="../../static/images/childEduBanner.jpg" mode="widthFix"></image>
			</view>	
			<scroll-view scroll-y="true" class="formInfoContainer" id="formInfoContainer">
				<view class="title"><view>小孩信息</view></view>
				<view class="listContent">
					<view class="ulBox">
						<view class="liBox">
							<view>昵称:</view>
							<view><input class="uni-input" v-model="eduPlanParam.name" maxlength="10" placeholder="昵称长度不超过10" /></view>
						</view>
						<view class="liBox">
							<view>年龄：</view>
							<view><input class="uni-input" v-model="eduPlanParam.age" type="number" maxlength="2" placeholder="请输入周岁年龄" /></view>
						</view>
						<view class="multiline liBox">
							<view class="multilineItem">
								<view>是否已上学：</view>
								<view class="selectBtnContent">
									<text :class="{'actived':haveAcceptEduFlag}" @click="haveAcceptEduFlag=true;eduPlanParam.ngoLearn=null">是</text>
									<text :class="{'actived':!haveAcceptEduFlag}" @click="haveAcceptEduFlag=false;eduPlanParam.maxGrade=null">否</text>
								</view>
							</view>
							<view class="multilineItem" v-if="haveAcceptEduFlag">
								<view>最高学历：</view>
								<view>
									<uni-data-picker placeholder="请选择最高学历" popup-title="请选择最高学历" :localdata="dataTree" v-model="eduPlanParam.maxGrade"
										@change="onchange" @nodeclick="onnodeclick">
									</uni-data-picker>
								</view>
							</view>
							<view class="multilineItem" v-if="!haveAcceptEduFlag">
								<view>几年后上学：</view>
								<view><input class="uni-input" v-model="eduPlanParam.ngoLearn" type="number" maxlength="1" placeholder="请输入整数" /></view>
							</view>
						</view>
						<view class="planGradeRange liBox">
							<view>规划阶段</view>
							<view>
								<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>
							</view>
						</view>
					</view>
				</view>
				<view class="title"><view>资源信息</view></view>
				<view class="listContent">
					<view class="ulBox">
						<view class="liBox">
							<view>已备教育资金总额：</view>
							<view><input class="uni-input" type="digit" maxlength="15" v-model="eduPlanParam.initEducationFund" placeholder="最高保留两位小数" />万元</view>
						</view>
						<view class="liBox">
							<view>每年预备投入教育资金总额：</view>
							<view><input class="uni-input" type="digit" maxlength="15" v-model="eduPlanParam.educationDeposit" placeholder="最高保留两位小数" />万元</view>
						</view>
					</view>
				</view>
				<view class="title"><view>参数</view></view>
				<view class="listContent">
					<view class="ulBox">
						<view class="liBox">
							<view>学费增长率：</view>
							<view><input class="uni-input" type="digit" maxlength="5" v-model="eduPlanParam.tuitionAddRate" placeholder="最高保留两位小数" />%</view>
						</view>
						<view class="liBox">
							<view>资产投资回报率：</view>
							<view><input class="uni-input" type="digit" maxlength="5" v-model="eduPlanParam.investmentRate" placeholder="最高保留两位小数" />%</view>
						</view>
					</view>
				</view>
				<!-- 学费设定 -->
				<view class="schoolingContent">
					<view class="ulBox">
						<view class="liBox">
							<view>学历</view>
							<view>学制（年）</view>
							<view style="flex-direction: column;">
								<view>首年预估费用</view>
								<view>(元)</view>
							</view>
							<view><view style="color: #ff5500;border-bottom: 1px solid #ff5500;" @click="schoolingLists=JSON.parse(JSON.stringify(dataTree))">恢复默认值</view></view>
						</view>
						<view class="liBox" v-for="item in schoolingLists" :key="item.value">
							<view>{{item.text}}</view>
							<view><input class="uni-input" maxlength="1" type="number" placeholder="最高不超过10" v-model="item.commonYears" @blur="updateSchoolingLists(item)"/></view>
							<view><input class="uni-input" maxlength="10" type="digit"  v-model="item.publicTuition" @blur="updateSchoolingLists(item)"/></view>
							<view><view class="settingButton" @click="settingYBY(item)">逐年设定</view></view>
						</view>
					</view>
				</view>
				<!-- 测算结果及建议 -->
				<view class="title"><view>测算结果及建议</view></view>
				<!-- 图表 -->
				<!-- 为 ECharts 准备一个定义了宽高的 DOM -->
				<!-- <view id="main" style="width:96vw;height:400px" v-if="resultInfo"></view> -->
				<l-echart ref="chart" @finished="init" v-if="resultInfo"></l-echart>
				<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>
							<view class="ulBox">
								<view class="liBox">1.提高已备教育资金总额到{{Math.abs(formatFloat(resultInfo.retEducationDeposit/10000))}}万元</view>
								<view class="liBox">2.提高每年预备投入教育资金总额到{{Math.abs(formatFloat(resultInfo.retInitEducationFund/10000))}}万元</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 操作 -->
				<view class="optionContent">
					<button type="default" plain="true" form-type="reset"
					@click="resetData()" >全部清空</button>
					<button type="default" plain="true"
					class="sfp_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>
				<view class="ulBox">
					<view class="liBox">
						<view>{{settingItem.text}}</view>
						<view>预估学费</view>
					</view>
					<view class="liBox" v-for="(item,index) in settingItem.children">
						<view>{{item.text}}</view>
						<view><input class="uni-input" type="digit" placeholder="最高保留两位小数" v-model="item.tuition"/></view>
					</view>
				</view>
				<button type="default" plain="true" @click="confirmOption()">确定</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {ref} from "vue";
	import commonHead from '../header/header.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";
	import { nanoid } from "nanoid";
	import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
	
	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:[],
				option:{}
			}
		},
		methods: {
			goBack(){
				uni.navigateTo({
					url:'/pages/product/finance-calculator'
				})
			},
			init() {
			    this.$refs.chart.init(echarts, chart => {
			        chart.setOption(this.option);
			    });
			},
			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) {
			},
			onchange(e) {
			},
			drawLine(){
				  // 基于准备好的dom，初始化echarts实例
				      // var myChart = echarts.init(document.getElementById('main'));
				      // 指定图表的配置项和数据
				      this.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);
					  this.$refs.chart.init(echarts, chart => {
					      chart.setOption(this.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(){
				this.flatEduGradeLists = JSON.parse(JSON.stringify(this.objFlat(this.schoolingLists)))
				this.flatEduGradeLists.map((val,idx)=>{
					val['educationNo'] = idx + 1;
				});
				// 数据校验
				if(this.eduPlanParam.age && (this.eduPlanParam.age > 40 || this.eduPlanParam.age < 0) ){
					common.errorDialog(2,'子女教育规划一般年龄不会小于0且不超过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.haveAcceptEduFlag && this.eduPlanParam.maxGrade > this.eduPlanParam.startPlan){
					common.errorDialog(2,'规划开始阶段应大于或等于最高学历');
					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:nanoid(),
					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),
					userId:uni.getStorageSync('cffp_userId'),
					systemType:1
				}
				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:{
			commonHead,
			foot,
			LEchart
		}
	}
</script>

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