<template>
	<div class="common-page device-manage">

		<div class="option page-row">
			<!--工具栏-->
			<div class="head-container">
				<!-- 搜索 -->

				<label class="el-form-item-label" style="font-weight: 500;">人员姓名</label>
				<el-input v-model="query.name" clearable size="small" placeholder="请输入人员姓名" style="width:180px;"/>

				<!-- <label class="el-form-item-label" style="font-weight: 500;">驾驶车辆</label>
				<el-select v-model="query.car" placeholder="请选择驾驶车辆" style="width:180px;">
					<el-option v-for="(obj,index) in selectList" :label="obj.number" :value="obj.number" :key="index"></el-option>
				</el-select> -->

				<el-button size="mini" type="success" icon="el-icon-search" @click="toSearch">搜索</el-button>
				<el-button size="mini" icon="el-icon-refresh" @click="clearLimit">重置</el-button>
			</div>
		</div>

    	<!-- 表格 -->
		<div class="panel-bottom page-row">
			<h3>用户管理</h3>
			<div class="ctin-box">
				<div class="content-within">
					<div class="content-fix">
						<div class="toolbar">
							<el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>
						</div>
						<div class="content">
							<el-table :data="tableData" v-loading="loading" border style="width:auto" :row-class-name="tableRowClassName">
								<el-table-column prop="name" label="名称" align="center"></el-table-column>
								<el-table-column prop="userName" label="用户名" align="center"></el-table-column>
								<el-table-column prop="phone" label="电话" align="center"></el-table-column>
								<el-table-column prop="age" label="驾龄(年)" align="center"></el-table-column>
								<el-table-column prop="depart" label="部门" align="center"></el-table-column>
								<el-table-column prop="post" label="岗位" align="center"></el-table-column>
								<el-table-column prop="company" label="公司名称" align="center"></el-table-column>
								<el-table-column prop="adr" label="住址" align="center"></el-table-column>
								<el-table-column label="操作" align="center" fixed="right">
									<template slot-scope="scope">
										<el-button size="mini" type="primary" icon="el-icon-edit" @click="toEdit(scope.row)"></el-button>
										<el-button size="mini" type="danger" icon="el-icon-delete" @click="toDelete(scope.row)"></el-button>
									</template>
								</el-table-column>
							</el-table>
							<!--分页组件-->
							<el-pagination :total="total" :current-page="page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChange" @current-change="pageChange" />
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 表单渲染 -->
		<el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible.sync="form.visible" :title="form.title" width="700px">
			<el-form :model="form.item" :rules="rules" ref="form1" :inline="true" size="small" label-width="150px">
				<el-form-item label="名称" prop="name">
					<el-input v-model="form.item.name" style="width:280px;" placeholder="请输入名称"/>
				</el-form-item>
				<el-form-item label="用户名" prop="userName">
					<el-input v-model="form.item.userName" style="width:280px;" placeholder="请选择用户名" :disabled="form.reqType == 'edit'"/>
				</el-form-item>
				<el-form-item label="角色" prop="roles">
					<el-select v-model="form.item.roles" placeholder="请选择角色" style="width:280px;" :disabled="form.reqType == 'edit'">
						<el-option v-for="(obj,index) in getAllapirolesData" :label="obj.name" :value="obj.name" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="form.item.phone" style="width:280px;" placeholder="请输入电话"/>
				</el-form-item>
				<el-form-item label="驾龄(年)" prop="age">
					<el-input v-model="form.item.age" style="width:280px;" placeholder="请输入驾龄"/>
				</el-form-item>
				<el-form-item label="部门" prop="depart" class="is-required">
					<treeselect
						:multiple="false"
						:options="allDepartmentData"
						:load-options="loadOptions"
						placeholder="请选择部门"
						style="width: 280px"
						@select="selectDepart"
						v-model="form.item.depart"
						/>
					</el-form-item>
				<el-form-item label="岗位" prop="post">
					<el-select v-model="form.item.post" placeholder="请选择岗位" style="width:280px;">
						<el-option v-for="(obj,index) in allPostData" :label="obj.name" :value="obj.name" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="公司名称" prop="company">
					<el-input v-model="form.item.company" style="width:280px;" placeholder="请输入公司名称"/>
				</el-form-item>
				<el-form-item label="住址" prop="adr">
					<el-input v-model="form.item.adr" style="width:280px;" placeholder="请输入住址"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="text" @click="cancelForm">取消</el-button>
				<el-button :loading="form.status.cu === 2" type="primary" @click="submitForm('form1', form.item)">确认</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
