<template>
  <div class="box" style="overflow-x: hidden;" :style="{'background-image': 'url(' + webContent.loginBgUrl + ')'}">
		<navBar :showLoginBtn="false" class="navBar"></navBar>
		<div class="content pa-5">
			<div class="mb-10 mt-5" style="font-size: 22px; font-family: 'MiSans-Bold'; text-align: center;">
				{{ isUpdate ? '注册信息修改' : '老师注册'}}
			</div>
			<CtForm class="mt-5" ref="CtFormRef" :items="formItems">
				<template #authDept>
					<div class="pa-5 mb-3" style="width: 100%; border: 1px dashed #ccc; border-radius: 4px;">
						<p class="color-999 font-size-14 mb-3">
							<span class="color-error">*</span>
							负责院系
						</p>
						<div v-for="(k, index) in departmentList" :key="index" class="d-flex align-center mb-5">
							<TextInput v-model="k.name" :item="textItem" />
							<v-icon v-if="index > 0" class="ml-3 cursor-pointer" @click="handleDeleteDepartment(index)" color="error">mdi-close-circle</v-icon>
						</div>
						<v-btn class="mt-3" color="primary" prepend-icon="mdi-plus" size="small" @click="handleAddDepartment">添加院系</v-btn>
					</div>
				</template>
				<template #tips>
					<p class="font-size-14 color-warning mb-3">图片上传提示：支持jpg、jpeg、png格式，图片大小不得超过20M</p>
				</template>
				<template #employmentCertificate="{ item }">
					<div class="d-flex flex-column">
						<p class="color-999 font-size-14 mb-3">
							<span class="color-error">*</span>
							在岗证明图片
						</p>
						<Img
							class="upload-box"
							tips="上传图片"
							:value="item.value"
							:showSnackbar="false"
							@imgClick="handlePreview"
							:showCursor="true"
							@success="url => item.value = url"
							@delete="item.value = null"
						/>
					</div>
				</template>
			</CtForm>
			<div class="text-center my-10">
				<v-btn color="primary" width="250" @click.stop="handleSubmit">提 交</v-btn>
			</div>
		</div>
  </div>

	<PreviewImage v-if="showPreview" :initialIndex="0" :urlList="[previewUrl]" @close="showPreview = !showPreview, previewUrl = ''" />
</template>

<script setup>
defineOptions({ name: 'register-schoolForm'})
import { ref, onMounted } from 'vue'
import { webContentStore } from '@/store/webContent'
import { getDict } from '@/hooks/web/useDictionaries'
import Snackbar from '@/plugins/snackbar'
import navBar from '@/layout/personal/navBar.vue'
import { schoolRegister } from '@/api/school'
import { useRouter } from 'vue-router'

const router = useRouter()
const webContent = webContentStore()

const previewUrl = ref('')
const showPreview = ref(false)
const departmentList = ref([{ name: '' }])
const textItem = {
	type: 'text',
  key: 'name',
	width: 450,
  label: '院系名称 *',
	hideDetails: true,
  rules: [v => !!v || '请输入您负责的院系名称']
}

