<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-dialog
			:title="title"
			:close-on-click-modal="false"
			draggable
			width="1400px"
			height="500px"
			@close="close"
			append-to-body
			v-model="visible">
			<div v-if="method == 'view'">
				<el-row type="flex" justify="end">
					<el-button @click="downloadRegistrationTpl">导出信息</el-button>
				</el-row>
			</div>
			<el-row>
				<el-row>
					<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''" :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'"
							 label-width="100px" @submit.native.prevent>

						<el-divider content-position="left"><i class="el-icon-document"></i> 基础信息</el-divider>
						<el-row :gutter="26">
							<el-col :span="12">
								<el-form-item label="姓名" prop="name" :rules="[{required: true, message: '姓名不能为空', trigger: 'blur'}]">
									<el-input v-model="inputForm.name"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="性别" prop="sex"
											  :rules="[
								  	{required: true, message: '性别不能为空', trigger: 'change'}
                 ]">
									<el-radio-group v-model="inputForm.sex">
										<el-radio v-for="item in $dictUtils.getDictList('sex')" :label="item.value" :key="item.value">{{item.label}}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="身份证号码" prop="idCard" :rules="[{required: true,validator: validator.isCardId, trigger:'blur'}]">
									<el-input v-model="inputForm.idCard" @blur="idCardOnly(inputForm.idCard, inputForm.id)"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="籍贯" prop="nativePlace"
											  :rules="[
											{required: true, message:'籍贯不能为空', trigger:'change'}
											 ]">
									<SelectTree
										ref="areaTree"
										:props="{
												  value: 'id',             // ID字段名
												  label: 'name',         // 显示名称
												  children: 'children'    // 子级字段名
											}"
										url="/system-server/sys/area/treeData"
										:value="inputForm.nativePlace"
										:clearable="true"
										size="large"
										:accordion="true"
										@getValue="(value) => {inputForm.nativePlace=value}"/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="民族" prop="nation" :rules="[]">
									<el-select v-model="inputForm.nation" placeholder="请选择民族" clearable
											   style="width: 100%;">
										<el-option v-for="item in $dictUtils.getDictList('sys_nation')"
												   :key="item.value" :label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="政治面貌" prop="politicalOutlook" :rules="[]">
									<el-select v-model="inputForm.politicalOutlook" placeholder="请选择政治面貌" style="width:100%;">
										<el-option
											v-for="item in $dictUtils.getDictList('political_outlook')"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="毕业院校" prop="graduatedFrom" :rules="[]">
									<el-input v-model="inputForm.graduatedFrom"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="专业" prop="speciality" :rules="[]">
									<el-input v-model="inputForm.speciality"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="联系电话" prop="mobilePhone" :rules="[{required: true, message: '联系电话不能为空', trigger: 'change'}]">
									<el-input v-model="inputForm.mobilePhone" @blur="mobilePhoneOnly(inputForm.mobilePhone)"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="QQ号/微信号" prop="qqNum" :rules="[]">
									<el-input v-model="inputForm.qqNum" :maxlength="20" :minlength="5"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="简介" prop="remarks" :rules="[]">
									<el-input type="textarea"
											  maxlength="200" placeholder="请输入简介"
											  show-word-limit v-model="inputForm.remarks"></el-input>
								</el-form-item>
							</el-col>
							<el-form style="width: 100%" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''" :disabled="method === 'view'"
									 label-width="110px" @submit.native.prevent>
								<el-row :gutter="15">
									<el-col :span="12">
										<el-form-item label="实习单位名称" prop="practiceUnitName" :rules="[]">
											<el-input v-model="inputForm.practiceUnitName"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="12" >
										<el-form-item label="实习部门" prop="practiceOffice"
													  :rules="[
                                {required: true, message:'实习部门不能为空', trigger:'blur'}
                   ]">
											<SelectTree
												ref="officeTree"
												:props="{
										  value: 'id',             // ID字段名
										  label: 'name',         // 显示名称
										  children: 'children'    // 子级字段名
										}"
												:url="`/system-server/sys/office/treeDataPgAndKjAndXm`"
												:value="inputForm.practiceOffice"
												:accordion="true"
												clearable
												size="default"
												@getValue="(value,valueTitle,node) => handleBlur(value,node)"/>
										</el-form-item>
									</el-col>
									<el-col :span="12" v-if="isXm">
										<el-form-item label="项目经理" prop="projectManager"
													  >
											<UserSelectSignatory style="width: 100%" ref="userSelect1"
																 :readonly="true" :limit='1' :modelValue="inputForm.projectManager"
																 @update:modelValue='(value, label) => {inputForm.projectManager = value}'></UserSelectSignatory>
										</el-form-item>
									</el-col>
									<el-col :span="12" v-else>
										<el-form-item label="项目经理" prop="projectManager"
													  :rules="[
								  	{required: true, message: '项目经理不能为空', trigger: 'change'}
                   ]">
											<UserSelectSignatory style="width: 100%" ref="userSelect1"
																 :readonly="true" :limit='1' :modelValue="inputForm.projectManager"
																 @update:modelValue='(value, label) => {inputForm.projectManager = value}'></UserSelectSignatory>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="实习开始日期" prop="practiceStartDay" :rules="[{required: true, message: '实习开始日期不能为空', trigger: 'change'}]">
											<el-date-picker
												style="width: 100%;"
												v-model="inputForm.practiceStartDay"
												type="date"
												value-format="YYYY-MM-DD"
												placeholder="选择实习开始日期">
											</el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="实习结束日期" prop="practiceCompleteDay" :rules="[{required: true, message: '实习结束日期不能为空', trigger: 'change'}]">
											<el-date-picker
												style="width: 100%;"
												v-model="inputForm.practiceCompleteDay"
												type="date"
												value-format="YYYY-MM-DD"
												placeholder="选择实习结束日期">
											</el-date-picker>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item label="实习状态" prop="practiceStatus"
													  :rules="[
                 ]">
											<el-radio-group v-model="inputForm.practiceStatus">
												<el-radio v-for="item in $dictUtils.getDictList('practice_type')" :label="item.value" :key="item.value">{{item.label}}</el-radio>
											</el-radio-group>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>
						</el-row>
						<el-divider content-position="left"><i class="el-icon-document"></i>
							实习经历
							<el-button style="margin-left: 20px" type="primary" :disabled="method==='view' || status === 'audit' || status === 'taskFormDetail' " @click="insertEvent('amount')" plain>
								新增
							</el-button>
						</el-divider>
						<el-row  :gutter="15" >
							<el-col :span="24">
								<vxe-table
									border
									show-overflow
									ref="amountTable"
									class="vxe-table-element"
									:data="inputForm.experiences"
									style="margin-left: 5em"
									:key="amountKey"
									highlight-current-row
									:edit-config="{trigger: 'click', mode: 'row', showStatus: true, autoClear: true, icon:'_'}"
								>
									<vxe-table-column field="startTime" title="开始时间" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-date-picker
												v-model="scope.row.startTime"
												type="date"
												value-format="YYYY-MM-DD"
												placeholder="选择开始时间"
												style="width:100%"
												size="default"
												placement="bottom-start"
												clearable>
											</el-date-picker>
										</template>
									</vxe-table-column>
									<vxe-table-column field="endTime" title="结束时间" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-date-picker
												v-model="scope.row.endTime"
												type="date"
												value-format="YYYY-MM-DD"
												placeholder="选择结束时间"
												style="width:100%"
												size="default"
												placement="bottom-start"
												clearable>
											</el-date-picker>
										</template>
									</vxe-table-column>
									<vxe-table-column field="practiceUnit" title="实践单位" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-input  placeholder="请填写实践单位"  v-model="scope.row.practiceUnit"/>
										</template>
									</vxe-table-column>
									<vxe-table-column field="post" title="岗位" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-input  placeholder="请填写岗位" v-model="scope.row.post"/>
										</template>
									</vxe-table-column>
									<vxe-table-column title="操作" width="100">
										<template v-slot="scope">
											<el-button size="small" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'amount')">删除</el-button>
										</template>
									</vxe-table-column>
								</vxe-table>
							</el-col>
						</el-row>
						<el-divider content-position="left"><i class="el-icon-document"></i>
							家庭成员
							<el-button style="margin-left: 20px" type="primary" :disabled="method==='view' || status === 'audit' || status === 'taskFormDetail' " @click="insertEvent('familyMembers')" plain>
								新增
							</el-button>
						</el-divider>
						<el-row  :gutter="15" >
							<el-col :span="24">
								<vxe-table
									border
									show-overflow
									ref="familyTable"
									class="vxe-table-element"
									:data="inputForm.familyMembers"
									style="margin-left: 5em"
									:key="membersKey"
									highlight-current-row
									:edit-config="{trigger: 'click', mode: 'row', showStatus: true, autoClear: true, icon:'_'}"
								>
									<vxe-table-column field="callName" title="关系" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-input  placeholder="请填写关系"  v-model="scope.row.callName"/>
										</template>
									</vxe-table-column>
									<vxe-table-column field="name" title="姓名" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-input  placeholder="请填写姓名" v-model="scope.row.name"/>
										</template>
									</vxe-table-column>
									<vxe-table-column field="phone" title="联系方式" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-input  placeholder="请填写联系方式"  v-model="scope.row.phone"/>
										</template>
									</vxe-table-column>
									<vxe-table-column field="workUnit" title="工作单位" :edit-render="{}">
										<template v-slot:edit="scope">
											<el-input  placeholder="请填写工作单位"  v-model="scope.row.workUnit"/>
										</template>
									</vxe-table-column>
									<vxe-table-column title="操作" width="100">
										<template v-slot="scope">
											<el-button size="small" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'familyMembers')">删除</el-button>
										</template>
									</vxe-table-column>
								</vxe-table>
							</el-col>
						</el-row>
					</el-form>
				</el-row>
			</el-row>
			<template #footer>
			<span class="dialog-footer">
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button  v-if="method === 'edit'||method === 'add'" type="primary" icon="el-icon-circle-check" @click="doSubmit()">确定</el-button>
			</span>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	import enrollmentRegistrationService from '@/api/human/enrollment/EnrollmentRegistrationService'
	import registerService from '@/api/human/register/RegisterService'
	import SelectTree from '@/components/treeSelect/treeSelect.vue'
	import UserSelectSignatory from '@/components/userSelectKjXmPg'
	import officeService from "@/api/sys/officeService";
	export default {
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			},
			status: {
				type: String,
				default: ''
			}
		},
		data () {
			return {
				title: '',
				method: '',
				visible: false,
				loading: false,
				inputForm: {
					userId: '',
					practiceOffice: '',
					name: '',
					practiceUnitName: '',
					qqNum: '',
					sex: '',
					practiceStatus: '',
					politicalOutlook: '',
					nativePlace: '',
					nation: '',
					mobilePhone: '',
					idCard: '',
					graduatedFrom: '',
					speciality: '',
					practiceStartDay: '',
					practiceCompleteDay: '',
					remarks: '',
					type: '',
					projectManager: '',
					experiences: [],
					familyMembers: [],
				},
				keyWatch: '',
				amountKey: '',
				membersKey: '',
				isXm: false
			}
		},
		created () {
		},
		components: {
			SelectTree,
			UserSelectSignatory,
		},
		computed: {
			bus: {
				get () {
					return this.businessId
				},
				set (val) {
					this.businessId = val
				}
			},
			name () {
				return this.$store.state.user.name
			},
			userId () {
				return this.$store.state.user.id
			}
		},
		watch: {
			'keyWatch': {
				handler (newVal) {
					if (this.commonJS.isNotEmpty(this.bus)) {
						this.init('', this.bus)
					} else {
						this.$nextTick(() => {
							this.$refs.inputForm.resetFields()
						})
					}
				}
			},
			'loading': {
				handler (newVal) {
					this.$emit('changeLoading', newVal)
				}
			}
		},
		methods: {
			getKeyWatch (keyWatch) {
				this.keyWatch = keyWatch
			},
			getUpload () {
			},
			init (method, id) {
				this.method = method
				this.inputForm = {
					userId: '',
					practiceOffice: '',
					name: '',
					practiceUnitName: '',
					qqNum: '',
					sex: '',
					practiceStatus: '',
					politicalOutlook: '',
					nativePlace: '',
					nation: '',
					mobilePhone: '',
					idCard: '',
					graduatedFrom: '',
					speciality: '',
					practiceStartDay: '',
					practiceCompleteDay: '',
					remarks: '',
					type: '',
					projectManager: '',
					experiences: [],
					familyMembers: [],
				}
				if (method === 'add') {
					this.title = `新建实习登记`
				} else if (method === 'edit') {
					this.title = '修改实习登记'
				} else if (method === 'view') {
					this.title = '查看实习登记信息'
				}
				this.inputForm.id = id
				this.visible = true
				this.loading = false
				this.$nextTick(() => {
					this.loading = true
					this.$refs.inputForm.resetFields()
					registerService.findById(this.inputForm.id).then((data) => {
						console.log('data',data)
						if (this.status === 'audit' || this.status === 'taskFormDetail') {
							method = 'view'
						}
						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
						if (data.parentOfficeName === '兴光项目公司'){
							this.isXm = true
						}else {
							this.isXm = false
						}
						this.loading = false
					})
				})
			},
			// 表单提交
			doSubmit () {
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						if (this.commonJS.isEmpty(this.inputForm.idCard)) {
							this.loading = false
							this.$message.error('身份证号码不能为空')
							throw new Error('身份证号码不能为空')
						}
						if (!this.validateXG.isPhoneOrMobile(this.inputForm.mobilePhone)) {
							this.$message.error('”联系电话“填写不正确，请重新填写')
							this.loading = false
							this.inputForm.mobilePhone = ''
							throw new Error('”联系电话“填写不正确，请重新填写')
						}
						if (this.commonJS.isNotEmpty(this.inputForm.qqNum)){
							//判断是否是汉字
							const chineseRegex = /[\u4e00-\u9fa5]/;
							if (chineseRegex.test(this.inputForm.qqNum)){
								this.$message.error('QQ号/微信号填写不正确，请重新填写')
								this.loading = false
								throw new Error('QQ号/微信号填写不正确，请重新填写')
							}
						}
						registerService.saveForm(this.inputForm).then((data) => {
							this.close()
							this.$message.success(data)
							this.$emit('refreshList')
							this.loading = false
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},
			close () {
				this.$refs.inputForm.resetFields()
				this.inputForm.experiences = []
				this.inputForm.familyMembers = []
				this.visible = false
			},
			reapplyForm (callback) {
				this.loading = true
				registerService.findById(this.inputForm.id).then((data) => {
					if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.startForm(callback)
					}
				})
			},
			// 送审
			async startForm (callback) {
				this.$refs['inputForm'].validate(async (valid) => {
					if (valid) {
						this.loading = true
						this.inputForm.type = '2'
						registerService.save(this.inputForm).then((data) => {
							this.inputForm.title = `${this.$store.state.user.name} 发起了 [${this.inputForm.name}] - [实习登记]`
							this.inputForm.id = data.businessId
							callback(data.businessTable, data.businessId, this.inputForm)
							this.$refs.inputForm.resetFields()
							this.loading = false
						}).catch(() => {
							this.$refs.inputForm.resetFields()
							this.loading = false
						})
					} else {
						this.loading = false
					}
				})
			},

			// 通过
			async agreeForm (callback) {
				this.loading = true
				registerService.findById(this.inputForm.id).then((data) => {
					if (data.type !== '2') { // 审核状态不是“审核中”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.$refs['inputForm'].validate(async (valid) => {
							if (valid) {
								this.loading = true
								this.inputForm.type = '5'
								console.log('this.inputForm',this.inputForm)
								registerService.save(this.inputForm).then((data) => {
									callback(data.businessTable, data.businessId, this.inputForm)
									this.loading = false
								}).catch(() => {
									this.loading = false
								})
							} else {
								this.loading = false
							}
						})
					}
				})
			},
			// 修改状态
			updateStatusById (type, callback) {
				if (type === 'reject') {
					this.loading = true
					registerService.findById(this.inputForm.id).then((data) => {
						if (data.type !== '2') { // 审核状态不是“审核中”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.inputForm.type = '4'
							registerService.updateStatusById(this.inputForm).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				} else if (type === 'hold') {
					this.loading = true
					registerService.findById(this.inputForm.id).then((data) => {
						if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.inputForm.type = '1'
							registerService.updateStatusById(this.inputForm).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				}
			},
			// 新增
			async insertEvent (type) {
				if (type === 'amount') {
					let d = {}
					if (this.commonJS.isEmpty(this.inputForm.experiences)) {
						this.inputForm.experiences = []
					}
					this.$refs.amountTable.insertAt(d)
					this.inputForm.experiences.push(d)
					this.amountKey = Math.random()
				}
				if (type === 'familyMembers') {
					let d = {}
					if (this.commonJS.isEmpty(this.inputForm.familyMembers)) {
						this.inputForm.familyMembers = []
					}
					this.$refs.familyTable.insertAt(d)
					this.inputForm.familyMembers.push(d)
					this.amountKey = Math.random()
				}
			},
			// 删除
			removeEvent (row, rowIndex, type) {
				if (type === 'amount') {
					this.$refs.amountTable.remove(row)
					this.inputForm.experiences.splice(rowIndex, 1)
				}
				if (type === 'familyMembers') {
					this.$refs.familyTable.remove(row)
					this.inputForm.familyMembers.splice(rowIndex, 1)
				}
			},
			//联系电话唯一性判断
			mobilePhoneOnly(mobilePhone) {
				if (!this.validateXG.isPhoneOrMobile(this.inputForm.mobilePhone)) {
					this.$message.error('”联系电话“填写不正确，请重新填写')
					this.loading = false
					this.inputForm.mobilePhone = ''
					throw new Error('”联系电话“填写不正确，请重新填写')
				}
				enrollmentRegistrationService.findMobilePhoneOnly(mobilePhone).then((data) => {
					if (data !== 0) {
						this.$message.error('联系电话已存在，请重新确认')
						this.inputForm.mobilePhone = ''
						throw new Error('联系电话已存在，请重新确认')
					}
				})

			},
			//身份证号码唯一性判断
			idCardOnly(idCard,id) {
				registerService.findIdCardOnly(idCard,id).then((data) => {
					if (data !== 0) {
						this.$message.error('身份证号码已存在，请重新确认')
						this.inputForm.idCard = ''
						throw new Error('身份证号码已存在，请重新确认')
					}
				})

			},
			downloadRegistrationTpl () {
				// this.$utils.downloadExcel('/sys/project/import/template')
				this.loading = true
				registerService.downloadRegistrationTpl(this.inputForm.id).then((res) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					this.$utils.downloadWord(res, this.inputForm.name + '实习用户信息')
					this.loading = false
				}).catch(function (err) {
					this.loading = false
					if (err.response) {
						console.log(err.response)
					}
				})
			},
			//获取实习部门是否所属项目公司
			async handleBlur(value,node){
				this.inputForm.practiceOffice = value
				if (node.parent.name === '兴光项目公司'){
					this.isXm = true
				}else {
					this.isXm = false
				}
			}
		}
	}
</script>
