<template>
	<view class="container" v-if="query">
		<xinsoft-form-input :itemDefine='itemDefine1' :bindSource.sync="dataItem1" @toSearch='searchFacility'></xinsoft-form-input>
		<!-- <xinsoft-form-input :itemDefine='itemDefine2' :bindSource.sync="dataItem2" @toScan='scanFacilityLocation'></xinsoft-form-input> -->
		<xinsoft-form-input :itemDefine='itemDefine2' :bindSource.sync="dataItem2" @toSearch='searchFacilityLocation' @toScan='scanFacilityLocation'></xinsoft-form-input>
		<view class="supplier" v-if="qrCodeProps.supplierId">供应商:{{qrCodeProps.supplierName}}</view>
		<xinsoft-scan :qrCodeProps.sync='qrCodeProps' @submitData='submitData' ></xinsoft-scan>
	<!-- //搜索仓库列表 -->
	<chooseFacilitySingle :showsearch.sync="show_search_facility"
				:itemInfo_.sync="search_value_facility"></chooseFacilitySingle>
	<!-- //搜索仓位列表 -->		
	<chooseFacilityLocationSingle :showsearch.sync="show_search_location" :facilityId='facilityId'
	:itemInfo_.sync="search_value_location"></chooseFacilityLocationSingle>
	<view class="goHome" @click='goMain()'>
		<img src="@/static/img/gohome.png">
	</view>
	</view>
</template>

