<template>
	<view class="page">
		<view class="m-cells m-cells-form">
			<view class="m-cell" @click="chooseCategory">
				<view class="m-cell-hd"><label class="u-label">{{__('需求类型')}}</label></view>
				<view class="m-cell-bd">
					<label>{{category_text}}</label>
				</view>
				<view v-if="(!service_category_id)" class="m-cell-ft">
					<view class="m-icon-warn uni-icon uni-icon-info" type="warn"></view>
				</view>
			</view>

			<view class="m-cell">
				<view class="m-cell-hd"><label class="u-label">{{__('货品名称')}}</label></view>
				<view class="m-cell-bd">
					<input class="u-input" type="text" v-model="purchase_order_title" :placeholder="__('货品名称')" />
				</view>
				<view v-if="(!purchase_order_title)" class="m-cell-ft">
					<view class="m-icon-warn uni-icon uni-icon-info" type="warn"></view>
				</view>
			</view>
			
			<view class="m-cell">
				<view class="m-cell-hd"><label class="u-label">{{__('规格')}}</label></view>
				<view class="m-cell-bd">
					<input class="u-input" type="text" v-model="purchase_product_spec" :placeholder="__('规格')" />
				</view>
				<view v-if="(!purchase_product_spec)" class="m-cell-ft">
					<view class="m-icon-warn uni-icon uni-icon-info" type="warn"></view>
				</view>
			</view>
			
			<view class="m-cell">
				<view class="m-cell-hd"><label class="u-label">{{__('期望单价上限')}}</label></view>
				<view class="m-cell-bd">
					<input class="u-input" type="text" v-model="purchase_origin_price_max" :placeholder="__('期望单价上限')" />
				</view>
				<view v-if="(!purchase_origin_price_max)" class="m-cell-ft">
					<view class="m-icon-warn uni-icon uni-icon-info" type="warn"></view>
				</view>
			</view>

			<view class="m-cells m-cells-form">
				<view class="m-upImg">
					<view class="m-upImg-item" v-for="(imglist, ii) in data_info.comment_image" :key="ii">
						<image lazy-load mode="aspectFit" :src="(imglist)" :data-src="(imglist)" @click="ImgTap"></image>
						<view v-if="true" class="u-del-item" :data-index="(ii)" @click.stop="delImg"><label class="iconfont icon-delete" :data-index="(ii)"></label></view>
					</view>
					<view v-if="true" class="m-upImg-item upSelect" @click.stop="upImgs">
						<label class="iconfont icon-xiangji"></label>
					</view>
				</view>
			</view>


			<view class="m-cell">
				<view class="m-cell-hd"><label class="u-label">{{__('采购数量')}}</label></view>
				<view class="m-cell-bd">
					<input class="u-input" type="number" v-model="purchase_order_quantity" :placeholder="__('采购数量')" />
				</view>
				<view v-if="(!purchase_order_quantity)" class="m-cell-ft">
					<view class="m-icon-warn uni-icon uni-icon-info" type="warn" style="right:250rpx"></view>
				</view>
				<view class="m-vcode-btn">
					<picker mode="selector" @change="onModeChange" :value="mode_index" :range="lists">
						<view class="uni-input" style="color:#000000">{{lists[purchase_order_unit]}}</view>
					</picker>
				</view>
			</view>
			
			<view class="m-cell">
				<view class="m-cell-hd"><label for="" class="u-label">{{__('是否开票')}}</label></view>
				<view class="m-cell-bd">
					<radio-group class="uni-flex" name="purchase_invoice_enable"  @change="onInvoiceEnable">
							<radio value="0" :checked="purchase_invoice_enable==0"/>{{__('否')}}
							<radio value="1" :checked="purchase_invoice_enable==1"  />{{__('是')}}
					</radio-group>
				</view>
			</view>

			<view class="m-cells">
				<view class="m-cell">
					<view class="m-cell-hd"><label class="u-label">{{__('货品描述')}}</label></view>
					<view class="m-cell-bd" style="border: 2rpx solid #F5F5F5;padding:10rpx;">
						<textarea class="u-textarea" maxlength="500" :placeholder="text" @input="inputRemark" style="height:300rpx;"></textarea>
						<!-- <view class="u-textarea-counter">
							<label>{{remarkLength}}</label>/500</view> -->
					</view>
				</view>
			</view>

			<view class="m-cell" @click="showCityBox">
				<view class="m-cell-hd"><label class="u-label">{{__('期望产地')}}</label></view>
				<view class="m-cell-bd">
					<label>{{seladstr}}</label>
				</view>
			</view>
			
			<view class="m-cell">
				<view class="m-cell-hd"><label class="u-label">{{__('期望收货日期')}}</label></view>
				<view class="m-cell-bd">
					<picker mode="date" @change="bindDateChange">
						<label>{{purchase_origin_receive_time || "请选择期望收货日期"}}</label>
					</picker>
				</view>
			</view>
			
			<view class="m-cell" @click="selectAddress">
				<view class="m-cell-hd"><label class="u-label">{{__('收货地址')}}</label></view>
				<view class="m-cell-bd">
					<label>{{receiving}}</label>
				</view>
			</view>
			
			<view class="m-cell">
				<view class="m-cell-hd"><label class="u-label">{{__('截止时间')}}</label></view>
				<view class="m-cell-bd">
					<picker mode="date" @change="bindDeadDateChange">
						<label>{{purchase_deadline || "请选择截止时间"}}</label>
					</picker>
				</view>
			</view>
		</view>

		<mpvue-city-picker :themeColor="themeColor" ref="mpvueCityPicker" :pickerValueDefault="cityPickerValueDefault" @onCancel="onCancel" @onConfirm="onConfirm"></mpvue-city-picker>

		<!-- 地区选择 -->
		<shopCategory ref="shopCategory" :height="height" @confirmCallback="confirmCallback">
		</shopCategory>


		<button class="u-btn u-btn-default" @click="submitInfo" style="margin-top:50rpx;">{{__('发布需求')}}</button>

		<payment-box :paymentDataDefault="paymentData" :order_id="service_order_id" ref="paymentBox" @onCancel="onCancel" @onPaid="onPaid" @onFail="onFail"></payment-box>

	</view>
