<template>
	<view class="content flex flex_column" v-if="billInfo">
		<view class="b_head">
			<view class="head_list">
				<text>分享时间</text>
				<text>{{ billInfo.createDate }}</text>
			</view>
			<view class="head_list" v-if="billInfo.customer">
				<text>客户名称</text>
				<text>{{ billInfo.customer.customerName }}</text>
			</view>
			<!-- <view class="head_list">
				<text>对账周期</text>
				<text>{{ timeInfo || '--' }}</text>
			</view> -->
			<view class="head_list">
				<text>付款状态</text>
				<text>{{ billInfo.billStatus == 'UNSETTLE' ? '未付款' : billInfo.settleStyleSnDictValue ? '已结清（' + billInfo.settleStyleSnDictValue + '）' : '已结清' }}</text>
			</view>
		</view>
		<view class="b_detail" v-if="billInfo.billStatus == 'UNSETTLE'">
			<view class="detail_list u-flex">
				<view class="detail_box">
					<text>总单数：</text>
					<text>{{ billInfo.detailNum }}</text>
				</view>
				<view class="detail_box">
					<text>待收：</text>
					<text>￥{{dueAmount}}</text>
				</view>
			</view>
			<view class="detail_list u-flex">
				<view class="detail_box">
					<text>折让：</text>
					<text>￥{{ billInfo.discountAmount||billInfo.discountAmount==0? toThousands(billInfo.discountAmount,2):'--'}}</text>
				</view>
				<view class="detail_box">
					<text>折后：</text>
					<text>￥{{ billInfo.settleAmount||billInfo.settleAmount ==0? toThousands(billInfo.settleAmount,2):'--' }}</text>
				</view>
			</view>
		</view>
		<view class="b_detail" v-else>
			<view class="detail_list u-flex">
				<view class="detail_box">
					<text>总单数：</text>
					<text>{{ billInfo.detailNum }}</text>
				</view>
				<view class="detail_box">
					<text>折让：</text>
					<text>￥{{ billInfo.discountAmount||billInfo.discountAmount==0? toThousands(billInfo.discountAmount,2):'--'}}</text>
				</view>
			</view>
			<view class="detail_list u-flex">
				<view class="detail_box">
					<text>折后：</text>
					<text>￥{{foldAmount}}</text>
				</view>
				<view class="detail_box">
					<text>实收：</text>
					<text>￥{{ billInfo.settleRealAmount||billInfo.settleRealAmount ==0? toThousands(billInfo.settleRealAmount,2):'--' }}</text>
				</view>
			</view>
		</view>
		<view class="detail_con"><billList ref="billBox" :showCheck="isShowEdit" :list="billArr"  @allChecked="chooseBillList"></billList></view>
		<view v-if="!isShowEdit">
		<view class="footer u-flex u-row-center" v-if="billInfo.billStatus == 'UNSETTLE'&& billArr&&billArr.length!=0">
			<view class="u-flex u-col-center" >
				<u-button type="primary" shape="circle" :loading="btnLoading" @click="submitOrder" :custom-style="customStyle">再次发送对账单</u-button>
				<u-button type="warning" shape="circle" style="margin-left:30rpx;width:290rpx;" @click="openPaymentModal">确认收款</u-button>
			</view>
		</view>
		<view class="footer" v-else-if="billInfo.billStatus != 'UNSETTLE'&& billArr&&billArr.length!=0">
			<u-button type="primary" shape="circle" :loading="btnLoading" @click="submitOrder" :custom-style="customStyle">再次发送对账单</u-button>
		</view>
		</view>
		<view v-else>
		<view class="footer flex align_center" v-if="billInfo.billStatus == 'UNSETTLE' && billArr&&billArr.length!=0">
			<u-checkbox-group style="flex:1;">
				<u-checkbox v-model="checkedAll" shape="circle" @change="chooseAll">{{checkedAll?'取消全选':'全选'}}</u-checkbox>
			</u-checkbox-group>
			<view class="u-flex u-row-right">
				<u-button type="error" shape="circle" :loading="btnLoading" @click="handleEvents('del')" :custom-style="customDelStyle">删除</u-button>
				<u-button type="warning" shape="circle" style="margin-left: 30rpx;" @click="handleEvents('update')">一键刷新</u-button>	
			</view>
		</view>
		</view>
		<!-- 一键刷新 删除 -->
		<u-modal v-model="modalShow" :show-title="false" :content="modalCon" :show-cancel-button="true" @cancel="closeDelModal" @confirm="handleConfirm"></u-modal>
		<!-- 确认收款弹窗 -->
		<u-popup v-model="showPayment" mode="center" @close="closePopup" :border-radius="20" width="82%">
			<view class="slot-content">
				<view style="padding:50rpx 30rpx 20rpx;">
					<u-form :model="form" ref="uForm" :error-type="['message']" :label-width="150" :rules="rules" :label-style="{color:'#999'}">
						<u-form-item :border-bottom ="false" label="总单数:" prop="num" v-if="billArr">{{billArr.length}}</u-form-item>
						<u-form-item :border-bottom ="false" label="结算方式:" prop="settleTypeName">
							<u-input type="select" placeholder="请选择结算方式" :height="60"  v-model="form.settleTypeName" @click="settleShow = true"/>
						</u-form-item>
						<u-form-item v-if="enableFundAccount" style="padding-top:0;" :border-bottom ="false" label="结算账户:" prop="settleAccountName">
							<u-input type="select" placeholder="请选择结算账户" :height="60"  v-model="form.settleAccountName" @click="openSettleAccount"/>
						</u-form-item>
						<u-form-item :border-bottom ="false" label="待收金额:" prop="num">￥{{dueAmount}}</u-form-item>
						<u-form-item :border-bottom ="false" label="折让金额:" prop="discountAmount"><u-input type="number" :custom-style="{color:'#ffa500'}" placeholder="请输入折让金额(最多2位小数)" :border="true" :height="60"  v-model="form.discountAmount"/></u-form-item>
						<view class="tip" v-if="form.discountAmount*1 > dueAmount*1">折让金额不能大于待收金额，请重新输入</view>
					</u-form>
				</view>
				<view class="costText">实收金额</view>
				<view class="costText1">￥{{settlement<0?0:settlement}}</view>
				<view class="paymentFooter flex algin-center">
					<view @click="closePopup">取消</view>
					<view @click="handlePay">确定</view>
				</view>
			</view>
		</u-popup>
		<!-- 提示弹窗 -->
		<u-modal v-model="showModal" confirm-text="知道了" :content="modalContent" :show-title="false"></u-modal>
		<u-picker mode="selector" v-model="settleShow" @confirm="confirmSettle" :default-selector="[0]"  :range="settleList" range-key="dispName"></u-picker>
		<u-picker mode="selector" v-model="settleAccount" @confirm="confirmSettleAccount" :default-selector="[0]"  :range="accountList" range-key="name"></u-picker>
		<!-- 分享询问弹窗 -->
		<u-modal v-model="shareShow" :show-cancel-button="true" :content="shareContent" @confirm="handleShare" @cancel="shareShow = false;btnLoading = false;"></u-modal>
	</view>
