<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''" :disabled="(status === 'audit' || status === 'taskFormDetail')"
				 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" :disabled="true"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="所属部门" prop="department" :rules="[
						{required: true, message:'请选择所属部门', trigger: 'blur'}
					]">
						<SelectTree
							ref="officeTree"
							:props="{
										  value: 'id',             // ID字段名
										  label: 'name',         // 显示名称
										  children: 'children'    // 子级字段名
										}"
							:url="`/system-server/sys/office/treeData?type=2`"
							:value="inputForm.department"
							:accordion="true"
							:disabled="true"
							size="default"
							@getValue="(value) => {inputForm.department=value}"/>
					</el-form-item>
				</el-col>
<!--				<el-col :span="12">-->
<!--					<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="arrivalDate" :rules="[
						{required: true, message: '到岗日期不能为空', trigger: 'change'},
						{ validator: validateDepartureDate2, trigger: 'change' }
						]">
						<el-date-picker
							style="width: 100%;"
							v-model="inputForm.arrivalDate"
							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="departResignationDate" :rules="[
						{required: true, message: '预定离职日期不能为空', trigger: 'change'},
						{ validator: validateDepartureDate, trigger: 'change' }
						]">
						<el-date-picker
							style="width: 100%;"
							v-model="inputForm.departResignationDate"
							type="date"
							value-format="YYYY-MM-DD"
							placeholder="选择预定离职日期">
						</el-date-picker>
					</el-form-item>
				</el-col>

			</el-row>
			<el-row :gutter="26">
				<el-col :span="12">
					<el-form-item label="备注" prop="remarks" :rules="[]">
						<!--						<el-input type="textarea" v-model="inputForm.remarks"></el-input>-->
						<el-input type="textarea"
								  maxlength="500" placeholder="请输入备注"
								  show-word-limit v-model="inputForm.remarks"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

		</el-form>
	</div>
</template>

<script>
	import SelectTree from '@/components/treeSelect/treeSelect.vue'
	import departRegistrationService from '@/api/human/depart/DepartRegistrationService'
	import CommonApi from '@/api/cw/common/CommonApi'
	import UserSelectSignatory from '@/views/cw/workClientInfo/clientUserSelect'

	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: '',
					name: '',
					procInsId: '',
					department: '',
					projectManager: '',
					arrivalDate: '',
					departResignationDate: '',
					remarks: '',
					type: '',
				},
				keyWatch: '',
			}
		},
		commonApi: null,
		created () {
			this.commonApi = new CommonApi()
		},
		components: {
			UserSelectSignatory,
			SelectTree,
		},
		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: {
			// 自定义验证函数
			validateDepartureDate(rule, value, callback) {
				if (this.commonJS.isNotEmpty(this.inputForm.arrivalDate)){
					if (value <= this.inputForm.arrivalDate) {
						this.inputForm.departResignationDate = ''
						callback(new Error('离职日期必须晚于到岗日期'));
					} else {
						callback();
					}
				} else {
					callback();
				}

			},
			validateDepartureDate2(rule, value, callback) {
				if (this.commonJS.isNotEmpty(this.inputForm.departResignationDate)) {
					if (value >= this.inputForm.departResignationDate) {
						this.inputForm.arrivalDate = ''
						callback(new Error('到岗日期必须早于离职日期'));
					} else {
						callback();
					}
				} else {
					callback();
				}

			},
			getKeyWatch (keyWatch) {
				this.keyWatch = keyWatch
			},
			init (method, id) {
				this.method = method
				this.inputForm = {
					userId: '',
					name: '',
					procInsId: '',
					department: '',
					projectManager: '',
					arrivalDate: '',
					departResignationDate: '',
					remarks: '',
					type: '',
				}
				if (method === 'add') {
					this.title = `新建离职申请`
				} else if (method === 'edit') {
					this.title = '修改离职申请信息'
				}
				this.inputForm.id = id
				this.visible = true
				this.loading = false
				this.$nextTick(() => {
					this.loading = true
					departRegistrationService.findById(this.inputForm.id).then((data) => {
						this.fileList = []
						this.fileList2 = []
						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 (this.commonJS.isEmpty(this.inputForm.name)){
							this.inputForm.name = this.$store.state.user.name
						}
						if (this.commonJS.isEmpty(this.inputForm.department)){
							this.inputForm.department = this.$store.state.user.office.id
						}

						if (this.commonJS.isEmpty(this.inputForm.arrivalDate)) {
							//去后台查询他入职登记时的入职日期
							departRegistrationService.selectContractStartDate().then((data) => {
								this.inputForm.arrivalDate = data
							})
						}

						this.loading = false
					})
				})
			},
			// 表单提交
			doSubmit () {
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						if (this.commonJS.isEmpty(this.inputForm.files)) {
							this.inputForm.files = []
						}
						this.inputForm.id = this.businessId
						departRegistrationService.save(this.inputForm).then((data) => {
							this.close()
							this.$message.success(data)
							this.$emit('refreshDataList')
							this.loading = false
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},
			close () {
				this.$refs.inputForm.resetFields()
				this.fileList = []
				this.fileList2 = []
				this.visible = false
			},
			reapplyForm (callback) {
				this.loading = true
				departRegistrationService.findById(this.inputForm.id).then((data) => {
					if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.startForm(callback)
					}
				})
			},
			// 暂存
			async saveForm (callback) {
				this.loading = true
				this.inputForm.type = '1'
				departRegistrationService.save(this.inputForm).then((data) => {
					callback()
					this.$refs.inputForm.resetFields()
					this.loading = false
				}).catch(() => {
					this.$refs.inputForm.resetFields()
					this.loading = false
				})
			},
			// 送审
			async startForm (callback) {
				this.$refs['inputForm'].validate(async (valid) => {
					if (valid) {
						this.loading = true
						this.inputForm.type = '2'
						departRegistrationService.save(this.inputForm).then((data) => {
							this.inputForm.title = `${this.$store.state.user.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
				departRegistrationService.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.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
									if (this.commonJS.isNotEmpty(data)) {
										if (data === '办公室主任审批') {
											this.inputForm.type = '5'
										}
									}
									departRegistrationService.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
					departRegistrationService.findById(this.inputForm.id).then(async (data) => {

						if (data.type !== '2') { // 审核状态不是“审核中”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							await this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
								if (this.commonJS.isNotEmpty(data)) {
									if (data === '部门主任审批') {
										this.inputForm.type = '0'
									} else {
										this.inputForm.type = '2'
									}
								}
							})
							departRegistrationService.updateStatusById(this.inputForm).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				} else if (type === 'hold') {
					this.loading = true
					departRegistrationService.findById(this.inputForm.id).then((data) => {
						if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.inputForm.type = '1'
							departRegistrationService.updateStatusById(this.inputForm).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				}
			},
		}
	}
</script>
