<template>
	<view class="content">
		<view class="top-tab">
			<u-tabs :list="tabsList" :scrollable="false" lineWidth="25" lineColor="#0A994A" color="#969696"
				:activeStyle="{color: '#15CA65', fontWeight: '400', transform: 'scale(1.05)', size:'20rpx'}"
				lineHeight="4" :current="tabCurrent" @change="tabChange"></u-tabs>
		</view>
		<u--form :model="needsPublishForm" ref="uNeedsForm" :labelStyle="formLabelStyle">
			<view style="margin-bottom: 20rpx;">
				<u-form-item label="姓名" borderBottom>
					<u-input v-model="needsPublishForm.name" :border="false" placeholder="请输入您的名称"
						placeholder-style="color:#CCCCCC" />
				</u-form-item>
				<u-form-item label="城市">
					<view class="select-view" @tap="showCityPicker = true">
						<text v-if="needsPublishForm.area_name">{{needsPublishForm.area_name}}</text>
						<text v-else style="color:#CCCCCC;">请选择所在城市</text>
						<u-icon name="arrow-right" color="#969696" size="14"></u-icon>
					</view>
					<cityPicker :show-picker="showCityPicker" @cancel="showCityPicker = false" @confirm="getCityValue">
					</cityPicker>
				</u-form-item>
			</view>

			<view style="margin-bottom: 20rpx;">
				<view v-if="tabCurrent === 1">
					<u-form-item label="品名" borderBottom>
						<u-input v-model="needsPublishForm.pname" :border="false" placeholder="请输入您的产品名称"
							placeholder-style="color:#CCCCCC" />
					</u-form-item>
					<u-form-item label="分类" borderBottom>
						<view class="select-view" @tap="showCategoryPicker = true">
							<text v-if="needsPublishForm.class">{{needsPublishForm.class}}</text>
							<text v-else style="color:#CCCCCC;">请选择分类</text>
							<u-icon name="arrow-right" color="#969696" size="14"></u-icon>
						</view>
						<u-picker :show="showCategoryPicker" :columns="categoryPickerList"
							@cancel="showCategoryPicker = false" @confirm="getCategoryValue"></u-picker>
					</u-form-item>
				</view>
				<u-form-item label="产品" borderBottom>
					<view class="select-view" @tap="showProductPicker = true">
						<text v-if="needsPublishForm.product">{{needsPublishForm.product}}</text>
						<text v-else style="color:#CCCCCC;">请选择产品类型</text>
						<u-icon name="arrow-right" color="#969696" size="14"></u-icon>
					</view>
					<u-picker :show="showProductPicker" :columns="productPickerColumn"
						@cancel="showProductPicker = false" @confirm="getProductValue"></u-picker>
				</u-form-item>
				<u-form-item label="定位" borderBottom>
					<view class="select-view" @tap="showPositionPicker = true">
						<text v-if="needsPublishForm.loc">{{needsPublishForm.loc}}</text>
						<text v-else style="color:#CCCCCC;">请选择产品定位</text>
						<u-icon name="arrow-right" color="#969696" size="14"></u-icon>
					</view>
					<u-picker :show=showPositionPicker :columns="positionPickerColumn"
						@cancel="showPositionPicker = false" @confirm="getPositionValue"></u-picker>
				</u-form-item>
				<view style="padding: 20rpx 15rpx;background-color: #fff;">
					<u-textarea v-model="needsPublishForm.desc" border="surround" placeholder="请输入具体描述(限120字)"
						:maxlength="120" placeholder-style="color:#CCCCCC"></u-textarea>
				</view>
			</view>

			<view v-if="tabCurrent === 1" style="margin-bottom: 20rpx;">
				<u-form-item label="上传图片" labelPosition="top">
					<view style="padding-left: 20rpx;margin-top: 20rpx;">
						<u-upload :fileList="fileList1" :auto-upload="false" @afterRead="afterRead" @delete="deletePic"
							name="1" multiple :maxCount="10"></u-upload>
					</view>
				</u-form-item>
			</view>

			<view style="background-color: #fff;">
				<u-form-item label="手机" borderBottom>
					<u--input placeholder="请输入手机号" :border="false" v-model="needsPublishForm.mobile"
						placeholder-style="color:#CCCCCC"></u--input>
				</u-form-item>
				<!-- <u-form-item label="验证" borderBottom>
					<view style="display: flex;padding-right: 20rpx;align-items: center;">
						<u--input placeholder="请输入验证码" :border="false" v-model="needsPublishForm.invalidCode"
							placeholder-style="color:#CCCCCC"></u--input>
						<u-code ref="uCode" @change="codeChange" keep-running change-text="倒计时XS"
							@start="disabled = true" @end="disabled = false"></u-code>
						<u-button size="small" type="primary" @tap="getCode" :text="tips" color="#EEEEEE"
							:disabled="disabled" customStyle="color:#666666; width:160rpx;"></u-button>
					</view>
				</u-form-item> -->
				<view style="padding: 30rpx;background-color: #fff;">
					<u-button color="#0EBB5B" text="确定发布" @tap.stop="submitForm"></u-button>
				</view>
				<view style="padding: 20rpx;text-align: center;background-color: #fff;">
					<text
						style="font-size: 24rpx;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: #C8C8C8;line-height: 28rpx;">承诺声明预留文字位置承诺声明预留文字位置</text>
				</view>
			</view>
		</u--form>
		<view style="margin:0 20rpx;">
			<u-overlay :show="!isLoad">
				<login @success="reOnLoad()" @fail="failToLoad()"></login>
			</u-overlay>
		</view>

	</view>
