<template>
	<view class="page1">
		<cmd-nav-bar iconOne="chevron-left" @iconOne="backPage" :title="shopName" background-color="#fff"></cmd-nav-bar>
		<view class="search" style="position: fixed;top: 0;z-index: 99;margin-top:176rpx;">
			<uni-datetime-picker style="margin-bottom:20rpx;" v-model="range" @change="searchList" type="daterange" />
			<view style="display: flex;">
				<view style="width: 80%;" :style="{'width':inStorageStatus!= 0?'80%':'100%'}">
					<uni-search-bar class="uni-mt-10" radius="5" placeholder="输入供应商名称搜索" cancelButton="none"
						@confirm="searchList" />
				</view>
				<view style="width: 20%;" v-if="inStorageStatus!= 0">
					<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" style="margin-top:176rpx;">
			<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('1')" class="paixu-content">
					查看已作废状态的订单
				</view>
			</view>
		</view>
		<u-alert description="点击可跳转至入库单" type="primary"></u-alert>
		<view class="ulList" v-if="list.length > 0" style="overflow: scroll;margin-top:480rpx;">
			<ul>
				<li v-for="(item,index) in list" @tap="goDetail(item)" :key="index">
					<uni-card :title="'供应商:'+(item.supplierName == null ?'暂无':item.supplierName)"
						:sub-title="'操作时间:'+(item.purchaseTime == null ?'暂无':item.purchaseTime)"
						:extra="'共'+(item.totalAmount == null ?'暂无':item.totalAmount) + '件'"
						thumbnail="/static/images/dingdan/dd1.png">
						<view class="uni-body"><text class="cardText">
							入库时间:</text>{{item.createTime == null ?'暂无':item.createTime}}
						</view>
						<view class="uni-body"><text class="cardText">
							入库人:</text>{{item.createByName == null ?'暂无':item.createByName}}
						</view>
						<view class="uni-body" v-if="item.inStorageStatus != 0 && type==0">
							<text class="cardText">总成本:</text> 
							<text class="priceText">{{item.shouldPay == null ?'暂无':item.shouldPay}} </text> 
							<text decode class="cardText">{{'&nbsp;&nbsp;&nbsp;&nbsp; 欠款： '}} </text> 
							<text class="priceText" style="color:red">{{item.noPay == null ?'暂无':item.noPay}}</text>
						</view>
						<view class="uni-body"> 
							<text class="cardText">订单状态:</text>{{item.delFlag == 1 ?'已撤销':item.inStorageStatus == 0 ?'未入库' :item.inStorageStatus == 1 ?'已入库':item.inStorageStatus == 2 ?'AI识别-识别中...':item.inStorageStatus == 3 || (item.inStorageStatus == 4 && item.ocrCount > 0) ?'AI识别-识别完成':item.ocrCount == 0 && item.inStorageStatus == 4?'AI识别-识别失败':'暂无'}}
						</view>
						<view v-if="storeFlag == 1" class="return-price" style="width:105rpx;right:30rpx;" @tap.stop="goConfirm(item)">去确认</view>
						<view v-if="item.inStorageStatus== 0 && type==0 && storeFlag != 1" class="return-price" @tap.stop="goDetail(item)">更新</view>
						<view v-if="item.inStorageStatus!= 0 && item.delFlag != 1 && type==0 && storeFlag != 1" class="return-price" style="width: auto;right: 130rpx;padding: 0 20rpx;" @tap.stop="cancelOrder(item)">撤销并复制</view>
						<view v-if="item.inStorageStatus!= 0 && item.delFlag != 1 && type==0 && storeFlag != 1" class="return-price" @tap.stop="returnPrice(item,index)">撤销</view>
						<view v-if="item.inStorageStatus!= 0 && item.delFlag == 1 && type==0 && storeFlag != 1" class="return-price" style="width:140rpx;" @tap.stop="goSaleGoods(item)">重新入库</view>
						<view v-if="item.inStorageStatus == 2 || item.inStorageStatus == 3 || item.inStorageStatus == 4 && item.delFlag != 1 && storeFlag != 1" class="return-price" style="width:105rpx;right:150rpx;" @tap.stop="returnPrice(item)">AI入库</view>
						
					</uni-card>
				</li>
			</ul>
			
		</view>
		<u-loadmore :status="status" />
		<!-- <u-empty v-else mode="order" margin-top="200"></u-empty> -->
	</view>
