<template>
	<div class="_box">
		<!-- <div><el-button type="primary" size="medium" @click="cancel" style="position: absolute; right: 30px; top: 15px;">返回</el-button></div> -->
		<div class="_title"><i class="el-icon-info"></i>&nbsp;&nbsp;{{title}}基础信息
		</div>
		<div class="formArea">
			<el-form ref="taskForm" :rules="taskRules" :model="form" label-width="70px">
				<el-form-item label="审批角色:" v-if="false" prop="approveRole">
					<el-select v-model="form.approveRole" clearable filterable placeholder="请选择审批角色" style="width: 100%">
						<el-option
							v-for="item in roleOptions"
							:key="item.roleId"
							:label="item.roleName"
							:value="item.roleId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="请假人：">
					<el-input v-model="form.userName" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="请假日期:" prop="leaveTime">
					<el-date-picker
						v-model="form.leaveTime"
						type="datetimerange"
						align="right"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						:default-time="['08:30:00', '18:00:00']"
						style="width: 100%">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="审批人员:" prop="approveuser">
					<el-select v-model="form.approveuser" clearable filterable placeholder="请选择审批人员" style="width: 100%">
						<el-option
							v-for="item in userOptions"
							:key="item.userId"
							:label="item.userName"
							:value="item.userId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="申请理由:" prop="reason">
					<el-input v-model="form.reason" type="textarea" :autosize="{ minRows: 4, maxRows: 8}"></el-input>
				</el-form-item>
			</el-form>
		</div>
		<div style="text-align: center; margin-top: 30px; margin-bottom: 30px;">
			<el-button type="primary" size="medium" @click="submit">提交</el-button>
			<el-button type="danger" size="medium" @click="clearForm">清空</el-button>
			<el-button size="medium" @click="cancel">返回</el-button>
		</div>
	</div>
</template>

<script type="text/javascript">
	import {  getCookie } from '@/utils/util.js';
	export default {
		name: 'userApplyStart',
		props: {
	        design: {
	            type: String,
	            default: ''
	        },
	        companyId: {
	        	type: String,
	        	default: ''
	        },
	        dataItem: {
	            type: Object,
	            default: () => {}
	        }
	    },
		data () {
			return {
				title: '',
				approveStatus: '审批人员', // 区分提交选择审批人情况
				form: {
					userName: '',
					startTime: '', // 请假开始时间
					endTime: '', // 请假结束时间
					leaveTime: '', // 请假总天数
					approveRole: '',
					approveuser: '',
					reason: ''
				},
				formKey: '',
				firstTaskParameters: '', //当前首个审批节点参数信息
				userId: '',
				roleOptions: '', //角色列表
				userOptions: '', //用户列表
				taskRules: {
	                approveuser: [
	                    {required: true, message: '审批人员不能为空', trigger: 'change'}
	                ],
	                leaveTime: [
	                	{required: true, message: '请假时间不能为空', trigger: 'change'}
	                ],
	                reason: [
	                	{required: true, message: '请假理由不能为空', trigger: 'change'}
	                ]
	            }
			}
		},
		mounted () {
			// 获取当前用户
			this.userId = getCookie('userId');
			this.getUserName(this.userId );
			this.formKey = this.dataItem.key;
			this.title = this.dataItem.name;
			this.getFirstTaskParameters(); //获取首个审批所需传递的参数
	        // this.getRoleOptions();
		},
		methods: {
			// 根据userId获取申请人姓名
			getUserName (id) {
				this.axios.get('pass/v1/sysusers/' + id).then(async(res) => {
					if(res.code === '0') {
						this.form.userName = res.data.userName;
					} else {
						this.$message.error(res.message)
					}
				});
			},
			// 获取角色列表
			getRoleOptions () {
				this.axios.get('pass/v1/sysroles/').then(res => {
					if (res.code === '0') {
						this.roleOptions = res.data.list;
					} else {
						this.$message.error(res.message);
					}
				}).catch((err) => {
					console.log(err);
				})
			},
			// 获取首个审批节点的参数信息
			getFirstTaskParameters () {
				this.axios.get('pass/act/v1/act/getFirstUserTask/' + this.dataItem.id).then(res => {
					if (res.code === '0') {
						this.firstTaskParameters = res.data;
						let id = this.firstTaskParameters.candidateGroups[0];
						this.getUserOptions(id);
					} else {
						this.$message.error(res.message);
					}
				}).catch((error) => {
					console.log(error);
				})
			},
			// 获取角色下用户列表
			getUserOptions (id) {
				this.axios.get('pass/v1/sysuserroles/getUsersByRoleId?roleId=' + id + '&companyId=' + this.companyId).then(res => {
					if (res.code === '0') {
						this.userOptions = res.data.list;
					} else {
						this.$message.error(res.message);
					}
				}).catch((error) => {
					console.log(error);
				})
			},
	        submit () {
				this.$refs['taskForm'].validate((valid) => {
					if (valid) {
			        	let taskParams = this.firstTaskParameters.assignee.match(/[a-zA-Z]+/)[0];
			        	let totalTime = this.getDays(this.form.leaveTime[0], this.form.leaveTime[1]);
			        	let params = {
			        		id: this.userId,
			        		reason: this.form.reason,
			        		startTime: this.form.startTime,
			        		endTime: this.form.endTime,
			        		leaveTime: totalTime,
			        		companyId: this.companyId
			        	}
			        	params[taskParams] = this.form.approveuser;
			        	this.axios.post('pass/act/v1/act/startProcess/var?userId=' + this.userId + '&formKey=' + this.formKey, params, {individualType:'json'}).then(res => {
			                if (res.code === '0') {
			                    this.$message.success('提交成功');
			                    this.$emit('on-then', 'success');
			                } else {
			                    this.$message.error(res.message)
			                }
			            })
			        }
			    })
	        },
	        // 时间格式化 调用方式为dateFormat("YYYY-mm-dd HH:MM", date)
	        dateFormat(fmt, date) {
				let ret;
				let opt = {
					"Y+": date.getFullYear().toString(),        // 年
					"m+": (date.getMonth() + 1).toString(),     // 月
					"d+": date.getDate().toString(),            // 日
					"H+": date.getHours().toString(),           // 时
					"M+": date.getMinutes().toString(),         // 分
					"S+": date.getSeconds().toString()          // 秒
					// 有其他格式化字符需求可以继续添加，必须转化成字符串
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					};
				};
				return fmt;
			},
	        // 计算时间间隔天数
			getDays (strDateStart,strDateEnd) {
				this.form.startTime = this.dateFormat("YYYY-mm-dd HH:MM", strDateStart);
				this.form.endTime = this.dateFormat("YYYY-mm-dd HH:MM", strDateEnd);
				let totalTime = new Date(strDateEnd).getTime() / 1000 - new Date(strDateStart).getTime() / 1000;
        		let timeDay = totalTime / 60 / 60 / 24;
				return timeDay;
			},
	        clearForm () {
	        	this.$refs['taskForm'].resetFields();
	        },
	        cancel () {
				// this.$router.back();
				this.$emit('on-then', '');
				this.clearForm();
			}
		}
	}
</script>

<style type="text/css" scoped>
	._box {
		margin: 0px 30px auto 50px;
	}
	._title {
		height: 50px;
		padding: 15px 15px;
		font-size: large;
		border-bottom: solid 1px #ddd;
	}
	.formArea {
		margin-top: 20px;
		padding: 15px 10%
	}
	.el-form-item {
	    margin-bottom: 20px;
	}
</style>
