<template>
	<view class="lists">
		<!-- <view class="status_bar" :style="navHeight">
		</view> -->
		<scroll-view class="scroll-area view" :scroll-top="scrollTop" show-scrollbar='false' scroll-y="true">
			<view class="main">
				<view class="middle view" v-if="!isTerminalType">
					<view class="text-block">
						<text class="middle-date">是否分流</text>
						<view class="middle-date-des uni-list picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="bindPickerChange($event,'shunt')" :value="orderItem.shuntName"
										range-key='name' mode="selector" :range="shuntArr">
										<text class="uni-input">{{orderItem.shuntName}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					<view class="text-block" @click="handleShunt" v-if="orderItem.isShunt - 1 === 0">
						<text class="middle-date">分流经销商</text>
						<view class="middle-date-des uni-list picker-year" >
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<text class="uni-input">{{orderItem.shuntDealerName}}</text>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					
					<view class="text-block text-block-last" v-if="orderItem.isShunt - 1 === 0">
						<text class="middle-date" v-if="orderItem.isShunt - 1 === 0">分流渠道</text>
						<view class="middle-date-des uni-list picker-year" v-if="orderItem.isShunt - 1 === 0">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="bindPickerChange($event,'shuntType')" :value="orderItem.shuntTypeName"
										range-key='name' mode="selector" :range="shuntTypeArr">
										<text class="uni-input">{{orderItem.shuntTypeName}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
				</view>
				<view class="middle view address-view">
					<view class="text-address" v-if="orderItem.isShunt - 1 === 0" @click="handleShuntAddress">
						<text class="middle-date-unit">分流收货单位</text>
						<view class="middle-date-des-unit uni-list picker-year" >
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<text class="middle-date-address-text">{{orderItem.shuntReceiveUnitName}}</text>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					<view class="text-address">
						<text class="middle-date-unit">{{isTerminalType ? '收货终端' :'收货单位'}}</text>
						<view class="middle-date-des-unit uni-list picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" :disabled="isTerminalType" @change="bindPickerChange($event,'receive')" :value="orderItem.receiveUnitName"
										range-key='PARTNER_NAME' mode="selector" :range="receiveUnitArr">
										<text class="middle-date-margin-des">{{orderItem.receiveUnitName}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					<view class="text-address">
						<text class="middle-date-unit">喷码单位</text>
						<!-- <view class="middle-date-des-unit uni-list picker-year" @click="handleCustomer"> -->
						<view class="middle-date-des-unit uni-list picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<text class="middle-date-margin-des">{{orderItem.spurtCodeUnitName}}</text>
								</view>
							</view>
							<!-- <image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image> -->
						</view>
					</view>
					<view class="text-block text-block-last">
						<text class="middle-date">收货联系人</text>
						<input class="middle-date-des" type="text" v-model="orderItem.contacPerson" placeholder="请输入" />
						<!-- <text class="middle-date-des">{{orderItem.contacPerson}}</text> -->
					</view>
				</view>
				<view class="middle view">
					<view class="text-block" v-if="isTerminalType">
						<text class="middle-date">省</text>
						<view class="middle-date-des uni-list picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="changeArea($event,'city')" :value="orderItem.REGION"
										range-key='BEZEI' mode="selector" :range="selectDataOptions['regionList']">
										<text class="uni-input">{{terminalAdd.REGION_TEXT}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					<view class="text-block" v-if="isTerminalType">
						<text class="middle-date">市</text>
						<view class="middle-date-des uni-list picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="changeArea($event,'street')" :value="orderItem.CITY_CODE"
										range-key='CITY_NAME' mode="selector" :range="selectDataOptions['cityList']">
										<text class="uni-input">{{terminalAdd.CITY_TEXT}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					<view class="text-block" v-if="isTerminalType">
						<text class="middle-date">区</text>
						<view class="middle-date-des uni-list picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="changeArea($event,'q')" :value="orderItem.STREET_CODE"
										range-key='MC_STREET' mode="selector" :range="selectDataOptions['streetList']">
										<text class="uni-input">{{terminalAdd.STREET_TEXT}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode=""></image>
						</view>
					</view>
					<view class="text-block" v-if="isTerminalType">
						<text class="middle-date">详细地址</text>
						<input class="middle-date-des" type="text" v-model="terminalAdd.STREET" @blur="changeStreet($event)" placeholder="请输入" />
					</view>
					<view class="text-block">
						<text class="middle-date">联系人电话</text>
						<input class="middle-date-des" type="text" v-model="orderItem.contactNumber" placeholder="请输入" />
					</view>
					<view class="text-address">
						<text class="middle-date-add">收货地址</text>
						<text class="middle-date-des-add">{{orderItem.receiveAddress}}</text>
					</view>
					<text class="edit-add" @click="handleAdd">修改地址</text>
					<view class="text-block text-block-last">
						<text class="middle-date">备注</text>
					</view>
					<view class="remark">
						<textarea class="remark-text" v-model="orderItem.remark" />
					</view>

					<!-- <view class="text-block title-first">
						<text class="middle-date title-first__text">上传文件</text>
					</view>
					<view class="upload-block">
						<uni-file-picker ref='files' :auto-upload='false' v-model="fileList" file-mediatype="image"
							:imageStyles="imageStyles" @select="select" @progress="progress" @success="success"
							@fail='fail'>
							<text>+</text>
						</uni-file-picker>
					</view> -->
				</view>
				<view class="middle summary">
					<view class="summary-block">
						<image class="icon_plan" src="@/static/image/icon_plan@3x.png" mode=""></image>
						<text class="upload-text">附件上传(最多上传3张图片)</text>
					</view>
					<view class="upload-block">
						<uni-file-picker ref='files' limit="3" :auto-upload='false' :value="allFilesPath" v-model="allFilesPath" file-mediatype="image"
							:imageStyles="imageStyles" @select="select" @progress="progress" @success="success" @fail='fail' @delete='deletes'>
							<text>+</text>
						</uni-file-picker>
					</view>
				</view>
				<!-- <text class="receive-record">历史收货信息</text>
				<view class="middle view receive-record-view">
					<view class="text-block text-block-last receive-record-info">
						<text class="record-info-title">唐伟 133****9732</text>
						<text class="record-info-des">广东省云浮市罗定市银霄街294号</text>
					</view>
				</view>-->
				<view class="bottom-area"></view>
				<view class="bottom">
					<button class="btn btn-l" type="default" @tap="preStep">
						<text class="btn-text btn-text-l">上一步</text>
					</button>
					<button class="btn btn-l" type="default" @tap="preSave" v-if="!orderItem.saveTimes || orderItem.saveTimes - 1 !== 0">
						<text class="btn-text btn-text-l">保存</text>
					</button>
					<button class="btn" type="default" @tap="nextStep">
						<text class="btn-text">提交</text>
					</button>
				</view>
			</view>
			<uni-popup ref="popup" background-color="#fff"  :mask-click='false'>
				<view class="popup-content">
					<view class="popup-content-head">
						<image class="popup-content-head__icon" src="@/static/image/order_success@3x.png" mode=""></image>
					</view>
					<view class="popup-content-content">
						<text class="popup-content-content__title">提交成功</text>
						<text class="popup-content-content__title2">要货单号：{{ objectId }}</text>
					</view>
					<view class="popup-content-foot">
						<text class="popup-content-foot__btn" @click="fnBackHome()">回到首页</text>
						<text class="popup-content-foot__btn popup-content-foot__sure"
							@click="fnCheckOrderByNo()">查看订单</text>
					</view>
				</view>
			</uni-popup>
		</scroll-view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import store from '@/store/index.js'
	import {
		querySysDictionaryDetailsByCode,
		getReceipt,
		findByCustomer,
		startProcessInstanceByKey,
		advance,
		saveBizData,
		webUploadFile,
		doDeleteFile,
		doQuery, 
		attachmentDownFile,
		findShuntAnyByDealer,
		findFirstByTerminalId
	} from '@/servers/purchaseList.js'
	import { getArea } from '@/servers/address.js'
	import { pathToBase64, base64ToPath } from 'image-tools'
	export default {
		data() {
			return {
				selectDataOptions: {
					cityList: [],
					streetList: [],
					regionList: []
				},
				terminalAdd: {
					REGION: '',
					REGION_TEXT: '',
					CITY_CODE: '',
					CITY_TEXT: '',
					STREET_CODE: '',
					STREET_TEXT: '',
					STREET: ''
				},
				isRadio: false,
				receiveUnitArr: [],
				shuntArr: [],
				shuntTypeArr: [],
				array: ['2021', '2020', '2019', '2018'],
				array1: [{'id':0,val:'00'},{'id':1,val:'01'}],
				index: 0,
				quantity: '',
				remark: '',
				fileList: [],
				scrollTop: 0,
				objectId: '',
				flag: false,
				allFiles: [],
				allFilesPath: [],
			}
		},
		props: {
			sourceType: {
				type: String,
				default: ''
			},
			orderItem: {
				type: Object,
				default () {
					return {}
				}
			},
		},
		watch: {
			'orderItem.isShunt' :function (newName,oldName){
				console.log(newName,'newName')
				if(newName - 0 === 0){
					this.orderItem.shuntReceiveUnitName = ''
					this.orderItem.shuntReceiveUnitCode = ''
					this.orderItem.shuntChannelsType = ''
					this.orderItem.shuntDealer = ''
					this.orderItem.shuntDealerName = ''
					this.orderItem.shuntTypeName = ''
				}else{
					//this.getShuntAnyByDealer()
				}
			}
		},
		computed: {
			isTerminalType() {
			  return this.orderItem.demandType == 'ZDZG'
			},
			imageStyles() {
				return {
					width: 64,
					height: 64,
					border: {
						radius: '50%'
					}
				}
			},
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			imageStyles() {
				return {
					width: 64,
					height: 64,
					border: {
						radius: '50%'
					}
				}
			},
			...mapState(['sysinfo', 'userInfo'])
		},
		// onLoad(option) {
		// 	this.orderItem = {
		// 		...this.orderItem,
		// 		...JSON.parse(option.order)
		// 	}
		// },
		// onBackPress(event) {
		// 	uni.switchTab({
		// 		url: `/pages/purchase-main/purchase-main?order=${JSON.stringify(this.orderItem)}`
		// 	})
		// 	return false
		// },
		mounted() {
			console.log('监听到事件来自 update');
			let _this = this
			uni.$on('selectShuntAccountInfo', function(data) {
				console.log('监听到事件来自 selectShuntAccountInfo ，携带参数 msg 为：', data);
				_this.orderItem.shuntDealerName = data.selectShuntAccountInfo.shuntingCustomer
				_this.orderItem.shuntDealer = data.selectShuntAccountInfo.shuntingCustomer
				// 渠道
				_this.orderItem.shuntChannelsType =  data.selectShuntAccountInfo.channels
				_this.orderItem.shuntTypeName =  data.selectShuntAccountInfo.channelsTextView
			})
			uni.$on('selectAllShuntCode', function(data) {
				console.log('监听到事件来自 selectAllShuntCode：', data);
				_this.orderItem.shuntDealerName = data.selectAllShuntCode.info.partner
				_this.orderItem.shuntDealer = data.selectAllShuntCode.info.partner
			})
			uni.$on('selectShuntAdressAccountInfo', function(data) {
				console.log('监听到事件来自 selectShuntAdressAccountInfo ，携带参数 msg 为：', data);
				_this.orderItem.shuntReceiveUnitName = data.selectShuntAdressAccountInfo.PARTNER_NAME
				_this.orderItem.shuntReceiveUnitCode = data.selectShuntAdressAccountInfo.PARTNER
				_this.orderItem.receiveCityCode = data.selectShuntAdressAccountInfo.CITY_CODE
				_this.orderItem.receiveCityName = data.selectShuntAdressAccountInfo.CITY_NAME
				_this.orderItem.receiveAddress = data.selectShuntAdressAccountInfo.STREET
				_this.orderItem.contactNumber = data.selectShuntAdressAccountInfo.TEL_NUMBER
				_this.orderItem.contacPerson = data.selectShuntAdressAccountInfo.C_O_NAME
				_this.orderItem.spurtCodeUnitName = data.selectShuntAdressAccountInfo.PARTNER_NAME
				_this.getReceipt(_this.orderItem.shuntDealer, true)
			})
			uni.$on('selectShuntCode', function(data) {
				console.log('监听到事件来自 selectShuntCode ，携带参数 msg 为：', data);
				_this.orderItem.spurtCodeUnit = data.selectShuntCode.info.partner
				_this.orderItem.spurtCodeUnitName = data.selectShuntCode.info.name_org1
			})
			if(this.sourceType === 'myPurchase'){
				this.getFiles(this.orderItem.id)
			}
			if(this.isTerminalType){
				this.changeTerminal()
				this.getAreaArr()
			}
		},
		onUnload() {
			uni.$off('selectShuntAccountInfo')
			uni.$off('selectShuntAdressAccountInfo')
			uni.$off('selectShuntCode')
			uni.$off('selectAllShuntCode')
		},
		beforeDestroy() {
			uni.$off('selectShuntAccountInfo')
			uni.$off('selectShuntAdressAccountInfo')
			uni.$off('selectShuntCode')
			uni.$off('selectAllShuntCode')
		},
		created() {
			// 是否分流：B0099
			// 分流渠道：A0054
			this.getSelectDictDataOrigin('B0099')
			this.getSelectDictDataOrigin('A0054')
			this.getReceipt()
			// this.queryData()
		},
		methods: {
			async changeArea(e, type) {
			  if (e) {
				 console.log('picker发送选择改变，携带值为', e.detail.value)
				 const index = e.detail.value || 0
				if (type === 'city') {
				  const code = this.selectDataOptions['regionList'][index].BLAND
				  const { DATA } = await getArea(code, type,"ZDZG")
				  this.selectDataOptions.cityList = DATA
				  this.terminalAdd.REGION_TEXT = this.selectDataOptions['regionList'].find(v => v.BLAND === code)?.BEZEI
				  this.orderItem.receiveAddress = this.terminalAdd.REGION_TEXT
				  this.terminalAdd.CITY_CODE = ''
				  this.terminalAdd.STREET_CODE = ''
				  this.terminalAdd.CITY_TEXT = ''
				  this.terminalAdd.STREET_TEXT = ''
				  this.terminalAdd.STREET = ''
				  this.selectDataOptions.streetList = []
				  console.log(this.selectDataOptions.cityList,this.terminalAdd.REGION_TEXT, this.orderItem.receiveAddress)
				} else if (type === 'street') {
				  const code = this.selectDataOptions['cityList'][index].CITY_CODE
				  const { DATA } = await getArea(code, type)
				  this.selectDataOptions.streetList = DATA
				  this.terminalAdd.STREET_CODE = ''
				  this.terminalAdd.STREET_TEXT = ''
				  this.terminalAdd.STREET = ''
				  this.terminalAdd.CITY_TEXT = this.selectDataOptions['cityList'].find(v => v.CITY_CODE === code)?.CITY_NAME
				  this.orderItem.receiveAddress = this.terminalAdd.REGION_TEXT + this.terminalAdd.CITY_TEXT
				} else {
				  const code = this.selectDataOptions['streetList'][index].STRT_CODE
				  this.terminalAdd.STREET_TEXT = this.selectDataOptions['streetList'].find(v => v.STRT_CODE === code)?.MC_STREET
				  this.orderItem.receiveAddress = this.terminalAdd.REGION_TEXT + this.terminalAdd.CITY_TEXT + this.terminalAdd.STREET_TEXT + this.terminalAdd.STREET
				}
			  }
			},
			async changeStreet(e){
			  const obj = this.terminalAdd
			  this.orderItem.receiveAddress = obj.REGION_TEXT + obj.CITY_TEXT + obj.STREET_TEXT + e.detail.value
			},
			// 请求历史收货地址
			async changeTerminal(){
			  await findFirstByTerminalId({terminalId: this.orderItem.terminalId}).then(res => {
				this.orderItem.receiveAddress = res.data.receiveAddress
				this.orderItem.contactNumber = res.data.contactNumber
				this.orderItem.contacPerson = res.data.contacPerson
			  })
			},
			// 省
			async getAreaArr(){
			  await getArea('','region',"ZDZG").then(res => {
				this.selectDataOptions['regionList'] = res.DATA
			  })
			},
			async getShuntAnyByDealer(){
				const res = await findShuntAnyByDealer({customerCode: this.userInfo.code})
				this.isRadio = res.data - 0 === 1
			},
			async getFiles(id) {
				const params = {
					bizId: id,
					bizCode: 'wantGoods'
				}
				const res= await doQuery(params)
				res.data.forEach((ele,idx) => {
					this.downFiles(ele)
				});
			},
			async downFiles(item) {
				console.log(item,'item')
				// 获取arraybuffer格式数据
				let res = await uni.request({
					method: "POST",
					url: `https://crm.wuliangye.com.cn/crm-app/attachmentDownFile?id=`+item.id, // 生产
					// url: `http://221.10.127.60:5000/crm-app/attachmentDownFile?id=`+item.id,
					params: {
					  id: item.id
					},
					header: {
						'X-Auth-Token': store.state.vuex_token,
						// 'content-type': 'multipart/form-data'
					},
					responseType: "arraybuffer"   //只有text、arraybuffer两种
				})
				 const buff = res[1].data
				// 转成base64格式路径
				const base64Src = 'data:image/png;base64,' + uni.arrayBufferToBase64(buff);
				// 通过 image-tools  中方法再将base64路径转为普通路径，用于预览
				const path = await  base64ToPath(base64Src);
				const picObj = {
					...item,
					"name": item.fileName,
					"extname": item.fileKind,
					"url":path,
				}
				this.allFilesPath.push(picObj)
			},
			fnCheckOrderByNo() {
				this.$refs.popup.close()
				uni.redirectTo({
					url: '/pages/my-purchase/my-purchase'
				})
			},
			fnBackHome() {
				this.$refs.popup.close()
				setTimeout(() => {
					uni.switchTab({
						url: `/pages/home/home`
					})
				}, 300)
			},
			handleCustomer() {
				uni.navigateTo({
					url: `/pages/select-customer/select-customer?order=${JSON.stringify(this.orderItem)}`
				})
			},
			handleShunt() {
				uni.navigateTo({
					url: `/pages/select-shunt-list/select-shunt-list?order=${JSON.stringify(this.orderItem)}`
				})
			},
			handleAdd() {
				uni.navigateTo({
					url: `/pages/select-address/select-address`
				})
			},
			handleReceiptAddress() {
				uni.navigateTo({
					url: `/pages/select-shunt-adress/select-shunt-adress?order=${JSON.stringify(this.orderItem)}&type=2`
				})
			},
			handleShuntAddress() {
				if(this.orderItem.shuntDealerName){
					uni.navigateTo({
						url: `/pages/select-shunt-adress/select-shunt-adress?order=${JSON.stringify(this.orderItem)}&type=1`
					})
				}else{
					uni.showToast({
						title: '请先选择分流经销商！',
						duration: 2000,
						icon: 'none'
					});
				}
			},
			// 查询
			async queryData() {
				const params = {
					'customerCode': this.orderItem.customerCode,
					'type': '2',
				}
				const { data } = await findByCustomer(params)
			},
			async getReceipt(partner = this.orderItem.customerCode, flag=false){
				const params = {
					partner,
					'role': "WLY001"
				}
				const res = await getReceipt(params)
				this.receiveUnitArr = res.DATA
				if(flag)return
				if(this.orderItem.saveTimes - 0 >= 0){
					return
				}
				this.orderItem.receiveUnitCode =  this.receiveUnitArr[0].PARTNER
				this.orderItem.spurtCodeUnitName =  this.receiveUnitArr[0].PARTNER_NAME
				this.orderItem.contactNumber = this.receiveUnitArr[0].TEL_NUMBER
				this.orderItem.contacPerson = this.receiveUnitArr[0].C_O_NAME
				this.orderItem.receiveAddress = this.receiveUnitArr[0].STREET
				if(this.isTerminalType){
					this.orderItem.contactNumber = ''
					this.orderItem.contacPerson = ''
					this.orderItem.receiveAddress = ''
				}else{
					this.orderItem.receiveUnitName =  this.receiveUnitArr[0].PARTNER_NAME
				}
			},
			getSelectDictDataOrigin(dictcode) {
			  querySysDictionaryDetailsByCode({'code': dictcode})
				.then(res => {
					if(res.data.Rows.length > 0){
						switch (dictcode){
							case 'B0099':
								this.shuntArr = res.data.Rows
								if(this.orderItem.saveTimes - 0 >= 0 && this.orderItem.isShunt - 1 === 0){
									this.orderItem.shuntName =  '是'
									return
								}
								this.orderItem.isShunt =  this.shuntArr[1].value
								this.orderItem.shuntName =  this.shuntArr[1].name
								break;
							case 'A0054':
								this.shuntTypeArr = res.data.Rows
								break;
							default:
								break;
						  }
					}
				  
				})
				.catch(() => {})
			},
			bindPickerChange(e,type) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				const index = e.detail.value || 0
				switch (type) {
					case 'shunt':
						this.orderItem.isShunt =  this.shuntArr[index].value
						this.orderItem.shuntName =  this.shuntArr[index].name
						break;
					case 'shuntType':
						this.orderItem.shuntChannelsType =  this.shuntTypeArr[index].value
						this.orderItem.shuntTypeName =  this.shuntTypeArr[index].name
						break;
					case 'receive':
						this.orderItem.receiveUnitName =  this.receiveUnitArr[index].PARTNER_NAME
						this.orderItem.receiveUnitCode =  this.receiveUnitArr[index].PARTNER
						this.orderItem.contactNumber = this.receiveUnitArr[index].TEL_NUMBER
						this.orderItem.receiveAddress = this.receiveUnitArr[index].STREET
						this.orderItem.contacPerson = this.receiveUnitArr[index].C_O_NAME
						if(this.isTerminalType){
							this.orderItem.contactNumber = ''
							this.orderItem.contacPerson = ''
							this.orderItem.receiveAddress = ''
						}
						
				}
			},
			submit() {
				this.$emit('submit')
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},
			async select(data) {
				data.tempFilePaths.forEach((item,idx) => {
					console.log('idx',data.tempFilePaths[idx],data.tempFiles[idx].file.name)
					uni.uploadFile({
						url: `https://crm.wuliangye.com.cn/crm-app/webUpload/ajaxUpload`, //生产
						// url: `http://221.10.127.60:5000/crm-app/webUpload/ajaxUpload`,
						filePath: data.tempFilePaths[idx],
						name: 'file',
						formData: {
							bizId: this.orderItem.fileBizId,
							bizCode: 'wantGoods',
							formSecretLevel: 0,
							name: data.tempFiles[idx].file.name,
							type: data.tempFiles[idx].file.fileType,
							lastModifiedDate: data.tempFiles[idx].file.lastModifiedDate,
							size: data.tempFiles[idx].file.size,
							// file: data.tempFiles[idx].file
						},
						header: {
							// 'Access-Control-Allow-Origin': 'http://221.10.127.60',
							'Access-Control-Allow-Origin': '*',
							'method': "POST",
							'X-Auth-Token': store.state.vuex_token,
							// 'content-type': 'multipart/form-data'
							
						},
						success: (uploadFileRes) => {
							this.allFiles.push(JSON.parse(uploadFileRes.data).data)
							console.log(this.allFiles, '成功');
							uni.showToast({
								title: '上传成功！',
								duration: 2000,
								icon: 'none'
							})
						},
						fail: (uploadFileRes) => {
							uni.showToast({
								title: '上传失败！',
								duration: 2000,
								icon: 'none'
							})
						},
					})
				})
			},
			// 上传成功
			success(e) {
				console.log('上传成功', e)
			},
			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			async deletes(e){
				const params = {
					id: e.tempFile.id,
					isCheck: false
				}
				const res = await doDeleteFile(params)
				if(res.status - 0 === 1){
					const arr = this.allFiles.filter(item => item.fileName === e.tempFile.name || item.fileName === e.tempFile.fileName )
					this.allFiles = [...arr]
					console.log(this.allFiles)
				}
			},
			preStep() {
				// uni.switchTab({
				// 	url: '/pages/purchase-main/purchase-main'
				// })
				// 返回上一级 把刚刚上传的附件删除
				if(this.allFiles.length > 0){
					this.allFiles.forEach(ele => {
						const params = {
							id: ele.id,
							isCheck: false
						}
						const res = doDeleteFile(params)
						this.allFiles = []
					});
				}
				this.$emit('click', 'purchaseMain')
			},
			checkData(){
				if(this.terminalAdd.REGION_TEXT || this.terminalAdd.CITY_TEXT || this.terminalAdd.STREET_TEXT || this.terminalAdd.STREET){
					if(!this.terminalAdd.REGION_TEXT){
						uni.showToast({
							title: '请选择省',
							duration: 2000,
							icon: 'none'
						});
						return false
				  }
				  if(!this.terminalAdd.CITY_TEXT){
					uni.showToast({
						title: '请选择市',
						duration: 2000,
						icon: 'none'
					});
					return false
				  }
				  if(!this.terminalAdd.STREET_TEXT){
					uni.showToast({
						title: '请选择区',
						duration: 2000,
						icon: 'none'
					});
					return false
				  }
				  if(!this.terminalAdd.STREET){
					uni.showToast({
						title: '请输入详细地址',
						duration: 2000,
						icon: 'none'
					});
					return false
				  }
				  return true
				}
				return true
			},
			async preSave(){
				const that = this
				try{
					if(this.flag){
						return
					}
					this.flag = true
					for(let k in this.orderItem){
						this.orderItem[k] = this.orderItem[k] === null ? '' : this.orderItem[k]
					}
					const obj = {
						...this.orderItem
					}
					if(this.isTerminalType){
						if(!this.checkData()){
							this.flag = false
							return
						}
						obj.province = this.terminalAdd.REGION_TEXT || this.orderItem.province
						obj.city = this.terminalAdd.CITY_TEXT || this.orderItem.city
						obj.district = this.terminalAdd.STREET_TEXT || this.orderItem.district
					}else{
						obj.demandType = 'none'
					}
					const params = JSON.parse(JSON.stringify(obj))
					params.wantGoodsDetailList = JSON.stringify(params.wantGoodsDetailList)
					let res = null
					if(params.id){
						// params.bizId = params.id
						const paramss = {
							bizId: params.id,
							...params,
						}
						res = await saveBizData(paramss)
					}else{
						res = await startProcessInstanceByKey(params)
					}
					if (res.status == 1) {
						uni.showToast({
							title: '保存成功',
							duration: 2000,
							icon: 'none'
						});
						
						setTimeout(function() {
							that.fnCheckOrderByNo()
						}, 1000)
					}else{
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						});
						this.flag = false
					}
				}catch(e){
					this.flag = false
					//TODO handle the exception
				}
			},
			async nextStep() {
				if(this.orderItem.isShunt - 1 === 0){
					if (!this.orderItem.shuntDealerName) {
						uni.showToast({
							title: '请先选择分流经销商',
							duration: 2000,
							icon: 'none'
						});
						return
					}
					if (!this.orderItem.shuntTypeName) {
						uni.showToast({
							title: '请先选择分流渠道',
							duration: 2000,
							icon: 'none'
						});
						return
					}
					if (!this.orderItem.shuntReceiveUnitName) {
						uni.showToast({
							title: '请先选择分流收货单位',
							duration: 2000,
							icon: 'none'
						});
						return
					}
				}
				if(this.flag){
					return
				}
				this.flag = true
				try {
					const obj = {
						...this.orderItem
					}
					if(this.isTerminalType){
						if(!this.checkData()){
							this.flag = false
							return
						}
						obj.province = this.terminalAdd.REGION_TEXT || this.orderItem.province
						obj.city = this.terminalAdd.CITY_TEXT || this.orderItem.city
						obj.district = this.terminalAdd.STREET_TEXT || this.orderItem.district
					}else{
						 obj.demandType = 'none'
					}
					const params = JSON.parse(JSON.stringify(obj))
					params.wantGoodsDetailList = JSON.stringify(params.wantGoodsDetailList)
					let flagStatus = false
					let status = 0
					let data = null
					if(params.id){
						flagStatus = true
						params.bizId = params.id
					}else{
						try{
							const res = await startProcessInstanceByKey(params)
							status = res.status
							data = res.data
						}catch(e){
							this.flag = false
						}
					}
					if (status == 1 || flagStatus) {
						if(!params.id){
							Object.assign(params, data.bizData)
							params.bizId = data.bizId
							params.procInstId = data.procInstId
							params.taskId = data.taskId
							// 提交
							params.wantGoodsDetailList = JSON.stringify(params.wantGoodsDetailList)
						}
						for(let k in params){
							params[k] = params[k] === null ? '' : params[k]
						}
						const res = await advance(params)
						if (res.status == 1) {
							this.objectId = res.data.bizData.wantCode
							this.$refs.popup.open('center')
							// uni.showToast({
							// 	title: '要货成功',
							// 	duration: 2000,
							// 	icon: 'none'
							// });
							// uni.switchTab({
							// 	url: '/pages/purchase/purchase'
							// })
						}
					}else{
						this.flag = false
					}
				} catch (e) {
					this.flag = false
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.view {
		flex-direction: column;
	}

	/* #ifndef APP-PLUS */
	page {
		width: 100%;
		min-height: 100%;
		display: flex;
		background: #fff;
	}

	.status_bar {
		height: var(--status-bar-height);
		background: #fff;
	}

	/* #endif */

	.lists {
		flex: 1;
		flex-direction: column;
		background: #f0f4f5;
		// overflow-y: scroll;
	}

	.scroll-area {
		flex: 1;
	}

	.main {
		margin: 0 16rpx;
		flex-direction: column;
		border-radius: 16rpx;
		margin-top: 16rpx;
	}

	.middle {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 64rpx 0 48rpx;
		margin-bottom: 16rpx;
	}
	.address-view{
		flex: 1;
	}

	.text-block {
		overflow: hidden;
		// height: 96rpx;
		// margin-bottom: 14rpx;
		border-bottom: 1px solid #f4f5f6;
	}
	.text-address {
		overflow: hidden;
		border-bottom: 1px solid #f4f5f6;
	}

	.text-block-last {
		margin-bottom: 0;
		border-bottom: 0;
	}

	.middle-date {
		flex: 2;
		font-size: 28rpx;
		line-height: 96rpx;
		color: #999;
	}

	.middle-date-des {
		flex: 3;
		font-size: 28rpx;
		height: 96rpx;
		line-height: 96rpx;
		color: $text-base-color;
	}
	.middle-date-address {
		color: #333;
		font-size: 28rpx;
		flex: 3;
		padding-top: 10rpx;
		justify-content: start;
		font-size: 28rpx;
		height: 96rpx;
	}
	.middle-date-address-text {
		color: #333;
		font-size: 28rpx;
		flex: 1;
		justify-content: start;
		font-size: 28rpx;
		height: 70rpx;
		line-height: 34rpx;
		align-items: center;
	}
	.middle-date-margin-des{
		flex: 1;
		font-size: 28rpx;
		color: #333;
		margin-top: 0rpx;
		margin-bottom: 20rpx;
		width: 200%;
		text-align: left;
		justify-content: end;
	}
	.picker-year {
		position: relative;
		align-items: center;
	}

	.uni-list-cell {
		flex: 1;
		height: 100%;
	}

	.uni-list-cell-db {
		flex: 1;
	}

	.picker-block {
		flex: 1;
	}

	.uni-input {
		line-height: 100%;
		height: 100%;
		font-size: 14px;
		color: $text-base-color;
	}

	.icon-arrow {
		position: absolute;
		right: 22rpx;
		top: 40rpx;
		width: 7px;
		height: 10px;
		z-index: 10;
	}

	.remark-text {
		flex: 1;
		height: 220rpx;
		background: #f5f6f7;
		border-radius: 4px;
		padding: 12rpx 18rpx;
		margin-bottom: 40rpx;
	}

	.title-first {
		border-bottom: 0;
	}

	.title-first__text {
		font-size: 28rpx;
		color: #333333;
		font-weight: 600;
	}

	.receive-record-view {
		padding: 40rpx 48rpx;
	}

	.receive-record {
		color: #555555;
		font-size: 28rpx;
		margin-bottom: 8rpx;
		margin-top: 32rpx;
	}

	.receive-record-info {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.record-info-title {
		color: #333;
		font-size: 28rpx;
		font-weight: 500;
		margin-bottom: 16rpx;
	}

	.record-info-des {
		color: #999;
		font-size: 24rpx;
	}

	.bottom-area {
		height: 140rpx;
		margin-top: 12rpx;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 10;
		width: 750rpx;
		height: 140rpx;
		padding: 0 32rpx;
		justify-content: space-between;
		align-items: center;
		background: #fff;
	}

	.btn {
		flex: 1;
		height: 92rpx;
		background: $wly-primary-color;
		border-radius: 46rpx;
	}

	.btn-l {
		margin-right: 30rpx;
		border: 1px solid $wly-primary-color;
		background-color: #fff;

	}

	.btn-text {
		color: #fff;
		font-size: 34rpx;
	}

	.btn-text-l {
		color: $wly-primary-color;
	}
	::v-deep  .uni-popup__wrapper {
		border-radius: 20rpx;
	}
	
	.popup-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 580rpx;
		height: 408rpx;
		background: #ffffff;
		border-radius: 24rpx;
	}
	
	.popup-content-head {
		margin-top: 56rpx;
		margin-bottom: 16rpx;
	}
	
	.popup-content-head__icon {
		width: 80rpx;
		height: 80rpx;
	}
	
	.popup-content-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 52rpx;
	}
	
	.popup-content-content__title {
		font-size: 32rpx;
		color: #444;
		font-weight: 500;
		margin-bottom: 8rpx;
	}
	
	.popup-content-content__title2 {
		color: #999999;
		font-size: 24rpx;
	}
	
	.popup-content-foot {}
	
	.popup-content-foot__btn {
		width: 152rpx;
		height: 60rpx;
		font-size: 22rpx;
		line-height: 60rpx;
		background: #ffedee;
		text-align: center;
		color: #ff0f00;
		font-weight: 500;
		border-radius: 32rpx;
	}
	
	.popup-content-foot__sure {
		margin-left: 40rpx;
		color: #fff;
		background: #ff1d32;
		border: 1px solid #ff1d32;
	}
	.middle-date-unit {
		flex: 2;
		font-size: 28rpx;
		color: #999;
		margin-bottom: 8rpx;
		padding-top: 30rpx;
	}
	
	.middle-date-des-unit {
		flex: 3;
		font-size: 28rpx;
		min-height: 96rpx;
		color: $text-base-color;
		padding-top: 30rpx;
		justify-content: start;
	}
	.middle-date-add {
		flex: 2;
		font-size: 28rpx;
		color: #999;
		margin-bottom: 8rpx;
		padding-top: 30rpx;
	}
	
	.middle-date-des-add {
		flex: 3;
		font-size: 28rpx;
		min-height: 124rpx;
		color: $text-base-color;
		padding-top: 30rpx;
		justify-content: start;
	}
	.summary-block {
		display: flex;
		align-items: center;
	}
	.summary {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		margin-bottom: 32rpx;
		padding: 32rpx 48rpx 140rpx;
	}
	.icon_plan {
		width: 36rpx;
		height: 36rpx;
		margin-right: 8rpx;
	}
	
	.upload-block {
		display: flex;
		// width: 100%;
		// align-items: center;
		// justify-content: center;
		// align-self: center;
		// width: 388rpx;
		height: 388rpx;
		// background: #f5f6f7;
		// border: 1px dashed #dedede;
		border-radius: 4px;
		margin-top: 90rpx;
		flex-direction: column;
	}
	.upload-text {
		flex: 2;
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
	}
	.summary {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		margin-bottom: 32rpx;
		padding: 32rpx 48rpx 140rpx;
	}
	.edit-add{
		text-align: right;
		padding-top: 10px;
	}
</style>
