<template>
	<view class="flex flex_column choosePartByVin">
		<!-- 头部车辆信息 -->
		<div class="flex align-center cpb_header" v-if="carInfo">
			<div>
				<u-image border-radius="30" :src="carInfo.icon" width="100" height="100" bg-color="#EBEBEB" ></u-image>
			</div>
			<div>
				<div class="flex align-center">
					<div class="carTits ellipsis-two">{{modelLabel||''}}</div>
				</div>
				<div class="flex align-center">
					<div>VIN码：{{vinNumber}}</div>
					<div class="copyText" @click="copyVin"><span>复制</span></div>
				</div>
				<view style="font-size: 0.8em;color: dodgerblue;margin-top: 0.5em;" v-if="dealerPhone" @click="callPhone()">
					<u-icon size="30" name="phone" color="dodgerblue"></u-icon><text>联系汽配商</text>
				</view>
			</div>
		</div>
		<!-- 配件列表 -->
		<div class="cpb_middle flex">
			<div class="slider-bar">
				<div class="tabs">
					<view :class="[curLeve2 == 'all' ? 'active' : '']" @click="selLeve2('all')">
						全部
					</view>
					<view :class="[curLeve2 == item.id ? 'active' : '']" v-for="(item, index) in leve2Data" :key="index" @click="selLeve2(item.id)">
						{{item.label}}
					</view>
				</div>
			</div>
			<div class="right-list">
				<scroll-view
				class="right-list-content" 
				scroll-y 
				@scrolltolower="onreachBottom">
					<!-- vin适配配件 -->
					<view>
						<view class="nav-right-title">适配推荐</view>
						 <view class="nav-right-item flex" v-for="(item, index) in vinPartList" :key="item.productSn">
						 	<view class="uni-col-2">
						 		<u-image :src="item.images+'?x-oss-process=image/resize,m_fixed,h_120,w_120,color_ffffff'" @click="viewImg(item)" border-radius="30" width="100" height="100" bg-color="#EBEBEB" ></u-image>
						 	</view>
						 	<view class="item-info uni-col-10">
						 		<view class="item-name">
						 			<text>{{item.name}}</text>
						 		</view>
						 		<view class="item-detail">
									<view class="item-detail-info">
										<view class="flex justify_between">
											<text class="item-detail-text flex_1">{{item.code}}</text>
											<text class="item-detail-text" v-if="item.affiliation=='SHELF'">库存：{{item.currentInven?item.currentInven:0}} {{item.unit}}</text>
										</view>
										<view class="flex justify_between">
											<view class="item-detail-text flex_1">
												<text class="item-price" v-if="item.affiliation=='SHELF'">￥{{item.price||0}}</text>
											</view>
											<view class="item-detail-text" v-if="item.currentInven">
												<u-button shape="circle" @click="addPart(item)" v-if="!item.checked" :custom-style="{width:'48upx',height:'48upx'}" type="primary" size="mini">
													<u-icon name="plus" color="#fff" size="28"></u-icon>
												</u-button>
												<u-number-box v-else @change="updateVinNums" @blur="updateVinNums" v-model="item.qty" :index="item.productSn" :min="0" :max="item.currentInven"></u-number-box>
											</view>
											<view class="item-detail-text" v-if="item.affiliation=='SUPER_CATALOGUE'||!item.currentInven">
												<text v-if="!item.checked" @click="addPart(item)" class="phtxt">我要临配</text>
												<u-number-box v-else @change="updateVinNums" @blur="updateVinNums" v-model="item.qty" :index="item.productSn" :min="0"></u-number-box>
											</view>
										</view>
									</view>
						 			<view class="nav-right-item-btns flex align_center justify_between">
						 				<view>
						 				</view>
						 			</view>
						 		</view>
						 	</view>
						 </view>
						 <view v-if="vinPartList&&vinPartList.length==0">
						 	<u-empty v-if="vinStatus!='loading'" :src="`/static/nodata.png`" icon-size="180" text="暂无适配推荐" mode="list" :margin-top="30"></u-empty>
						 </view>
						 <view style="padding: 20upx;">
						 	<u-loadmore v-if="vinStatus=='loading'" :status="vinStatus" />
						 </view>
					</view>
					<!-- 其它配件 -->
					<view class="nav-right-title flex align_center justify_between" @click="showOther=!showOther" style="margin-top: 20rpx;">
						其它配件
						<text>{{showOther?'隐藏':'展开'}}</text>
					</view>
					<view class="nav-right-item flex" v-if="showOther" v-for="(item, index) in partList" :key="item.productSn">
						<view class="uni-col-2">
							<u-image :src="item.images+'?x-oss-process=image/resize,m_fixed,h_120,w_120,color_ffffff'" @click="viewImg(item)" border-radius="30" width="100" height="100" bg-color="#EBEBEB" ></u-image>
						</view>
						<view class="item-info uni-col-10">
							<view class="item-name">
								<text>{{item.name}}</text>
							</view>
							<view class="item-detail">
								<view class="item-detail-info">
									<view class="flex justify_between">
										<text class="item-detail-text flex_1">{{item.code}}</text>
										<text class="item-detail-text">库存：{{item.currentInven?item.currentInven:0}} {{item.unit}}</text>
									</view>
									<view class="flex justify_between">
										<view class="item-detail-text flex_1">
											<text class="item-price">￥{{item.price||0}}</text>
										</view>
										<view class="item-detail-text" v-if="item.currentInven">
											<u-button shape="circle" @click="addPart(item)" v-if="!item.checked" :custom-style="{width:'48upx',height:'48upx',background:'#066cff'}" type="primary" size="mini">
												<u-icon name="plus" color="#fff" size="28"></u-icon>
											</u-button>
											<u-number-box v-else @change="updateNums" @blur="updateNums" v-model="item.qty" :index="item.productSn" :min="0" :max="item.currentInven"></u-number-box>
										</view>
										<view class="item-detail-text" v-else>
											<text @click="addPart(item)" v-if="!item.checked" class="phtxt">我要临配</text>
											<u-number-box v-else @change="updateNums" @blur="updateNums" v-model="item.qty" :index="item.productSn" :min="0"></u-number-box>
										</view>
									</view>
								</view>
								<view class="nav-right-item-btns flex align_center justify_between">
									<view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-if="partList&&partList.length==0">
						<u-empty v-if="status!='loading'" :src="`/static/nodata.png`" icon-size="180" :text="noDataText" mode="list" :margin-top="150"></u-empty>
					</view>
					<view style="padding: 20upx;">
						<u-loadmore v-if="total>pageSize || status=='loading'" :status="status" />
					</view>
				</scroll-view>
			</div>
		</div>
		<!-- 底部提交按钮 -->
		<div class="cpb_footer flex align-center" :class="isIphoneXup?'isIPXup':''">
			<div>
				<div class="cpb_cart" @click="openCart">
					<u-badge type="error" :count="cartNums" :offset="[-4,-4]" bgColor="#FF5200"></u-badge>
					<u-image width="44" height="44" :src="`/static/icon_shopping@3x.png`"></u-image>
				</div>
			</div>
			<div>
				<u-button type="primary" :loading="saveLoading" @click="submitForm" :custom-style="{background:'#066cff',fontSize:'32rpx'}" shape="circle">立即提交</u-button>
			</div>
		</div>
		<!-- 已选配件 购物车 -->
		<div class="cpb_cart-mask" v-if="showCart">
			<div class="cpb_cart-box">
				<div class="cpb_close flex align-center justify_center" @click="showCart=false"><u-icon name="close"></u-icon></div>
				<div class="cpb_cart-tit">
					已选配件
				</div>
				<div class="cpb_cart-list">
					<view class="nav-right-item flex" v-for="(item, index) in partListData" :key="item.productSn">
						<view class="uni-col-2">
							<u-image border-radius="30" :src="item.images" width="100" height="100" bg-color="#EBEBEB" ></u-image>
						</view>
						<view class="item-info uni-col-10">
							<view class="item-name">
								<text class="item-tempPart" v-if="!item.currentInven">临配</text>
								<text>{{item.name}}</text>
							</view>
							<view class="item-detail">
								<view class="item-detail-info">
									<view class="flex justify_between">
										<text class="item-detail-text flex_1">{{item.code}}</text>
										<text class="item-detail-text" v-if="item.affiliation!='SUPER_CATALOGUE'">库存：{{item.currentInven?item.currentInven:0}} {{item.unit}}</text>
									</view>
									<view class="flex justify_between">
										<view class="item-detail-text flex_1">
											<text class="item-price" v-if="item.affiliation!='SUPER_CATALOGUE'">￥{{item.price||0}}</text>
										</view>
										<view class="item-detail-text">
											<u-number-box @change="updateCartNums" @blur="updateCartNums" v-model="item.qty" :index="'cart_'+item.productSn" :min="0" :max="item.currentInven||999999"></u-number-box>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</div>
			</div>
		</div>
		<!-- 去认证 -->
		<u-popup v-model="showPopup" mode="center" :border-radius="20" closeable>
			<view style="background-color: #fff;padding:1rem;">
				<u-image width="533" height="415" src="/static/authimg.jpg"></u-image>
				<view style="padding-top:1rem;" class="flex justify_center">
					<u-button @click="toAuthStore()" shape="circle" :custom-style="{background:'#066cff',color:'#fff',width:'350rpx'}">开始认证</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import { getShelfProductList, getShelfProductType, queryPartCodeByVin, getShelfQueryList, saveShelfOrder } from '@/api/shelf'
	export default {
		data() {
			return {
				showOther: false,
				theme: '',
				vinNumber: '',
				leve2Data: [],  //  二级菜单数据
				curLeve2: '',  //  当前所选二级菜单
				carInfo: null,
				status: 'loading',
				vinStatus: 'loading',
				noDataText: '暂无配件',
				pageNo: 1,
				pageSize: 10,
				total: 0, // 列表总数
				noMore: false ,// 没有更多
				showCart: false, // 购物车
				carList:[], // 车型列表
				partList: [], // 配件列表
				partListData: [], // 已选配件
				vinPartList: [],
				isIphoneXup: false,
				saveLoading: false,
				showPopup: false
			}
		},
		computed:{
			modelLabel(){
				return this.carInfo&&this.carInfo.text||''
			},
			cartNums(){
				let ret = 0
				this.partListData.map(item => {
					ret = ret + item.qty
				})
				return ret
			},
			dealerPhone(){
				const shelfInfo = this.$store.state.vuex_storeShelf
				return shelfInfo&&shelfInfo.contactMobile ? shelfInfo.contactMobile : ''
			},
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
			storeApply(){
				return this.$store.state.vuex_storeAuthInfo || null
			}
		},
		onLoad(opts) {
			this.theme = getApp().globalData.theme
			this.vinNumber = opts.vinNumber
			this.carInfo = opts.carList?JSON.parse(decodeURIComponent(opts.carList)):null
			// 获取vin 对应code
			this.getCarCodeByVin()
			
			// 游客
			if(this.userInfo.sysUserFlag == '0'){
				// 未认证
				if(!this.storeApply || this.storeApply&&!this.storeApply.auditStatus){
					this.showPopup = true
				}
			}
		},
		onShow() {
			this.$store.state.vuex_shelfChoosePart = []
		},
		methods: {
			toAuthStore(){
				this.showPopup = false
				uni.navigateTo({
					url: '/pages/storeManage/storeAuth'
				})
			},
			callPhone() {
				if(this.dealerPhone!=''){
					uni.makePhoneCall({
						phoneNumber: this.dealerPhone
					})
				}
			},
			viewImg(item){
				uni.previewImage({
					urls: [item.images]
				})
			},
			// 复制
			copyVin(){
				uni.setClipboardData({
					data: this.vinNumber||'',
				})
			},
			// 格式化标签数据和配件分类数据一样
			labelToPart(data){
				let arr = []
				data.map(item => {
					arr.push({
						id: item.id || item.productTypeSn,
						label: item.name
					})
				})
				return arr
			},
			getCarCodeByVin(){
				queryPartCodeByVin({vinNumber:this.vinNumber}).then(res => {
					console.log(res,'this.vinCode')
					this.vinCode = res.data
					this.getShelfProductType()
				})
			},
			// 获取数字货架分类作为二级分类
			getShelfProductType(){
				const storeShelf = this.$store.state.vuex_storeShelf
				getShelfProductType({
					codeList: this.vinCode,
					shelfSn: storeShelf?storeShelf.shelfSn:''
				}).then(res => {
					console.log(res,'getShelfProductType')
					this.leve2Data = this.labelToPart(res.data || [])
					// 默认该车适用或全部
					this.selLeve2('all')
				})
			},
			// 单击二级菜单
			selLeve2 (v) {
				this.pageNo = 1
				this.partList = []
				this.vinPartList = []
				this.curLeve2 = v
				if(this.vinNumber){
					this.getVinShelfPartList()
				}
				this.getShelfProductList()
			},
			 // 获取数字货架配件列表
			 getShelfProductList(){
			 	const _this = this
			 	let params = {
			 	    pageNo: this.pageNo,
			 	    pageSize: this.pageSize,
			 		excludeCodeList: this.vinCode,
			 		productTypeSn: this.curLeve2 == 'all' ? '' : this.curLeve2
			 	}
			 	_this.status = 'loading'
			 	getShelfProductList(params).then(res => {
					console.log(res,'获取数字货架配件列表')
			 		uni.hideLoading()
			 		if(res.status == 200){
			 			let list = res.data.list
			 			if (list && list.length){
			 				// 分页 拼接数据
			 				if (_this.pageNo != 1) {
			 					_this.partList = _this.partList ? _this.partList.concat(this.fiterChecked(list)) : this.fiterChecked(list)
			 				} else {
			 					_this.partList = this.fiterChecked(list)
			 				}
			 				this.total = res.data.count
			 				if (_this.partList.length == res.data.count) {
			 					_this.status = 'nomore'
			 				} else {
			 					_this.status = 'loadmore'
			 				}
			 			} else {
			 				_this.partList = list || []
			 				this.total = 0
			 				_this.status = 'nomore'
			 			}
			 			_this.noDataText = '暂无配件'
			 		}else{
			 			_this.status = 'loadmore'
			 			_this.partList = []
			 			this.total = 0
			 			_this.noDataText = res.message ? res.message : '网络似乎出错了，请稍后再试'
			 		}
			 	})
			 },
			// 根据客户vin查询该车可用数字货架中的配件
			getVinShelfPartList(){
				let params = {
				      queryWord: this.queryWord,
				      productTypeSn: this.curLeve2 == 'all' ? '' : this.curLeve2,
					  codeList: this.vinCode
				  }
				this.vinStatus = 'loading'
				getShelfQueryList(params).then(res => {
					this.vinPartList = this.fiterChecked(res.data || []) 
					this.vinStatus = 'nomore'
				})
			},
			// 过滤已选择的
			fiterChecked (list){
				this.partListData.map(item => {
					let p = list.find(k => {
						return k.productSn == item.productSn
					})
					if (p){
						p.checked = true
						p.qty = item.qty
					}
				})
				return list
			},
			// 加载更多
			onreachBottom () {
				if(this.partList.length < this.total ){
					this.pageNo++
					this.getShelfProductList()
				}else{
					this.status = "nomore"
				}
			},
			// 添加到购物车
			addPart(item){
				item.checked = true
				item.qty = 1
				this.partListData.unshift({
					id: item.id,
					productSn: item.productSn,
					name: item.name,
					unit: item.unit,
					price: item.price,
					cost: item.cost,
					currentInven: item.currentInven,
					code: item.code,
					qty: item.qty,
					images: item.images,
					checked: true,
					affiliation: item.affiliation
				})
			},
			// 更新配件列表数量
			updatePartList(data,type){
				const prow = this[type].find(item => item.productSn == data.index)
				const index = this.partListData.findIndex(item => item.productSn == data.index)
				// 删除
				if(!data.value){
					prow.checked = false
					if(index>=0){
						this.partListData.splice(index,1)
					}
					if(this.partListData.length==0){
						this.showCart = false
					}
				}else{
					this.partListData[index].qty = data.value
					this.partListData.splice()
				}
			},
			// 修改适配配件上数量
			updateVinNums(data){
				this.updatePartList(data,'vinPartList')
			},
			// 修改其它配件上的数量
			updateNums(data){
				this.updatePartList(data,'partList')
			},
			// 点击购物车修改数量
			updateCartNums(data){
				console.log(data)
				if(!data.value){
					const index = this.partListData.findIndex(item => 'cart_'+item.productSn == data.index)
					if(index>=0){
						this.partListData.splice(index,1)
					}
					if(this.partListData.length==0){
						this.showCart = false
					}
				}
				// 同步更新Vin适配配件列表上的
				const vinprow = this.vinPartList.find(item => 'cart_'+item.productSn == data.index)
				if(vinprow){
					vinprow.qty = data.value
					vinprow.checked = !!data.value
					this.vinPartList.splice()
				}
				// 同步更新其它配件列表上的
				const prow = this.partList.find(item => 'cart_'+item.productSn == data.index)
				if(prow){
					prow.qty = data.value
					prow.checked = !!data.value
					this.partList.splice()
				}
			},
			// 打开购物车
			openCart(){
				if(this.partListData.length){
					this.showCart=!this.showCart
				}else{
					uni.showToast({
						icon: 'none',
						title: '请选择配件'
					})
				}
			},
			// 格式化数据
			formatData(){
				const partList = []
				const tempList = []
				this.partListData.map(item => {
					if(item.currentInven){
						partList.push({
							"productSn": item.productSn,
							"totalQty": item.qty
						})
					}else{
						tempList.push({
							"productSn": item.productSn,
							"qty": item.qty,
							"price": item.cost
						})
					}
				})
				return [partList,tempList]
			},
			// 立即提交
			submitForm(){
				// 游客去认证
				if(this.userInfo.sysUserFlag == '0'){
					// 未认证
					if(!this.storeApply || this.storeApply&&!this.storeApply.auditStatus){
						this.showPopup = true
					}
					// 认证通过
					if(this.storeApply&&(this.storeApply.auditStatus=='WAIT' || this.storeApply.auditStatus == 'REFUSE')){
						uni.showModal({
							title: '提示',
							content: this.storeApply.auditStatus=='WAIT' ? '门店认证资料审核中，请耐心等待！' : '门店认证资料审核不通过，请重新提交审核！',
							confirmText: '好的',
							showCancel: false
						})
					}
				}else{
					// 已认证用户
					if(this.partListData.length==0){
						uni.showToast({
							icon: 'none',
							title: '请选择配件'
						})
						return
					}
					
					// 开始提交
					const params = {
						shelfOrderDetailList: this.formatData()[0],
						tempBillDetailList: this.formatData()[1],
						vin: this.vinNumber,
						vehicleModel: this.modelLabel || '',
						vehicleLogo: this.carInfo.icon||'',
					}
					console.log(params,'立即提交')
					this.saveLoading = true
					saveShelfOrder(params).then(res => {
						console.log(res,'saveShelfOrder')
						if(res.status == 200){
							// 提交成功
							uni.redirectTo({
								url:"/pages/digitalShelf/choosePartResult?data="+encodeURIComponent(JSON.stringify(res.data))+"&state=1"
							})
						}else{
							// 或失败
							uni.redirectTo({
								url:"/pages/digitalShelf/choosePartResult?data="+encodeURIComponent(JSON.stringify({shelfOrder:{remindMessage:res.message}}))+"&state=0"
							})
						}
						this.saveLoading = false
					})
				}
			}
		}
	}
