<template>
	<view class="container">
		<view class="searchBox" :style="{ height: localHeight + 'px', paddingTop: top + 'px' }">
			<view class="searchBox_add">
				<view class="searchBox_left">
					<u-icon bold color="#000" size="40" name="arrow-left" @click="back"></u-icon>
				</view>
				<view class="searchBox_mid">报修信息</view>
				<view class="searchBox_right"></view>
			</view>
		</view>

		<view class="repairMsg">
			<view class="repairTit">
				报修信息
			</view>

			<view class="label"><span class="red">*</span>选择房源信息</view>
			<view class="roomList">
				<view v-for="(item, index) in roomList" :key="index" :class="active == index ?'roomItem active':'roomItem'" @click="changeAct(index)">{{ item.name }}</view>
			</view>

			<view class="row">
				<view class="row_label"><span class="red">*</span>报修类型</view>
				<view class="row_con" @click="chose">
					<input type="text" :value="category.category_name" placeholder="请选择报修类型" disabled>
					<u-icon bold color="#999999" size="30" name="arrow-right"></u-icon>
				</view>
			</view>

			<view class="row">
				<view class="row_label"><span class="red">*</span>问题描述</view>
				<view class="row_con">
					<input type="text" placeholder="请描述故障" :value="repairInfo" data-name="repairInfo"  @input="handlerInputClick">
				</view>
			</view>

			<view class="row">
				<view class="row_label"><span class="red">*</span>联系人</view>
				<view class="row_con">
					<input type="text" placeholder="请输入您的姓名" :value="contactName" data-name="contactName"  @input="handlerInputClick">
				</view>
			</view>

			<view class="row">
				<view class="row_label"><span class="red">*</span>联系电话</view>
				<view class="row_con">
					<input type="number" maxlength="11" placeholder="请输入您的联系方式" :value="contactPhone" data-name="contactPhone"  @input="handlerInputClick">
				</view>
			</view>

			<view class="row noneBorder">
				<view class="row_label"><span class="red">*</span>上门时间</view>
				<view class="row_con" @click="choseTime">
					<input type="text" :value="time" placeholder="请选择上门时间" disabled>
					<u-icon bold color="#999999" size="30" name="arrow-right"></u-icon>
				</view>
			</view>
		</view>

		<view class="repairMedia">
			<view class="row df">
				<view class="row_label">上传图片</view>
				<view class="row_con2">
					<u-upload :fileList="imgList" name="imgList" @afterRead="afterReadImg" @delete="deletePic" multiple
						:maxCount="5">
						<view class="imgCon">
							<image src="https://static.hshuishang.com/property-img-file/com_imageImg.png" mode="widthFix"></image>
							上传图片
						</view>
					</u-upload>
				</view>
			</view>

			<view class="row df">
				<view class="row_label">上传视频</view>
				<view class="row_con2">
					<u-upload v-if="!videoList.url" :fileList="videoList" @afterRead="afterReadVideo" @delete="deleteVideo" name="videoList"
						:maxCount="1" accept="video">
						<view class="imgCon">
							<image src="https://static.hshuishang.com/property-img-file/com_videoImg.png"  mode="widthFix"></image>
							上传视频
						</view>
					</u-upload>

					<view v-if="videoList.url" class="videoBOX">
						<video id="myVideo" :src="videoList.url" playsinline webkit-playsinline></video>
						<view class="mask" @click="playFullScreenVideo">
							<view class="mask_cancel" @click="cancels">删除</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<u-picker :show="show" :columns="[columns]" keyName="category_name" @confirm="confirm1" @cancel="cancel1" />
		<u-datetime-picker
			:show="show2"
			mode="datetime"
			:closeOnClickOverlay="true"
			:minDate="minDate"
			:formatter="formatter"
			@confirm="confirm2"
			@cancel="cancel2"
			@close="cancel2"
		/>

		<view class="btn" @click="handlerSubmitClick">确认报修</view>

	</view>
</template>