</template>

<script>
import billList from './billListComponent.vue';
import { findBySn, insert,settleVerify,settle,flushBill,deleteDetails } from '@/api/verify.js';
import getDate from '@/libs/getDate.js';
import { toThousands } from '@/libs/tools.js'
import { getLookUpDatas } from '@/api/data';
import { queryFunctionState,settleAccountList } from '@/api/user';
export default {
	components: { billList },
	data() {
		return {
			customStyle: {
				backgroundColor: this.$config('primaryColor'),
				color: '#fff'
			},
			customDelStyle: {
				width:'200rpx',
				color: '#fff'
			},
			verifySn: '',
			billInfo: null,
			billArr: [],
			timeInfo: '',
			btnLoading: false,
			shareShow: false,
			isShowEdit:false,//编辑
			settleShow:false,//结算方式
			shareContent: `是否同意发送对账单给微信好友？`,
			toThousands,
			showPayment:false,
			form:{
				receiptAmount:0,
				discountAmount:undefined,
				settleType:'',
				settleTypeName:'',
				settleAccountSn:'',
				settleAccountName:''
			},
			settleList:[],
			rules: {
				settleTypeName: [
					{ 
						required: true, 
						message: '请选择结算方式', 
						trigger: ['change','blur'],
					}
				],
				settleAccountName:[
					{ 
						required: true, 
						message: '请选择结算账户', 
						trigger: ['change','blur'],
					}
				]
			},
			showModal:false,
			modalContent:'',
			enableFundAccount:false,
			accountList:[],//结算账户列表
			settleAccount:false,
			orderList:[],
			modalShow:false,
			modalCon:'刷新后，将删除对账单中已收款的订单，更新待收款单据。确定刷新吗？',
			eventsType:'' //打开弹窗类型 del删除  update更新
		};
	},
	onReady() {
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: this.$config('primaryColor')
		});
	},
	onLoad(options) {
		if (options && options.billId) {
			this.verifySn = options.billId;
			this.loadData({ verifySn: options.billId });
		}
	},
	//编辑事件
	onNavigationBarButtonTap(e){
		this.isShowEdit = !this.isShowEdit
		var pages = getCurrentPages();
		var page = pages[pages.length - 1];
		var currentWebview = page.$getAppWebview();
		var tn = currentWebview.getStyle().titleNView;
		
		let _this = this
		if(_this.isShowEdit){
			tn.buttons[0].text = '\ue601 取消';
		}else{
			tn.buttons[0].text = '\ue601 编辑';
		}
		_this.$nextTick(()=>{
			currentWebview.setStyle({
			    titleNView: tn
			});
		})
		
	},
	computed: {
		//经销商信息
		userData() {
			return this.$store.state.vuex_userData;
		},
		settlement() {
			let totalPrice=this.billInfo.totalAmount?this.billInfo.totalAmount:0;
			let settleRealAmount = this.billInfo.settleRealAmount?this.billInfo.settleRealAmount:0
			let discountPrice=this.form.discountAmount?this.form.discountAmount:0
			let priceNum=totalPrice - discountPrice - settleRealAmount;
			let endPay=Number(priceNum)>0 ? priceNum : 0
			const ret = endPay.toFixed(2)
			this.form.receiptAmount = ret
			return ret
		},
		 // 待收金额
		dueAmount(){
			let totalAmount = this.billInfo.totalAmount?this.billInfo.totalAmount:0
			let settleRealAmount = this.billInfo.settleRealAmount?this.billInfo.settleRealAmount:0
			let duePrice = totalAmount - settleRealAmount
			duePrice=Number(duePrice)>0 ? duePrice : 0
			const resPrice = duePrice.toFixed(2)
			return resPrice
		},
		//经销商信息
		userData() {
			return this.$store.state.vuex_userData;
		},
		// 折后金额
		foldAmount(){
			let totalAmount = this.billInfo.totalAmount?this.billInfo.totalAmount:0
			let discountPrice=this.billInfo.discountAmount?this.billInfo.discountAmount:0
			let foldPrice = totalAmount - discountPrice 
			foldPrice=Number(foldPrice)>0 ? foldPrice : 0
			const newFoldPrice = foldPrice.toFixed(2)
			return newFoldPrice
		}
	},
	methods: {
		loadData(ajaxData) {
			let that = this;
			findBySn(ajaxData).then(res => {
				if (res.status == 200) {
					that.billInfo = res.data;
					that.billArr = res.data.detailList;
					let timeobj = getDate.editDay(res.data.bizBeginDate, res.data.bizEndDate);
					that.timeInfo = timeobj.starttime + '~' + timeobj.endtime;
					that.$nextTick(() => {
						that.$refs.billBox.setData(res.data.detailList);
					});
					this.isShowEditBtn()
				}
			});
		},
		//关闭编辑按钮
		isShowEditBtn(){
			// #ifdef APP-PLUS
			let webview = this.$mp.page.$getAppWebview();
			if(this.billInfo.billStatus != 'UNSETTLE' || !this.billArr || this.showPayment || this.modalShow){
				webview.setTitleNViewButtonStyle(0, {
						  width:'0px'
						})
			}else{
				webview.setTitleNViewButtonStyle(0, {
						  width:'60px'
						})
			}
			// #endif
		},
		// 关闭弹窗
		closePopup(){
			this.form={
				receiptAmount:0,
				discountAmount:this.billInfo.discountAmount,
				settleType:'',
				settleTypeName:'',
				settleAccountSn:'',
				settleAccountName:''
			}
			this.showPayment = false
			this.isShowEditBtn()
		},
		// 打开确认收款弹窗
		openPaymentModal(){
			let _this=this
			// 校验弹窗是否需要打开
			settleVerify({ verifySn: _this.verifySn}).then(res => {
				if (res.status == 200) {
					if(!res.data.falg){
						_this.modalContent = res.data.message
						_this.$nextTick(()=>{
							_this.showModal = true
						})
					}else{
						// 判断是否显示结算类型
						queryFunctionState().then(res => {
						  if (res.status == 200) {
						    _this.enableFundAccount = res.data.functionEnableFlag == 1
						  }
						})
						_this.getPayType();
						_this.showPayment = true
						_this.form.discountAmount=_this.billInfo.discountAmount?toThousands(_this.billInfo.discountAmount):'0.00'
						_this.$nextTick(()=>{
							_this.isShowEditBtn();
							_this.$refs.uForm.setRules(_this.rules);
						})
					}
				}
			});
		},
		//获取结算类型列表
		getPayType(){
			getLookUpDatas({
				lookupCode: 'SETTLE_STYLE',
				pageNo: 1,
				pageSize: 1000
			}).then(result => {
				if (result && result.status == 200) {
					this.settleList = result.data.list;
				}
			});
		},
		//获取结算账户
		getPayAccount(typeCode){
			settleAccountList({settleStyleSn: typeCode,pageNo:1,pageSize:500,state:'ENABLE'}).then(result => {
				if (result && result.status == 200) {
					 result.data.list.forEach(item=>{
						 item.name = item.accountName+'-'+item.accountNo
					 })
					this.accountList = result.data.list;
				}
			});
		},
		//结算类型 确定
		confirmSettle(e){
			let pos=e[0]
			this.form.settleType = this.settleList[pos].code
			this.form.settleTypeName = this.settleList[pos].dispName
			if(this.enableFundAccount){
				this.form.settleAccountSn=''
				this.form.settleAccountName=''
				this.getPayAccount(this.settleList[pos].code)
			}
		},
		submitOrder() {
			//发送对账单
			this.shareShow = true;
		},
		//结算账户弹窗
		openSettleAccount(){
			if(!this.form.settleTypeName){
				uni.showToast({
					title:'请先选择结算类型',
					icon:'none'
				})
				return
			}
			if(this.accountList && this.accountList.length==0){
				uni.showToast({
					title:'结算账户暂时没有数据，请重新选择结算类型',
					icon:'none'
				})
				return
			}
			this.settleAccount = true
		},
		//结算账户 确定
		confirmSettleAccount(e){
			let pos=e[0]
			this.form.settleAccountSn=this.accountList[pos].settleAccountSn
			this.form.settleAccountName=this.accountList[pos].name
		},
		//确认收款
		handlePay(){
			let _this=this
			_this.$refs.uForm.validate(valid => {
				if (valid) {
					let totalPrice=this.billInfo.totalAmount?this.billInfo.totalAmount:0;
					let discountPrice=this.form.discountAmount?this.form.discountAmount:0
					if (discountPrice > totalPrice) {
						uni.showToast({
							title: '折让金额不能大于待收金额，请重新输入',
							icon: 'none'
						});
						return;
					}
					let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
					if(discountPrice && discountPrice!=0){
						if (!reg.test(discountPrice)) {
							uni.showToast({
								title: '折让金额格式不正确，请重新输入',
								icon: 'none'
							});
							return;
						}
					}
					let ajaxData=JSON.stringify(_this.form)
					let newAjaxData = JSON.parse(ajaxData)
					newAjaxData.verifySn = _this.verifySn
					newAjaxData.discountAmount = _this.form.discountAmount?_this.form.discountAmount:0
					delete newAjaxData.settleAccountName
					settle(newAjaxData).then(result => {
						if (result && result.status == 200) {
							uni.showToast({
								title:result.message
							});
							_this.closePopup()
							_this.loadData({ verifySn: _this.verifySn });
						}
					});
				} else {
					console.log('验证失败');
				}
			});
		},
		// 分享图文
		handleShare() {
			let jumpUrl = getApp().globalData.baseUrl.replace('qpls-md/','')
			let url = jumpUrl+'dzd/index.html?' + this.userData.orgSn + '&' + this.verifySn;
			if (uni.getSystemInfoSync().platform == 'ios') {
				uni.share({
					provider: 'weixin',
					scene: 'WXSceneSession',
					type: 0,
					href: url,
					title: this.billInfo.customer.customerName + '的对账单',
					summary: '共' + this.billInfo.settleAmount + '元，请您查阅',
					imageUrl: '../../static/logo.png',
					success: function(res) {
						console.log('success:' + JSON.stringify(res));
					},
					fail: function(err) {
						console.log('fail:' + JSON.stringify(err));
					}
				});
			} else {
				uni.shareWithSystem({
					summary: this.billInfo.customer.customerName + '您好，您有一个对账单共' + this.billInfo.settleAmount + '元，请您查阅',
					href: url,
					success() {
						console.log('调取微信列表成功，分享不一定成功');
					},
					fail() {
						console.log('分享失败');
					}
				});
			}
		},
		//一键刷新
		handleUpdate(){
			this.checkedAll = false
			this.$refs.billBox.allSelect(false);
			flushBill({verifySn:this.verifySn}).then(res => {
				if (res.status == 200) {
					this.loadData({ verifySn: this.verifySn })
				}
			});
		},
		//删除
		deleteOrder(){
			let that=this
			deleteDetails({verifySn:that.verifySn,detailSnList:that.orderList}).then(res => {
				if (res.status == 200) {
					uni.showToast({
						title:res.message,
						duration: 2000
					})
					that.loadData({ verifySn: that.verifySn });
				}
			});
		},
		closeDelModal(){
			this.modalShow = false
			let that=this
			that.$nextTick(()=>{
				that.isShowEditBtn()
			})
		},
		handleEvents(type){
			this.eventsType=type
			if(type == 'del'){
				let allList=this.$refs.billBox.getAllData();
				let newChooseList = []
				let num = 0
				allList.forEach(item=>{
					if(item.checked){
						newChooseList.push(item.detailSn)
						num+=item.unsettleAmount
					}
				})
				if(newChooseList.length == 0){
					uni.showToast({
						title:'请先选择要删除的销售单',
						icon:'none'
					})
					return
				}
				this.orderList=newChooseList
				let newNum=toThousands(num,2)
				
				this.modalCon = '选中'+newChooseList.length+'项，待收金额￥'+newNum+'，确认删除吗？'
			}else{
				this.modalCon='刷新后，将删除对账单中已收款的订单，更新待收款单据。确定刷新吗？'
			}
			let that=this
			that.$nextTick(()=>{
				that.modalShow = true
				that.isShowEditBtn()
			})
		},
		//确定提交删除、刷新
		handleConfirm(){
			if(this.eventsType=='del'){
				this.deleteOrder();
			}else{
				this.handleUpdate();
			}
		},
		chooseBillList(flag){
			this.checkedAll = flag
		},
		chooseAll(){
			this.$refs.billBox.allSelect(!this.checkedAll);
		}
	}
};
</script>

