<template>
	<view class="flex-col padding">
		<view class="response flex-col align-center">

			<view class="response flex-col justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">照片</text>
				</view>
				<view class="w700 flex-row align-center margin-top">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						accept='image' :previewFullImage="true" :maxCount="5" width="120" height="120"
						maxSize="10485760"></u-upload>
				</view>
			</view>

			<view class="response flex-col justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs"></text>
					<text class="text-black">视频</text>
				</view>
				<view class="w700 flex-row align-center margin-top">
					<u-upload v-if="!postData.carVideo" :fileList="videoList" @afterRead="afterReadVideo"
						@delete="deleteVideo" accept='video' :maxCount="1" width="120" height="120" maxSize="52428800">
					</u-upload>
					<view style=" height: 320rpx;" class="response flex-row align-end" v-if="postData.carVideo">
						<video style="width: 180rpx; height: 320rpx;" :src="baseUrl+postData.carVideo"
							class="margin-right" v-if="postData.carVideo" controls></video>
						<text @click="deleteVideo" class="text-sm text-red">删除视频</text>
					</view>
				</view>

			</view>
			<view style="display: none;">
				<u--input inputAlign="right" :readonly="true" :hidden="false" :value="postData.carPics"></u--input>
			</view>
			<view class="response flex-row justify-between bg-white margin-top padding">
				<u--textarea v-model="postData.carDesc" placeholder="请描述维修车辆情况" count autoHeight></u--textarea>
			</view>


			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">地区</text>
				</view>
				<view class="w350 flex-row align-center" @click="addressShow = true">
					<pickerAddress v-model="addressShow" @confirm="addresspick" />
					<u--input inputAlign="right" placeholder="点击选择地址" border="none" :readonly="true"
						:value="address"></u--input>
					<u-icon name="arrow-right" class="margin-left-xs"></u-icon>
				</view>
			</view>

			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">品牌</text>
				</view>
				<view class="w250">
					<u--input inputAlign="right" placeholder="请输入品牌" border="none"
						v-model.trim="postData.carBrand"></u--input>
				</view>
			</view>


			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">型号</text>
				</view>
				<view class="w250">
					<u--input inputAlign="right" placeholder="请输入型号" border="none"
						v-model.trim="postData.carModel"></u--input>
				</view>
			</view>


			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">上户日期</text>
				</view>
				<u-datetime-picker :show="carRecordDatePickerShow" v-model="maxDate" :maxDate="maxDate"
					:minDate="minDate" confirmColor="#242a38" @confirm="carRecordDatePickerConfirm"
					@cancel="carRecordDatePickerShow = false" mode="date" visibleItemCount="5"
					itemHeight="80"></u-datetime-picker>
				<view class="w250 flex-row align-center" @click="carRecordDatePickerShow = true">
					<u--input inputAlign="right" placeholder="请选择上户日期" border="none" :readonly="true"
						v-model.trim="postData.carRecordDate"></u--input>
					<u-icon name="arrow-right" class="margin-left-xs"></u-icon>
				</view>
			</view>


			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">公里数</text>
				</view>
				<view class="w250">
					<u--input inputAlign="right" placeholder="请输入公里数" border="none" type="number"
						v-model.trim="postData.carKilometers"></u--input>
				</view>
			</view>

			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">价格</text>
				</view>
				<view class="w250">
					<u--input inputAlign="right" placeholder="请输入价格" border="none" type="number"
						v-model.trim="postData.carPrice"></u--input>
				</view>
			</view>

			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">姓名</text>
				</view>
				<view class="w250">
					<u--input inputAlign="right" placeholder="请输入姓名" border="none"
						v-model.trim="postData.contactName"></u--input>
				</view>
			</view>
			<view class="response flex-row justify-between bg-white margin-top padding">
				<view class="flex-row align-center">
					<text class="text-red margin-right-xs">*</text>
					<text class="text-black">电话</text>
				</view>
				<view class="w250">
					<u--input inputAlign="right" placeholder="请输入电话" border="none"
						v-model.trim="postData.contectTel"></u--input>
				</view>
			</view>

			<view class="response margin-top">
				<u-button text="提交" :customStyle="{color:'#8a6e4b'}" @click="editWx" throttleTime="3000"
					color="linear-gradient(to right, rgb(244, 230, 186), rgb(252, 236, 210))"></u-button>
			</view>
		</view>
	</view>

