<template>
	<view class="chooseProduct-wrap">
		<!-- 产品列表 -->
		<view class="product-list-box">
			<scroll-view class="product-list-con" :style="{height: scrollH+'upx'}" scroll-y @scrolltolower="onreachBottom">
				<view class="product-list-item font_13" v-for="(item, index) in listData" :key="item.id">
					<view class="list-item-tit">
						<view class="item-tit ellipsis-one" :style="{borderColor: $config('primaryColor')}">{{item.productName}}</view>
					</view>
					<view class="list-item-con flex align_center justify_between">
						<view class="flex align_center justify_between flex_1">
							<view class="pimgs">
								<u-image :src="item.productMainImage?item.productMainImage:`../../static/${theme}/def_img@2x.png`" width="128" height="128" border-radius="10"></u-image>
							</view>
							<view class="flex_1">
								<view>产品编码：{{item.productCode || '--'}}</view>
								<view class="padding_3">原厂编码：{{item.productOrigCode || '--'}}</view>
								<view v-if="item.warehouseName || item.warehouseLocationName">仓库仓位：{{item.warehouseName}} > {{item.warehouseLocationName}}</view>
							</view>
						</view>
						<view class="list-item-btn">
							<u-icon class="item-btn-add" name="plus-circle" :color="$config('primaryColor')" size="42" @click="handleAdd(item, 'add')"></u-icon>
						</view>
					</view>
					<view class="list-item-footer flex align_center justify_between">
						<view class="footer-item" v-if="searchParams && searchParams.cost &&$hasPermissions('M_showCostPrice_mobile')">
							<view>{{toThousands(item.putCost||0, 2)}}</view>
							<view class="color_6">成本价</view>
						</view>
						<view class="footer-item" v-if="searchParams && searchParams.cityPrice">
							<view>{{toThousands(item.dealerProduct && item.dealerProduct.cityPrice || 0, 2)}}</view>
							<view class="color_6">市级价</view>
						</view>
						<view class="footer-item">
							<view>{{toThousands(item.currentQty||0)}}{{item.unit}}</view>
							<view class="color_6">库存数量</view>
						</view>
						<view class="footer-item">
							<view>
								<text :style="{color: $config('errorColor')}">￥{{toThousands(item.price||0, 2)}}</text>
								<text v-if="item.origSalePriceFlag == 1">（原）</text>
							</view>
							<view class="color_6">参考售价</view>
						</view>
					</view>
				</view>
				<view v-if="listData && listData.length == 0">
					<u-empty :src="`/static/${$config('themePath')}/def_no_data@3x.png`" icon-size="150" :text="noDataText" mode="list" :margin-top="50"></u-empty>
				</view>
				<view style="padding-bottom: 20upx;">
					<u-loadmore v-if="totalNum>listData.length || status=='loading'" :status="status" />
				</view>
			</scroll-view>
		</view>
		<!-- 合计 -->
		<view ref="productTotal" class="selected-box flex align_center justify_between">
			<view class="choose-info flex_1 flex align_center justify_between" @click="lookProduct">
				<text>已选 {{detailData && (detailData.totalCategory || detailData.totalCategory==0) ? toThousands(detailData.totalCategory) : '--'}} 款，合计 ￥{{detailData && (detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount, 2) : '--'}}</text>
				<u-icon name="arrow-up" :color="$config('primaryColor')" size="34" class="close-circle"></u-icon>
			</view>
			<view class="choose-btn" @click="handleChoose" :style="{backgroundColor: $config('primaryColor')}">选好了</view>
		</view>
		<!-- 查询右侧弹框 -->
		<productSearch :openModal="openModal" :defaultParams="searchParams" @refresh="refresh" @close="openModal=false" />
		<!-- 添加/编辑产品 -->
		<productModal :openModal="openProductModal" :infoData="productInfo" @confirm="productConfirm" @close="openProductModal=false" />
		<!-- 已选产品 -->
		<selectedProductsModal ref="selectedProducts" :openModal="openSelectedModal" :nowData="detailData" @edit="handleEdit" @confirm="handleChoose" @delete="handleDel" @close="openSelectedModal=false" />
		<!-- 弹框 -->
		<common-modal :openModal="commonModal" :content="modalText" @confirm="handleCommon" @cancel="handleCancel" @close="commonModal=false" />
	</view>
</template>

