<template>
	<view class="lr-form-container">
		<l-input v-model="StuInfoFreshData.StuNo" disabled title="学号" placeholder="请填写学号" right/>
		<l-input v-model="StuInfoFreshData.StuName" disabled title="姓名" placeholder="请填写学号" right />
		<l-input :value="displayListItem(StuInfoFreshData, 'ClassNo')" disabled title="班级" placeholder="请填写班级" right />
		<!-- <l-input :value="displayListItem(StuInfoFreshData, 'DeptNo')" disabled title="系别" placeholder="请填写系别" right /> -->
		<l-input :value="displayListItem(StuInfoFreshData, 'MajorNo')" disabled title="专业" right />
		<l-input :value="StuInfoFreshData.FSYear" disabled title="缴费年度" placeholder="请填写系别" right />
		<!-- 姓名 StuName 班级 className 系别 deptName  FinaChargesStandardList [缴费项目 ChargeItemName 收费标准 Standard 本次实缴 SJAmount] -->
		<l-customform-table
		  @input="($event)=>{FinaChargesStandardList = $event}"
		  :value="FinaChargesStandardList"
		  :item="item"
		  :edit="false"
		/>
		<view style="margin-top: 8px;">
			<l-input v-model="PayFeeTotal" disabled title="应缴合计" disabled right />
			<l-input v-model="payfeetotal" disabled title="实缴合计" disabled right />
			<l-input v-model="SJAmount" disabled title="已缴金额" disabled right />
		</view>
		<view style="display:flex;justify-content: center;padding-top: 18px;">
			<image v-if="qrCodeUrl" :src="qrCodeUrl" mode="widthFix"></image>
		</view>
		
		
		<!-- :edit="isEdit(item)" -->
		<!-- @input="setValue(item.__valuePath__, $event)" -->
	   <!-- <view>
			<l-select v-model="queryData.PayFeeStatus" :range="dataSource.PayStatus" title="线上缴费状态" placeholder="请选择" />
	    </view>
	    <view>
			<l-input v-model="queryData.StudentLoan" :disabled="disabled" title="贷款回执码" placeholder="请填写贷款回执码" right />
	    </view>
	    <view>
			<l-select v-model="queryData.OnsitePayFeeStatus" :range="dataSource.OnsitePayStatus" title="现场缴费状态" placeholder="请选择" />
	    </view> -->
		<view v-if="ready&&canPay&&!qrCodeUrl" class="btn" @click="tapBtn('getQRCode')">
			生成二维码
		</view>
		<view v-if="ready&&canPay" class="btn" @click="tapBtn('getPayRes')">
			查询缴费结果
		</view>
		<view class="btn" v-if="ready" @click="lookInvioce">
			查看发票
		</view>
		<view class="btn" @click="NAV_BACK()">
			取消缴费
		</view>
		<view style="height: 18px;">
			
		</view>
	</view>
</template>

