<template>
	<view class="content flex flex_column">
		<view class="header">
			<view class="headerList u-flex">
				<view class="list_l">
					<u-icon name="account" color="#00aaff" size="32"></u-icon>
					<text>客户名称</text>
				</view>
				<view class="list_r u-flex">
					<u-input v-model="customerObj.customerName" @click="goChooseCustomer" type="select" placeholder="请选择客户名称" />
				</view>
			</view>
			<view class="headerList u-flex">
				<view class="list_l">
					<u-icon name="clock" color="#00aaff" size="32"></u-icon>
					<text>对账周期</text>
					<u-icon name="question-circle-fill" @click="tipShow = true" :color="wordColor" size="32"></u-icon>
				</view>
				<view class="list_r u-flex">
					<u-input v-model="cycleName" @click="chooseCycleData" type="select" placeholder="请选择对账日期" />
				</view>
			</view>
			<view class="statistical u-flex">
				<view class="statisticalList">
					<text>总单数：</text>
					<text>{{ bill.length }}</text>
				</view>
				<view class="statisticalList">
					<text>待收金额合计：</text>
					<text>￥{{ totalPayPrice }}</text>
				</view>
			</view>
		</view>
		<view class="chooseCon"><billList ref="bill" :showCheck="true" :list="bill" @allChecked="allCheckedCallback"></billList></view>
		<view class="footerCon u-flex">
			<view class="f-left">
				<u-checkbox @change="allCheckeChange" v-model="allChecked" shape="circle">{{ allChecked ? '取消全选' : '全选' }}</u-checkbox>
			</view>
			<view class="f-mid" @click="isDetailShow = !isDetailShow">
				<view>
					待收：
					<text class="fontColor">￥{{ chooseTotalPayPrice }}</text>
				</view>
				<view v-if="chooseList.length > 0 && backDiscountVal">
					折后：
					<text class="fontColor">￥{{ backDiscountPrice }}</text>
				</view>
				<view class="u-flex" v-if="chooseList.length > 0">
					<view>
						折让：
						<text>￥{{ Number(backDiscountVal) ? Number(backDiscountVal).toFixed(2) : 0 }}</text>
					</view>
					<view class="costBtn" @click="openCostShow">打折</view>
				</view>
			</view>
			<view class="f-btns">
				<u-button size="medium" @click="submitOrder" :custom-style="customBtnStyle" :loading="submitLoading" shape="circle" type="primary" hover-class="none">
					发送对账单
				</u-button>
			</view>
		</view>
		<!-- 对账周期弹窗 -->
		<u-popup v-model="showSearch" mode="right" width="70%">
			<view class="tabBox">
				<view class="tabs">
					<view class="flex">
						<view :class="item.val == curTab ? 'active' : 'all'" v-for="item in placeTab" :key="item.val" @click="tabChange(item)">{{ item.name }}</view>
					</view>
				</view>
				<view class="flex align_center form-item-inp" style="padding: 0 30rpx;" v-if="curTab == 6">
					<u-input clearable v-model="dateArray" @clear="dateArray==''" clearWarehouse placeholder="请选择时间段" input-align="center" @click="showDate = true" />
				</view>
				<view class="form-footer-btn">
					<u-button class="handle-btn" shape="circle" size="medium" hover-class="none" @click="handleClean">重置</u-button>
					<u-button class="handle-btn" shape="circle" size="medium" hover-class="none" :custom-style="customBtnStyle" @click="handleSearch">查询</u-button>
				</view>
			</view>
		</u-popup>
		<!-- 选择日期范围 -->
		<u-calendar v-model="showDate" ref="rangeDate" @change="dateChange" mode="range"></u-calendar>
		<!-- 打折弹窗 -->
		<u-popup v-model="costShow" mode="center" @close="closeCost" :border-radius="20" closeable width="82%">
			<view class="costPopup">
				<view class="costPopupTit">{{customerObj&&customerObj.customerName||'--'}}</view>
				<view class="costPopupCon">
					<view class="costList">
						<text class="label">待收金额：</text>
						<text>￥{{ chooseTotalPayPrice }}</text>
					</view>
					<view class="costList u-flex">
						<view class="label">折让金额：</view>
						<u-input type="number" :custom-style="{color:'#ffa500'}" placeholder="请输入折让金额(最多2位小数)" v-model="discountVal" :border="true" :height="50" />
					</view>
					<view class="tip" v-if="discountVal*1 > chooseTotalPayPrice*1">折让金额不能大于待收金额，请重新输入</view>
					<view class="costText">折让后金额</view>
					<view class="costText">￥{{ settlement<0?0:settlement }}</view>
				</view>
				<u-button type="primary" :custom-style="customStyle"  shape="circle" @click="handleDisCount">确定</u-button>
			</view>
		</u-popup>
		<!-- 对账周期弹窗 -->
		<u-modal v-model="tipShow" :show-title="false" confirm-text="知道了">
			<view class="slot-content"><rich-text :nodes="tipContent"></rich-text></view>
		</u-modal>
		<!-- 分享询问弹窗 -->
		<u-modal v-model="shareShow" :show-cancel-button="true" :content="shareContent" @confirm="handleShare" @cancel="shareShow = false;submitLoading = false;"></u-modal>
	</view>
