<template>
	<!-- 添加外卖商品 -->
	<view class="productpages">		
		<view class="noecellbox">
			<view class="title" >产品名称</view>
			<view class="inputbox flex">
				<input class="input flex1"  type="text" v-model="form.product_name" value="" placeholder-class="plclass" placeholder="请填写产品名称"  />
			</view>
		</view>

			<view class="noecellbox" >
				<view class="title">商品库存(库存剩余{{form.code.length == 13 || form.code.length == 0?form.stock:form.stock/1000}}{{form.code.length == 13 || form.code.length == 0?'件':'kg'}})</view>
				<view class="inputbox flex">
					<radio-group @change="radioChanges">
						<view class="chindlost ali-c flex flex-wrap" >
							<view class="" style="margin-right: 20rpx;"  v-for="(item, index) in storeNumber" :key="item.value">
								<label class="lableitem flex ali-c" >
									<view>
										<radio  color="#FF6900" :value="item.value" :checked="item.checked == 1" />
									</view>
									<view class="titles">{{item.name}}</view>
								</label>
							</view>	
						</view>
					</radio-group>
					数量：<input class="input flex1" v-if=""  @input="bingInput" type="number" v-model="stock_number" value="" placeholder-class="plclass" placeholder="增加库存数量"  />
				</view>
			</view>
			
			<!-- <view class="noecellbox" >
				<view class="title">商品库存</view>
				<view class="inputbox flex">
					<input class="input flex1" v-if=""  type="number" v-model="stock_number" value="" placeholder-class="plclass" placeholder="增加库存数量"  />
				</view>
			</view> -->
			
			<view class="noecellbox" v-if="form.code !='' && form.code !=0">
				<view class="title" >条形编码</view>
				<view class="inputbox flex">
					<input class="input flex1" disabled="disabled" type="number" v-model="form.code" value="" placeholder-class="plclass" placeholder="请填写产品价格"  />
				</view>
			</view>
		<view class="" :hidden="linkage_product_id != 0 "  v-if="is_datashow">
	</view>
		<view class="submitbtn active" @tap="getForm">提交</view>
		
	</view>
</template>

