<template>
	<view style="padding: 30rpx;">
		<uni-forms ref="formRef" :modelValue="formData" :rules="formRules" validateTrigger="bind" label-width="80px" label-align="right" label-position="left">
			<uni-forms-item name="time" label="面试时间" required>
				<uni-datetime-picker
					v-model="formData.time"
					type="datetime"
					:border="true"
					returnType="timestamp"
					:hide-second="true"
					@change="handleDate"
				 />
			</uni-forms-item>
			<uni-forms-item name="jobId" label="招聘职位" required>
				<view style="max-width: calc(100vw - 110px);">
          <uni-data-select	v-model="formData.jobId" :disabled="jobDisabled" :localdata="jobList"	@change="handleChangeJob"	placeholder="请选择招聘职位"></uni-data-select>
        </view>
			</uni-forms-item>
			<uni-forms-item name="address" label="面试地点" required>
				<uni-easyinput v-model="formData.address" placeholder="请输入面试地点"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="invitePhone" label="联系电话" required>
				<uni-easyinput v-model="formData.invitePhone" placeholder="请输入联系电话"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="remark" label="备注事项">
				<uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入备注事项"></uni-easyinput>
			</uni-forms-item>
		</uni-forms>
		<button class="send-button" @tap="handleSubmit">提 交</button>
	</view>
</template>

<script setup>
import { ref, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { userStore } from '@/store/user'
import { mobile } from '@/utils/validate'
import { getJobAdvertised } from '@/api/new/position'
import { formatName } from '@/utils/getText'
import { getInterviewInviteDefaultTime } from '@/utils/date'
import { saveInterviewInvite } from '@/api/interview'
import { send } from '@/hooks/useIM'

const formRef = ref(null)
const useUserStore = userStore()
const jobDisabled = ref(false)
const formData = ref({
	userId: null,
	address: null,
	invitePhone: useUserStore?.userInfo?.phone || '',
	time: getInterviewInviteDefaultTime().timeStamp,
	jobId: null,
	remark: null,
	type: 1
})
const formRules = {
	time: {
		rules: [{ required: true, errorMessage: '请选择面试时间' }]
	},
  invitePhone: mobile,
	address: {
		rules: [{ required: true, errorMessage: '请输入面试地点' }]
	},
	jobId: {
		rules: [{ required: true, errorMessage: '请选择邀请面试的职位' }]
	}
}

// 职位列表
const jobList = ref([])
const getJobList = async (jobId) => {
  const { data } = await getJobAdvertised({ status: '0', exTime: 0 })
  jobList.value = data.map(e => {
    return { text: formatName(e.name), value: e.id, data: e }
  })

	// 有职位id的则默认选中
	if (jobId) {
		formData.value.jobId = jobId
		formData.value.address = jobList.value.find(item => item.value === jobId)?.data.address
		jobDisabled.value = true
	}
}

const handleChangeJob = (e) => {
	const job = jobList.value.find(item => item.value === e)
	if (!job) return
	formData.value.address = job.data.address

	// 沟通-面试邀请需携带职位信息
	if (channerl.value && Object.keys(channerl.value).length > 0) formData.value.positionInfo = job
}

const handleDate = (val) => {
	const selectedDate = new Date(val)
  const currentDate = new Date()
  if (selectedDate < currentDate) {
		uni.showToast({
			title: '面试时间不得小于当前时间',
      icon: 'none',
			duration: 2000
    })
  }
}

const channerl = ref({})
onLoad(async (options) => {
	// 编辑面试、重新邀约
	if (options?.editData) {
		const obj = JSON.parse(decodeURIComponent(options.editData))
		for (let key in formData.value) {
			formData.value[key] = obj[key]
		}
		formData.value.id = obj.id
		if (obj.jobFairId) formData.value.jobFairId = obj.jobFairId
		// 有实习时间的则为学生，需传递实习时间
		if (obj?.practiceStartTime && obj?.practiceEndTime) {
			formData.value.practiceStartTime = obj.practiceStartTime
			formData.value.practiceEndTime = obj.practiceEndTime
		}
		await getJobList()
		return
	}

	// 沟通-面试邀请
	if (options?.chartData) {
		const obj = JSON.parse(decodeURIComponent(options.chartData))
		formData.value.userId = obj.id
		channerl.value = {
			channelID: obj.channelID,
			channelType: obj.channelType
		}
		await getJobList()
		return
	}

	const { id, jobId } = options
	if (!id) {
		uni.showToast({
			title: '缺少人员id',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack({ delta: 1 })
		}, 1000)
		return
	}

	formData.value.userId = id
	await getJobList(jobId)
})

// 提交
const handleSubmit = async () => {
	const valid = await unref(formRef).validate()
	if (!valid) return

	const selectedDate = new Date(formData.value.time)
  const currentDate = new Date()
  if (selectedDate < currentDate) {
		uni.showToast({
			title: '面试时间不得小于当前时间',
      icon: 'none',
			duration: 2000
    })
		return
  }

	uni.showLoading({ title: '提交中' })
	try {
		await saveInterviewInvite(formData.value)
		
		// 从沟通过来的需要发消息
		if (channerl.value && Object.keys(channerl.value).length > 0) send(JSON.stringify(formData.value), channerl.value, 101)
		
		uni.hideLoading()
		uni.showToast({
			title: '提交成功',
			icon: 'success'
		})
		channerl.value = {}
		setTimeout(() => {
			uni.navigateBack({ delta: 1 })
		}, 1000)
	} catch {
		uni.hideLoading()
	}
}
</script>

<style scoped lang="scss">

</style>