</script>

<style lang="less">
.choosePartByVin{
	height: 100vh;
	.cpb_header{
		background-color: #FFFFFF;
		padding: 10rpx;
		align-items: center;
		> div{
			padding: 10rpx;
			align-items: center;
			&:first-child{
				padding-right: 20rpx;
			}
			> div{
				&:first-child{
					padding-right: 20rpx;
					flex-grow: 1;
					color: #818b94;
					font-size: 24rpx;
				}
			}
		}
		.copyText{
			background-color: #EBEBEB;
			border-radius: 100rpx;
			padding: 0 20rpx;
			color: #033692;
			font-size: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 20rpx;
		}
		.carTits{
			font-size: 32rpx;
			font-weight: bold;
			color: #222222;
			line-height: normal;
			margin-bottom: 10rpx;
			flex-grow: 1;
		}
		.qhbtns{
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			color: #0485F6;
			border:2rpx solid #0485F6;
			border-radius: 50rpx;
			background: rgba(88, 177, 255, 0.2);
			width: 200rpx;
			height: 36rpx;
			margin-left: 10rpx;
		}
	}
	.cpb_middle{
		flex-grow: 1;
		padding-top: 10rpx;
		overflow: auto;
		.slider-bar{
			width: 25%;
			background: #F5F6F7;
			height: 100%;
			overflow: auto;
			.tabs{
				> view{
					border-left: 6rpx solid #F5F6F7;
					padding: 30rpx 10rpx;
					font-size: 30rpx;
					color: #666E75;
				}
				.active{
					border-color: #0485F6;
					color: #0485F6;
					background: #fff;
				}
			}
		}
		.right-list{
			flex-grow: 1;
			background: #fff;
			height: 100%;
			width: 75%;
			.right-list-content{
				height: 100%;
				.nav-right-title{
					font-weight: bold;
					padding: 5upx 25upx;
					> text{
						color: #9E9E9E;
						font-weight: normal;
					}
				}
				.nav-right-item{
					padding: 15upx 25upx;
					border-bottom: 2rpx solid #f5f5f5;
					.item-info{
						padding-left: 20upx;
						flex-grow: 1;
						.item-name{
							font-size: 32upx;
							color: #191919;
							display: flex;
							align-items: center;
							>image{
								width: 38rpx;
								height: 38rpx;
								margin-right: 10rpx;
							}
							>text{
								flex: 1;
								word-break: break-all;
							}
						}
						.item-detail{
							.item-detail-info{
								padding: 10upx 0 4upx;
								> view{
									padding-bottom: 10rpx;
									align-items: center;
									.item-detail-text{
										color: #999;
										.phtxt{
											color: #0485F6;
											font-size: 28upx;
										}
										.item-price{
											color: #FB1E1E;
											font-size: 28upx;
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	.cpb_footer{
		padding: 20rpx;
		background-color: #fff;
		align-items: center;
		justify-content: space-between;
		.cpb_cart{
			width: 84rpx;
			height: 84rpx;
			background-color: #0485F6;
			border-radius: 200rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
		}
		> div{
			&:last-child{
				width: 40%;
			}
		}
	}
	.cpb_cart-mask{
		position: fixed;
		width: 100%;
		background: rgba(0,0,0,0.5);
		z-index: 900;
		bottom: 120rpx;
		top: 0;
	}
	.cpb_cart-box{
		background-color: #fff;
		position: absolute;
		width: 100%;
		z-index: 1000;
		bottom: 0;
		padding: 20rpx 0;
		border-radius: 30rpx 30rpx 0 0;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
		.cpb_close{
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			width: 70rpx;
			height: 70rpx;
			font-size: 32rpx;
			color: #999;
		}
		.cpb_cart-tit{
			text-align: center;
			padding: 20rpx;
			font-size: 36rpx;
		}
		.cpb_cart-list{
			padding: 20rpx 30rpx;
			overflow: auto;
			flex-grow: 1;
			> view{
				margin-bottom: 30rpx;
			}
			.item-name{
				font-size: 32rpx;
				.item-tempPart{
					background: #0055ff;
					color: #fff;
					border-radius: 1em;
					font-size: 0.8em;
					padding: 0 0.5em;
				}
			}
			.item-info{
				border-bottom:2rpx solid #f8f8f8;
				flex-grow: 1;
				padding-left: 0.8em;
			}
			.item-detail{
				.item-detail-info{
					padding: 10upx 0 4upx;
					> view{
						padding-bottom: 30rpx;
						align-items: center;
						.item-detail-text{
							color: #999;
							.phtxt{
								color: #0485F6;
								font-size: 28upx;
							}
							.item-price{
								color: #FB1E1E;
								font-size: 28upx;
							}
						}
					}
				}
			}
		}
	}
}
</style>