<style lang="scss" scoped>
.content {
	height: 100vh;
	width: 100%;
	box-sizing: border-box;
	.b_head {
		background-color: #fff;
		.head_list {
			padding: 14rpx 20rpx;
			border-bottom: 1rpx solid #f8f8f8;
			
			text {
				&:first-child {
					color: $uni-text-color-grey;
					display: inline-block;
					width: 160rpx;
				}
			}
		}
	}
	.b_detail {
		margin: 6rpx 0;
		background-color: #fff;
		padding: 20rpx;
		box-sizing: border-box;
		.detail_list {
			margin-bottom: 10rpx;
			&:last-child {
				margin-bottom: 0rpx;
			}
			.detail_box::after {
				content: '；';
				color: $uni-text-color-grey;
			}
			.detail_box {
				text {
					&:first-child {
						color: $uni-text-color-grey;
					}
					&:last-child {
						color: $uni-color-warning;
						font-weight: 600;
					}
				}
			}
		}
	}
	.detail_con {
		flex-grow: 1;
		overflow: auto;
		background-color: #fff;
	}
	.footer {
		width: 100%;
		box-sizing: border-box;
		padding: 10rpx 20rpx;
		background: #fff;
	}
}
// 确认收款弹窗
.slot-content{
	.u-form-item{
			line-height:0 !important;
		}
		.paymentFooter{
			border-top:1rpx solid #eee;
			view{
				width: 50%;
				text-align:center;
				padding:26rpx 0;
			}
		}
		.paymentFooter view:last-child{
			color:#007aff;
			border-left:1rpx solid #eee;
		}
		.costText {
			text-align: center;
			color: $uni-text-color-grey;
			font-size: 22rpx;
		}
		.costText1 {
			text-align: center;
			font-weight: bold;
			color: $uni-color-error;
			font-size: 36rpx;
			line-height: 60rpx;
			padding-bottom: 30rpx;
		}
		.tip {
			color: #fa3534;
			font-size: 20rpx;
			margin-left: 160rpx;
		}
}

</style>