</template>
<script>
	import pickerAddress from '../components/liudx-pickerAddress/index.vue'
	import {
		getToken
	} from "@/utils/auth.js"
	export default {
		components: {
			pickerAddress
		},
		data() {
			return {
				baseUrl: getApp().globalData.config.baseUrl,
				fileList1: [],
				maxDate: null,
				minDate: null,
				videoList: [],
				postData: {
					carId: '',
					province: null,
					city: null,
					county: null,
					carPics: '',
					carRecordDate: null,
					carKilometers: null,
					carBrand: null,
					carModel: null,
					contactName: null,
					contectTel: null,
					carPrice: null,
					carType: null,
					carVideo: null,
					carDesc: ''
				},
				user: {},
				addressShow: false,
				carRecordDatePickerShow: false,
				address: '',
				postNum: 0,
				limitNum: 0,
				role: ''
			};
		},
		onShow() {
			this.getConfig();
			this.getMaxDateAndMinDate();
		},
		onLoad(option) {
			if (option) {
				this.postData.carId = option.carId
				this.getCarInfo(option.carId)
			} else {
				this.$tab.navigateBack()
			}
		},
		methods: {
			async getCarInfo(carId) {
				const res = await this.$request({
					url: '/system/car/getInfoWx/' + carId,
				})
				this.postData = res.data
				console.log(this.postData);
				let url = res.data.carPics.split(",");

				for (let i = 0; i < url.length; i++) {
					this.fileList1.push({
						url: this.baseUrl + url[i]
					})
				}
				console.log(this.fileList1);

				// this.postData.carVideo = this.baseUrl + this.postData.carVideo

				const getProvince = await this.$request({
					url: '/shop/region/getInfoWx/' + res.data.province,
				})
				const getCity = await this.$request({
					url: '/shop/region/getInfoWx/' + res.data.city,
				})
				const getCounty = await this.$request({
					url: '/shop/region/getInfoWx/' + res.data.county,
				})
				this.address = getProvince.data.name + getCity.data.name + getCounty.data.name

			},
			// 删除图片
			deletePic(event) {
				console.log(event);
				let pics = this.postData.carPics.split(',');
				pics.splice(event.index, 1); // 使用 splice() 方法删除指定索引处的元素
				let str = pics.join(',');
				this.$set(this.postData, 'carPics', str)
				this[`fileList${event.name}`].splice(event.index, 1)
			},

			deleteVideo(event) {
				this.postData.carVideo = null;
			},

			// 新增视频
			async afterReadVideo(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.videoList.length
				lists.map((item) => {
					this.videoList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadVideoPromise(lists[i].url)
					let item = this.videoList[fileListLen]
					this.videoList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file)
				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++) {
					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++
				}
				
			},
			// 上传视频
			uploadVideoPromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.baseUrl + '/common/uploadImg',
						headers: {
							Authorization: "Bearer " + getToken(),
						},
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							try {
								let video = JSON.parse(res.data);
								this.postData.carVideo = video.fileName

							} catch (e) {
								//TODO handle the exception
							}
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.baseUrl + '/common/uploadImg',
						headers: {
							Authorization: "Bearer " + getToken(),
						},
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							try {
								let img = JSON.parse(res.data);
								if (!this.postData.carPics.length) {
									this.postData.carPics = img.fileName
								} else {
									this.postData.carPics = this.postData.carPics + ',' + img.fileName
								}

							} catch (e) {
								//TODO handle the exception
							}
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			// 获取最大日期和最小日期
			getMaxDateAndMinDate() {
				const currentDate = new Date(); // 获取当前日期
				const thirtyYearsAgo = new Date(currentDate.getFullYear() - 30, currentDate.getMonth(), currentDate
					.getDate()); // 30年之前的日期
				this.maxDate = Number(currentDate);
				this.minDate = thirtyYearsAgo.getTime();
			},

			// 获取省市区
			addresspick(result) {
				console.log(result);
				this.address = result.province.name + result.city.name + result.area.name
				this.postData.city = result.city.code
				this.postData.province = result.province.code
				this.postData.county = result.area.code
			},

			// 获得上户日期
			carRecordDatePickerConfirm(e) {
				// console.log(e.value);
				this.postData.carRecordDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.carRecordDatePickerShow = false
			},


			//提交数据
			async editWx() {
				if (uni.$u.test.isEmpty(this.postData.province)) {
					return this.$modal.msgError('请选择地址-省')
				}
				if (uni.$u.test.isEmpty(this.postData.city)) {
					return this.$modal.msgError('请选择地址-市')
				}
				if (uni.$u.test.isEmpty(this.postData.county)) {
					return this.$modal.msgError('请选择地址-县')
				}
				if (uni.$u.test.isEmpty(this.postData.carPics.length)) {
					return this.$modal.msgError('请上传图片')
				}
				if (uni.$u.test.isEmpty(this.postData.carRecordDate)) {
					return this.$modal.msgError('请选择上牌日期')
				}
				if (uni.$u.test.isEmpty(this.postData.carKilometers)) {
					return this.$modal.msgError('请填写公里数')
				}
				if (uni.$u.test.isEmpty(this.postData.carBrand)) {
					return this.$modal.msgError('请填写品牌')
				}
				if (uni.$u.test.isEmpty(this.postData.carModel)) {
					return this.$modal.msgError('请填写型号')
				}
				if (uni.$u.test.isEmpty(this.postData.contactName)) {
					return this.$modal.msgError('请填写姓名')
				}
				if (uni.$u.test.isEmpty(this.postData.contectTel)) {
					return this.$modal.msgError('请填写电话')
				}
				const res = await this.$request({
					url: '/system/car/editWx',
					method: 'PUT',
					data: this.postData
				})
				this.$modal.msgSuccess('提交成功')
				setTimeout(() => {
					this.$tab.navigateBack()
				}, 2500)
			},
			// 获取配置
			async getConfig() {
				const user = await this.$request({
					url: '/getInfo',
				})
				if (user.code == 200 && user.hasOwnProperty('user')) {
					this.user = user.user
					this.postData.contectTel = user.user.phonenumber
					this.postData.contactName = user.user.realName
					if (user.roles.length > 0 && user.roles[0] == 'dealers') {
						this.role = user.roles[0]
					}
				}
			},
		},
	};
</script>
<style>
</style>