<script>
import moment from 'moment';
import get from 'lodash/get';
import set from 'lodash/set';
import pickBy from 'lodash/pickBy';
import mapValues from 'lodash/mapValues';
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue"
export default{
	components:{
		tkiQrcode,
	},
	data() {
		return {
			disabled: false,
			ready:false,
			canPay:false,
			// 数据源
			dataSource: {
				ClassNo:[],
				DeptNo:[],
				MajorNo:[],
				// PayStatus: Object.values(this.GET_GLOBAL('dataDictionary').PayStatus).map(t => ({ value: t.value, text: t.text })),
				// OnsitePayStatus: Object.values(this.GET_GLOBAL('dataDictionary').OnsitePayStatus).map(t => ({ value: t.value, text: t.text }))
			},
			queryData: {
				StudentLoan: '',
				PayFeeStatus: '',
				OnsitePayFeeStatus: '',
				StudentLoanStatus: '0'
			},
			pageInfo:{},
			scheme: {
				ClassNo: {
					type: 'select',
					dataSource: '1',
					dataSourceId: 'bjsj,classname,classno'
				},
				DeptNo:{
					type: 'dataItem',
					dataType: 'dataDictionary'
				},
				MajorNo:{
					type: 'dataItem',
					dataType: 'dataDictionary'
				},
			},
			
			StuInfoFreshData:{},
			PayFeeTotal:'',
			payfeetotal:'',
			SJAmount:'',
			FinaChargesStandardList:[],
			item:{
				title:'缴费信息',
				fieldsData:[
					{type:'label',field:'ChargeItemName',name:'缴费项目'},
					{type:'label',field:'Standard',name:'收费标准'},
					{type:'input',field:'NeedToPay',name:'本次实缴（可修改）',edit:true},
				]
			},
			qrCodeUrl:'',
		}
	},
	
	watch: {
	    FinaChargesStandardList: {
	      handler (val) {
			  this.getpayfeetotal()
	      },
	      // 这里是关键，代表递归监听 demo 的变化
	      deep: true
	    }
	},
	methods:{
		async init() {
			this.pageInfo = this.GET_PARAM(); //获取页面传递参数
			this.LOADING('加载数据中…');
			await Promise.all([
				this.FETCH_DATASOURCE('bjsj').then(data => {
					this.dataSource.ClassNo = data.data.map(t => ({
						text: t.classname,
						value: t.classno
					}));
				}),
				
				this.FETCH_DATASOURCE('CdDeptInfo').then(data => {
					this.dataSource.DeptNo = data.data.map(t => ({
						text: t.deptname,
						value: t.deptno
					}));
				}),
				
				this.FETCH_DATASOURCE('CdMajorInfo').then(data => {
					this.dataSource.MajorNo = data.data.map(t => ({
						text: t.majorname,
						value: t.majorno
					}));
				}),
			
				() => {}
			]);
			this.HTTP_GET('/ReceiveSendFeeManagement/FinaChargeStuYearApi/getpayfeeinfo?keyValue='+this.pageInfo.FSYId, null,'加载数据时出错').then(res => {
				this.HIDE_LOADING();
				if(!res){
					return
				}
				if (res['FinaChargesStandardList'].length == 0) {
				    this.TOAST("未查询到该学生收费标准！请先维护收费明细。");
				    return;
				}
				this.FinaChargesStandardList = res.FinaChargesStandardList.map((item)=>{
					item.copy_SJAmount = item.NeedToPay
					return item
				})
				this.StuInfoFreshData = res.StuInfoFreshData
				this.PayFeeTotal = res.PayFeeTotal
				this.getpayfeetotal()
				if(Number(this.payfeetotal)>0){
					this.canPay = true
				}else{
					this.changeIpnutEdit(false)
					this.TOAST("缴费已完成")
				}
				this.SJAmount = res.SJAmount
				this.ready = true
			})
		},
		// 显示列表中的标题项
		displayListItem(item, field) {
			const fieldItem = this.scheme[field];
			const value = item[field];
		
			switch (fieldItem.type) {
				case 'currentInfo':
				case 'organize':
					return fieldItem.dataType === 'time' ? value : get(this.GET_GLOBAL(fieldItem.dataType), `${value}.name`, '');
		
				case 'radio':
				case 'select':
					const selectItem = this.dataSource[field].find(t => t.value === String(value));
					return get(selectItem, 'text', '');
					
				case 'dataItem':
					const sex = this.dataSource[field].find(t => t.value === String(value));
					return get(sex, 'text', '');
		
				case 'checkbox':
					if (!value || value.split(',').length <= 0) {
						return '';
					}
					const checkboxItems = value.split(',');
					return this.dataSource[field]
						.filter(t => checkboxItems.includes(t.value))
						.map(t => t.text)
						.join('，');
		
				case 'datetime':
					if (!value) {
						return '';
					}
					return moment(value).format(Number(fieldItem.dateformat) === 0 ? 'YYYY年 M月 D日' : 'YYYY-MM-DD HH:mm');
		
				default:
					return value === null || value === undefined ? '' : value;
			}
		},
		tapBtn(action) {
			if(action == "getQRCode"){
				let list = [],isNull=false,tooMuch=false;
				this.FinaChargesStandardList.forEach(item=>{
					let value = 0
					if(/^-?\d+(,\d{3})*(\.\d{1,2})?$/.test(item.NeedToPay)&&Number(item.NeedToPay)>=0){
						value = Number(item.NeedToPay)
					}else{ 
						isNull=true
					}
					if(Number(item.NeedToPay)>Number(item.copy_SJAmount))
					{
						tooMuch=true;
						
					}
					let entity = {
						ChargeItemName: item.ChargeItemName.replace(/^\s*|\s*$/g, ""),
						ChargeItemCode: item.ChargeItemCode,
						YJAmount: item.Standard,
						SJAmount: value
					}
					list.push(entity)
				})
				if (tooMuch) {
				    this.TOAST("[本次实缴]金额不能超过待缴金额！");
				    return;
				}
				if (isNull) {
				    this.TOAST("[本次实缴]金额为空或错误！最多两位小数。");
				    return;
				}
				if(Number(this.payfeetotal) == 0){
					this.TOAST("[实缴合计]不能为0！缴费失败。");
					return;
				}
				var param = {};
				param.FSYId=this.pageInfo.FSYId;
				param.StuNo=this.StuInfoFreshData.StuNo;
				param.FSYear=this.StuInfoFreshData.FSYear;
				param.PayMoney = this.payfeetotal;
				let postData = { strEntity: JSON.stringify(param), detailList: JSON.stringify(list) }
				this.changeIpnutEdit(false)
				this.LOADING('正在生成付款信息请稍等…');
				this.HTTP_POST('/ReceiveSendFeeManagement/FinaChargeStuYearApi/generateqrcode', postData ).then((res)=> {
				    this.HIDE_LOADING();
					if(!res){
						return
					}
					this.qrCodeUrl = this.CONFIG("webHost")+res.imgUrl
				});
			}
			if(action == "getPayRes"){
				this.StuInfoFreshData = {}
				this.PayFeeTotal = ''
				this.payfeetotal = ''
				this.SJAmountReceiveSendFeeManagement = ''
				this.FinaChargesStandardList = []
				this.init()
			}
		},
		lookInvioce(){
			this.NAV_TO("./payInvioce?keyValue="+this.pageInfo.FSYId)
		},
		getpayfeetotal(){
			let value = 0
			this.FinaChargesStandardList.map(item=>{
				let strValue = item.NeedToPay.toString()
				// if(strValue.split(".")[1]&&strValue.split(".")[1].length>2){
				// 	item.SJAmount = strValue.match(/^\d+(?:\.\d{0,2})?/)
				// }
				if(/^-?\d+(,\d{3})*(\.\d{1,2})?$/.test(item.NeedToPay)){
					if(strValue.indexOf(".") == -1&&Number(item.NeedToPay)%1 === 0){
						item.NeedToPay = Number(item.NeedToPay)
					}
					value = this.numSub(value,Number(item.NeedToPay))
					// value += Number(item.SJAmount)
				}
			})
			this.payfeetotal = value
		},
		changeIpnutEdit(edit){
			let item = JSON.parse(JSON.stringify(this.item))
			item.fieldsData = item.fieldsData.map((item1)=>{
				if(["NeedToPay"].includes(item1.field)){
					item1.edit = edit
				}
				return item1
			})
			this.item = item
		},
		numSub(num1, num2) {
			var baseNum, baseNum1, baseNum2; 
			var precision;// 精度 
			try { 
			baseNum1 = num1.toString().split(".")[1].length; 
			} catch (e) { 
			baseNum1 = 0; 
			} 
			try { 
			baseNum2 = num2.toString().split(".")[1].length; 
			} catch (e) { 
			baseNum2 = 0; 
			} 
			baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); 
			precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2; 
			return ((num1 * baseNum + num2 * baseNum) / baseNum).toFixed(precision); 
		}
	},
	created() {
		this.init()
	}
}
</script>

<style lang="less" scoped>
	@import '~@/common/css/customlist.less';
	@import '~@/common/css/sidepage.less';
</style>