</template>

<script>
	import {
		apiService
	} from '../../service/request'
	import login from '../my/login/login.vue'
	export default {
		components: {
			login
		},
		data() {
			return {
				tabsList: [{
					name: '需求发布'
				}, {
					name: '创意发布'
				}],
				tabCurrent: 0,
				needsPublishForm: {},
				formLabelStyle: {
					'font-size': '32rpx !important'
				},
				showCityPicker: false,
				showProductPicker: false,
				showPositionPicker: false,
				showCategoryPicker: false,
				seconds: 10,
				disabled: false,
				tips: '获取验证码',
				productPickerList: [],
				productPickerColumn: [
					[]
					// {name: '烘焙', val: 'hongbei'}
					// {name: '零食', val: 'ls'}
					// {name: '饮料', val: 'yl'}
				],
				positionPickerList: [],
				positionPickerColumn: [
					[]
				],
				categoryPickerList: [],
				fileList1: [
					// uploads/images/20230117/202301172309397deda1543.jpg
				],
				isLoad: true,
				cateName: null,
				tagName: null,
				token: null,
				imgUrl: null
			}
		},
		onTabItemTap() {
      this.imgUrl = uni.getStorageSync('img_url')
			console.log('----onShow')
			if (!uni.getStorageSync('loginToken') || uni.getStorageSync('loginToken').length === 0) {
				console.log(uni.getStorageSync('loginToken'))
				this.isLoad = false
				// uni.navigateTo({
				// 	url: '../../pages/my/login/login'
				// })
				return
			}
			this.isLoad = true
			this.token = uni.getStorageSync('loginToken')
			this.tabCurrent = 0
			this.fileList1 = []
			this.needsPublishForm = {}
		},
		onLoad(options) {
			this.imgUrl = uni.getStorageSync('img_url')
			//我的发布点击修改回显数据
			if (options && options.item && uni.getStorageSync(options.item)) {
				try {
					let publishFormList = uni.getStorageSync(options.item)
					console.log(publishFormList.images)
					this.fileList1 = publishFormList.images.map(item => {
						console.log(this.imgUrl)
						return {
							url: item
						}
					})
					console.log(this.fileList1)
					this.needsPublishForm = publishFormList
				} catch (error) {
					this.$toast.warn(error)
				}
			}
			if (options.index == 0) {
				this.tabCurrent = 0
			} else if (options.index == 1) {
				this.tabCurrent = 1
			}
			// this.getProductPickerList()
		},
		onShow() {
			this.getFormData()
		},
		methods: {
			tabChange(data) {
				this.tabCurrent = data.index
				this.needsPublishForm = {}
			},
			getFormData() {
				this.$apiServe.getIdeasAndNeedsFormdata().then(res => {
					console.log(res.data.data)
					const formData = res.data.data
					this.productPickerColumn[0] = formData.product
					this.positionPickerColumn[0] = formData.loc
					this.categoryPickerList[0] = formData.class
					// this.productPickerList = res.data.data.map((item, index) => {
					// 	temp.push(item.name)
					// 	return item
					// })
					// this.productPickerColumn[0] = [...temp]
				}).finally(_ => {})
			},
			// getProductPickerList() {
			// 	const data = {}
			// 	const temp = []
			// 	this.$apiServe.getCategories(data).then(res => {
			// 		this.productPickerList = res.data.data.map((item, index) => {
			// 			temp.push(item.name)
			// 			return item
			// 		})
			// 		// this.productPickerColumn[0] = [...temp]
			// 	}).finally(_ => {})
			// },
			// getPositionPickerList() {
			// 	if (this.needsPublishForm.cate_id) {
			// 		const data = {
			// 			pid: this.needsPublishForm.cate_id
			// 		}
			// 		this.$apiServe.getTags(data).then(res => {
			// 			const temp = []
			// 			this.positionPickerList = res.data.data.map((item, index) => {
			// 				temp.push(item.name)
			// 				return item
			// 			})
			// 			this.positionPickerColumn[0] = temp
			// 		}).finally(_ => {})
			// 	} else {
			// 		that.$toast.warn('请先选择产品类型')
			// 	}
			// },
			getCityValue(data) {
				console.log(data)
				this.showCityPicker = false
				this.needsPublishForm.area_name = data[0].join('-')
				this.needsPublishForm.area_code = data[1]
			},
			getProductValue(data) {
				this.showProductPicker = false
				this.showCategoryPicker = false
				this.needsPublishForm.product = data.value[0]
				// console.log(data)
				// const obj = this.productPickerList.find(item => {
				// 	return item.name === data.value[0]
				// })
				// this.cateName = data.value[0]
				// if (obj) {
				// 	this.needsPublishForm.cate_id = obj.id
				// }
				// this.needsPublishForm.tagids = null
				// this.getPositionPickerList()
			},
			getPositionValue(data) {
				this.showPositionPicker = false
				this.needsPublishForm.loc = data.value[0]
				// const obj = this.positionPickerList.find(item => {
				// 	return item.name === data.value[0]
				// })
				// this.tagName = data.value[0]
				// if (obj) {
				// 	this.needsPublishForm.tagids = obj.id
				// }
			},
			getCategoryValue(data) {
				this.showCategoryPicker = false
				this.needsPublishForm.class = data.value[0]
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					setTimeout(() => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}, 2000);
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			codeChange(text) {
				this.tips = text;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log(this.fileList1)
				console.log(lists)
				console.log(this[`fileList${event.name}`])
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					console.log(lists[i])
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					// const data = {
					// 	file: new File
					// }
					// let a = apiService.postImage(data).then(res => {
					// 	console.log(res)
					// })
					console.log('--345')
					console.log(url)
					console.log(this.token)
					console.log(apiService.uploadImgUrl)
					let a = uni.uploadFile({
						url: apiService.uploadImgUrl,
						filePath: url,
						name: 'file',
						header: {
							"Content-Type": "multipart/form-data",
							"token": this.token
						},
						success: (res) => {
							setTimeout(() => {
								console.log('---355')
								console.log(JSON.parse(res.data).data.url)
								resolve(JSON.parse(res.data).data.url)
							}, 1000)
						}
					});
				})
			},
			submitForm() {
				console.log(this.fileList1)
				if (!/^1[3456789]\d{9}$/.test(this.needsPublishForm.mobile)) {
					this.$toast.warn('请输入正确的手机号')
					return false
				}
				this.needsPublishForm.type = Number(this.tabCurrent + 1)
				this.needsPublishForm.pub_time = this.needsPublishForm.pub_time ? this.needsPublishForm.pub_time :
					Math.round(new Date().getTime() / 1000)
				const temp = []
				if (this.fileList1.length > 0) {
					this.fileList1.map(item => {
						const url = item.url
						temp.push(url.replace(this.imgUrl + '/', ''))
					})
				}
				this.needsPublishForm.images = temp.join(';')
				const data = {
					type: null,
					name: null,
					pname: null,
					area_code: null,
					area_name: null,
					images: null,
					mobile: null,
					class: null,
					product: null,
					loc: null,
					desc: null,
					pub_time: null,
					...this.needsPublishForm
				}
				console.log(data)
				apiService.submitIdeasAndNeeds(data).then(res => {
					this.$toast.success('提交成功')
					console.log('esf=', res);
					if (res.data.code == 1) {
						uni.navigateTo({
							url: '../../packageMy/myRelease/myRelease?index=' + (this.tabCurrent + 1)
						})
					}
					this.tabCurrent = 0
					this.fileList1 = []
					this.needsPublishForm = {}
					// this.$toast.success(res.data.msg)
				}).catch(error => {
					this.$toast.warn(error)
				})
			},
			reOnLoad() {
				console.log('----------------true')
				if (!uni.getStorageSync('loginToken') || uni.getStorageSync('loginToken').length === 0) {
					this.$toast.warn('登录失败请重试')
					this.isLoad = false
					// uni.navigateTo({
					// 	url: '../../pages/my/login/login'
					// })
					return
				}
				this.token = uni.getStorageSync('loginToken')
				this.isLoad = true
				this.getFormData()
			},
			failToLoad() {
				console.log('----------------false')
				this.$toast.warn('登录失败请重试')
				uni.reLaunch({
					url: '/pages/index/index'
				})
				// uni.navigateBack({
				//   success: () => {
				//     let page = getCurrentPages().pop();
				//     if (page) {
				//        page.onLoad(page.options);//执行上个页面的方法
				//     };
				//   }
				// })
			}
		}

	}
</script>

<style lang="less" scoped>
	.content {
		background-color: #F8F8F8;

		.top-tab {
			background-color: #fff;
			margin-bottom: 10rpx;
		}

		.select-view {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 14rpx 18rpx;
			font-size: 30rpx;
		}

		/deep/.u-form-item__body__left__content__label {
			font-size: 32rpx !important;
		}

		/deep/.u-form-item__body {
			padding: 13rpx 0 !important;
		}

		/deep/.u-textarea {
			border-radius: 20rpx;
			border: 1px solid #EEEEEE;
		}
	}
</style>
