<template>
	<view class="page1">
		<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" />
			<uni-search-bar class="uni-mt-10" radius="5" placeholder="输入客户名称/销售人员搜索" cancelButton="none"
				@confirm="searchList" />
		</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>
		<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.saleId)">
								<!-- :extra="'数量：'+(item.productCount == null ?'暂无':item.productCount)" -->
								<uni-card :title="item.userName == null ?'暂无':item.userName" :sub-title="item.createTime == null ?'暂无':item.createTime" >
									<view class="uni-body"><text class="cardText">销售员：</text> {{item.createByName == null ?'暂无':item.createByName}}</view>
									<view class="uni-body" v-if="item.totalAmount > 0">
										<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">{{item.productCount == null ?'暂无':item.productCount}}</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 == 4" @tap.stop="cancelOrder(item)">撤销</view>
									<view class="floatRight" v-if="item.status == 4" @tap.stop="cancelOrder(item,'goPay')">撤销并复制</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,
				totalPages: 0,
				// type:'',
				range:[],
				btnStatus:true,
				returnList:new Map(),
			};
		},
		onLoad(options) {
			this.getMonth();
			this.type = options.type;
			this.listStatus = options.listStatus
			
		},
		onShow(){
			this.getOrderInfoList()
		},
		onReachBottom() {
			if (this.page >= this.totalPages) return;
			this.status = 'loading';
			this.page = ++this.page;
			this.getOrderInfoList();
		},
		methods: {
			//获取当月1日到当前时间
			getMonth() {
				let date = new Date()
				let year = date.getFullYear().toString()   //'年'
				let month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1).toString():(date.getMonth()+1).toString()  //'月'
				let da = date.getDate() < 10 ? '0'+date.getDate().toString():date.getDate().toString()  //'日'
				let end = year + '-' + month + '-' + da  //当天
				let beg = year + '-' + month + '-01'    //当月第一天
				this.range = [beg,end]
			},
			gotoDetail(id) {
				this.page = 1
				uni.navigateTo({
					url: '/package1/index/orderDetail?id=' + id
				})
			},
			searchList(res) {
				this.searchStr = res.value
				this.page = 1;
				this.inventoryList = [];
				this.getOrderInfoList()
			},
			// 订单查询 
			getOrderInfoList() {
				this.status = 'loading';
				this.tui.request("/app/return/getReturnSaleList", "POST", {
					pageNum:this.page,
					pageSize:10,
					startTime:this.range[0],
					endTime:this.range[1],
					createByName:"",
					userId:"",//(客户精准搜索)
					userName:"",//(客户模糊搜索)
				}, 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.totalPages = res.result.page
					} else {
						this.tui.toast(res.message)
					}
				}).catch((res) => {})
			},
			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].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 cancelOrder(item, type) {
				let that = this;
				await this.getReturnOrder(item.saleId)
				await this.tui.modal("提示", "您确定要撤销订单吗？", true, (res) => {
					if (res) {
						that.cancelOk(item,type)
					}
				})
			},
			// 取消订单
			cancelOk(item,type) {
				let that = this;
				that.tui.request('/app/sale/cancelSale', "POST", {
					id:item.saleId
				}, true, true).then((res1) => {
					if (res1.code == 200) {
						if (type == 'goPay') {
							that.goSaleGoods(item)
						} else {
							that.getOrderInfoList()
						}
					} else {
						that.tui.toast(res.message)
					}
				}).catch((res1) => {})
			},
			//带参数跳转到开单页
			goSaleGoods(item) {
				let dataList = []
				if(!item.saleDetailDTOList){
					item.saleDetailDTOList = []
				}
				this.returnList.forEach(function(value, key) {
					item.saleDetailDTOList.push(value)
				})
				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)
							} else {
								item.saleDetailDTOList[i].stockLogList1[m].name = this.sliceMsg(item.saleDetailDTOList[i]
									.stockLogList1[m].attributeList)
								newSaleDetailDTOList.push(item.saleDetailDTOList[i].stockLogList1[m])
								attrMap.set(item.saleDetailDTOList[i].stockLogList1[m].attributeList, num)
								num++
							}
							
						}
						obj.saleDetailQueryDTO = newSaleDetailDTOList
						obj.num = 0
						obj.id = item.saleDetailDTOList[i].productId
						obj.price = item.saleDetailDTOList[i].price
						obj.lsprice = item.saleDetailDTOList[i].price
						obj.categoryId = item.saleDetailDTOList[i].categoryId
						obj.zPrice = item.saleDetailDTOList[i].discountAmount
						obj.unitPrice = item.saleDetailDTOList[i].discountAmount || item.saleDetailDTOList[i]
							.wholesalePrice
						obj.productName = item.saleDetailDTOList[i].productName
						obj.productPicture = item.saleDetailDTOList[i].productPicture + '?time=' + new Date().getTime()
						obj.productSn = item.saleDetailDTOList[i].productSn
						obj.wholesalePrice = item.saleDetailDTOList[i].wholesalePrice
						obj.returnPrice = item.saleDetailDTOList[i].returnPrice
						obj.saleId = item.id
						obj.remark = item.remark
						obj.xsyId = item.createBy
						obj.createByName = item.createByName
						dataList.push(obj)
					}
				} else {
					let obj = {}
					obj.num = 0
					obj.price = 0
					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/customer/list", "post", {
						notBuyDays: "",
						pageNum: 1,
						pageSize: 10,
						searchStr: item.userName,
						sort: "",
					}, false, false).then((res) => {
						if (res.code == 200) {
							this.returnList = new Map()
							uni.setStorageSync('khName', JSON.stringify(res.result.records[0]))
							uni.setStorageSync('carList1', JSON.stringify(dataList))
							uni.setStorageSync('hangOrder', true)
							uni.switchTab({
								url: '/pages/inventory/goodsList1'
							})
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	page,.page1{
		font-size: 28rpx;
	}
	.u-transition{
		width: 100%;
		position: fixed;
		top: 226rpx;
		z-index: 99;
	}
	.search {
		padding: 20rpx;
		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: 26rpx;
				}

				.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;
		}
	}
</style>