const isUpdate = ref(false)
const CtFormRef = ref()
const formItems = ref({
  options: [
    {
      type: 'text',
      key: 'name',
      value: '',
      label: '姓名 *',
			col: 6,
      outlined: true,
      rules: [v => !!v || '请输入您的姓名']
    },
    {
      type: 'ifRadio',
      key: 'sex',
      value: '1',
			defaultValue: '1',
      label: '性别 *',
      col: 6,
			flexStyle: 'ml-5',
      width: 50,
      dictTypeName: 'menduner_sex',
			rules: [v => !!v || '请选择您的性别'],
      items: []
    },
    {
      type: 'phoneNumber',
      key: 'phone',
      value: localStorage.getItem('schoolLoginAccount') ? JSON.parse(localStorage.getItem('schoolLoginAccount')).phone : '',
      label: '联系电话 *',
			col: 6,
      outlined: true,
      rules: [v => !!v || '请填写您的联系电话']
    },
    {
      type: 'autocomplete',
      key: 'schoolId',
      value: null,
      label: '所在学校 *',
			col: 6,
			itemText: 'name',
			itemValue: 'id',
			flexStyle: 'ml-5',
      outlined: true,
			items: [],
      rules: [v => !!v || '请选择您所在的学校名称']
    },
    {
			slotName: 'authDept',
      key: 'authDept',
			noParam: true,
      label: '负责院系 *',
      rules: [v => !!v || '请填写您在学校负责的院系']
    },
		{
			slotName: 'tips',
			noParam: true
		},
		{
			slotName: 'employmentCertificate',
			key: 'employmentCertificate',
			value: '',
			col: 4,
			rules: [v => !!v || '请上传您的在岗证明图片']
		}
  ]
})

const formData = ref({})
onMounted(async () => {
  await webContent.getSystemWebContent()

	// 获取性别字典数据
	const sexItem = formItems.value.options.find(e => e.key === 'sex')
	if (!sexItem || !Object.keys(sexItem).length) return
	const { data } = await getDict(sexItem.dictTypeName)
	sexItem.items = data || []

	// 获取学校列表
	const schoolItem = formItems.value.options.find(e => e.key === 'schoolId')
	if (!schoolItem || !Object.keys(schoolItem).length) return
	getDict('schoolList', {}, 'schoolList').then(({ data }) => {
		schoolItem.items = data || []
	})

	// 重新提交，数据回显
	formData.value = localStorage.getItem('registerSchoolInfo') ? JSON.parse(localStorage.getItem('registerSchoolInfo')) : {}
	if (formData.value && formData.value && formData.value?.authStatus === '2') {
		isUpdate.value = true
		departmentList.value = formData.value?.authDept || [{ name: '' }]
		formItems.value.options.forEach(item => {
			if (item.key !== 'authDept' && !item.noParam) item.value = formData.value[item.key] || item?.defaultValue
		})
	}
})

// 图片预览
const handlePreview = (url) => {
	previewUrl.value = url
	showPreview.value = true
}

// 添加院系
const handleAddDepartment = () => {
	departmentList.value.push({ name: '' })
}
// 删除院系
const handleDeleteDepartment = (index) => {
	departmentList.value.splice(index, 1)
}

// 提交注册
const handleSubmit = async () => {
	const { valid } = await CtFormRef.value.formRef.validate()
	if (!valid) return
	const isCheck = departmentList.value.every(item => item.name)
	if (!isCheck) return Snackbar.warning('请将院系信息填写完整')

	let obj = {
		authDept: departmentList.value
	}
	formItems.value.options.forEach(item => {
		if (item.noParam) return
		obj[item.key] = item.value
	})

	if (!obj.employmentCertificate) return Snackbar.warning('请上传在岗证明')

	// 修改信息需提交原始数据
	if (isUpdate.value) obj = Object.assign(formData.value, obj)

	try {
		await schoolRegister(obj)
		console.log(obj, 'submit-data提交成功，等待系统管理员审核')

		Snackbar.success('提交成功，等待系统管理员审核！')
		// 重新提交审核的需将authStatus改为0（待审核状态）
		localStorage.setItem('registerSchoolInfo', JSON.stringify({ ...obj, authStatus: '0' }))
		isUpdate.value = false
		router.push('/register/school/inReview')
	} catch {}
}
</script>

<style scoped lang="scss">
.navBar {
  position: absolute;
  top: 0;
}
.box {
  position: relative;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}
.content {
  position: absolute;
  top: 50%;
  left: 50%;
  translate: -50% -50%;
  width: 600px;
  height: 80%;
  overflow: auto;
  background-color: #fff;
  border-radius: 10px;
}
.upload-box {
	width: 100px;
}
</style>