</template>


<script>
	import mpvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker.vue'
	import Attachment from '@/components/jin-attachment/jin-attachment.vue';
	import shopCategory from '@/components/shop/category.vue';
	import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue"

	import paymentBox from '../../components/payment-box.vue'

	import {
		mapState,
		mapMutations
	} from 'vuex'

	export default {
		data: function() {
			const currentDate = this.$.dateFormatter(new Date().getTime() / 1000 + 60 * 60 * 24 * 7);

			return {
				options: {},
				service_category_id: 0,
				category_text: '',
				height: '500px',

				mode_index: 0,
				purchase_order_title: '',
				purchase_order_description: '',
				user_number: '8',
				contacts_phone: '',

				editorCtx: null,
				receiving: "请选择收货地址",
				ud_id: 0,

				data_info: {
					order: {
						item: {}
					},
					comment_image: []
				},



				lists: [],

				text: '请描述你的需求......',
				remarkLength: 0,


				isDistrict: true,
				purchase_order_quantity: 0,
				purchase_product_spec: "",
				purchase_origin_price_max: 0,
				purchase_order_unit: 0,
				purchase_origin_receive_time: '',
				purchase_deadline: '',
				purchase_invoice_enable: 0,


				Pindex: 0,
				selectedProId: 0,
				selectedCityId: 0,
				selectedCountyId: 0,
				purchase_order_amount: 0,
				selectedPro: '',
				selectedCity: '',
				selectedCounty: '',
				seladstr: "请选择地域",

				cityPickerValueDefault: [0, 0, 0],
				themeColor: '#007AFF',

				urlArgs: {},

				header: {
					// 如果需要header，请上传
				},
				attachmentList: [],
				service_order_files: [],

				paymentData: {},
				service_order_id: '',

				order_id: '',



				protocol_checked: true
			}
		},
		computed: {
			...mapState(['Config', 'StateCode', 'notice', 'plantformInfo', 'shopInfo', 'userInfo', 'hasLogin']),
			startDate() {
				return this.$.dateFormatter(new Date().getTime() / 1000);
			},
			endDate() {
				return this.$.dateFormatter(new Date().getTime() / 1000 + 60 * 60 * 24 * 7);
			}
		},
		components: {
			mpvueCityPicker,
			Attachment,
			shopCategory,
			uniNumberBox,
			paymentBox
		},
		onLoad: function(options) {
			uni.setNavigationBarTitle({
				title: this.__('发布需求')
			});

			this.category_text = this.__("请选择所属分类");
			this.seladstr = this.__("请选择所属地区");

			let that = this;

			that.setData({
				options: options,
				order_id: options.order_id,
			});

			this.notice.addNotification("RefreshOrder", that.RefreshOrder, that);

			this.forceUserInfo(function(user) {


				that.load()

			});

			// that.getUnit()
		},
		onShow: function(opt) {
			let that = this;
		},

		onUnload: function() {
			var that = this
			this.notice.removeNotification("RefreshOrder", that);
		},
		methods: {
			...mapMutations(['login', 'logout', 'getPlantformInfo', 'forceUserInfo', 'getUserInfo']),
			load: function() {
				var that = this;
				var params = {
					purchase_order_id: that.order_id,


				};
				that.$.request({
					url: this.Config.URL.hall.user_purchase_order_index,
					data: params,
					success: function(data, status, msg, code) {
						if (status == 200) {
							
							if (data.purchase_deadline) {
								data.purchase_deadline = that.$.dateFormat(data.purchase_deadline, "yyyy-MM-dd")
							}
							
							if (data.purchase_origin_receive_time) {
								data.purchase_origin_receive_time = that.$.dateFormat(data.purchase_origin_receive_time, "yyyy-MM-dd")
							}
							that.setData({
								service_category_id: data.category_id,
								category_text: data.purchase_category_name,
								text: data.purchase_order_description,
								purchase_order_title: data.purchase_order_title,
								purchase_order_quantity: data.purchase_order_quantity,
								ud_id: data.origin_place_id,
								receiving: data.purchase_address ? data.purchase_address.district_info + data.purchase_address.ud_address : '',
								selectedProId: data.purchase_province_id,
								selectedCityId: data.purchase_city_id,
								selectedCountyId: data.purchase_county_id,
								selectedPro: data.purchase_province,
								selectedCity: data.purchase_city,
								selectedCounty: data.purchase_county,
								seladstr: data.purchase_province ? data.purchase_province + '/' + data.purchase_city + '/' + data.purchase_county : '',
								purchase_order_description: data.purchase_order_description,
								purchase_product_spec: data.purchase_product_spec,
								purchase_origin_price_max: data.purchase_origin_price_max,
								purchase_origin_receive_time: data.purchase_origin_receive_time,
								purchase_deadline: data.purchase_deadline,
								lists: data.product_unit,
								purchase_invoice_enable: data.purchase_invoice_enable ? 1 : 0,
								purchase_order_unit: data.purchase_order_unit ? data.purchase_order_unit : 0,

							})

							that.data_info.comment_image = data.purchase_product_images || []

						}
					}
				});
			},
			chooseCategory: function(e) {
				let that = this;

				this.height = '550rpx';
				this.$refs.shopCategory.show();
			},
			
			onInvoiceEnable:function(e){
				this.purchase_invoice_enable = e.target.value
			},

			onModeChange: function(e) {
				var that = this;
				var index = e.detail.value
				this.setData({
					mode_index: e.detail.value,
					purchase_order_unit: index
				})
			},
			//回调
			confirmCallback: function(category_text, service_category_id) {
				console.log(category_text);
				console.log(service_category_id);

				this.service_category_id = service_category_id;
				this.category_text = category_text;


			},

			ImgTap: function(e) {
				var that = this,
					urls = [];


				for (var i in this.data_info.comment_image) {
					urls.push(this.data_info.comment_image[i]);
				}
				var s = e.target.dataset.src;


				that.$.previewImage({
					current: s,
					urls: urls
				});
			},

			upImgs: function(e) {

				var that = this;
				var dataInfo = this.data_info;
				if (dataInfo.comment_image && dataInfo.comment_image.length == 3) {
					that.$.alert('最多上传3张图片！');
					return;
				}

				that.$.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					success: function(n) {
						that.$.showLoading();
						var r = n.tempFilePaths;
						that.$.uploadFile({
							url: that.Config.URL.upload,
							method: 'POST',
							filePath: r[0],
							name: 'upfile',
							//header: { 'content-type': 'multipart/form-data' },
							success: function(n) {
								that.$.hideLoading();
								var up_res = that.$.parseJSON(n.data);

								var s = up_res.data.url;
								dataInfo.comment_image.push(s);
								console.log(dataInfo)
								that.setData({
									data_info: dataInfo
								});

							},
							fail: function(e) {
								that.$.hideLoading();
							},
							complete: function(e) {
								that.$.hideLoading();
							}
						});
					},
					fail: function(e) {
						that.$.hideLoading();
					},
					complete: function(e) {
						that.$.hideLoading();
					}
				});
			},
			
			bindDateChange: function(e) {
				console.log(e)
				this.setData({
					purchase_origin_receive_time: e.detail.value
				})
			},
			
			bindDeadDateChange: function(e) {
				console.log(e)
				this.setData({
					purchase_deadline: e.detail.value
				})
			},

			delImg: function(e) {
				//console.info(e);
				var dataInfo = this.data_info;
				console.log(dataInfo)
				var that = this;
				that.$.confirm(
					'是否放弃上传本张图片?',
					function(n) {
						if (n.confirm) {
							var i = [];
							for (let s = 0; s < dataInfo.comment_image.length; s++) {
								if (s != e.target.dataset.index) {
									var o = dataInfo.comment_image[s];
									i.push(o);
								}
							}
							dataInfo.comment_image = i;

							that.setData({
								data_info: dataInfo
							});
						}
					},
					true
				);
			},




			inputRemark: function(e) {
				this.setData({
					purchase_order_description: e.detail.value,
					remarkLength: e.detail.value.length
				});
			},

			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},

			onInput(e) {
				let that = this;
				console.log(e)
				this.editorCtx.getContents({
					success: function(e) {
						that.purchase_order_description = e.html
					}
				})
			},

			submitInfo: function(e) {
				let that = this;

				this.update();
			},

			update: function() {
				var that = this;

				if (!that.service_category_id || !that.purchase_order_title || !that.purchase_order_quantity || !that.purchase_order_description || !that.receiving) {
					return;
				}
				
				if (!that.purchase_origin_price_max) {
					that.$.confirm(that.__("请输入期望单价上限！"));
					return;
				}
				
				if (!that.purchase_origin_receive_time) {
					that.$.confirm(that.__("请选择期望收货日期！"));
					return;
				}
				
				if (!that.purchase_deadline) {
					that.$.confirm(that.__("请选择截止时间！"));
					return;
				}

				var params = {
					purchase_order_id: that.order_id,
					category_id: that.service_category_id,
					purchase_order_title: that.purchase_order_title,
					purchase_order_quantity: parseInt(that.purchase_order_quantity),
					origin_place_id: that.ud_id,
					purchase_province_id: that.selectedProId,
					purchase_city_id: that.selectedCityId,
					purchase_county_id: that.selectedCountyId,
					purchase_province: that.selectedPro,
					purchase_city: that.selectedCity,
					purchase_county: that.selectedCounty,
					purchase_order_description: that.purchase_order_description,
					purchase_product_spec: that.purchase_product_spec,
					purchase_origin_price_max: that.purchase_origin_price_max,
					purchase_invoice_enable: that.purchase_invoice_enable,
					purchase_origin_receive_time: that.purchase_origin_receive_time,
					purchase_deadline: that.purchase_deadline,
					purchase_order_unit: that.purchase_order_unit,
					purchase_product_images: that.data_info.comment_image.join(','),
				};





				that.$.request({
					url: this.Config.URL.hall.user_purchase_order,
					data: params,
					method: 'POST',
					success: function(data, status, msg, code) {
						if (status == 200) {

							that.$.showToast({
								title: that.__("更新成功!"),
								success: function() {
									that.$.gotopage("/hall/purchase/detail?order_id=" + data.purchase_order_id)
								}
							})


						} else {
							that.$.confirm(msg);
						}
					}
				});
			},

			selectAddress: function() {
				var that = this;
				var urlArgs = that.urlArgs;
				var url = '';

				if (true) {
					url = "/member/address/list";
					urlArgs.issub = "true";
					urlArgs.ud_id = that.ud_id;
				}
				that.$.navigateTo({
					url: that.$.createUrl(url, urlArgs)
				});

			},

			RefreshOrder: function(e) {
				console.log(e)
				this.setData({
					ud_id: e.ud_id,
					receiving: e.address
				})


			},

			onCancel: function(e) {
				return
			},




			onFail: function(e) {},

			// 三级联动选择
			showCityBox() {
				/*
				this.setData({
				    isShow: true
				})
				*/
				this.$refs.mpvueCityPicker.show()
			},



			onConfirm(e) {
				let that = this;
				console.info(e);
				//console.info(JSON.stringify(e));
				this.pickerText = JSON.stringify(e)



				this.setData({
					isDistrict: true,
					Pindex: this.cityCode,
					selectedProId: e.value[0],
					selectedCityId: e.value[1],
					selectedCountyId: e.value[2],
					selectedPro: e.label[0],
					selectedCity: e.label[1],
					selectedCounty: e.label[2],
					seladstr: that.$.isNull(e.label.toString()) ? that.__("请选择地址") : e.label.toString()
				});
			},


			onChangeProtocol: function(e) {
				var values = e.detail.value;

				if (values.length > 0) {
					this.protocol_checked = true;
				} else {
					this.protocol_checked = false;
				}
			},

			showProtocol: function(id) {
				uni.navigateTo({
					url: '/member/member/protocol?id=' + id
				})
			},
			onNumberChange: function(e) {
				console.log(e)
				this.user_number = e
			},

			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();


				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			}
		}
	};