</template>
<script>
	import color from "../../uni_modules/uview-ui/libs/config/color";

	export default {
		name: "uparrears",
		computed: {
			color() {
				return color
			}
		},
		data() {
			return {
				searchStr: '',
				list: [],
				inStorageStatus: '',
				supplierName: '',
				startDate: '',
				shopName:uni.getStorageSync('shopName'),
				endDate: '',
				noDaysort:false,
				type: '',
				cancel:false,
				pages: 1,
				pageNum:1,
				status: 'loadmore',
				range:[],
				storeFlag:""
			}
		},
		onLoad(option) {
			this.inStorageStatus = option.inStorageStatus || ''
			this.storeFlag = option.storeFlag || ""
			this.type = uni.getStorageSync('type')			
		},
		onShow(){
			
			if(uni.getStorageSync('noReload') == true){
				uni.removeStorageSync('noReload')
			}else{
				this.list = []
				this.pageNum = 1
				this.getList()
			}
			
		},
		onReachBottom() {
			if(this.inStorageStatus != 0){
				if (this.pageNum >= this.pages) return;
				this.status = 'loading';
				this.pageNum += 1;
				
				if(this.cancel == true){
					this.getList("1");
				}else{
					this.getList();
				}
			}
		},
		methods: {
			// 取消订单
			cancelOrder(item) {
				let that = this;
				// await this.getReturnOrder(item.id)
				this.tui.modal("提示", "您确定要撤销此采购单吗？", true, (res) => {
					if (res) {
						that.cancelOk(item)
					}
				})
			},
			// 取消订单
			cancelOk(item) {
				let that = this;
				that.tui.request('/app/purchase/cancelPurchase', "POST", {
					id:item.id
				}, true, true).then((res1) => {
					if (res1.code == 200) {
						that.goSaleGoods(item)
					} else {
						that.tui.toast(res.message)
					}
				}).catch((res1) => {})
			},
			sliceMsg(val) {
				var name = ''
				if (typeof(val) == 'string') {
					let newObj = JSON.parse(val)
					for (let as in newObj) {
						name += newObj[as] + '/'
					}
				}
				return name;
			},
			//带参数跳转到入库页
			async goSaleGoods(item) {
				let dataList = []
				await this.tui.request('/app/purchase/getPurchaseAllData', "POST", {
					id:item.id
				}, false, true).then((res1) => {
					if(res1.code == 200){
						if(!res1.result.purchaseDetails){
							res1.result.purchaseDetails = []
						}
						if (res1.result.purchaseDetails) {
							for (let i = 0; i < res1.result.purchaseDetails.length; i++) {
									
								let obj = {}
								let attrMap = new Map()
								let newSaleDetailDTOList = []
								let num = 0
								
								for (let m = 0; m < res1.result.purchaseDetails[i].stockLogList1.length; m++) {
									if (attrMap.has(res1.result.purchaseDetails[i].stockLogList1[m].attributeList) == true) {
										let hasCount = attrMap.get(res1.result.purchaseDetails[i].stockLogList1[m].attributeList)
										newSaleDetailDTOList[hasCount].productCount = Number(newSaleDetailDTOList[hasCount]
											.productCount) + Number(res1.result.purchaseDetails[i].stockLogList1[m].productCount)
									} else {
										res1.result.purchaseDetails[i].stockLogList1[m].name = this.sliceMsg(res1.result.purchaseDetails[i]
											.stockLogList1[m].attributeList)
										newSaleDetailDTOList.push(res1.result.purchaseDetails[i].stockLogList1[m])
										attrMap.set(res1.result.purchaseDetails[i].stockLogList1[m].attributeList, num)
										num++
									}
									
								}
								obj.saleDetailQueryDTO = newSaleDetailDTOList
								obj.num = 0
								obj.attrId = res1.result.purchaseDetails[i].attrId
								obj.id = res1.result.purchaseDetails[i].productId
								obj.customerCategoryRule = res1.result.purchaseDetails[i].customerCategoryRule != null ?JSON.parse(res1.result.purchaseDetails[i].customerCategoryRule):null
								obj.purchasePrice = res1.result.purchaseDetails[i].stockLogList1[0].purchasePrice
								obj.price = res1.result.purchaseDetails[i].price
								obj.categoryId = res1.result.purchaseDetails[i].categoryId
								obj.productName = res1.result.purchaseDetails[i].productName
								obj.productPicture = res1.result.purchaseDetails[i].productPicture
								obj.productSn = res1.result.purchaseDetails[i].productSn
								obj.productId = res1.result.purchaseDetails[i].productId
								obj.wholesalePrice = res1.result.purchaseDetails[i].wholesalePrice
								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)
						}
						uni.setStorageSync('AiInventoryId',"")
					}
				}).catch((res1) => {})
				
				await this.tui.request("/app/debt/selectByUserId", "post", {
					shopId:uni.getStorageSync('shopId'),
					userId:item.supplierId
				}, false, true).then((res) => {
					if (res.code == 200) {
						
						res.result.noEarn = res.result.amountOwed
						res.result.consigneeName = res.result.userName
						res.result.id = res.result.userId
						uni.setStorageSync('khName', JSON.stringify(res.result))
						uni.setStorageSync('carList1', JSON.stringify(dataList))
						uni.setStorageSync('hangOrder', true)
						uni.navigateTo({
							url: '/package1/AI/voiceInventory',
						})
					}
				})
			},
			searchTime(res){
				
				if(res == ''){
					this.range = []
				}
				this.pages = 1;
				this.pageNum = 1;
				this.list = [];
				if(this.cancel == true){
					this.getList("1");
				}else{
					this.getList();
				}
			},
			searchList(res) {
				this.searchStr = res.value
				this.pages = 1;
				this.pageNum = 1;
				this.list = [];
				if(this.cancel == true){
					this.getList("1");
				}else{
					this.getList();
				}
			},
			getList(type) {
				var url,data;
				if(this.inStorageStatus == 0){
					this.tui.request("/app/purchase/list", "POST", {
						inStorageStatus: this.inStorageStatus
					}, false, false).then((res) => {
						this.status = 'nomore';
						if (res.code == 200) {
							this.pages = res.result.pages
							if (this.pages == 1) {
								this.list = res.result.records
							} else {
								this.list = [...this.list, ...res.result.records]
							}
							this.searchStr = ""
							this.noDaysort = false
						} else {
							this.tui.toast(res.message)
						}
					})
				}else{
					this.tui.request("/app/purchase/getPurchaseList", "POST", {
						inStorageStatus: this.inStorageStatus,
						searchStr: this.searchStr,
						startDate: this.range[0],
						endDate: this.range[1],
						delFlag:type,
						pageNum:this.pageNum,
						pageSize:10,
						storeFlag:this.storeFlag
					}, false, false).then((res) => {
						this.status = 'nomore';
						if (res.code == 200) {
							// this.list = []
							this.pages = res.result.pages
							if (this.pages == 1) {
								this.list = res.result.records
							} else {
								this.list = [...this.list, ...res.result.records]
							}
							// this.searchStr = ""
							this.noDaysort = false
						} else {
							this.tui.toast(res.message)
						}
					})
				}
			},
			getCancelOrder(type){
				this.pageNum =1
				this.list = []
				if(type == "1"){
					this.cancel = true
				}else{
					this.cancel = false
				}
				this.getList(type)
			},
			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()
			},
			goDetail(item){
				// uni.setStorageSync('noReload',true)
				uni.navigateTo({
					url: '/package1/index/waitStorageDetail?id=' + item.id
				})
			},
			goConfirm(item){
				uni.navigateTo({
					url: '/package1/index/waitStorageDetail?id=' + item.id +'&storeFlag=1'
				})
			},
			backPage(){
				uni.reLaunch({
					url: '/pages/index/home'
				})
			},
			returnPrice(item,index) {
				let that = this;
				if(item.inStorageStatus == 2 || item.inStorageStatus == 3 || item.inStorageStatus == 4){
					uni.navigateTo({
						url: '/package1/AI/AIInventoryList'
					})
				}else if(item.inStorageStatus == 1){
					uni.showModal({
						title: "提示",
						content: "确定撤销该采购单吗？",
						success: function(res) {
							uni.showLoading({
								title: '加载中...'
							})
							if (res.confirm) {
								that.tui.request("/app/purchase/cancelPurchase", "POST", {
									id: item.id,
								}, false, true).then((res) => {
									if (res.code == 200) {
										// that.pages = 1;
										// that.pageNum = 1;
										// that.list = [];
										that.list[index].delFlag = 1
										that.$forceUpdate()
										// that.getList()
										that.tui.toast("撤销成功！")
									} else {
										that.tui.toast(res.message)
									}
								})
							}
							setTimeout(res => {
								uni.hideLoading();
							}, 500)
						}
					})
					
				}
			}
		}
	}
</script>
<style lang="scss">
	page,.page1{
		font-size: 28rpx;
	}
	.u-transition{
		width: 100%;
		position: fixed;
		top: 402rpx;
		z-index: 99;
	}
	.uni-searchbar{
		padding: 20rpx 0 !important;
	}
	.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;
				}
			}
		}
	}

	.return-price {
		position: absolute;
		bottom: 30rpx;
		right: 30rpx;
		background: #5fd9ee;
		color: #fff;
		width: 80rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border-radius: 10px;
	}
	.search {
		padding: 20rpx;
		background-color: #fff;
		width: 100%;
	}
	.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>