</template>

<script>
import billList from './billListComponent.vue';
import { queryUnsettleSaleList, insert } from '@/api/verify.js';
import getDate from '@/libs/getDate.js';
export default {
	components: { billList },
	data() {
		return {
			customBtnStyle: {
				//  自定义按钮样式
				borderColor: this.$config('primaryColor'),
				backgroundColor: this.$config('primaryColor'),
				color: '#fff',
				width: '180rpx'
			},
			wordColor: this.$config('infoColor'),
			customStyle: {
				borderColor: this.$config('primaryColor'),
				backgroundColor: this.$config('primaryColor'),
				color: '#fff'
			},
			allChecked: false,
			tipShow: false,
			discountVal: null, //折让金额
			tipContent: `账单周期指<br>销售单的创建时间`,
			shareContent: `是否同意发送对账单给微信好友？`,
			placeTab: [
				{
					name: '今日',
					val: '0'
				},
				{
					name: '昨日',
					val: '1'
				},
				{
					name: '本周',
					val: '2'
				},

				{
					name: '上周',
					val: '3'
				},
				{
					name: '本月',
					val: '4'
				},
				{
					name: '上月',
					val: '5'
				},
				{
					name: '自定义',
					val: '6'
				},
				{
					name: '全部',
					val: '7'
				}
			],
			curTab: '0',

			showSearch: false,
			showDate: false,
			costShow: false,

			customerObj: {
				customerName: null
			},
			cycleName: '',

			params: {
				targetSn: undefined,
				bizBeginDate: undefined,
				bizEndDate: undefined
			},
			bill: [],
			dateArray: '',
			chooseList: [],
			isDetailShow: false,
			submitLoading: false,
			shareShow: false,
			verifySn:'',
			backDiscountPrice:null,
			backDiscountVal: 0,
			cycleNameShow:'',
			verifyIdNum:''
		};
	},
	onReady() {
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: this.$config('primaryColor')
		});
	},
	onLoad(options) {
		//获取对账周期默认值
		if (uni.getStorageSync('curTab')) {
			this.curTab = uni.getStorageSync('curTab');
		} else {
			let systemList = this.$store.state.vuex_systemSetList;
			if(systemList){
				let cycleObj = systemList.find(item => {
					return item.remarks == 'sales_bill_period';
				});
				this.curTab = this.placeTab.findIndex(con => con.name == cycleObj.valueShow);
			}
		}
		
		// 获取选择客户
		if (options && options.data) {
			this.customerObj = JSON.parse(decodeURIComponent(options.data));
			this.params.targetSn = this.customerObj.customerSn;
		}
		uni.$on('customerInfo', res => {
			this.customerObj = res;
			this.params.targetSn = res.customerSn;
			this.changeTime();
		});
		if(this.curTab !=6 && this.curTab !=7){
			this.cycleName = this.changeShowTime();
		}
	},
	onReady() {
		setTimeout(()=>{
			this.changeTime();
		},500)
	},
	onBackPress() {
		if (this.showSearch) {
			this.showSearch = false;
		} else {
			uni.removeStorageSync('curTab');
			uni.removeStorageSync('chooseList');
		}
	},
	onUnload() {
		uni.removeStorageSync('curTab');
		uni.removeStorageSync('chooseList');
	},
	computed: {
		//经销商信息
		userData() {
			return this.$store.state.vuex_userData;
		},
		totalPayPrice() {
			let totalPrice = 0;
			for (let i = 0; i < this.bill.length; i++) {
				this.bill[i].unsettleAmount = this.bill[i].unsettleAmount ? this.bill[i].unsettleAmount : 0;
				totalPrice += this.bill[i].unsettleAmount;
			}
			return totalPrice.toFixed(2);
		},
		chooseTotalPayPrice() {
			let price = 0;
			this.chooseList.forEach(item => {
				item.unsettleAmount = item.unsettleAmount ? item.unsettleAmount : 0;
				price += item.unsettleAmount;
			});
			return price.toFixed(2);
		},
		settlement() {
			let totalPrice=this.chooseTotalPayPrice?this.chooseTotalPayPrice:0;
			let discountPrice=this.discountVal?this.discountVal:0
			let priceNum=totalPrice - discountPrice;
			const ret = priceNum.toFixed(2)
			return Number(this.chooseTotalPayPrice)>=Number(this.backDiscountVal) ? ret : 0
		}
	},
	methods: {
		closeCost(){
			this.costShow = false
		},
		chooseCycleData() {
			uni.setStorageSync('chooseList', this.chooseList);
			this.showSearch = true;
		},
		handleClean() {
			this.showSearch = false;
			// 清空选择周期时组件值
			this.$refs.rangeDate.init();
			let systemList = this.$store.state.vuex_systemSetList;
			let cycleObj = systemList.find(item => {
				return item.remarks == 'sales_bill_period';
			});
			this.curTab = this.placeTab.findIndex(con => con.name == cycleObj.valueShow);
			this.cycleName = this.changeShowTime();
			this.changeTime();
		},
		//选择客户
		goChooseCustomer() {
			uni.setStorageSync('curTab', this.curTab);
			this.jumpPage('/pages/sales/chooseCustomerBill');
			this.allChecked = false
		},
		changeTime() {
			if (this.curTab != 6 && this.curTab != 7) {
				this.params.bizBeginDate = this.getQueryDate().beginDate;
				this.params.bizEndDate = this.getQueryDate().endDate;
				this.cycleName = this.changeShowTime();
			} else if (this.curTab == 7) {
				this.cycleName = this.placeTab[this.curTab].name;
				this.params.bizBeginDate = undefined;
				this.params.bizEndDate = undefined;
			}
			this.dateArray = '';
			this.getList();
		},
		getList() {
			const _this = this;
			queryUnsettleSaleList(this.params).then(res => {
				if (res.status == 200) {
					let chooseArr = uni.getStorageSync('chooseList');
					if (chooseArr && chooseArr.length > 0) {
					res.data.forEach(item => {
							const row = chooseArr.findIndex(k => k.bizSn == item.bizSn);
							item.checked = row > -1;
						});
					}
					this.bill = res.data;
					this.$refs.bill.setData(res.data);
					this.getChooseList()
				}
			});
		},
		getChooseList(){
			this.chooseList=this.bill.filter(item=>item.checked);
		},
		// 时间  change
		dateChange(date) {
			this.dateArray = date.startDate + ' ~ ' + date.endDate;
			this.params.bizBeginDate = date.startDate + ' 00:00:00';
			this.params.bizEndDate = date.endDate + ' 23:59:59';
			this.cycleNameShow = date.startDate + '至' + date.endDate;
		},
		// 更改日期格式显示
		changeShowTime() {
			const fun = [
				getDate.getTodayInfo,
				getDate.getYesterdayInfo,
				getDate.getCurrWeekDaysInfo,
				getDate.getLastWeekDaysInfo,
				getDate.getCurrLastMonthDaysInfo,
				getDate.getLastMonthDaysInfo
			];
			return fun[this.curTab]();
		},
		tabChange(data) {
			this.curTab = data.val;
		},
		getQueryDate() {
			const fun = [getDate.getToday, getDate.getYesterday, getDate.getCurrWeekDays, getDate.getLastWeekDays, getDate.getCurrLastMonthDays, getDate.getLastMonthDays];
			return {
				beginDate: fun[this.curTab]().starttime,
				endDate: fun[this.curTab]().endtime
			};
		},
		handleSearch() {
			this.showSearch = false;
			if(this.curTab == 6){
				this.cycleName = this.cycleNameShow;
			}else{
				this.cycleNameShow = ''
			}
			this.changeTime();
		},
		jumpPage(url) {
			uni.navigateTo({
				url
			});
		},
		openCostShow(){
			this.costShow = true
			this.discountVal = this.backDiscountVal||''
		},
		handleDisCount() {
			if (this.discountVal*1 > this.chooseTotalPayPrice*1) {
				uni.showToast({
					title: '折让金额不能大于待收金额，请重新输入',
					icon: 'none'
				});
				return;
			}
			let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
			console.log(this.discountVal,!reg.test(this.discountVal),this.discountVal && !reg.test(this.discountVal))
			if(this.discountVal!=0){
				if (!reg.test(this.discountVal)) {
					uni.showToast({
						title: '折让金额格式不正确，请重新输入',
						icon: 'none'
					});
					return;
				}
			}
			this.costShow = false;
			this.backDiscountPrice = this.settlement
			this.backDiscountVal = Number(this.discountVal||0).toFixed(2)
		},
		submitOrder() {
			//发送对账单
			if (this.chooseList.length == 0) {
				uni.showToast({
					title: '请选择要发送的对账单',
					icon: 'none'
				});
				return;
			}
			this.shareShow = true;
			this.submitLoading = true;
		},
		allCheckeChange(e) {
			this.$refs.bill.allSelect(e.value);
			const list = this.$refs.bill.getAllData();
			list.map(item => {
				this.allCheckedCallback(true,item)
			})
			
		},
		// 选中事件
		allCheckedCallback(isAllChecked, row) {
			const has = this.chooseList.findIndex(k => k.bizSn == row.bizSn);
			// 在已选列表中
			if (has >= 0) {
				// 取消选中
				if (!row.checked) {
					this.chooseList.splice(has, 1);
				}
			} else {
				if (row.checked) {
					this.chooseList.push(row);
					// this.backDiscountVal = 0
				}
			}
			 this.backDiscountPrice = this.settlement
			 
			if(Number(this.chooseTotalPayPrice)<Number(this.backDiscountVal)){
				this.backDiscountVal = 0
				this.discountVal = 0
			}
			// 是否全选
			this.allChecked = isAllChecked;
		},
		// 分享图文
		handleShare() {
			this.submitLoading = false;
			let verifyId = Date.now()+this.nanoid();
			this.verifyIdNum = verifyId
			let settlement=this.chooseTotalPayPrice - this.backDiscountVal
			let jumpUrl = getApp().globalData.baseUrl.replace('qpls-md/','')
			let url = jumpUrl +'dzd/index.html?' + this.userData.orgSn + '&'+verifyId;
			if (uni.getSystemInfoSync().platform == 'ios') {
				this.setBillOrder();
				uni.share({
					provider: 'weixin',
					scene: 'WXSceneSession',
					type: 0,
					href: url,
					title: this.customerObj.customerName+'的对账单',
					summary: '共' + settlement + '元，请您查阅',
					imageUrl: '../../static/logo.png',
					success: (res)=> {
						console.log('success:' + JSON.stringify(res));
					},
					fail: (err)=> {
						console.log('fail:' + JSON.stringify(err));
					}
				});
			} else {
				uni.shareWithSystem({
					summary: this.customerObj.customerName + '您好，您有一个对账单共' + settlement + '元，请您查阅',
					href: url,
					success:()=> {
						this.setBillOrder();
						console.log('调取微信列表成功，分享不一定成功')
					},
					fail:()=> {
						console.log('分享失败')
					}
				});
			}
		},
		// 生成历史对账单
		setBillOrder(){
			let obj = {
				detailNum: this.chooseList.length,
				totalAmount: this.chooseTotalPayPrice,
				discountAmount: this.backDiscountVal || 0,
				settleAmount: this.chooseTotalPayPrice - this.backDiscountVal ,
				detailList: this.chooseList,
				verifySn:this.verifyIdNum
			};
			let ajaxData = Object.assign(this.params, obj);
			insert(ajaxData).then(res => {
				this.shareShow = false;
				if (res.status == 200) {
					console.log('生成历史对账单成功')
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			});
		},
		// 生成随机对账单id
		nanoid (size = 5) {
			let urlAlphabet ='0123456789'
		  let id = ''
		  let i = size
		  while (i--) {
		    id += urlAlphabet[(Math.random() * 10) | 0]
		  }
		  return id
		}
	}
};
</script>