</script>

<style lang="scss">
	@import "../../styles/_variables";

	.m-cell-bd label {
		color: #888;
	}

	.m-cell-vcode {
		padding-top: 0;
		padding-right: 0;
		padding-bottom: 0;
	}

	.m-vcode-img {
		width: 216rpx;
		height: 88rpx;
	}

	.btn_box {
		padding: 20rpx;
	}

	.m-code {
		right: 210rpx;
	}

	.m-vcode-btn {
		width: 150rpx;
		text-align: center;
	}

	#editor {
		width: 100%;
		height: 300rpx;
	}

	.ql-container {
		min-height: 300rpx;
	}

	.m-upImg {
		box-sizing: border-box;
		padding: 20rpx;
		background-color: #fff;
	}

	.m-upImg-item {
		width: 120rpx;
		height: 120rpx;
		border: 1px solid #eee;
		display: inline-block;
		margin: 9rpx;
		border-radius: 4rpx;
		vertical-align: middle;
		position: relative;
	}

	.m-upImg-item image {
		width: 100%;
		height: 100%;
	}

	.upSelect {
		background-color: #eee;
		text-align: center;
		line-height: 120rpx;
	}

	.upSelect label {
		font-size: 40rpx;
	}

	.u-del-item {
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		text-align: center;
		line-height: 40rpx;
		color: #fff;
		z-index: 5;
	}

	.u-del-item label {
		font-size: 28rpx;
	}
</style>