import { Tools, HttpReq, Dates} from '@/assets/js/common.js';
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
export default {
	name: 'DriverManage',
	components: {Treeselect},
	data() {
		return {
			depts:"",
			loading: false,
			page: 1,
			size: 10,
			total: 0,
			query:{},
			tableData: [],
			selectList:[],
			allSystemUserNameData:[],
			allDepartmentData:[],
			allPostData:[],
			//最终选择部门信息
			lastDeptData:{},
			//修改用户信息
			xiugaiUserData:{},
			//所有用户信息
			getAllSystemUserNameData:[],
			//所有角色信息
			getAllapirolesData:[],
			//角色单独属性
			rolesLonely:"",
			form: {
				title:'新增人员',
				visible:false,
				reqType:'add',
				status:{cu:0},
				item:{},
			},
			rules: {
				name: [
					{required: true, message: '请输入姓名', trigger: 'blur' }
				],
				userName: [
					{required: true, message: '请选择用户名', trigger: 'blur' }
				],
				phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: 'blur'
					},
					{
						required: true,
						pattern: /^1[3456789]\d{9}$/,
						message: '手机号格式不正确',
						trigger: 'blur'
					}
				],
				age: [
					{required: true, message: '请输入驾驶年龄', trigger: 'blur'},
					{required: true, pattern: /^[0-9]*$/, message: '请输入数字', trigger: 'blur'},
				],
				depart: [
					{required: true, message: '请输入部门', trigger: 'blur' }
				],
				post: [
					{required: true, message: '请输入岗位', trigger: 'blur' }
				],
				roles: [
					{required: true, message: '请输入角色', trigger: 'blur' }
				],
				company: [
					{required: true, message: '请输入公司名称', trigger: 'blur' }
				],
				adr: [
					{required: true, message: '请输入住址', trigger: 'blur' }
				],
			},
		}
	},
	mounted() {
		var that = this;
		this.$nextTick(() => {
			this.loadData();
		})
	},
	methods: {
    normalizer(node) {
      if(node){
        node.id = node.name?node.name:null;
        node.label = node.name?node.name:null;
        if (node.children == null || node.children == 'null'|| node.children.length == 0) {
          delete node.children
        }
      }
    },
		selectDepart(val){
			console.log('selectDepart', val);
			this.lastDeptData = val;
			return this.depts = val.label
		},
		loadOptions({ action, parentNode, callback }) {
			if (action === LOAD_CHILDREN_OPTIONS) {
				HttpReq.truckDispatching.getAllDepartmentQuery({enabled: true, pid: parentNode.id}).then(response => {
					let arr = [];
					for(let index of response.content){
						let chiledModeInfo = {};
						chiledModeInfo.id = index.id;
						chiledModeInfo.label = index.name;
						arr.push(chiledModeInfo);
					}
					parentNode.children = response.content.map(function(obj) {
						if(obj.hasChildren) {
							obj.children = null;
						}
						console.log(obj);
						return obj
					})
				});
				setTimeout(() => {
					callback()
				}, 200)
			}
		},
		loadData() {
			var sort = 'id,desc';
			var param = this.query;
			this.allDepartmentData = []
			param.page = this.page - 1;
			param.size = this.size;
			param.sort = sort;

			this.$nextTick(()=>{
				//获取司机人员信息
				HttpReq.truckDispatching.driverManagementPCQuery(param).then((res) => {
					if(res.code == 200){
						this.loading = false;
						this.tableData = res.data.content;
						this.total = res.data.totalElements;
					}
				})
				//获取车辆信息
				HttpReq.truckDispatching.carInformationQuery({size:9999}).then((res) => {
					if(res.code == 200){
						this.selectList = res.data.content;
					}
				})
				//获取用于选择的用户名
				HttpReq.truckDispatching.getNoUseSystemUserNameQuery({size:9999}).then((res) => {
					this.allSystemUserNameData = res;
				})
				//获取用于选择的部门
				HttpReq.truckDispatching.getAllDepartmentQuery({enabled: true}).then((response) => {
					for(let index of response.content){
						let modeInfo = {} ;
						modeInfo.id = index.id
						modeInfo.label = index.name;
						modeInfo.children = null;
						this.allDepartmentData.push(modeInfo);
					}
				})
				//获取用于选择的岗位
				HttpReq.truckDispatching.getAllPostQuery({size:9999}).then((res) => {
					this.allPostData = res.content;
				})
				//获取所有的用户信息
				HttpReq.truckDispatching.getAllSystemUserNameQuery({size:9999}).then((res) => {
					this.getAllSystemUserNameData = res.content;
				})
				//获取所有的角色信息
				HttpReq.truckDispatching.apirolesallQuery().then((res) => {
					this.getAllapirolesData = res;
				})
			})

		},
		tableRowClassName({row, rowIndex}) {
			if (rowIndex === 1) {
				return 'warning-row';
			} else if (rowIndex === 3) {
				return 'success-row';
			}
			return '';
		},
		// 点击搜索
		toSearch() {
			this.page = 1;
			this.loadData();
		},
		// 重置搜索
		clearLimit(){
			this.query = {};
			this.loadData()
		},
		cancelForm(a, b, c){
			this.form.visible = false;
		},
		toAdd() {
			// 请除表单验证
			this.$refs['form1'] && this.$refs['form1'].clearValidate();
			this.form.title = '新增人员';
			this.form.status.cu = 0;
			this.form.visible = true;
			this.form.reqType = 'add';
			this.form.item = {};
		},
		toEdit(item) {
			// 请除表单验证
			this.$refs['form1'] && this.$refs['form1'].clearValidate();
			this.form.title = '修改人员';
			this.form.status.cu = 0;
			this.form.visible = true;
			this.form.item = {...item};
			this.form.reqType = 'edit';
			this.getAllSystemUserNameData.forEach((item1,index1)=>{
				if(item1.username == item.userName){
					this.xiugaiUserData = item1;
				}
			})
			this.getAllapirolesData.forEach((item1,index1)=>{
				if(item1.id == this.xiugaiUserData.roles[0].id){
					this.form.item.roles = item1.name;
				}
			})
		},
		toDelete(item) {
			var id = item.id;
			this.getAllSystemUserNameData.forEach((item1,index1)=>{
				if(item1.username == item.userName){
					this.xiugaiUserData = item1;
				}
			})
			this.$confirm('确认删除该条数据吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then((e) => {
				this.reqRemoveProject([id])
			}).catch((e) => {})
		},
		pageChange(e) {
			this.page = e
			this.loadData()
		},
		sizeChange(e) {
			this.page = 1
			this.size = e
			this.loadData()
		},
		submitForm(validateName, item){
			let that = this
			if(!this.form.status.cu){
				this.form.status.cu = 2;
				this.$refs[validateName].validate(valid => {
					item.depart = that.depts
					if(valid){
						if(this.form.reqType === 'add'){
							this.reqAddItem(this.form, item)
							//this.allDepartmentData = []
						}else{
							this.reqUpdateItem(this.form, item)
							//this.allDepartmentData = []
						}
					}else{
						this.form.status.cu = 0
					}
				});
			};
		},
		//新增司机人员
		reqAddItem(form, item){
			let panduanchongfu = true;
			let panduanchongfu2 = true;
			this.getAllSystemUserNameData.forEach((obj1,index1)=>{
				if(obj1.username == item.userName){
					panduanchongfu = false;
				}
			})
			this.getAllSystemUserNameData.forEach((obj1,index1)=>{
				if(obj1.phone == item.phone){
					panduanchongfu2 = false;
				}
			})
			if(panduanchongfu && panduanchongfu2){
				let lastData = {...item};
				HttpReq.truckDispatching.driverManagementPCAdd(lastData).then((res) => {
					form.visible = false;
					if(res.code == 200){
						this.$notify({
							title: '司机人员新增成功！',
							type: 'success',
							duration: 2500
						});
						this.loadData()
					}else{
						this.$notify({
							title: res.msg,
							type: 'error',
							duration: 2500
						})
					}
				}).catch(function(error) {
					form.status.cu = 0
				});
				let addUsers = {};
				addUsers.createBy = "admin";
				addUsers.createTime = this.currentTime();
				addUsers.dept = {id:this.lastDeptData.id};
				addUsers.deptId = this.lastDeptData.id;
				addUsers.email = lastData.userName + '@qq.com';
				addUsers.enabled = "true";
				addUsers.gender = "男";
				addUsers.id = null;
				this.allPostData.forEach((item1,index1)=>{
					if(item1.name == lastData.post){
						addUsers.jobs = [{id:item1.id}];
					}
				})
				this.getAllapirolesData.forEach((item1,index1)=>{
					if(item1.name == lastData.roles){
						addUsers.roles = [{id:item1.id}];
					}
				})
				addUsers.nickName = lastData.userName;
				addUsers.phone = lastData.phone;
				addUsers.pwdResetTime = "2022-11-10 14:49:59";
				addUsers.updateBy = "admin";
				addUsers.updateTime = this.currentTime();
				addUsers.username = lastData.userName;
				HttpReq.truckDispatching.apiusersAdd(addUsers).then((res) => {})
				this.lastDeptData = {};
			}else{
				form.status.cu = 0
				if(!panduanchongfu){
					this.$notify({
						title: '用户名不允许重复，请重新输入！',
						type: 'error',
						duration: 2500
					})
				}else if(!panduanchongfu2){
					this.$notify({
						title: '手机号已存在，请重新输入！',
						type: 'error',
						duration: 2500
					})
				}
			}
		},
		//修改司机人员
		reqUpdateItem(form, item){
			let lastData = {...item};
			HttpReq.truckDispatching.driverManagementPCUpdate(lastData).then((res) => {
				form.visible = false;
				if(res.code == 200){
					this.$notify({
						title: '司机人员修改成功！',
						type: 'success',
						duration: 2500
					});
					this.loadData()
				}else{
					this.$notify({
						title: res.msg,
						type: 'error',
						duration: 2500
					})
				}
			}).catch(function(error) {
				form.status.cu = 0
			});
			this.lastDeptData = {};
		},
		//删除司机人员
		reqRemoveProject(item){
			HttpReq.truckDispatching.driverManagementPCDel(item).then((res) => {
				if(res.status == 400){
					this.$notify({
						title: res.msg,
						type: 'error',
						duration: 2500
					})
				}else{
					this.$notify({
						title: '删除成功！',
						type: 'success',
						duration: 2500
					});
				}
				this.loadData();
			})
			if(this.xiugaiUserData.id){
				HttpReq.truckDispatching.apiusersDel([this.xiugaiUserData.id]).then((res) => {})
			}

		},
		//转换时间
		currentTime(){
			var date = new Date();
			var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
			var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
			var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
			var hours = date.getHours();          //小时 ,返回 Date 对象的小时 (0 ~ 23)
			var minutes = date.getMinutes();      //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
			var seconds = date.getSeconds();      //秒 ,返回 Date 对象的秒数 (0 ~ 59)
			//修改月份格式
			if (month >= 1 && month <= 9) {
				month = "0" + month;
			}
			//修改日期格式
			if (day >= 0 && day <= 9) {
				day = "0" + day;
			}
			//修改小时格式
			if (hours >= 0 && hours <= 9) {
				hours = "0" + hours;
			}
			//修改分钟格式
			if (minutes >= 0 && minutes <= 9) {
				minutes = "0" + minutes;
			}
			//修改秒格式
			if (seconds >= 0 && seconds <= 9) {
				seconds = "0" + seconds;
			}
			//获取当前系统时间  格式(yyyy-mm-dd hh:mm:ss)
			let currentFormatDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
			return currentFormatDate;
		}
	}
}
</script>

<style rel="stylesheet/scss" lang="scss" scope>
	.el-table .warning-row {
		background: oldlace;
	}
	.el-table .success-row {
		background: #f0f9eb;
	}

	.device-manage{
		.panel-bottom{
			.el-button{margin:2px 0;padding:6px 15px;font-size:14px;}
			.btn-groub2{
				display:inline-block;
				.el-button{margin:2px 0;padding:6px 15px;font-size:15px;}
				.el-button--warning {
					background-color: #e6a23c;
					border-color: #e6a23c;
				}
				.el-button--warning:focus,.el-button--warning:hover{background:#ebb563;border-color:#ebb563;}
			}
		}
	}

	.ecahrt1-dialog{
		display:flex;align-items:center;
		.el-dialog{
			margin-top:inherit !important;display:table !important;width:fit-content;
			.el-form-item{margin-right:0;}
		}

		.el-dialog__header{height:0;padding:0;display:block;}
		.form-body{
			border:1px solid #999;width:800px;height:500px;position:relative;
			>div{position:absolute;top:0;left:0;height:100%;width:100%;}
		}
	}
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