<script>
import {
	request,
	picUrl,
	upload,
	uploadVideo,
	menuButtonInfo
} from '../../../utils';
import {
	apiArr
} from '../../../api/v2Community';
export default {
	data() {
		return {
			picUrl,
			active: 0,
			top: "",
			localHeight: "",
			roomList: [],
			columns: [],
			category: {}, // 报修类型信息
			repairInfo: '', // 问题描述
			contactName: '', // 联系人名称
			contactPhone: '', // 联系人电话
			show: false,
			show2: false,
			time: '',
			minDate: new Date().getTime(),
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`;
				}
				if (type === 'month') {
					return `${value}月`;
				}
				if (type === 'day') {
					return `${value}日`;
				}
				return value;
			},


			imgList: [],
			videoList: {},
		}
	},
	methods: {
		back() {
			uni.navigateBack({
				delta: 1
			});
		},
		chose() {
			this.show = true;
		},
		cancel1() {
			this.show = false;
		},
		confirm1(e) {
			const { value } = e;
			this.category = value[0];
			this.show = false;
		},
		choseTime() {
			this.show2 = true;
		},

		cancel2() {
			this.show2 = false;
		},

		handlerInputClick(e) {
			const { name} = e.currentTarget.dataset;
			this[name] = e.detail.value
		},
		
		// 时间选择器点击确定
		confirm2(e) {
			const date = new Date(e.value); // 获取选中的 Date 对象
			const year = date.getFullYear(); // 获取年份
			const month = date.getMonth() + 1; // 获取月份（注意月份从 0 开始，需要 +1）
			const day = date.getDate(); // 获取日期
			const hours =date.getHours()
			const minutes = date.getMinutes(); 
			const time = `${year}-${month}-${day} ${hours}:${minutes}`;
			this.time = time;
			this.show2 = false;
		},

		// 上传图片
		async afterReadImg(e){
			const { file} = e;
      file.forEach(item => {
        upload(item.url, res => {
          this.imgList.push({
            url: picUrl + res.data.path,
						picUrl: res.data.path,
          })
        })
      })
			uni.hideLoading();
      uni.showToast({
				title: '上传成功',
				icon: 'success'
			});
		},
		deletePic(e) {
			this.imgList.splice(e.index, 1);
		},
		afterReadVideo(e){
			uploadVideo(e.file.url, res => {
				this.videoList = {
					url: this.picUrl + res.data.url,
					videos: res.data.url
				}
			})
		},
		deleteVideo(e) {
			this.videoList = {};
		},

		changeAct(e){
			this.active = e;
		},
		async handlerSubmitClick() {
			// 表单验证
			if (!this.roomList[this.active]) {
				uni.showToast({
					title: '请选择房源信息',
					icon: 'none'
				});
				return;
			}
			
			if (!this.category.id) {
				uni.showToast({
					title: '请选择报修类型',
					icon: 'none'
				});
				return;
			}
			
			if (!this.repairInfo.trim()) {
				uni.showToast({
					title: '请输入问题描述',
					icon: 'none'
				});
				return;
			}
			
			if (!this.contactName.trim()) {
				uni.showToast({
					title: '请输入联系人姓名',
					icon: 'none'
				});
				return;
			}
			
			if (!this.contactPhone.trim() || this.contactPhone.length !== 11) {
				uni.showToast({
					title: '请输入有效的联系电话',
					icon: 'none'
				});
				return;
			}
			
			if (!this.time) {
				uni.showToast({
					title: '请选择上门时间',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({
				title: '提交中'
			});
			const res = await request(apiArr.workOrderCrudCreat, 'POST', {
				"community_id": uni.getStorageSync('changeCommData').id, // 所属小区ID
				"room_id": this.roomList[this.active].room_id, // 房源ID
				// "location": "具体位置", // 具体位置
				"order_category_id": this.category.id, // 报修类型ID
				"problem_description": this.repairInfo, // 问题描述
				"images": this.imgList.length !== 0 ? this.imgList.map(item => item.picUrl).join(',') : '', // 图片信息,可为空
				"videos": this.videoList.videos || '', // 视频
				// "urgency_level": 3, // 紧急程度
				"service_time": this.time, // 上门时间
				// "remarks": "备注", // 备注
				"source": 1, // 工单来源（1小程序 2后台）
				// "reporter_type": 3, // 上报人类型（1物业 2业主 3家属 4租户 5其它）
				// "reporter_id": 0, // 上报人ID
				"contact_name": this.contactName, // 联系人
				"contact_phone": this.contactPhone // 联系人手机号
			}, { silent: false });
			uni.hideLoading();
			uni.showToast({
				title: '提交成功'
			});
			setTimeout(() => {
				uni.navigateBack({
				delta: 1
			})
			}, 2000)
			
		},
		async init() {
			uni.showLoading({
				title: '加载中'
			})
			const res1 = await request(apiArr.workCommunityRoomList, 'POST', { community_id: uni.getStorageSync('changeCommData').id});
			this.roomList = res1.rows;
			const res = await request(apiArr.workOrderCategoryCrudList, 'POST', {});
			uni.hideLoading();
			this.columns = res.rows;
		},
		playFullScreenVideo() {
			this.videoContext = this.videoContext || wx.createVideoContext('myVideo')
			this.videoContext.requestFullScreen() // 请求全屏
		},
		cancels(e) {
			this.videoList = {};
		},
	},

	onLoad(options) {
		const meun = menuButtonInfo();
		this.top = meun.top;
		this.localHeight = meun.height;
		this.init();
	},

	onShow() {

	},

}
</script>

<style>
@import url("./index.css");
</style>