<script>
	import jweixin from '@/jweixin-module/index.js';
	import xinsoftFormInput from '@/components/xinsoft-form-input/xinsoft-form-input.vue'
	//搜索仓库列表
	import chooseFacilitySingle from '@/components/xinsoft-search-list/chooseFacilitySingle.vue'
	//搜索仓位列表
	import chooseFacilityLocationSingle from '@/components/xinsoft-search-list/chooseFacilityLocationSingle.vue'
	//扫码组件
	import xinsoftScan from '@/components/wms/xinsoft-scan.vue'
	export default {
		components: {
			xinsoftFormInput,chooseFacilitySingle,chooseFacilityLocationSingle,xinsoftScan
		},
		data() {
			return { 
				userId:'',
				deptId:'',
				query:false,
				qrCodeProps:{
					title:'扫码入库明细',
					countType:'入库数量',
					qrCodeDetailUrl:'/apis/scm/qrcode/inDetail',
					countEdit:true,//入库/出库数量是否有disabled. true数量不可修改,false数量可修改
					supplierId:'',//供应商id
					inType:2,//入库类型 0：采购入库，1：生产入库，2：委外入库，3：其他入库
					isMultiple:1,//是否多单入库 1：是，0：否
					contractNo:'',//合同号
				supplierName:'',//供应商
				id:'',//源单id
				},
				itemDefine1:{
						title: "仓库",
						fieldName: "valueName",
						type: "kd-vlookup-edit",
						required: true,
						disabled: true,
						placeholder: "",
						canClear:false,//是否带清空按钮
				},
				dataItem1:{
					valueName: "",
				},
				itemDefine2:{
						title: "仓位",
						fieldName: "valueName",
						// type: "kd-vlookup-scan",
						type: "kd-vlookup-scan-edit",
						required: false,
						disabled: true,
						placeholder: "",
						canClear:false
				},
				dataItem2:{
					valueName: "",
				},
				show_search_facility:false,//显示仓库搜索列表
					search_value_facility:[],//选择的仓库信息
				show_search_location:false,//显示仓位搜索列表
					search_value_location:[],//选择的仓位信息
					facilityId:'',//选的仓库id，
					facilityLocationId:'',//选的仓位id，
				}
			},
			mounted() {
				let _this=this;
				uni.getStorage({
				    key: 'userInfo',
				    success: function (res) {
						_this.userId=res.data.userId
						_this.deptId=res.data.deptId
				    }
				});
				let query=this.$route.query;
				if(query.contractNo){//获取列表页带过来的参数
					this.qrCodeProps.contractNo=decodeURIComponent(query.contractNo)
					this.qrCodeProps.supplierId=decodeURIComponent(query.supplierId)
					this.qrCodeProps.supplierName=decodeURIComponent(query.supplierName)
					this.qrCodeProps.id=decodeURIComponent(query.id)
					this.qrCodeProps.isMultiple=0
				}
				this.query=true//必须要有这句 
				this.initiateWX();
			},
			
			methods:{
				//获取微信相关
				initiateWX() {
					this.$http
						.request({
							url: '/apis/weChat/getSignature',
							params: {
								// url:"http://120.132.17.220:18093/gyhl-app/"
								url: window.location.href.split('#')[0]
							}
						})
						.then(res => {
							if (res.data.code == 0) {
								var s = res.data;
								jweixin.config({
									beta: true,
									debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
									appId: s.corpId, // 必填，公众号的唯一标识
									timestamp: s.timestamp, // 必填，生成签名的时间戳
									nonceStr: s.nonceStr, // 必填，生成签名的随机串
									signature: s.signature.toLowerCase(), // 必填，签名，见附录1
									jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'scanQRCode']
								});
							} else {
								uni.showToast({
									title: res.msg ? res.msg : '获取微信配置失败',
									icon: 'none',
									duration: 2000
								});
							}
						})
						.catch(err => {
							uni.showToast({
								title: err,
								icon: 'none',
								duration: 2000
							});
						});
				},
				//点击显示仓库列表
				searchFacility(){
					this.show_search_facility=true;
				},
				////点击显示仓位列表
				searchFacilityLocation(){
					if(this.facilityId==''){
						uni.showToast({
						    title:'请先选择仓库',
							icon:"none",
						    duration: 2000
						});
					}else{
						this.show_search_location=true;
					}
				},
				//点击扫码仓位
				scanFacilityLocation(){
						console.log("你点击了按钮")
						if(this.facilityId==''){
							uni.showToast({
							    title:'请先选择仓库',
								icon:"none",
							    duration: 2000
							});
						} else {
							// 允许从相机和相册扫码
				            let _this = this;
							jweixin.scanQRCode({
								desc: 'scanQRCode desc',
								needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
								scanType: ['qrCode'], // 可以指定扫二维码还是条形码（一维码），默认二者都有"qrCode", "barCode"
								success: function(res) {
									if (res.errMsg != 'scanQRCode:ok') {
										uni.showToast({
											title: '扫描结果:' + res.resultStr,
											icon: 'none',
											duration: 2000
										});
									} else {
										//扫码正确
										let resultStr = res.resultStr;
										try {
											resultStr = JSON.parse(resultStr);
											if (resultStr.facilityLocationId) {
												
												_this.getQrCodeInfo(resultStr.facilityLocationId);
											} else {
												uni.showToast({
													title: '二维码错误，请扫描正确的二维码',
													icon: 'none',
													duration: 2000
												});
											}
										} catch (e) {
											uni.showToast({
												title: '二维码错误，请扫描正确的二维码',
												icon: 'none',
												duration: 2000
											});
										}
									}
									// 回调
								},
								error: function(res) {
									uni.showToast({
										title: 'error:' + res,
										icon: 'none',
										duration: 2000
									});
									if (res.errMsg.indexOf('function_not_exist') > 0) {
										alert('版本过低请升级');
									}
								}
							});
						}
						
					},
					//调用接口获取二维码信息
					getQrCodeInfo(facilityLocationId) {
						var _this = this
						this.$http
							.request({
								url: '/apis/facilityLocation/detail',
								params: {
									id: facilityLocationId,
								},
								method: 'GET'
							})
							.then(res => {
								if (res.data.code == 0) {
									if(res.data.data.facilityId==_this.facilityId) {
										_this.dataItem2.valueName=res.data.data.name
										_this.facilityLocationId=res.data.data.id
										
									} else {
										uni.showToast({
											title: '对不起，当前扫描的仓位不属于所选仓库，请核对后重新操作。',
											icon: 'none',
											duration: 2000
										});
										_this.dataItem2.valueName=''
										_this.facilityLocationId=''
									
									}
									
								}else{
									uni.showToast({
										title: res.data.msg? res.data.msg:'扫码失败',
										icon: 'none',
										duration: 2000
									});
								}
							});
					},
				getCurrentTime(){
						   let date = new Date();
						    let y = date.getFullYear();
						    let MM = date.getMonth() + 1;
						    MM = MM < 10 ? ('0' + MM) : MM;
						    let d = date.getDate();
						    d = d < 10 ? ('0' + d) : d;
						    let h = date.getHours();
						    h = h < 10 ? ('0' + h) : h;
						    let m = date.getMinutes();
						    m = m < 10 ? ('0' + m) : m;
						    let s = date.getSeconds();
						    s = s < 10 ? ('0' + s) : s;
						    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
				},
				submitData(data){
					if(this.facilityId==''){
						uni.showToast({
							title: '请先选择仓库',
							icon: 'none',
							duration: 2000
						});
						return
					}
					if(data.length==0){
						uni.showToast({
							title: '请先扫码',
							icon: 'none',
							duration: 2000
						});
						return
					}
					let _this=this;
					let bodyDetail=[];
					data.forEach(p=>{
						let json_={
							materielId:p.materielId,
							count:p.count?p.count:0,
							warehouse:_this.facilityId,
							qrcodeId:p.qrcodeId,
							unitPrice:p.unitPrice,
							amount:p.amount
						}
						if(p.batch){
							json_.batch=p.batch
						}
						if(p.facilityLocationId){
							json_.warehLocation=p.facilityLocationId
						}
						if(this.qrCodeProps.contractNo){
							json_.sourceType=271//委外合同的源单类型
							json_.sourceId=this.qrCodeProps.id
							json_.sourceCode=this.qrCodeProps.contractNo
						}
						bodyDetail.push(json_)
					})
						this.$http.request({
							url: '/apis/scm/outsourcingInStock/saveAndChange',
							params: {
								operator:this.userId,
								inOutTime:this.getCurrentTime(),
								sourceCompany:this.qrCodeProps.supplierId,
								qrSign:1,
								bodyDetail:encodeURIComponent(JSON.stringify(bodyDetail))
							},
						}).then(res => {
							if(res.data.code==0){
							uni.showToast({
							    title:"提交成功",
								icon:"none",
							    duration: 2000
							});
							setTimeout(function(){
								uni.redirectTo({
								    url: 'index'
								});
							},1000)
							}else{
								uni.showToast({
								    title:res.data.msg?res.data.msg:"提交失败",
									icon:"none",
								    duration: 2000
								});
							}
							
						}).catch(err => {
								uni.showToast({
								    title:err,
									icon:"none",
								    duration: 2000
								});
						});
				}
			},
			watch:{
				search_value_facility(newv){
					this.dataItem1.valueName=newv.name
					this.facilityId=newv.id;
					},
					search_value_location(newv){
					this.dataItem2.valueName=newv.name
					this.facilityLocationId=newv.id
					},
					facilityId(newv,oldv){
						if(newv!=oldv&&oldv!=''){
							this.facilityLocationId='';
							this.dataItem2.valueName=''
						}
					}
					}
		}
</script>

<style scoped>
	
	.container{
		position: relative;
		min-height: 100%;
		background-color: #fff;
	}
	.supplier{
		height: 40px;
		line-height: 40px;
		border-bottom: 1px solid #e6e6e6;
		box-sizing: border-box;
		font-size: 15px;
		padding: 0 10px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>