<script>
	import ProductSearch from './productSearch.vue'
	import ProductModal from './productModal.vue'
	import SelectedProductsModal from './selectedProductsModal.vue'
	import commonModal from '@/pages/common/commonModal.vue'
	import { toThousands } from '@/libs/tools'
	import { querySumByProductLocation, stockByProductSn } from '@/api/stock'
	import { salesDetail, supperCodeByVin, salesDetailInsert, salesDetailUpdate, salesDetailList } from '@/api/sales'
	export default{
		components: { ProductSearch, ProductModal, SelectedProductsModal, commonModal },
		data(){
			return{
				toThousands,
				listData: [],
				pageNo: 1,
				pageSize: 6,
				totalNum: 0,
				status: 'loadmore',
				noDataText: '暂无数据',
				searchParams: null,
				openModal: false,
				theme: '',
				salesInfo: null,  // 销售单信息
				scrollH: 0,
				openProductModal: false,  // 编辑产品信息弹框是否显示
				productData: null,  // 当前操作的产品信息
				productInfo: null,  // 添加/编辑产品需要的参数
				chooseType: 'add',  // 添加产品add，编辑产品edit
				commonModal: false,  // 公共弹框是否显示
				modalText: '',  // 公共弹框提示语
				commonType: 1,  // 公共弹框类型  1为添加产品时库存不足，2为编辑产品时库存不足，3为售价低于定价，4为售价低于成本价
				openSelectedModal: false,  // 已选产品弹框是否显示
				detailData: null,  // 销售单详情数据
				editInfo: null,  // 添加/编辑 提交的值
			}
		},
		onNavigationBarButtonTap(e){  // 标题栏 按钮操作
			this.openModal = true
		},
		onBackPress() {
			uni.$emit("refreshEditBL")
		},
		onLoad(opt) {
			this.theme = getApp().globalData.theme
			if(opt){
				this.salesInfo = opt.data ? JSON.parse(opt.data) : null
			}
			this.init()
			
			const _this = this
			uni.getSystemInfo({
				success: function (res) {
					const winH = res.windowHeight * 2
					_this.scrollH = winH - 180
				}
			})
		},
		methods: {
			init(){
				this.getList(1)  // 产品列表
				this.selectedProductTotal()  // 已选产品合计
			},
			// 获取查询参数 刷新列表
			refresh(params){
				console.log('查询', params)
				const _this = this
				if(params.vinCode && params.vinCode.length == 17){
					// 查询vin码
					supperCodeByVin({ vin: params.vinCode }).then(res => {
						if(res.status == 200){
							params.productCodeList = res.data.partCodeList || []
							this.searchParams = params
							this.getList(1)
						}
					})
				}else{
					this.searchParams = params
					this.getList(1)
				}
			},
			// 列表
			getList(pageNo){
				const _this = this
				if (pageNo) {
					this.pageNo = pageNo
				}
				let params = {
					pageNo: this.pageNo,
					pageSize: this.pageSize
				}
				let searchParams = JSON.parse(JSON.stringify(this.searchParams))
				console.log(searchParams)
				if(searchParams){
					searchParams.brandName = undefined
					searchParams.nowData = undefined
					searchParams.warehouseName = undefined
					searchParams.cost = undefined
					searchParams.cityPrice = undefined
				}
				this.status = "loading"
				querySumByProductLocation(Object.assign(params, searchParams, { customerSn: this.salesInfo.buyerSn, salePriceType: this.salesInfo.priceType, salesBillSn: this.salesInfo.salesBillSn })).then(res => {
					if (res.status == 200) {
						if(res.data && res.data.list){
							res.data.list.map(item => {
								item.salesNums = 1
								item.currentQty = item.currentQty || 0
								item.price = item.lastSalePrice ? item.lastSalePrice : item.salePrice
							})
						}
						if(this.pageNo>1){
							this.listData = this.listData.concat(res.data.list || [])
						}else{
							this.listData = res.data.list || []
						}
						this.totalNum = res.data.count || 0
					} else {
						this.listData = []
						this.totalNum = 0
						this.noDataText = res.message
					}
					this.status = "loadmore"
				})
			},
			// scroll-view到底部加载更多
			onreachBottom() {
				if(this.listData.length < this.totalNum){
					this.pageNo += 1
					this.getList()
				}
			},
			// 添加/编辑产品
			handleAdd(data, type){
				if(type == 'add'){
					this.productInfo = {
						productName: data.productName,
						productMainImage: data.productMainImage,
						productCode: data.productCode,
						productOrigCode: data.productOrigCode,
						warehouseName: data.warehouseName,
						warehouseLocationName: data.warehouseLocationName,
						price: data.price,
						qty: 1
					}
				}else if(type == 'edit'){
					this.productInfo = {
						productName: data.productName,
						productMainImage: data.productMainImage,
						productCode: data.productCode,
						productOrigCode: data.productOrigCode,
						warehouseName: data.warehouseEntity && data.warehouseEntity.name,
						warehouseLocationName: data.warehouseLocationEntity && data.warehouseLocationEntity.name,
						price: data.price,
						qty: data.qty
					}
				}
				this.openProductModal = true
				this.chooseType = type
				this.productData = data
			},
			// 已选产品  编辑
			handleEdit(data){
				this.handleAdd(data, 'edit')
			},
			// 选好了
			handleChoose(){
				// uni.redirectTo({ url: '/pages/sales/edit?pageType=edit&data='+JSON.stringify(this.detailData) })
				uni.$emit("refreshEditBL")
				uni.navigateBack()
			},
			// 查看已选产品
			lookProduct(){
				this.openSelectedModal = true
			},
			// 确认产品信息
			productConfirm(data){
				this.editInfo = data
				if(this.chooseType == 'add'){
					this.validatePrice()  //验证  售价是否低于定价
				}else if(this.chooseType == 'edit'){
					this.validateStock()  //验证  库存是否不足
				}
			},
			// 售价低于定价
			validatePrice(){
				if (this.productData.lastSalePrice && (this.editInfo.price < this.productData.salePrice)) {  // 售价低于定价
					this.commonType = 1
					this.modalText = '售价低于定价，确认要添加吗？'
					this.commonModal = true
				}else{
					this.validateStock()  //验证  库存是否不足
				}
			},
			// 库存不足
			validateStock(){
				if(this.chooseType == 'add'){  // 添加产品
					if (this.productData.currentQty < this.editInfo.qty) {
						this.commonType = 2
						this.modalText = '库存不足，将产生急件，确认要添加吗？'
						this.commonModal = true
					}else{
						this.validateCost()  //验证  售价是否低于成本价
					}
				}else if(this.chooseType == 'edit'){  // 编辑产品
					//  校验库存
					stockByProductSn({ productSn: this.productData.productSn }).then(res => {
						if (res.status == 200) {
							if (res.data && (!res.data.currentStockQty || this.editInfo.qty <= res.data.currentStockQty)) {
								this.editProduct()
							} else {  // 库存不足
								this.commonType = 3
								this.modalText = '库存不足，将产生急件，确认修改吗？'
								this.commonModal = true
							}
						}
					})
				}
			},
			// 售价低于成本价
			validateCost(){
				if (this.productData.putCost > this.editInfo.price) {
					this.commonType = 4
					this.modalText = '售价低于成本价，确认要添加吗？'
					this.commonModal = true
				}else{
					this.addProduct()
				}
			},
			// 添加产品
			addProduct(){
				let params = {
					buyerSn: this.detailData.buyerSn,
					productSn: this.productData.productSn,
					cost: this.productData.putCost,
					price: this.editInfo.price,
					qty: this.editInfo.qty,
					salesBillSn: this.detailData.salesBillSn,
					salesBillNo: this.detailData.salesBillNo,
					warehouseSn: this.productData.warehouseSn,
					warehouseLocationSn: this.productData.warehouseLocationSn,
					stockSn: this.productData.stockSn
				}
				salesDetailInsert(params).then(res => {
					if(res.status == 200){
						this.toashMsg(res.message)
						this.changeList('add', params)  // 变更  列表产品可选状态
						this.selectedProductTotal()  // 已选产品合计
						this.commonModal = false
						this.openProductModal = false
					}
				})
			},
			// 编辑产品
			editProduct(){
				let params = {
					id: this.productData.id,
					qty: this.editInfo.qty,
					price: this.editInfo.price,
					productSn: this.productData.productSn,
					salesBillSn: this.detailData.salesBillSn,
				}
				salesDetailUpdate(params).then(res => {
					if(res.status == 200){
						this.toashMsg(res.message)
						this.$refs.selectedProducts.getList(1)
						this.changeList('add', params)  // 变更  列表产品可选状态
						this.selectedProductTotal()  // 已选产品合计
						this.commonModal = false
						this.openProductModal = false
					}
				})
			},
			// 更改产品列表参数
			changeList(type, obj){
				const _this = this
				// 查询已选产品列表中产品编码一致的产品，则为需要变更“已添加”状态的产品
				let params = {
					pageNo: 1,
					pageSize: 100,
					salesBillSn: this.detailData.salesBillSn,
					productSn: obj.productSn
				}
				salesDetailList(params).then(res => {
					if(res.status == 200){
						if(res.data && res.data.list){
							let listArr = []
							let listInd = []
							this.listData.filter(function(item, index){
								if(item.productSn == obj.productSn){
									listArr.push(item)
									listInd.push(index)
								}
							})
							let chooseList = res.data.list || []
							if(type == 'add'){
								console.log('添加', chooseList,'++',listArr)
								listArr.map((subItem, subInd) => {
									chooseList.map(item => {  // 已选产品 产品sn一致的数据
										if(subItem.productSn == item.productSn && subItem.warehouseLocationSn == item.warehouseLocationSn){
											_this.$nextTick(() => {
												_this.listData[listInd[subInd]].saleQty = 1  // 非0即可，用于判断是否显示添加产品按钮
											})
										}
									})
								})
								// 添加 产品总库存为0添加为急件时的情况
								if(chooseList.length == 1 && chooseList[0].oosFlag==1){
									_this.$nextTick(() => {
										_this.listData[listInd[0]].saleQty = 1  // 非0即可，用于判断是否显示添加产品按钮
									})
								}
							}else if(type == 'del'){
								console.log('删除', chooseList,'++',listArr)
								listArr.map((subItem, subInd) => {
									_this.$nextTick(() => {
										_this.listData[listInd[subInd]].saleQty = 0  // 非0即可，用于判断是否显示添加产品按钮
									})
								})
								listArr.map((subItem, subInd) => {
									chooseList.map(item => {  // 已选产品 产品sn一致的数据
										if(subItem.productSn == item.productSn && subItem.warehouseLocationSn == item.warehouseLocationSn){
											_this.$nextTick(() => {
												_this.listData[listInd[subInd]].saleQty = 1  // 非0即可，用于判断是否显示添加产品按钮
											})
										}
									})
								})
								this.selectedProductTotal()  // 更新产品款数
							}
						}
					}
				})
			},
			// 删除已选产品
			handleDel(data){
				this.changeList('del', data)  // 变更  列表产品可选状态
			},
			// 公共弹框  确定
			handleCommon(){
				if(this.commonType == 1){  // 添加产品时售价低于定价
					this.validateStock()  //验证  库存是否不足
				}else if(this.commonType == 2){  // 添加产品时库存不足
					this.validateCost()  //验证  售价是否低于成本价
				}else if(this.commonType == 3){  // 编辑产品时库存不足
					this.editProduct()
				}else if(this.commonType == 4){  // 添加产品时售价低于成本价
					this.addProduct()
				}
			},
			// 公共弹框  取消
			handleCancel(){
				this.openProductModal = false
			},
			// 已选产品合计
			selectedProductTotal(){
				salesDetail({ id: this.salesInfo.id }).then(res => {
					if(res.status == 200){
						this.detailData = res.data
					}else{
						this.detailData = null
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.chooseProduct-wrap{
		width: 100%;
		position: relative;
		height: 100vh;
		overflow: hidden;
		.padding_3{
			padding: 6upx 0;
		}
		.color_6{
			color: #666;
		}
		.product-list-box{
			padding: 14upx 20upx;
			.product-list-con{
				.product-list-item{
					background: #ffffff;
					padding: 20upx 20upx 0;
					margin-bottom: 25upx;
					border-radius: 25upx;
					box-shadow: 1px 1px 3px #EEEEEE;
					.list-item-tit{
						padding-bottom: 12upx;
						border-bottom: 1px solid #e4e7ed;
						.item-tit{
							font-weight: bold;
							color: rgb(48, 49, 51);
							font-size: 28upx;
							padding-left: 10upx;
							border-left: 6upx solid #000;
							line-height: 1;
						}
					}
					.list-item-con{
						padding: 14upx 0 16upx;
						font-size: 26upx;
						.pimgs{
							margin-right: 16upx;
						}
						.list-item-btn{
							width: 10%;
							text-align: center;
						}
					}
					.list-item-footer{
						border-top: 1px solid #e4e7ed;
						.footer-item{
							width: 50%;
							text-align: center;
							border-right: 1px solid #e4e7ed;
							font-size: 26upx;
							padding: 8upx 0 12upx;
						}
						.footer-item:last-child{
							border: none;
						}
					}
				}
			}
		}
		.selected-box{
			background-color: #fff;
			box-shadow: 1px -1px 3px #EEEEEE;
			.choose-info{
				padding: 0 30upx;
			}
			.choose-btn{
				color: #fff;
				width: 28%;
				padding: 26upx 0;
				text-align: center;
			}
		}
	}
</style>