<style lang="scss" scoped>
.content {
	width: 100%;
	height: 100vh;
	.header {
		width: 100%;
		.headerList {
			width: 100%;
			box-sizing: border-box;
			padding: 16rpx 20rpx;
			background: #fff;
			&:nth-child(2) {
				border-top: 1rpx solid #e4e7ed;
			}
			.list_l {
				width: 208rpx;
				text {
					font-size: 28rpx;
					color: #666666;
					margin-left: 10rpx;
					margin-right: 10rpx;
				}
			}
			.list_r {
				width: calc(100% - 208rpx);
			}
		}

		.statistical {
			padding: 20rpx;
			background: #fff;
			margin: 10rpx 0;
			.statisticalList {
				&:first-child {
					width: 210rpx;
				}
			}
			text {
				&:last-child {
					color: $uni-color-warning;
					font-weight: 600;
				}
			}
		}
	}

	.chooseCon {
		flex-grow: 1;
		flex-basis: 0;
		overflow: auto;
		background-color: #fff;
	}
	.footerCon {
		background-color: #f8f8f8;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
		.f-mid {
			flex: 1;
			color: #666;
			font-size: 0.8rem;
			font-weight: 600;
			.fontColor {
				color: $uni-color-warning;
				vertical-align: middle;
			}
			.costBtn {
				width: 70rpx;
				height: 40rpx;
				line-height: 40rpx;
				text-align: center;
				color: #fff;
				font-size: 20rpx;
				border-radius: 30rpx;
				background: #999;
				margin-left: 20rpx;
			}
		}
	}
	// 历史对账单弹窗
	.tabBox {
		height: 100vh;
		.tabs {
			flex-grow: 1;
			overflow: auto;
			padding: 20rpx;
			> view {
				flex-wrap: wrap;
				justify-content: space-between;
				> view {
					width: 45%;
					border: 1rpx solid #eee;
					padding: 15rpx;
					border-radius: 50rpx;
					text-align: center;
					margin-bottom: 15rpx;
				}
				.active {
					border: 0;
					background-color: #0485f6;
					color: #fff;
				}
			}
		}
		.form-item-inp {
			border-bottom: 1rpx solid #eee;
		}
		.form-footer-btn {
			margin: 30upx;
			display: flex;
			justify-content: space-between;
		}
		.form-footer-btn {
			display: flex;
			.handle-btn {
				font-size: 28upx;
				margin: 0 10upx;
				flex: 1;
			}
		}
	}
	//打折弹窗
	.costPopup {
		padding: 26rpx 20rpx 40rpx;
		box-sizing: border-box;
		.costPopupTit {
			text-align: center;
			font-weight: bold;
		}
		.costPopupCon {
			margin-top: 40rpx;
			.costList {
				margin-bottom: 20rpx;
				.label {
					color: $uni-text-color-grey;
				}
			}
			.tip {
				color: $uni-color-error;
				font-size: 20rpx;
				margin-left: 140rpx;
			}
			.costText {
				text-align: center;
				color: $uni-text-color-grey;
				font-size: 22rpx;
				margin-top: 40rpx;
				&:last-child {
					font-weight: bold;
					color: $uni-color-error;
					font-size: 32rpx;
					line-height: 60rpx;
					margin-top: 0rpx;
					margin-bottom: 50rpx;
				}
			}
		}
	}
	.slot-content {
		font-size: 28rpx;
		color: $u-content-color;
		padding: 60rpx 30rpx;
		text-align: center;
	}
}
</style>