<script>
	import QSApp from '@/components/QS-inputs-split/js/app.js';
	import {addEditEleProduct,typeManager,eleProductInfo,findEleProduct} from "@/utils/api/api.js";
	import{getskipShop,getshopclass} from "@/utils/api/merchant.js";
	
	import robbyImageUpload from '@/components/plan-image-upload/up_img';//上传资质图片组件
	import {getActivityList} from '@/utils/api/merchant.js';
	export default {
		components:{
			robbyImageUpload
		},
		data() {
			return {
				linkage_id:'',
				is_datashow:true,
				bools:'',
				linkage_product_id:'',
				classValue:'',
				ordinary :[],
				 weigh :[],
				classData:[
					['普通商品','称重商品'],
					[]
					],
				classDataValue:[0,0],
				is_bld:'',
				isadd:0,  //0 填写商品库存  1修改库存 
				stock_number:'',
				stockType:1,
				qualitYears:"",
				qualityMonths:"",
				qualityDays:"",
				sellType: [{
                    value: '1',
                    name: '计件（件）',
					checked:'1'
                }, {
                    value: '2',
                    name: '计重（kg）',
					checked:'2'
                }],
				storeNumber: [{
				    value: '1',
				    name: '增加库存',
					checked:'1'
				}, {
				    value: '2',
				    name: '减少库存',
					checked:'2'
				}],
				// issancodeType:1,
				ischeckedtime:[0],//默认选中，
				myProps: {
				      label: 'cate_name',
				      value: 'cate_id',
				},
				name: 'product',
				result:[],
				form: {
					
					 linkage_id:'',
					//cost_price 成本价 stock 商品库存purchase 进货价钱code 条形编码commission 返佣比例original_name 原始商品名
					specifications:'',//商品规格
					stock:'', //商品库存
					cost_price:'', //进货价钱
					code:'' ,//条形编码
					commission:'', //返佣比例
					sell_type:0,// 售卖类型
					commodity_data:{}, //原始商品名
					quality_guarantee_period:0, //保质期（月）
					manufacture_date:'' ,    //生产日期
					manufacturer :'',    ///生产厂商
					brand  :'',     // 品牌 
					checkbox: [],//断选
					product_id:"",//修改的时候的产品id
					product_name:"",//产品名称
					desc:"",//产品描述
					cate_id:"",//产品分类id
					photo:"",//产品图片
					lunch_box_fee:'',//餐盒费
					is_new:"",//是否新产品
					is_hot:"",//是否热卖产品
					action:"add",//	方式（添加：add，修改:edit）
					price:"",//价格
					activity_price:"",//秒杀价
					store_count:""	,// 秒杀库存
					is_seckill:"0",//0 1 是否秒杀产品
					activity_id:'0',//秒杀activity_id
					activity_list:'',//秒杀列表
					limit_num:"0" //秒杀限购数量 0 不限制 
				},
				timeList:[
					{}
				],
				isShow:false,
				chindformList:[],
				//上传图片相关的
				c_pics: [],
				c_photos: [],
				c_formData: {
					model:"shopphoto",
				},
				product_id:"",//修改产品时候用的修改id
				defaultinfo:{},//修改的时候的默认初始数据
				listchind:[
					{name:"是否新产品",value:"is_new",checked:false},
					{name:"是否热卖产品",value:"is_hot",checked:false},
				],
				isshowsetkilltime:false,//是否显示秒杀时间
				listissetkill:[{name:"是否秒杀产品",value:"is_seckill",checked:false}],
				activity_type:"",//判断是否可以秒杀
				seckilltimelist:[],//秒杀时段列表
				selchildList:[],
				cate_name:"",
				index:0,
				isScanCode:true,//是不是点击了扫码 
				codeDisabled:false,//条形码是否能输入
				update:true
			}
		},
		computed: {
			uploadurl1(){
				return this.$store.state.uploadurl1;
			},
			staticUrl(){
				return this.$store.state.staticUrl;
			},
			// startDate() {
			//      return '2020-11-20';
			// },
			// endDate() {
			//     return this.getDate('');
			// }
		},
		onLoad(opdata) {
			
			this.product_id = opdata.id
			
			getskipShop({
				type:'bld'
			}).then(res=>{
				if(res.code == 0){
					this.is_bld = res.data.is_bld
					// this.is_bld=1
					
				}
			})
			getshopclass({}).then(res=>{
				
				if(res.code == 0){
					this.ordinary = res.data.ordinary
					this.weigh = res.data.weigh
					this.classData[1] = Array.from(res.data.ordinary)
					if(this.ordinary.length!=[]){
					for(let i=0;i<res.data.ordinary.length;i++){
						this.classData[1][i] = res.data.ordinary[i].product_name	
						
					}
					}
				}
			})
			
			this.isadd = opdata.isadd
			this.c_formData.user_token = this.$store.state.token;
			this.activity_type = opdata.activity_type,
			this.isShow = this.activity_type==1?true:false
			
			this.typeManagerfun();
			this.getActivityListfun(); //获取数据列表

			
			// let results=JSON.parse(opdata.results);
		
			// this.issancodeType = opdata.results.issancodeType
			// this.isType = opdata.results.isType
		},
		methods: {
			
			columnbindData(e){
				
				this.classDataValue[e.detail.column]=e.detail.value;
				
				if(e.detail.column == 0){ 
					
					if(e.detail.value == 0){
						this.$set(this.classData,1,[]);
						if(this.ordinary.length!=0){
							this.ordinary.map(item=>{
								this.classData[1].push(item.product_name);
							})
						}
						
					}else {
						// this.classData[1] = [];
						this.$set(this.classData,1,[]);
						if(this.weigh.length!=0){
							this.weigh.map(item=>{
								this.classData[1].push(item.product_name);
							})
						}
						
					}
				}
			},
			bindData(e){
				let that = this
				if(e.detail.value[0] == 0){
					if(that.ordinary.length != 0){
						that.linkage_id = that.ordinary[e.detail.value[1]].product_id
						that.product_id = that.ordinary[e.detail.value[1]].product_id
						that.classValue = that.ordinary[e.detail.value[1]].product_name
					}else{AZ
						uni.showToast({
							title:'没有选中商品',
							icon:'none'
						})
						return false;
					}
				}else{

					if(that.weigh.length != 0){
						that.linkage_id = that.weigh[e.detail.value[1]].product_id
						that.product_id = that.weigh[e.detail.value[1]].product_id
						that.classValue = that.weigh[e.detail.value[1]].product_name
					}else{
						uni.showToast({
							title:'没有选中商品',
							icon:'none'
						})
						return false;
					}	
				}
				that.eleProductInfofun();
				this.is_datashow = false;
				
			},
			
			bingInput(e){
				let stock_number=e.detail.value;
				this.stock_number=stock_number;
				let stock=Number(this.form.stock);//库存
				let checked=this.storeNumber[1].checked;
				if(checked==1){
					if(stock-stock_number < 0 ){
						//this.$set(this,'stock_number',0);
						this.stock_number=0;
						
						this.$api.msg('库存不足')
					}
				}
				
			},
			bindDateChange: function(e) {
			      this.form.manufacture_date = e.target.value
			 },
			
			
			onCodeFocus(){  //条形码输入框聚焦事件
				if(this.codeDisabled){
					this.$api.msg('不能修改条形编码');
				}
			},
			async findEleProduct(results){
				uni.showLoading({title:'请稍后'});
				
				let res=await findEleProduct({code:results.code});
				uni.hideLoading();
				if(res.code==-1){ //没有就录入
					this.isadd=0;
					this.form.manufacturer = results.data.data.supplier
					this.form.brand   =   results.data.data.brand
					this.form.code=results.code;//条形码
					this.form.original_name = results.data.data.goodsName;
					this.form.product_name = results.data.data.goodsName;
					// this.c_pics = [{code:0,data:results.data.data.img,msg:"success",time:"1587101904"}];
					this.form.commodity_data = results.data.data;
					this.form.price=results.data.data.price;
					this.isScanCode=results.isScanCode;
					this.codeDisabled=false;//条形码输入框是否禁止输入
					
				}else if(res.code==0){ //有就把信息展示
					this.isadd=1;
					this.form.quality_guarantee_period = res.data.quality_guarantee_period
					this.qualitYears = parseInt(res.data.quality_guarantee_period/365)
					this.qualityMonths = parseInt((res.data.quality_guarantee_period%365)/30)
					this.qualityDays = parseInt((res.data.quality_guarantee_period%365)%30)
					
					this.form.manufacture_date = res.data.manufacture_date
					this.form.manufacturer = res.data.manufacturer
					this.form.brand = res.data.brand
					this.form.sell_type = res.data.sell_type,	
					
					this.form.stock=res.data.stock, //商品库存
					this.form.cost_price=res.data.cost_price, //进货价钱
					this.form.code=res.data.code ,//条形编码
					this.form.commission=res.data.commission, //返佣比例
					this.form.commodity_data=res.data.commodity_data, //原始商品名
					this.form.product_id=res.data.product_id,//修改的时候的产品id
					this.form.product_name=res.data.product_name,//产品名称
					this.form.desc=res.data.desc,//产品描述
					this.form.cate_id=res.data.cate_id,//产品分类id
					this.form.lunch_box_fee=res.data.lunch_box_fee,//餐盒费
					this.form.is_new=res.data.is_new,//是否新产品
					this.form.is_hot=res.data.is_hot,//是否热卖产品
					this.form.price=res.data.price,//价格
					this.form.activity_price=res.data.activity_price,//秒杀价
					this.form.store_count=res.data.store_count	,// 秒杀库存
					this.form.activity_id=res.data.activity_id,//秒杀activity_id
					this.form.activity_list=res.data.activity_list,//秒杀列表
					this.form.limit_num=res.data.limit_num//秒杀限购数量 0 不限制 
					this.isScanCode=false;
					this.codeDisabled=true;//条形码输入框是否禁止输入
					this.c_pics=[{code:0,data:res.data.photo,msg:"success",time:"1587101904"}];
					for(var i = 0; i < this.chindformList.length; i++) {
						 if(this.chindformList[i].cate_id==res.data.cate_id){
						 	this.cate_name=this.chindformList[i].cate_name;
							break;
						 }
					}
				}
			},
			saoma(e){
				uni.scanCode({
				    success:(res) => {
						var code =  res.result; 
						uni.request({
							url: 'https://www.mxnzp.com/api/barcode/goods/details', //仅为示例，并非真实接口地址。
							data: {
							    barcode:code,
								needImg: true,
								app_id:'qkkbptetyohxoiod',
								app_secret:'Wkp2a3NiNjAzTFJLRmwrZXN3QW1jZz09'
							},
							method:'GET',
							success: (results) => {
								if(results.data.code==0){
									this.$api.msg(results.data.msg);
								}else if(results.data.code==1){
									results.code=code;
									results.isScanCode=false;
									this.findEleProduct(results);
								}
							
							 }
							 
						})
				    },
					fail:(err)=>{
						
					}
				});
			},
			
			radioChange(e){
				 this.form.sell_type = e.detail.value
				 
			},
			
			radioChanges(e){	
				
				let index=Number(e.detail.value)-1;
				let storeNumber=this.storeNumber;
				storeNumber.map(item=>{
					item.checked=2;
				})
				storeNumber[index].checked=1;
				this.$set(this,'storeNumber',storeNumber);
				
				 
			},
			confirm(e){
				this.cate_name = e.item.cate_name;
				this.form.cate_id =e.item.cate_id;
				this.index = e.index;
			},
			pickerone(){
				this.$refs.picker.show() // 显示
			},
			
			isInt(e){
				if(!this.isInteger(e.detail.value)){
					this.$api.msg("秒杀库存或限购数量不能为小数");
				}
			},
			//分类选中
			bindPickerChange(e){
				this.cate_name = this.chindformList[e.detail.value].cate_name;
				this.form.cate_id = this.chindformList[e.detail.value].cate_id;
				this.index = e.detail.value;
				
			},
			//标记选中属性列表
			checkboxChange(e){
				this.selchildList = e.detail.value;
				this.isshowsetkilltime = e.detail.value.indexOf('is_seckill') ==-1? false:true;
				if(this.isshowsetkilltime){
					this.form.activity_list ="49,"
				}else{
					this.form.activity_list =""
				}
				this.selchildList = e.detail.value;
				
			},
			//修改的时候赋初始值
		 	async eleProductInfofun(){
				let res = await eleProductInfo({
					product_id:this.product_id,
				});
				if(res.code==0){	
					this.linkage_product_id = res.data.linkage_product_id
					this.bools = res.data.product_name;
					this.defaultinfo = res.data;
					this.form.product_name = res.data.product_name;//名称
					this.form.desc = res.data.desc;//描述
					this.form.lunch_box_fee = res.data.lunch_box_fee/100;//餐盒费
					this.form.price = res.data.price;//价格
					this.form.photo = res.data.photo;//图片
					this.form.activity_price = res.data.activity_price //秒杀价
					this.form.store_count = res.data.store_count //秒杀库存
					this.form.cate_id = res.data.cate_id;//分类id
					this.form.activity_id = res.data.activity_id//秒杀时段id
					this.form.limit_num = res.data.limit_num
					// this.classValue = res.data.product_name
					this.form.specifications = res.data.gram
					// quality_guarantee_period:this.qualitYears*365+this.qualityMonths*30+this.qualityDays, //保质期（月）
					// manufacture_date:'' ,    //生产日期
					// manufacturer :'',    ///生产厂商
					// brand  :'',     // 品牌 
					this.form.quality_guarantee_period = res.data.quality_guarantee_period
					this.qualitYears = parseInt(res.data.quality_guarantee_period/365)
					this.qualityMonths = parseInt((res.data.quality_guarantee_period%365)/30)
					this.qualityDays = parseInt((res.data.quality_guarantee_period%365)%30)
					this.form.manufacture_date = res.data.manufacture_date
					this.form.manufacturer = res.data.manufacturer
					this.form.brand = res.data.brand
					// 2020-10-22 添加字段
					this.form.stock = res.data.stock, 					//商品库存
					this.form.cost_price  =  res.data.cost_price/100, 				//进货价钱
					this.form.code  =  res.data.code ,						//条形编码
					this.form.commission  = res.data.commission, 				//返佣比例
					this.form.sell_type = res.data.sell_type,				// 售卖类型
					// this.form.commodity_data:{},			//原始商品名
					// 2020-10-22 添加字段
					
				
					
					
					// this.commodity_type = ordinary
					
					//下拉分类 初始值
					this.chindformList.forEach((item,index)=>{
						if(item.cate_id==res.data.cate_id){
							this.index =index;
							this.cate_name = item.cate_name;
						}
					});
					
					// this.classValue = res.data.product_name
					
					if(res.data.commodity_type == 'ordinary') {
						this.ordinary.map(item=>{
							if(this.linkage_product_id == item.product_id){
								this.classValue = item.product_name
							}
						}) 
					}else if(res.data.commodity_type == 'weigh'){
						
						this.weigh.map(item=>{
							if(this.linkage_product_id == item.product_id){
								this.classValue = item.product_name
							}

						})
						
					}else{
						this.classValue = '';
					}
						
					
					//属性选默认值
					if(res.data.is_new==1){
						this.selchildList.push("is_new");
						this.listchind[0].checked = true;
					}else{
						this.listchind[0].checked = false;
					}
					if(res.data.is_hot==1){
						this.selchildList.push("is_hot");
						this.listchind[1].checked = true;
					}else{
						this.listchind[1].checked = false;
					}
					
					if(res.data.activity_list == '49,'){
						this.listissetkill[0].checked = true
						this.isshowsetkilltime = true
						this.form.activity_list = res.data.activity_list
						
					let indexlist =	this.seckilltimelist.filter((item,index)=>{
						if(item.activity_id==this.form.activity_id){
							return item
						}
					})
					let temparr = indexlist[0] 
					let index = this.seckilltimelist.indexOf(temparr)
						this.ischeckedtime[0] = index
					}
					//处理上传的图片默认值
					this.c_pics = [{code:0,data:res.data.photo,msg:"success",time:"1587101904"}];
					this.form.photo = res.data.photo;
					this.c_photos = ["res.data.photo"]
					
				}else{
					this.$api.msg(res.msg);
				}
			},
			getForm() {
				if(this.isshowsetkilltime && (this.form.activity_price==""||this.form.store_count==""||this.form.limit_num=="") ){
					this.$api.msg("请填写完整秒杀数据");
					 return false;
				}
				if(!this.isInteger(this.form.limit_num) || !this.isInteger(this.form.store_count)){
					this.$api.msg("秒杀库存或限购数量不能为小数");
					return false;
				}
				
				// quality_guarantee_period = this.qualitYears*365 + this.qualityMonths*30 + this.qualityDays
				
				
				// if(this.c_pics.length == 0){
				// 	this.$api.msg('产品图片未上传');
				// }
				
				let can = {
					linkage_id:this.linkage_id,
					
					gram:this.form.specifications, //商品规格
					quality_guarantee_period : this.qualitYears*365+this.qualityMonths*30+this.qualityDays*1, //保质期（月）
					manufacture_date :this.form.manufacture_date,    //生产日期
					manufacturer: this.form.manufacturer,    ///生产厂商
					brand  : this.form.brand,     // 品牌 
					// stock:this.form.stock, //商品库存
					cost_price:this.form.cost_price, //进货价钱
					code:this.form.code,//条形编码
					sell_type:this.form.sell_type,
					commission:this.form.commission, //返佣比例
					commodity_data:this.form.commodity_data, //产品数据
					product_name:this.form.product_name,//产品名称
					desc:this.form.desc,//产品描述
					lunch_box_fee:this.form.lunch_box_fee,//餐盒费
					action:this.form.action,//方式（添加：add，修改:edit）
					price:this.form.price,//价格
					cate_id:this.form.cate_id,
					photo:this.c_pics[0].data, //图片
					activity_price:this.form.activity_price,//秒杀价
					store_count:this.form.store_count ,//秒杀库存
					activity_id:this.form.activity_id,//秒杀时间id
					activity_list:this.form.activity_list,
					limit_num:this.form.limit_num ,//秒杀限购数量	
				};
				
					this.storeNumber.map((item,index)=>{
						if(item.checked==1){
							if(index==0){
								can.stock = this.stock_number
							}else{
								can.stock = '-'+ this.stock_number
							}
							
						}
					})
					
				// if(this.stockType==1){
				// 	can.stock = this.stock_number
				// }else{
				// 	can.stock = '-'+this.stock_number
				// }
				
				
				if(this.selchildList.includes("is_new")){
					can.is_new = 1;
				}else{
					can.is_new = 0;
				}
				if(this.selchildList.includes("is_hot")){
					can.is_hot = 1;
				}else{
					can.is_hot = 0;
				}
				if(this.product_id!="" && this.is_datashow !=false ){ 
					can.action = "edit";
					can.product_id = this.product_id;
				}
				//添加修改外卖产品
				addEditEleProduct(can).then((res1)=>{
					if(res1.code==0){
						this.$api.msg(res1.msg);
						setTimeout(()=>{
							// let pages = getCurrentPages()
							// var prevPage = pages[pages.length - 2]; 
							// prevPage.$vm.searchProduct();
							uni.navigateBack({});
						},1000)
					}else{
						this.$api.msg(res1.msg);
					}
				})
			},
			
			pickerChange(e){
				this.form.activity_id  = this.seckilltimelist[e.detail.value[0]].activity_id;
			},
			// 秒杀列表
			async getActivityListfun(){
				let res = await getActivityList({
					audit:2,
				})
				if(res.code==0){
					this.seckilltimelist =  res.data.head
				}
			},
			//获取外卖分类列表 用于下拉选择
			async typeManagerfun(){
				let res = await typeManager({});
				if(res.code==0){
					this.chindformList = res.data;
					if(this.product_id!=undefined && this.product_id!=""){
						this.eleProductInfofun();
					}
				}else{
					this.$api.msg(res.msg);
				}
			},
			// 判断是否为整数
			isInteger(obj){
				return  obj%1 === 0;
			},
			//图片上传
			c_delImage(e) {
				let arr = []
				for (let k in e.allImages) {
					arr[k] = e.allImages[k].id
				}
				this.c_photos = arr
			},
			c_onImg1(e) {
				this.isScanCode=true;
				this.c_pics = e.allImages
				const obj = e.allImages
				for (let index in obj) {
					let id = obj[index].data
					this.c_photos[index] = id
				}
			},
			onMove_c(e) {
				this.c_pics = e;
				const obj = e
				for (let index in obj) {
					let id = obj[index].data
					this.c_photos[index] = id
				} 
			}
		},
	}
</script>


<style lang="scss">
	@import  "../edit/product/addProjuct.scss";
	page{
		background: #fff;
	}
	.productpages{
		background: #FFFFFF;
	}
	
	.submitbtn{
		margin: 60upx 24upx;
		height:88upx;
		line-height: 88upx;
		text-align: center;
		background:rgba(254,197,156,1);
		border-radius:6upx;
		font-size:32upx;
		color:rgba(255,255,255,1);
	}
	
	.submitbtn.active{
		background: #FF6900;
	}
	.briefIntroduction,.Specificationsbox,.addmigs,.checkboxs{
		border-bottom:1px solid #F5F2F2;
		border-radius: 0 !important;
	}
	.img{
		width: 100upx;height: 100upx;
	}
	.input1::-ms-input-placeholder {
	    text-align: center;
	}
	 
	.input1::-webkit-input-placeholder {
	    text-align: center;
	}
</style>