<template>
	<view>
		<view class="search" style="position: fixed;top: 0;z-index: 99;">
			<uni-datetime-picker style="margin-bottom:20rpx;" v-model="range" @change="searchList" type="daterange" />
			<view style="display: flex;">
				<view style="width: 80%;" :style="{'width':listStatus!= 6?'80%':'100%'}">
					<uni-search-bar class="uni-mt-10" radius="5" placeholder="输入客户名称/销售人员/单号搜索" cancelButton="none"
						@confirm="searchList" />
				</view>
				<view style="width: 20%;" v-if="listStatus !=6">
					<view style="width: 80%;height: 70rpx;background: #5fd9ee;text-align: center;line-height: 70rpx;border-radius: 10px;margin: 20rpx;color: #fff;" @tap="changeSort('paixu')">
						查看
						<uni-icons type="down" color="#fff" size="11" v-if="noDaysort == false"></uni-icons>
						<uni-icons type="up" color="#fff" size="11" v-if="noDaysort"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<view class="nahuo-mask" v-if="noDaysort">
			<view style="width: 100%;margin: 0 auto;background: #fff;height: 200rpx;border: 1px solid #eee;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px;">
				<view @tap="getCancelOrder()" class="paixu-content" style="border-bottom: 1px solid #eee;">
					查看全部订单
				</view>
				<view @tap="getCancelOrder('2')" class="paixu-content">
					查看已作废状态的订单
				</view>
			</view>
		</view>
		<view class="u-transition" style="display:flex;background: #ecf5ff;width: 100%;color: #5fd9ee;height: 80rpx;line-height: 80rpx;padding-left: 20rpx;">
			<view>点击列表可跳转至销售单</view>
			<!-- <view @tap.stop="printCodeBtn" class="dayin-text" v-if="btnStatus">打印商品码</view>
			<view @tap.stop="printCodeBtn" class="dayin-text" v-else>取消操作</view> -->
		</view>
		<view class="ulList" v-if="inventoryList.length > 0" style="overflow: scroll;margin-top:300rpx;">
			<ul :style="{'margin-bottom':btnStatus==false?'160rpx':''}">
				<li v-for="(item,index) in inventoryList" :key="index">
					<checkbox-group @change="checkboxChange">
						<label class="uni-list-cell uni-list-cell-pd" >
							<checkbox v-if="btnStatus==false" :value="item" style="float: left;width: 60rpx;line-height: 300rpx;margin: 0 20rpx;" />
							<view :style="{width:btnStatus==false?'95%':'100%'}" @tap="gotoDetail(item.id,item.userId)">
								<uni-card :title="item.userName == null ?'暂无':((shopId == '1810179818189361152' || shopId == '1863043415453863936') && item.userName == '散客')?'客户':item.userName" :sub-title="item.createTime == null ?'暂无':item.createTime" :extra="'数量：'+(item.productCount == null ?'暂无':item.productCount)">
									<view class="uni-body" style="font-weight: bold;font-size: 30rpx;">
										<text class="cardText" style="font-size: 30rpx;">单号：</text> 
										{{item.id}}
									</view>
									<view class="uni-body"><text class="cardText">销售员：</text> {{item.createByName == null ?'暂无':item.createByName}}</view>
									<view class="uni-body"> 
										<text class="cardText">销售金额：</text>
										<text class="priceText">{{item.totalAmount == null ?'暂无':item.totalAmount}}</text>
										<text decode class="cardText">{{'&nbsp;&nbsp;&nbsp;&nbsp; 欠款： '}}</text> 
										<text class="priceText" style="color:red;">{{item.noEarn == null ?'暂无':item.noEarn}}</text>
									</view>
									<view class="uni-body" v-if="item.returnSaleProductCount > 0">
										<text class="cardText">退货金额：</text>
										<text class="priceText">{{item.returnSaleTotalAmount == null ?'暂无':item.returnSaleTotalAmount}}</text>
										<text decode class="cardText">{{'&nbsp;&nbsp;&nbsp;&nbsp; 退货数： '}}</text> 
										<text class="priceText">{{item.returnSaleProductCount == null ?'暂无':item.returnSaleProductCount}}</text>
									</view>
									<view class="uni-body"> <text class="cardText">
										订单状态：</text>{{item.status == '0' ?'待抢单' :item.status == '2' ?'作废' :item.status == '1' ?'待取货' :item.status == '3' ?'待送达' :item.status == '4' ?'已完成' :item.status == '5' ?'下游客户待退货' :item.status == '00' ?'退货待抢单' :item.status == '01' ?'退货待取货' :item.status == '03' ?'退货待送达' :item.status == '04' ?'待确认退货' :item.status == '6' ?'待配货':item.status == '8' ?'待物流上门':item.status == '9' ?'已完成' :'挂单'}}
									</view>
									<view class="floatRight" v-if="item.status == 6" @tap.stop="goSaleGoods(item,'')">去开单</view>
									<view class="floatRight" v-if="item.status == 4" @tap.stop="cancelOrder(item,'',index)">撤销</view>
									<view class="floatRight" v-if="item.status == 4" @tap.stop="cancelOrder(item,'goPay')">撤销并复制</view>
									<view class="floatRight" v-if="item.status == 4" @tap.stop="copyOrder(item,'')">复制</view>
									<view class="floatRight" v-if="item.status == 2" @tap.stop="againOrder(item)">重新开单</view>
									<view class="floatRight" style="color: red;width: 150rpx;" @tap.stop="delItemModal(item)" v-if="item.status == 6">删除订单</view>
								</uni-card>
							</view>
						</label>
					</checkbox-group>
				</li>
				<u-loadmore :status="status" />
			</ul>

		</view>
		<u-empty v-else mode="order" margin-top="200"></u-empty>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchStr: '',
				type: '',
				inventoryList: [],
				status: 'loadmore',
				page: 1,
				returnList:new Map(),
				noDaysort:false,
				cancel:false,
				totalPages: 0,
				isCancel:false,
				listStatus:'',
				// type:'',
				range:[],
				btnStatus:true,
				shopId:uni.getStorageSync('shopId')
			};
		},
		onLoad(options) {
			this.type = options.type;
			this.listStatus = options.listStatus
			
		},
		onShow(){
			
			if(uni.getStorageSync('noReload') == true){
				uni.removeStorageSync('noReload')
			}else{
				this.list = []
				this.pageNum = 1
				this.getOrderInfoList()
			}
		},
		onReachBottom() {
			if (this.page >= this.totalPages) return;
			this.status = 'loading';
			this.page = ++this.page;
			if(this.cancel == true){
				this.getOrderInfoList("2");
			}else{
				this.getOrderInfoList();
			}
			
		},
		methods: {
			gotoDetail(id,userId) {
				uni.setStorageSync('noReload',true)
				uni.navigateTo({
					url: '/package1/index/orderDetail?id=' + id +'&userId='+userId
				})
				
			},
			searchList(res) {
				this.searchStr = res.value
				this.page = 1;
				this.inventoryList = [];
				if(this.cancel == true){
					this.getOrderInfoList("2");
				}else{
					this.getOrderInfoList();
				}
			},
			// 订单查询 
			getOrderInfoList(type) {
				this.status = 'loading';
				this.tui.request("/app/sale/listPages", "POST", {
					pageVo: {
						pageSize: 10,
						pageNumber: this.page
					},
					fromWhere:type == '2' || this.listStatus==6?2:0,
					startTime:this.range[0],
					endTime:this.range[1],
					searchStr:this.searchStr,
					status:type == '2'?2:this.listStatus,
					shopId:uni.getStorageSync('shopId')
				}, false, false).then((res) => {
					this.status = 'nomore';
					if (res.code == 200) {
						if (this.page == 1) {
							this.inventoryList = res.result.records
						} else {
							this.inventoryList = [...this.inventoryList, ...res.result.records]
						}
						// this.searchName = ""
						this.noDaysort = false
						this.totalPages = res.result.pages
					} else {
						this.tui.toast(res.message)
					}
				}).catch((res) => {})
			},
			changeSort(type){
				this.nahuoDay = false
				this.noDaysort = !this.noDaysort
				
			},
			paixuChange(text){
				this.sort = text
				this.popleList = []
				this.pages = 1
				this.searchName = ""
				this.noDaysort = false
				this.khOrGysList()
			},
			sliceMsg(val) {
				var name = ''
				if (typeof(val) == 'string') {
					let newObj = JSON.parse(val)
					for (let as in newObj) {
						name += newObj[as] + '/'
					}
				}
				return name;
			},
			//退款接口
			async getReturnOrder(id) {
				let that = this;
				await this.tui.request("/app/return/list", "post", {
					remark: 3,
					saleId: id
				}, false, false).then((res) => {
					if (res.code == 200 && res.result != null && res.result != undefined) {
						if (res.result != '') {
							res.result.forEach(item => {
								this.tui.request("/app/return/get/" + item.id, "GET", null, false,false).then((res) => {
									if (res.code == 200 && res.result != null && res.result != undefined) {
										for(let i=0;i<res.result.saleDetailDTOList.length;i++){
											res.result.saleDetailDTOList[i].returnPrice = res.result.saleDetailDTOList[i].discountAmount
											res.result.saleDetailDTOList[i].stockLogList = new Map()
											that.returnList.set(res.result.saleDetailDTOList[i].productId,res.result.saleDetailDTOList[i])
											for(let m=0;m<res.result.saleDetailDTOList[i].stockLogList1.length;m++){
												res.result.saleDetailDTOList[i].stockLogList1[m].productCount = 0-res.result.saleDetailDTOList[i].stockLogList1[m].productCount
												that.returnList.get(res.result.saleDetailDTOList[i].productId).stockLogList.set(res.result.saleDetailDTOList[i].stockLogList1[m].attributeList,res.result.saleDetailDTOList[i].stockLogList1[m])
											}
											
										}
									}
								}).catch((res) => {})
							})
						}
					} else {
						this.tui.toast(res.message)
					}
				})
			},
			// 重新开单订单
			async againOrder(item1,type,index) {
				let that = this;
				await this.tui.request("/app/return/list", "post", {
					remark: 3,
					saleId: item1.id
				}, false, false).then((res) => {
					if (res.code == 200 && res.result != null && res.result != undefined) {
						if (res.result != '') {
							res.result.forEach(item => {
								this.tui.request("/app/return/get/" + item.id, "GET", null, false,false).then((res) => {
									if (res.code == 200 && res.result != null && res.result != undefined) {
										for(let i=0;i<res.result.saleDetailDTOList.length;i++){
											res.result.saleDetailDTOList[i].returnPrice = res.result.saleDetailDTOList[i].discountAmount
											res.result.saleDetailDTOList[i].stockLogList = new Map()
											that.returnList.set(res.result.saleDetailDTOList[i].productId,res.result.saleDetailDTOList[i])
											for(let m=0;m<res.result.saleDetailDTOList[i].stockLogList1.length;m++){
												res.result.saleDetailDTOList[i].stockLogList1[m].productCount = 0-res.result.saleDetailDTOList[i].stockLogList1[m].productCount
												that.returnList.get(res.result.saleDetailDTOList[i].productId).stockLogList.set(res.result.saleDetailDTOList[i].stockLogList1[m].attributeList,res.result.saleDetailDTOList[i].stockLogList1[m])
											}
											
										}
									}
									this.$nextTick(() => {
										this.tui.modal("提示", "您确定要重新开单吗？", true, (res) => {
											if (res) {
												that.goSaleGoods(item1)
											}else{
												that.returnList = new Map()
											}
										})
									})
								}).catch((res) => {})
							})
						}else{
							this.$nextTick(() => {
								this.tui.modal("提示", "您确定要重新开单吗？", true, (res) => {
									if (res) {
										that.goSaleGoods(item1)
									}else{
										that.returnList = new Map()
									}
								})
							})
						}
					} else {
						this.tui.toast(res.message)
					}
				})
			},
			// 取消订单
			async cancelOrder(item1,type,index) {
				let that = this;
				await this.tui.request("/app/return/list", "post", {
					remark: 3,
					saleId: item1.id
				}, false, false).then((res) => {
					if (res.code == 200 && res.result != null && res.result != undefined) {
						if (res.result != '') {
							res.result.forEach(item => {
								this.tui.request("/app/return/get/" + item.id, "GET", null, false,false).then((res) => {
									if (res.code == 200 && res.result != null && res.result != undefined) {
										for(let i=0;i<res.result.saleDetailDTOList.length;i++){
											res.result.saleDetailDTOList[i].returnPrice = res.result.saleDetailDTOList[i].discountAmount
											res.result.saleDetailDTOList[i].stockLogList = new Map()
											that.returnList.set(res.result.saleDetailDTOList[i].productId,res.result.saleDetailDTOList[i])
											for(let m=0;m<res.result.saleDetailDTOList[i].stockLogList1.length;m++){
												res.result.saleDetailDTOList[i].stockLogList1[m].productCount = 0-res.result.saleDetailDTOList[i].stockLogList1[m].productCount
												that.returnList.get(res.result.saleDetailDTOList[i].productId).stockLogList.set(res.result.saleDetailDTOList[i].stockLogList1[m].attributeList,res.result.saleDetailDTOList[i].stockLogList1[m])
											}
											
										}
									}
									this.$nextTick(() => {
										this.tui.modal("提示", "您确定要撤销订单吗？", true, (res) => {
											if (res) {
												that.cancelOk(item1,type,index)
											}else{
												that.returnList = new Map()
											}
										})
									})
								}).catch((res) => {})
							})
						}else{
							this.$nextTick(() => {
								this.tui.modal("提示", "您确定要撤销订单吗？", true, (res) => {
									if (res) {
										that.cancelOk(item1,type,index)
									}else{
										that.returnList = new Map()
									}
								})
							})
						}
					} else {
						this.tui.toast(res.message)
					}
				})
			},
			async copyOrder(item1){
				let that = this;
				await this.tui.request("/app/return/list", "post", {
					remark: 3,
					saleId: item1.id
				}, false, false).then((res) => {
					if (res.code == 200 && res.result != null && res.result != undefined) {
						if (res.result != '') {
							res.result.forEach(item => {
								this.tui.request("/app/return/get/" + item.id, "GET", null, false,false).then((res) => {
									if (res.code == 200 && res.result != null && res.result != undefined) {
										for(let i=0;i<res.result.saleDetailDTOList.length;i++){
											res.result.saleDetailDTOList[i].returnPrice = res.result.saleDetailDTOList[i].discountAmount
											res.result.saleDetailDTOList[i].stockLogList = new Map()
											that.returnList.set(res.result.saleDetailDTOList[i].productId,res.result.saleDetailDTOList[i])
											for(let m=0;m<res.result.saleDetailDTOList[i].stockLogList1.length;m++){
												res.result.saleDetailDTOList[i].stockLogList1[m].productCount = 0-res.result.saleDetailDTOList[i].stockLogList1[m].productCount
												that.returnList.get(res.result.saleDetailDTOList[i].productId).stockLogList.set(res.result.saleDetailDTOList[i].stockLogList1[m].attributeList,res.result.saleDetailDTOList[i].stockLogList1[m])
											}
											
										}
									}
									this.$nextTick(() => {
										this.tui.modal("提示", "您确定要复制订单并重新开单吗？", true, (res) => {
											if (res) {
												this.goSaleGoods(item1,'copy')
											}else{
												that.returnList = new Map()
											}
										})
									})
								}).catch((res) => {})
							})
						}else{
							this.$nextTick(() => {
								this.tui.modal("提示", "您确定要复制订单并重新开单吗？", true, (res) => {
									if (res) {
										this.goSaleGoods(item1,'copy')
									}else{
										that.returnList = new Map()
									}
								})
							})
						}
					} else {
						this.tui.toast(res.message)
					}
				})
			},
			getCancelOrder(type){
				this.page =1
				this.inventoryList = []
				if(type == "2"){
					this.cancel = true
				}else{
					this.cancel = false
				}
				this.getOrderInfoList(type)
			},
			// 取消订单
			cancelOk(item,type,index) {
				let that = this;
				that.tui.request('/app/sale/cancelSale', "POST", {
					id:item.id
				}, true, true).then((res1) => {
					if (res1.code == 200) {
						if (type == 'goPay') {
							this.isCancel = true
							that.goSaleGoods(item,'cancel')
						} else {
							that.inventoryList[index].status = 2
							that.$forceUpdate()
							// that.getOrderInfoList()
						}
					} else {
						that.tui.toast(res.message)
					}
				}).catch((res1) => {})
			},
			getUnitPrice(item,items){
				if(item.discount != 10){
					if(item.discount == null || item.discount == 0 || item.discount ==undefined){
						return items.discountAmount
					}else{
						return ((items.discountAmount * 10000) / (item.discount * 100) / 10).toFixed(2)
					}
				}else if(items.discount!= 10){
					if(items.discount == null || items.discount == 0 || items.discount ==undefined){
						return items.discountAmount
					}else{
						return ((items.discountAmount * 10000) / (items.discount * 100) / 10).toFixed(2)
					}
				}else{
					return items.discountAmount || items.wholesalePrice
				}
			},
			//带参数跳转到开单页
			goSaleGoods(item,type) {
				let dataList = []
				if(!item.saleDetailDTOList){
					item.saleDetailDTOList = []
				}
				this.returnList.forEach(function(value, key) {
					item.saleDetailDTOList.push(value)
				})
				item.discount = item.discount==null?10:item.discount
				if (item.saleDetailDTOList) {
					for (let i = 0; i < item.saleDetailDTOList.length; i++) {
			
						let obj = {}
						let attrMap = new Map()
						let newSaleDetailDTOList = []
						let num = 0
						
						for (let m = 0; m < item.saleDetailDTOList[i].stockLogList1.length; m++) {
							if (attrMap.has(item.saleDetailDTOList[i].stockLogList1[m].attributeList) == true) {
								let hasCount = attrMap.get(item.saleDetailDTOList[i].stockLogList1[m].attributeList)
								newSaleDetailDTOList[hasCount].productCount = Number(newSaleDetailDTOList[hasCount]
									.productCount) + Number(item.saleDetailDTOList[i].stockLogList1[m].productCount)
								if(this.isCancel == true){
									newSaleDetailDTOList[hasCount].stockCount = newSaleDetailDTOList[hasCount].stockCount + newSaleDetailDTOList[hasCount].productCount
								}
							} else {
								item.saleDetailDTOList[i].stockLogList1[m].name = this.sliceMsg(item.saleDetailDTOList[i]
									.stockLogList1[m].attributeList)
								if(this.isCancel == true){
									item.saleDetailDTOList[i].stockLogList1[m].stockCount = item.saleDetailDTOList[i].stockLogList1[m].stockCount + item.saleDetailDTOList[i].stockLogList1[m].productCount
								}
								newSaleDetailDTOList.push(item.saleDetailDTOList[i].stockLogList1[m])
								attrMap.set(item.saleDetailDTOList[i].stockLogList1[m].attributeList, num)
								num++
							}
							
						}
						obj.saleDetailQueryDTO = newSaleDetailDTOList
						obj.num = 0
						obj.customerCategoryRule = item.saleDetailDTOList[i].customerCategoryRule != null ?JSON.parse(item.saleDetailDTOList[i].customerCategoryRule):null
						obj.id = item.saleDetailDTOList[i].productId
						obj.price = item.saleDetailDTOList[i].price
						if(item.status == '6'){
							obj.buyCount = item.saleDetailDTOList[i].buyCount
						}else{
							obj.buyCount = item.saleDetailDTOList[i].buyCount - 1
						}
						
						obj.lsprice = item.saleDetailDTOList[i].price
						obj.categoryId = item.saleDetailDTOList[i].categoryId
						obj.zPrice = item.saleDetailDTOList[i].discountAmount
						obj.attrId = item.saleDetailDTOList[i].attrId
						obj.discountAmount = item.saleDetailDTOList[i].discountAmount
						obj.productName = item.saleDetailDTOList[i].productName
						if(item.saleDetailDTOList[i].productPicture != null && item.saleDetailDTOList[i].productPicture != ''){
							obj.productPicture = item.saleDetailDTOList[i].productPicture + '?time=' + new Date().getTime()
						}else{
							obj.productPicture = ""
						}
						obj.productSn = item.saleDetailDTOList[i].productSn
						obj.wholesalePrice = item.saleDetailDTOList[i].wholesalePrice
						obj.returnPrice = item.saleDetailDTOList[i].returnPrice
						if(type == 'copy'){
							obj.saleId = ''
						}else{
							obj.saleId = item.id
						}
						obj.remark = item.remark
						obj.xsyId = item.createBy
						obj.createByName = item.createByName
						if(type == 'cancel'){
							obj.unitPrice = this.getUnitPrice(item,item.saleDetailDTOList[i])
						}else{
							obj.unitPrice = item.saleDetailDTOList[i].discountAmount
						}
						dataList.push(obj)
					}
				} else {
					let obj = {}
					obj.num = 0
					obj.price = 0
					if(type == 'copy'){
						obj.saleId = ''
					}else{
						obj.saleId = item.id
					}
					obj.remark = item.remark
					obj.xsyId = item.createBy
					obj.createByName = item.createByName
					dataList.push(obj)
				}
				this.$nextTick(()=>{
					this.tui.request("/app/debt/selectByUserId", "post", {
						shopId:uni.getStorageSync('shopId'),
						userId:item.userId
					}, false, true).then((res) => {
						if (res.code == 200) {
							this.returnList = new Map()
							res.result.noEarn = res.result.amountOwed
							res.result.name = res.result.userName
							res.result.id = item.userId
							uni.setStorageSync('khName', JSON.stringify(res.result))
							uni.setStorageSync('carList1', JSON.stringify(dataList))
							if(type == 'cancel'){
								uni.setStorageSync('discountAll', item.discount != null ?item.discount:10)
							}
							uni.setStorageSync('hangOrder', true)
							let windowWidth = '1'
							if(uni.getStorageSync('shopName').indexOf('杰娜世家') != -1){
								windowWidth = '0'
							}
							if(windowWidth == '1'){
								uni.switchTab({
									url: '/pages/inventory/goodsList1'
								})
							}else{
								uni.navigateTo({
									url: '/package2/inventory/goodsList1HENG'
								})
							}
						}
					})
				})
			},
			//点击打印按钮
			printCodeBtn(){
				this.btnStatus = !this.btnStatus
			},
			// checkboxChange(e){

			// },
			delItemModal(item) {
				
				let that = this;
				uni.showModal({
					title: "提示",
					content: "确定删除此条待配货订单吗？",
					success: function(res) {
						if (res.confirm) {
							that.tui.request("/app/sale/delById", "post", {
								id: item.id,
							}, false, true).then((res) => {
								if (res.code == 200) {
									that.getOrderInfoList();
									uni.showToast({
										title:"删除成功",
										icon: 'none'
									})
								} else {
									uni.showToast({
										title:"删除失败",
										icon: 'none'
									})
								}
							}).catch((res) => {})
						}
					}
				})
				
			}
		}
	}
