<template>
	<view class="container">
		<view class="detail-bg"></view>
		<nav-bar title="面试邀约"></nav-bar>
		<view class="content">
			<view class="detail-title">邀请面试</view>
			<view class="card-box">
				<view class="cell">
					<view class="cell-label">面试类型</view>
					<u-radio-group v-model="radioValue">
						<u-radio name="0">线下面试</u-radio>
						<u-radio name="1">线上面试</u-radio>
					</u-radio-group>

				</view>
				<view class="cell">
					<view class="cell-label">面试职位</view>
					<view class="cell-input" hover-class="cell-hover" @click="position = true">
						<view class="m-ellipsis">
							{{ selectedJob ? selectedJob.ruleClassifyName + ' · ' + selectedJob.salaryRange : '请选择职位' }}
						</view>
						<image class="cell-icon" src="/static/images/msg/down_arrow.svg" mode="aspectFit"></image>
					</view>
				</view>
				<view class="cell" v-if="radioValue == 0">
					<view class="cell-label">面试地址</view>
					<view class="cell-input" hover-class="cell-hover" @click="goPage('address',{detailedAddress,address,latitude,longitude})">
						<view class="m-ellipsis">{{selectedAddress || '请选择地址'}}</view>
						<image class="cell-icon" src="/static/images/msg/down_arrow.svg" mode="aspectFit"></image>
					</view>
				</view>
				<view class="cell" v-if="radioValue == 1">
					<view class="cell-label">面试方式</view>
					<view class="cell-input" hover-class="cell-hover" @click="method = true">
						<view class="m-ellipsis">{{selecteMethodText || '请选择面试方式'}}</view>
						<image class="cell-icon" src="/static/images/msg/down_arrow.svg" mode="aspectFit"></image>
					</view>
				</view>
				<view class="cell">
					<view class="cell-label">联系人</view>
					<view class="cell-input" hover-class="cell-hover" @click="person = true">
						<view class="m-ellipsis">{{personText || '请选择联系人'}}</view>
						<image class="cell-icon" src="/static/images/msg/down_arrow.svg" mode="aspectFit"></image>
					</view>
				</view>
				<view class="explanation">为保证求职者联系到面试企业，求职者接受面试后，可查看职位发布人＆联系人的电话</view>
			</view>
			<view class="card-box" style="padding: 0;">
				<view class="note">
					<view class="note-label note-time">面试日期</view>
					<uni-calendar class="uni-calendar--hook" :selected="selectedDate" :startDate="date" :showMonth="false" @change="change"
						@monthSwitch="monthSwitch" />
				</view>
			</view>
			<!-- 选择时间 -->
			<view class="card-box">
				<view class="cell" style="margin-bottom: 0;">
					<view class="cell-label">开始时间</view>
					<view class="cell-input flex-end" hover-class="cell-hover" @click="isShowTime = true">
						<view class="m-ellipsis">{{selectedTime || '请选择时间' }}</view>
						<image class="cell-icon" src="/static/images/msg/down_arrow.svg" mode="aspectFit"></image>
					</view>
				</view>
			</view>
			<view class="card-box">
				<view class="note">
					<view class="note-label">备注事项</view>
					<view class="textarea-wrapper">
						<textarea v-model="textareaValue" placeholder-class="placeholder-text"
							placeholder="请输入告知求职者的其他内容，例如具体路线，所需材料等。" @input="updateLength" :maxlength="140">
						</textarea>
						<view class="word-count"><text style="color: #016BF6;">{{ textareaLength }}</text>/140</view>
					</view>
				</view>
			</view>
		</view>
		<button class="btn" @click="rules = true">发送面试邀请</button>

		<!-- 面试职位 -->
		<u-popup v-model="position" mode="bottom" border-radius="40">
			<view class="pop-content">
				<view class="pop-title">选择面试职位</view>
				<scroll-view class="pop-card" scroll-y>
					<view class="pop-card-item" v-for="(item, index) in jobList" :key="index" @click="chooseJob(item)">
						<u-radio-group v-model="popRadioValue">
							<u-radio :name="item.ruleClassifyId"></u-radio>
						</u-radio-group>
						<view>{{ item.ruleClassifyName }}</view>
						<view class="pop-tag">
							{{ item.city }}
							<u-line color="#999999" direction="col" length="20rpx" margin="10rpx"></u-line>
							{{ item.education }}
							<u-line color="#999999" direction="col" length="20rpx" margin="10rpx"></u-line>
							{{ item.salaryRange }}
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<!-- 选择联系人 -->
		<u-popup v-model="person" mode="bottom" border-radius="40">
			<view class="pop-content">
				<view class="pop-title">
					<view>选择联系人</view>
					<view class="note">您可填写其他面试联系人电话，请保证已获得其授权同意，求职者接受面试后可以查看该号码</view>
				</view>
				<scroll-view class="pop-card" scroll-y>
					<view class="person-item" v-for="(item,index) in personList" :key="item.id"
						@click="selectPerson(item)">
						<view>{{item.hrName}}</view>
						<view class="pop-phone">{{item.hrPhone}}</view>
						<image class="pop-icon" src="/static/images/msg/edit.svg" mode="aspectFit"
							@click="goPage('editPerson',item)"></image>
					</view>
				</scroll-view>
				<button class="pop-btn" @click="goPage('addPerson')">新增联系人</button>
			</view>
		</u-popup>
		<!-- 选择面试方式 -->
		<u-popup v-model="method" mode="bottom" border-radius="40">
			<view class="pop-content">
				<view class="pop-title">选择面试方式</view>
				<view class="pop-method">
					<view v-for="(item,i) in methodList" :key="i" class="method-item"
						:class="methodActiveIndex == i?'active-item':''" @click="changeMethod(i,item)">{{ item }}
					</view>
					<view class="method-text">
						<textarea placeholder-class="pop-placeholder-text" v-model="onlineMsg" placeholder="粘贴会议邀请信息">
						</textarea>
					</view>
				</view>
				<button class="btn btn-m" @click="method = false">确定</button>
			</view>
		</u-popup>
		<!-- 选择时间 -->
		<u-popup v-model="isShowTime" mode="bottom" border-radius="40">
			<view class="pop-content">
				<view class="pop-title">请选择面试开始时间</view>
				<picker-view :value="timeValue" @change="bindChange" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in hours" :key="index">{{ item }}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in minutes" :key="index">{{ item }}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in meridiem" :key="index">{{ item }}</view>
					</picker-view-column>
				</picker-view>
				<button class="pop-time-btn" @click="changeBtn">确定</button>
			</view>
		</u-popup>
		<!-- 原则 -->
		<u-popup v-model="rules" mode="center" border-radius="40">
			<view class="pop-rules">
				<view class="pop-text">
					<view class="pop-rules-title">约面试诚信原则</view>
					<view v-if="isCancel">1.面试前3小时，双方可以申请取消<br />
						2.如不取消，请按时出席，不要爽约<br />
						3.对方爽约，可在平台内投诉<br />
						4.为了方便联系，约面试后上双方自动交换手机联系方式
					</view>
					<view v-else>请及时关注面试时间，以免忘记面试</view>
				</view>
				<view class="rules-btn" v-if="isCancel">
					<button class="cancel" hover-class="none" @click="rules = false">思考片刻再决定</button>
					<button class="guarantee" @click="isCancel = false">保证不爽约</button>
				</view>
				<view v-else>
					<button class="confirm" @click="confirmRules">确认</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import navBar from "@/components/nav-bar/index.vue";
	export default {
		data() {
			return {
				radioValue: 0, //类型
				position: false,
				textareaValue: '',
				textareaLength: 0,
				popRadioValue: '',
				jobList: {},
				selectedJob: '',
				selectedAddress: '',
				person: false,
				personList: [{
					id: 0,
					name: '宋先生',
					phone: '18888888888'
				}],
				personText: '',
				method: false,
				selected: [],
				// 选择时间
				isShowTime: false,
				selectedTime: '',
				timeValue: [0, 0, 0],
				hours: Array.from({
					length: 12
				}, (_, i) => i + 1),
				minutes: Array.from({
					length: 60
				}, (_, i) => i),
				meridiem: ['AM', 'PM'],
				methodList: ['腾讯会议', '钉钉', '微信视频', '电话面试'],
				methodActiveIndex: 0,
				selecteMethodText: '',
				rules: false,
				isCancel: true,
				postPushId: "",

				interviewDateTime: "",
				resumesId: "",
				companyId: "",
				remarks: "",
				detailedAddress: "",
				address: "",
				latitude:0,
				longitude:0,
				detailTime: "",
				onlineType: "",
				onlineMsg: "",
				hrPhone: "",
				interviewerId: "",
				hrName: "",
				signTime: "",
				date: "",
				time: "",
				recordId:'',
				selectedDate:[]
			};
		},
		components: {
			navBar
		},

		onLoad(option) {
			if (option.postPushId) {
				this.postPushId = option.postPushId
					console.log("接收到的参数postPushId：",option.postPushId)
			} 
			if (option.resumesId) {
				this.resumesId = option.resumesId
					console.log("接收到的参数resumesId：",option.resumesId)
			}
			if (option.interviewerId) {
				this.interviewerId = option.interviewerId
				console.log("接收到的参数interviewerId：",option.interviewerId)
			}
			
			if (option&&option.recordId) {
				this.recordId = option.recordId
					console.log("接收到的参数resumesId：",option.resumesId)
			}
			let stationNameInfo = this.$queue.getJson('companyAddressInfo') || [];
			this.selectedAddress = this.$queue.getData('companyAddress')
			this.detailedAddress = stationNameInfo.addressDetail
			this.address = stationNameInfo.address
			this.latitude=stationNameInfo.latitude
			this.longitude=stationNameInfo.longitude
			this.PostPushDetails()
			this.getCurrentDateTime()
			this.selectHrPhone()
		},

		methods: {
			change(e) {

				this.interviewDateTime = e.fulldate
				console.log('change 返回:', this.interviewDateTime)
			},
			monthSwitch(e) {
				console.log('monthSwitchs 返回:', e)
			},
			updateLength(e) {
				this.textareaLength = e.target.value.length
			},

			//根据传过来的Id查询对应岗位
			PostPushDetails() {
				uni.showLoading({
					title: '加载中'
				})
				let data = {
					postPushId: this.postPushId,
				}
				this.$Request.get('/app/postPush/selectPostPushDetails', data).then(res => {
					if (res.code == 0) {
						uni.hideLoading()
						this.jobList = [{
							...res.data,
							index: 0 // 添加下标
						}];
						this.companyId = res.data.companyId;
						this.selectedJob = res.data;
						this.popRadioValue = res.data.ruleClassifyId;
						if(this.recordId!=''){
							this.getData()
						}
						console.log(this.jobList)
					} else {
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '数据不存在',
							showCancel: false,
							complete(ret) {
								uni.navigateBack()
							}
						})
					}
				})
			
			},
			
		//获取联系人列表
			selectHrPhone(){
				this.$Request.get('/app/interviewRecord/selectHrPhone', {}).then(res => {
					if (res.code == 0) {
						uni.hideLoading()
						this.personList=res.data;
						if(res.data.length > 0){
							this.personText = res.data[0].hrName;
							this.hrPhone = res.data[0].hrPhone
						}else{
							this.personText = this.$queue.getData("userName");
							this.hrPhone = this.$queue.getData("phone");
						}
						console.log(res.data)
					} else {
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '数据不存在',
							showCancel: false,
							complete(ret) {
								uni.navigateBack()
							}
						})
					}
				})
			},
			
			chooseJob(item) {
				this.selectedJob = item;
				this.popRadioValue = item.ruleClassifyId;
				this.position = false;
			},
			// 选择地址  联系人  以及编辑联系人
			goPage(type, item) {
				uni.navigateTo({
					url: `/pages/msg/selectInterview?type=${type}`,
					success: (res) => {
						res.eventChannel.emit('sendData', {
							type,
							item,
							callback: (data) => {
								console.log(data)
								if (type === 'address') {
									this.selectedAddress = data.address + data.floor
									this.detailedAddress = data.floor
									this.address = data.address
									this.latitude=data.latitude
									this.longitude=data.longitude
								} else if (type === 'addPerson') {
									this.personList.push(data)
								} else if (type === 'editPerson') {
									const index = this.personList.findIndex(p => p.id === data.id)
									if (index !== -1) this.personList.splice(index, 1, data);
									this.personText = data.hrName;
								}
							}
						})
					}
				})
			},
			selectPerson(item) {
				this.personText = item.hrName;
				this.person = false;
				this.hrPhone = item.hrPhone
			},
			bindChange(e) {
				console.log(e.detail.value)
				this.timeValue = e.detail.value
			},
			changeBtn() {
				console.log(this.timeValue)
				const val = this.timeValue
				const hour = this.hours[val[0]]
				const minute = this.minutes[val[1]]
				const ampm = this.meridiem[val[2]]
				this.selectedTime = `${hour}:${minute < 10 ? '0' + minute : minute} ${ampm}`
				console.log(ampm)
				var hourss = hour
				if (ampm == "PM") {
					hourss = hour + 12;
				}
				var time = `${hourss}:${minute < 10 ? '0' + minute : minute}`
				if (this.isTimeGreaterThanNow(time)) {
					uni.showToast({
						title: '选择的时间不能早于当前时间',
						icon: 'none'
					});
					this.selectedTime = '';
					return;
				}
				this.isShowTime = false;
			},



			// 判断时间是否大于当前时间（同一天）
			isTimeGreaterThanNow(selectedTime) {
				const now = new Date();
				//const today = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;

				const timeString = `${this.interviewDateTime} ${selectedTime}`;
				const selectedDate = new Date(timeString);
				console.log(this.interviewDateTime)
				console.log("选择的日期和时间：", timeString);
				console.log("选择的日期和时间chuooooo：", selectedDate);
				console.log("今天的chuooooo：", now);
				return selectedDate < now;
			},

			// 获取当前日期和时间（格式：YYYY-MM-DD HH:mm:ss）
			getCurrentDateTime() {
				const now = new Date();

				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0');
				const day = now.getDate().toString().padStart(2, '0');
				const hours = now.getHours().toString().padStart(2, '0');
				const minutes = now.getMinutes().toString().padStart(2, '0');
				const seconds = now.getSeconds().toString().padStart(2, '0');

				this.date = `${year}-${month}-${day}`
				this.time = `${hours}:${minutes}:${seconds}`
				this.interviewDateTime = `${year}-${month}-${day}`
				// dateTime: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
				// fullDate: `${year}年${month}月${day}日`,
				// fullTime: `${hours}:${minutes}:${seconds}`
				console.log(this.date)

			},


			changeMethod(i, val) {
				this.methodActiveIndex = i
				this.selecteMethodText = val
			},
			getData(){
				var that=this
				this.$Request.getT("/app/interviewRecord/getInterviewInfo", {recordId:this.recordId}).then((res) => {
				  if (res.code == 0) {
					  this.type=res.data.type
					  this.popRadioValue = res.data.postPush.ruleClassifyId;
					  this.jobList.forEach(function(item){
						  if(item.ruleClassifyId==that.popRadioValue)
							that.selectedJob = item
					  })
						this.latitude=res.data.lat
					  this.longitude=res.data.lng
					  
					  this.textareaValue=res.data.remarks
					  this.interviewDateTime=res.data.interviewDateTime.substring(0,10)
					  this.selectedDate=[{date:this.interviewDateTime,info:'已预约'}]
					  this.address=res.data.address
					  this.detailedAddress=res.data.detailedAddress
					  this.selectedAddress = this.address + this.detailedAddress
					  this.hrPhone=res.data.hrPhone
					  this.personText=res.data.hrName
					  
					this.selectedTime=res.data.detailTime
					if(this.selectedTime){
						var timeLimit=res.data.detailTime.split(' ')
						var hourMinute=timeLimit[0].split(':')
						this.timeValue=[this.hours.indexOf(parseInt(hourMinute[0])),this.minutes.indexOf(parseInt(hourMinute[1])),this.meridiem.indexOf(timeLimit[1])]
					}
					this.selecteMethodText=res.data.onlineType||''
					this.onlineMsg=res.data=res.data.onlineMsg||''
				  } else {
				    uni.showToast({
				      title: res.msg,
				      icon: "none",
				    });
				  }
				});
			}, 
			confirmRules() {
				
				var data = {
					recordId:this.recordId,
					interviewDateTime: this.interviewDateTime+' 00:00:00',
					postPushId: this.postPushId,
					resumesId: this.resumesId,
					companyId: this.companyId,
					remarks: this.textareaValue,
					detailedAddress: this.detailedAddress,
					type: this.radioValue,
					address: this.address,
					lat:this.latitude,
					lng:this.longitude,
					detailTime: this.selectedTime,
					onlineType: this.selecteMethodText,
					onlineMsg: this.onlineMsg,
					interviewerId: this.interviewerId,
					hrPhone: this.hrPhone,
					hrName: this.personText,
				}
				
				
				if(!data.hrPhone || !data.hrName){
					uni.showToast({
						title: '请选择联系人',
						icon: 'none'
					});
					return
				}
				if(!this.interviewDateTime || !data.detailTime){
					uni.showToast({
						title: '请选择面试时间',
						icon: 'none'
					});
					return
				}
				
				if(!this.postPushId){
					uni.showToast({
						title: '请选择面试岗位',
						icon: 'none'
					});
					return
				}
				
				console.log('面试邀约信息====', data);

				//发哦那个面试邀约
				this.$Request.postJson('/app/interviewRecord/saveInterview', data).then(ret => {
					if (ret.code == 0) {
						     // 回传上一页
							 this.$Request.getT("/app/chat/selectByTwoIds", {userId:this.interviewerId,'focusedUserId':this.$queue.getData('userId')}).then((res) => {
							   if (res.code == 0) 
								this.$queue.sendImMessage(this.interviewerId,'一份面试邀约',99,res.data)
							 })
						      uni.$emit('saveInterviewResult', "success");
						      uni.navigateBack();
					}
				})

				setTimeout(() => {
					this.isCancel = true;
				}, 200);
			},
		}
	};
</script>

<style scoped lang="scss">
	@import "./css/interviewInvitation.scss";
</style>