</script>

<style lang="scss">
	page{
		font-size: 24rpx;
	}
	.u-transition{
		width: 100%;
		position: fixed;
		top: 226rpx;
		z-index: 99;
	}
	@media screen and (min-width: 760px) {
		.u-transition{
			width: 100%;
			position: fixed;
			top: 221rpx;
			z-index: 99;
		}
	}
	.search {
		padding: 20upx;
		background-color: #fff;
		width: 100%;
		background-color: #fff;
	}
	.uni-searchbar{
		padding: 20rpx 0 !important;
	}
	.dayin-text{
		flex: 1;
		text-align: right;
		padding-right: 20rpx;
		text-decoration: underline;
		color: blue;
	}
	.ulList {

		ul {
			li {
				font-size: 24rpx;

				.floatRight {
					float: right;
					padding: 14rpx;
					color: $u-primary;
					font-size: 26upx;
				}

				.cardText {
					font-size: 24rpx;
				}

				.priceText {
					color: $u-primary;
					font-size: 28rpx;
				}
			}
		}
	}
	.order-bottom{
		background: #fff;
		height: 120rpx;
		width: 100%;
		position: fixed;
		bottom:0;
		
		button{
			width: 90%;
			height: 80rpx;
			margin: 0 auto;
			background: #088FEB;
			color: #fff;
			margin-top: 20rpx;
		}
	}
	.paixu-content{
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
	}
	.nahuo-mask{
		height: 1200rpx;
		background: rgba(0, 0, 0, 0.6);
		position: fixed;
		top: 200rpx;
		right: 0;
		z-index: 100;
		width: 100%;
	}
</style>