<template>
	<div class="depart_container">
		<div class="left_cont">
			<div class="company_top" @click="initDepart">
				<img src="~@/assets/img/set_m/home_ico.png" alt="" style="width:30px;height:30px;">
				<span :class="!defaultGroup&&!defaultDepart?'act':''">部门信息</span>
			</div>
			<el-tree
				ref="departTree"
				class="depart_tree"
				style="marginTop:27px;"
				:data="departArr"
				node-key="unicodeKey"
				:props="defaultProp"
				draggable 
				:allow-drag="checkAllowDrag"
				:allow-drop="checkAllowDrop"
				check-strictly
				empty-text="暂无部门"
				@node-drop="handleDropOver">
				<span class="custom-tree-node"  slot-scope="{node,data}" @click="clickNode(node,data)">
					<span>{{ node.label }}</span>
					<span style="display:flex;alignItems:center;" v-show="act_node===data.unicodeKey">
                        <img src="~@/assets/img/data_m/move_ico.png" alt="" style="width:12px;height:12px;marginRight:10px;" @click.stop>
						<img src="~@/assets/img/set_m/add.png" alt="" style="width:12px;height:12px;marginRight:10px;" @click.stop="addNode(data)" v-if="data.IsDepartment">
						<img src="~@/assets/img/set_m/add.png" alt="" style="width:12px;height:12px;marginRight:10px;" @click.stop="addNode(data)" v-if="data.IsGroup">
						<img src="~@/assets/img/set_m/edit.png" alt="" style="width:12px;height:12px;marginRight:10px;" @click.stop="editNode(data)">
						<el-popconfirm
						@onConfirm="removeNode(node,data)"
						confirmButtonText='删除'
						cancelButtonText='取消'
						confirmButtonType="text"
						icon="el-icon-info"
						iconColor="red"
						title="确定删除吗"
						v-if="data.DepartmentId!=shareCustomDepartmentId"
						>
						<!-- 共享客户组不允许删除 -->
							<img slot="reference" src="~@/assets/img/set_m/del.png" alt="" style="width:12px;height:12px;marginTop:4px">
						</el-popconfirm>
					</span>
				</span>
			</el-tree>
			<div class="noDepart" @click="addDepart">
				<img src="~@/assets/img/set_m/add_ico.png" alt="" style="width:16px;height:16px;marginRight:10px;">
				<span>新建部门</span>
			</div>
		</div>
		<div class="right_cont">
			<div class="right_cont_top">
				<div>
					<el-button type="primary" @click="addUser">添加用户</el-button>
					<el-button type="primary" @click="synchronizationMEIKE" style="margin-left: 26px;">同步每刻</el-button>
				</div>
				<el-input
					placeholder="姓名/账号/手机号搜索"
					v-model="search_txt"
					@input="searchHandle"
					style="maxWidth:359px">
					<i slot="prefix" class="el-input__icon el-icon-search"></i>
				</el-input>
			</div>
			<div class="right_cont_bot">
				<!-- 表格 -->
				<el-table
				ref="userTable"
				:data="tableData"
				@row-click="getUserDetail"
				v-loading="isShowloadding"
				element-loading-text="数据加载中..."
				highlight-current-row
				border>
					<el-table-column
					prop="RealName"
					label="姓名"
					align="center">
						<template slot-scope="scope">
							<el-tag size="small" v-if="scope.row.LabelVal" :style="scope.row.LabelVal==1||scope.row.LabelVal==2?'color:#fff;background:#409EFF':'color:#409EFF;background:#ECF5FF'" style="position:absolute;left:10px">{{scope.row.LabelVal==1?'超管':scope.row.LabelVal==2?'管理员':scope.row.LabelVal==3?'部门经理':scope.row.LabelVal==4?'组长':'主管'}}</el-tag>
							<span style="position: relative;">{{scope.row.RealName}}</span>
						</template>
					</el-table-column>
					<el-table-column 
						prop="AdminName"
						label="账号"
						align="center"
					/>
					<el-table-column
					prop="Mobile"
					label="手机号"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.Mobile||''}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="RoleName"
					label="角色"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.RoleName||''}}</span> </template>
					</el-table-column>
					<el-table-column
					prop="DepartmentGroup"
					label="部门/分组"
					align="center">
						<template slot-scope="scope"> <span>{{scope.row.DepartmentGroup||''}}</span> </template>
					</el-table-column>
					<el-table-column label="状态" align="center">
						<template slot-scope="scope">
							<span :style="{color:scope.row.Enabled===0?'#FF0000':null}">{{scope.row.Enabled===0?'禁用':'启用'}}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="260">
						<template slot-scope="scope">
							<div style="color:#4099ef; font-size:24px;display: flex;gap:0 10px;">
								<span class="editsty" @click.stop="editUser(scope.row)">编辑</span>
								<span class="editsty" @click.stop="resetPassWord(scope.row)">重置密码</span>
								<span class="editsty" @click.stop="moveDepart(scope.row)">移动分组</span>
								<span 
									class="editsty" 
									@click.stop="handleChangeStatus(scope.row)"
								>{{scope.row.Enabled===0?'启用':'禁用'}}</span>
								<!-- <span class="deletesty" @click.stop="delUser(scope.row)">删除</span> -->
							</div>
						</template>
					</el-table-column>
					<div slot="empty" style="lineHeight:25px;margin:20px 0;color:#95A9C5;">
						<img src="../../assets/img/data_m/table_no.png" alt="" style="display:block;width:105px;height:68px;margin: auto;">
						<span>暂无数据</span>
					</div>
				</el-table>
				<el-col :span="24" class="toolbar">
					<el-pagination 
					layout="total,prev,pager,next,jumper" 
					background 
					:current-page="page_no"
					@current-change="handleCurrentChange"
					:page-size="pageSize" 
					@size-change="handleSizeChange" 
					:total="total" 
					style="float:right;margin-top: 20px;">
					</el-pagination>
				</el-col>
				<!-- 用户详情右侧弹窗 -->
				<transition name="fade">
					<div class="right_shadow" v-if="isShowUserdtl">
						<div class="shadow_top">
							<img src="~@/assets/img/set_m/user_img.png" alt="" style="width:38px;height:38px;marginRight:10px;">
							<span style="marginRight:50px;fontSize:16px;width:100px;display:inline-block;" class="text_oneLine">{{userObj.name}}</span>
						</div>
						<ul class="shadow_info">
							<li class="info_item">
								<h4 class="item_tit">手机号：</h4>
								<span>{{userObj.tel}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">部门/分组：</h4>
								<span>{{userObj.depart}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">工号：</h4>
								<span>{{userObj.employeeNumber}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">职务：</h4>
								<span>{{userObj.post}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">角色：</h4>
								<span>{{userObj.role}}</span>
							</li>
							<li class="info_item" v-if="userObj.depart.includes('FICC研究部')">
								<h4 class="item_tit">研究方向：</h4>
								<span>{{userObj.direct.map(i=>i.join('/')).join('、')||'暂无'}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">工作地点：</h4>
								<span>{{userObj.city?userObj.province+' '+userObj.city:'暂无'}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">管理权限：</h4>
								<span>{{userObj.auth||'暂无'}}</span>
							</li>
							<li class="info_item">
								<h4 class="item_tit">登录账号/密码：</h4>
								<span>{{userObj.account+'/***'}}</span>
							</li>
						</ul>
						<el-popover
							placement="left"
							:title="userObj.name+'权限'"
							width="560"
							trigger="hover">
							<div class="auth_cont" style="padding:30px 0;max-height: 70vh; overflow-y: auto;">
								<template v-if="authList.length">
									<div v-for="item in authList" :key="item" class="menu_item">
										<el-checkbox  v-model="item.checkAll" disabled>{{item.Name}}</el-checkbox>
										<div style="margin: 15px 0; padding:24px;border:1px solid #DCDFE6">
											<el-checkbox-group v-model="item.CheckList" disabled>
												<el-checkbox v-for="list in item.Child" :label="list.MenuId" :key="list">{{list.Name}}</el-checkbox>
											</el-checkbox-group>
										</div>
									</div>
								</template>
								<span v-else style="fontSize:16px;color:#999;marginLeft:20px;">暂无权限</span>
							</div>
							<span slot="reference" style="fontSize:16px;color:#409EFF;cursior:pointer;">查看权限</span>
						</el-popover>
						<img src="~@/assets/img/ppt_m/close.png" alt="" class="close_btn" @click="closeShadow">
					</div>
				</transition>
			</div>
		</div>
		<!-- 添加部门弹窗 -->
		<el-dialog
		:title="departForm.title" 
		:visible.sync="isAddDepart"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelHandle(1)"
		center
		width="30%"
		v-dialogDrag>
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="departForm.title=='新建部门'?$icons.add:$icons.edit" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">{{departForm.title}}</span>
			</div>
			<el-form :model="departForm" :rules="departRule" ref="departForm" label-width="100px" class="demo-ruleForm" style="marginTop:15px;">
				<el-form-item label="部门" prop="name">
					<el-input v-model="departForm.name" placeholder="请填写部门名称" style="width: 90%"></el-input>
				</el-form-item>
			</el-form>	
			<div style="display:flex;justify-content:center;margin:75px 0 26px;">
				<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveDepart">保存</el-button>
				<el-button  style="width:80px;" @click="cancelHandle(1)">取消</el-button>
			</div>
		</el-dialog>
		<!-- 添加分组弹窗 -->
		<el-dialog
		:title="groupForm.title" 
		:visible.sync="isAddGroup"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelHandle(2)"
		center
		width="30%"
		v-dialogDrag>
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="groupForm.title=='添加分组'?$icons.add:$icons.edit" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">{{groupForm.title}}</span>
			</div>
			<el-form @submit.native.prevent :model="groupForm" :rules="groupRule" ref="groupForm" label-width="100px" class="demo-ruleForm" style="marginTop:15px;">
				<el-form-item label="部门" prop="depart">
					<span style="fontSize:16px;">{{groupForm.depart}}</span>
				</el-form-item>
				<el-form-item label="分组" prop="group">
					<el-tag
					:key="tag"
					v-for="tag in groupForm.group"
					closable
					:disable-transitions="false"
					@close="handleClose(tag)">
					{{tag.DepartmentName}}
					</el-tag>
					<el-input
					class="input-new-tag"
					v-if="inputVisible"
					v-model="inputValue"
					placeholder="分组名"
					ref="saveTagInput"
					size="small"
					style="width:120px"
					@keyup.enter.native="handleInputConfirm"
					@blur="handleInputConfirm"
					>
					</el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showInput">+添加分组</el-button>
				</el-form-item>
			</el-form>	
			<div style="display:flex;justify-content:center;margin:75px 0 26px;">
				<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveGroup">保存</el-button>
				<el-button  style="width:80px;" @click="cancelHandle(2)">取消</el-button>
			</div>
		</el-dialog>
		<el-dialog
		title="编辑分组"
		:visible.sync="isEditGroup"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelHandle(4)"
		center
		width="30%">
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="$icons.edit" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">编辑分组</span>
			</div>
			<el-form :model="editGroupForm"  ref="editGroupForm" label-width="100px" class="demo-ruleForm" style="marginTop:15px;">
				<!-- <el-form-item label="部门" prop="depart">
					<el-select v-model="editGroupForm.depart" placeholder="请选择部门" @change="frequencyChange" style="width:90%">
						<el-option
							v-for="item in ['ficc','ficc销售']"
							:key="item"
							:label="item"
							:value="item">
						</el-option>
					</el-select>
				</el-form-item> -->
				<el-form-item label="分组" prop="group">
					<el-input v-model="editGroupForm.group" placeholder="请填写分组名称" style="width: 90%"></el-input>
				</el-form-item>
			</el-form>	
			<div style="display:flex;justify-content:center;margin:75px 0 26px;">
				<el-button type="primary" style="width:80px;marginRight:24px;" @click="editGroupOver">保存</el-button>
				<el-button  style="width:80px;" @click="cancelHandle(4)">取消</el-button>
			</div>
		</el-dialog>
		<!-- 添加用户弹窗 -->
		<Add-User-Dialog 
			ref="addUserDialog"
			:isAddUserDialogShow="isAddUser"
			:userForm="userForm"
			:departArr="departArr"
			:roleArr="roleArr"
			:hasEmployeeNo="hasEmployeeNo"
			:researchGroup="researchGroup"
			:areaCode="areaCode"
			@close="cancelHandle(3)"
			@save="saveUser"
			@selectRegion="selectRegion"
		/>
		<!-- 重置密码 -->
		<el-dialog
			class="custom-dialog"
			title="重置密码"
			:visible.sync="isResetPasswordShow"
			:close-on-click-modal="false" 
			:modal-append-to-body="false"
			@close="isResetPasswordShow=false" center width="460px" v-dialogDrag
		>
			<div class="dialog-container">
				<el-form ref="resetForm" :model="resetForm" :rules="resetRules" label-width="100px">
					<el-form-item label="账号">
						<span>{{modifyAdminName}}</span>
					</el-form-item>
					<el-form-item label="新密码" prop="password">
						<el-input v-model="resetForm.password" style="width:100%" :show-password="true"></el-input>
					</el-form-item>
					<el-form-item label="确认新密码" prop="check">
						<el-input v-model="resetForm.check" style="width:100%" :show-password="true"></el-input>
					</el-form-item>
				</el-form>
				<div style="display:flex;justify-content:center;margin:26px 0">
					<el-button type="primary" style="width:80px;margin-right:24px;" @click="resetPassWord(_,'execute')">保存</el-button>
					<el-button style="width:80px;" @click="isResetPasswordShow=false">取消</el-button>
				</div>
			</div>
		</el-dialog>
		<!-- 移动分组 -->
		<el-dialog
			title="移动分组"
			:visible.sync="isMoveDepartShow"
			:close-on-click-modal="false" 
			:modal-append-to-body="false"
			@close="isMoveDepartShow=false" center width="460px" v-dialogDrag
		>
			<div class="dialog-cotainer">
				<div class="form-item" style="display: flex;align-items: center;margin-bottom:20px">
					<p style="width:90px">账号</p>
					<span>{{modifyAdminName}}</span>
				</div>
				<div class="form-item" style="display: flex;align-items: center;">
					<p style="width:90px">选择分组</p>
					<el-cascader :options="departArr" v-model="resetDepart" :props="form_departProp" style="width:100%"
						placeholder="请选择部门分组">
					</el-cascader>
				</div>
				<div style="display:flex;justify-content:center;margin:26px 0">
					<el-button type="primary" style="width:80px;margin-right:24px;" @click="moveDepart(_,'execute')">保存</el-button>
					<el-button style="width:80px;" @click="isMoveDepartShow=false">取消</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { validateTel,validatePwd } from '@/utils/validate.js';
import { departInterence } from '@/api/api.js';
import http from '@/api/http.js'
import md5 from '@/utils/md5.js';
import mixin from './mixin/departManageMixin.js';
//自定义省市数据
import{province_sorce,city_sorce} from '@/utils/distpicker'; 
export default {
	name:'',
	mixins:[mixin],
	props:{'':{},'':{}},
	components: {},
	data () {
		var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('登录密码不能为空'));
        }else if(!validatePwd(value)) {
			  callback(new Error('请输入正确的密码格式'));
		  } else {
          callback();
        }
		};
		var validateMobile = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('手机号码不能为空'));
        }else if(isNaN(value)) {
			  callback(new Error('请输入正确的手机号格式'));
		  } else {
          callback();
        }
		}
		return {
			isAddDepart:false,//添加部门弹窗
			departForm:{
				title:"添加部门",
				name:''
			},//部门表单
			departRule:{
				name:[
					{ required: true, message: '请输入部门名称', trigger: 'blur' },
				]
			},//部门校验
			isAddGroup:false,//添加分组
			// 共享客户组的部门Id 
			shareCustomDepartmentId:0,
			inputVisible:false,//分组input显示
			inputValue:'',//分组input值
			groupForm:{
				title:"添加分组",
				depart:'',
				group:[],
				depart_id:'',
			},//分组表单
			groupRule:{
				group:[
					{ required: true, message: '请添加分组', trigger: 'blur' },
				]
			},//分组校验
			isEditGroup:false,//编辑分组
			editGroupForm:{
				// depart:'',
				group:''
			},
			act_node:'',//被选中的数组
			departArr:[],//总部门分组数组
			cascaderIdx: 0,
			defaultProp:{
				label:'DepartmentName',
				children:'Child'
			},
			search_txt:'',//关键字搜索
			tableData:[],//用户列表
			isShowloadding:false,
			total:1,
			page_no:1,
			pageSize:10,
			defaultGroup:'',
			defaultDepart:'',
			groupTeamId:0,
			isAddUser:false,//添加用户弹框
			userForm:{
				title:'添加用户',
				account:'',
				pwd:'',
				name:'',
				depart:'',
				role:'',
				direct:'',
				province:'',
				city:'',
				post:'',
				employeeNumber:'',
				mobile:'',
				auth:0,
				status:1,//状态 1启用 0禁用
				email:'',
				areacode:'86',
			},//用户弹框表单
			// 是否有工号
			hasEmployeeNo:false,
			userRule:{
				account:[
					{ required: true, message: '登录账号不能为空', trigger: 'blur' },
				],	
				pwd:[
					// { required: true, message: '登录密码不能为空', trigger: 'blur' },
					// { validator: validatePass, trigger: 'blur'},
				],
				employeeNumber:[{validator:(rule,value,callback)=>{
					if(!value){
						callback()
						return 
					}
					// 取消空格
					let tempValue = parseInt(value.replaceAll(' ',''))
					if(!tempValue || value.replaceAll(' ','').length!=4){
						callback(new Error('请输入四位数字'))
					}else{
						callback()
					}
				},trigger:'blur'}],
				name:[
					{ required: true, message: '姓名不能为空', trigger: 'blur' },
				],
				depart:[
					{ required: true, message: '部门分组不能为空', trigger: 'change' },
				],
				role:[
					{ required: true, message: '角色不能为空', trigger: 'change' },
				],
				// post:[
				// 	{ required: true, message: '职务不能为空', trigger: 'blur' },
				// ],
				mobile:[
					{ validator: validateMobile, trigger: 'blur'},
				],
				/* direct:[
					{ required: true, message: '研究方向不能为空', trigger: 'blur' },
				] */
				
			},//用户信息表单校验
			form_departArr:[{
				label:'ficc销售',
				value:1
			},{
				label:'ficc研究',
				value:2
			}],//表单部门数组
			authArr:[
				{
					label:'无',
					value:0,
				},
				{
					label:'部门负责人',
					value:1,
				},
				{
					label:'小组负责人',
					value:2,
				},
			],
			roleArr:[],//角色列表
			isShowUserdtl:false,//用户信息抽屉弹窗
			userObj:{
				name:'',
				tel:'',
				depart:'',
				post:'',
				roleId:0,
				role:'',
				auth:'',
				account:'',
				pwd:'',
				employeeNumber:'',
				direct:'',
				province:'',
				city:'',
			},//用户详情信息
			authList:[],//权限列表
			click_roleId:'',//角色id
			province_sorce:province_sorce,
			city_sorce:city_sorce,
			form_departProp:{
				value:'DepartmentId',
				label:'DepartmentName',
				children:'Child',
				checkStrictly:true
			},//部门分组选择配置
		};
	},
	watch: {
		click_roleId() {
			this.getAuth();
		}
	},
	created() {
		// 不同环境下 共享客户组的DepartmentId不一样
		if(process.env.NODE_ENV == 'development'||process.env.NODE_ENV == 'test'){
			this.shareCustomDepartmentId = 61
		}else if(process.env.NODE_ENV == 'production'){
			this.shareCustomDepartmentId = 37
		}
		this.getAreaCode()
	},
	mounted() {
		this.getDepartArr();
		this.getTableUser();
		this.getRoles();
		this.getResearchGroup();
	},
	methods: {
		async handleChangeStatus(e){
			const res=await departInterence.statusChange({
				AdminId:Number(e.AdminId),
				Enabled:e.Enabled===1?0:1
			})
			if(res.Ret===200){
				this.getTableUser();
			}
		},

		// 重置部门选中
		initDepart() {
			this.defaultDepart = ''
			this.defaultGroup = ''
			this.act_node = ''
			this.groupTeamId = 0
			this.cascaderIdx ++;
			this.getDepartArr();
			this.getTableUser();
		},
		/* 部门结构总列表 */
		getDepartArr() {
			departInterence.getDepartList().then(res => {
				if(res.Ret === 200) {
					this.departArr = res.Data.List || []
					//给节点增加唯一key和parentkey
					this.departArr = this.departArr.map(depart=>{
						depart.unicodeKey='depart_'+depart.DepartmentId
						depart.parentKey = 0
						if(depart.Child){
							depart.Child = depart.Child.map(group=>{
								group.unicodeKey = 'group_'+group.DepartmentId
								group.parentKey = depart.unicodeKey
								if(group.Child){
									group.Child = group.Child.map(team=>{
										team.unicodeKey = 'team_'+team.DepartmentId
										team.parentKey = group.unicodeKey
										return team
									})
								}
								return group
							})
						}
						return depart
					})
				}
			})
		},
		/* 用户表格数据 */
		getTableUser() {
			let params = {
				PageSize:this.pageSize,
				CurrentIndex:this.page_no,
				KeyWord:this.search_txt,
				DepartmentId:this.defaultDepart,
				GroupId:this.defaultGroup,
				TeamId:this.groupTeamId,
			}
			departInterence.getUserList(params).then(res => {
				if(res.Ret === 200) {
					this.tableData = res.Data.List || [];
					this.total = res.Data.Paging.Totals;
				}
			})
		},
		/* 获取已有角色列表 */
		getRoles() {
			departInterence.getRole({ RoleLevel:0 }).then(res => {
				if(res.Ret === 200) {
					this.roleArr = res.Data.List;
				}
			})
		},
		/* 根据角色id获取已有权限 */
		getAuth() {
			departInterence.getAuthList({
				RoleId:Number(this.click_roleId)
			}).then(res => {
				if(res.Ret === 200) {
					let list = [];
					/* 校验是否有选中的权限列表 如果有显示已勾选的权限 没有就不显示权限列表 */
					let Bol = res.Data.List.some(item => {
						return item.CheckList&&item.CheckList.length !=0
					})
					console.log(Bol)
					if(Bol) {
						res.Data.List.length&&res.Data.List.forEach(item => {
							let obj = {
								checkAll:item.CheckList.length===item.Child.length?true:false,
								...item,
							}
							list.push(obj)
						})
					}
					this.authList = list;
				}
			})
		},
		// 节点点击时显示操作按钮更新表格
		clickNode(e,data) {
			this.act_node = data.unicodeKey;
			/* 部门节点 */
			if(data.IsDepartment) {
				this.defaultDepart = data.DepartmentId;
				this.defaultGroup = '';
				this.groupTeamId = 0
			}else if(data.IsGroup){
				/* 分组节点 */
				this.defaultGroup = data.DepartmentId;
				this.defaultDepart = ''
				this.groupTeamId = 0
			} else {
				this.defaultGroup = data.GroupId;
				this.groupTeamId = data.DepartmentId
				this.defaultDepart = ''
			}
			this.page_no = 1;
			this.getTableUser();
		},
		/* 删出节点 */
		removeNode(node,data) {
			// console.log(node,data)
			// const parent = node.parent;
			// const children = parent.data.children || parent.data;
			// const index = children.findIndex(d => d.id === data.id);
			// children.splice(index, 1);
			// 删除部门
			if(data.IsDepartment) {
				departInterence.delDepart({
					DepartmentId:data.DepartmentId
				}).then(res =>{
					if(res.Ret === 200) {
						this.$message.success('删除部门成功')
						this.getDepartArr();
					}
				})
			}else if(data.IsGroup) {
				/* 删除分组 */
				departInterence.delGroup({
					GroupId:data.DepartmentId
				}).then(res =>{
					if(res.Ret === 200) {
						this.$message.success('删除分组成功')
						this.getDepartArr();
					}
				})
			}else {
				departInterence.delTeamGroup({
					TeamId:data.DepartmentId
				}).then(res =>{
					if(res.Ret === 200) {
						this.$message.success('删除成功')
						this.getDepartArr();
					}
				})
			}
		},
		// 编辑节点 部门/分组
		editNode(data) {
			if(data.IsDepartment) {
				this.isAddDepart = true;
				this.departForm = {
					title:"编辑部门",
					name:data.DepartmentName,
					depart_id:data.DepartmentId
				}
			}else if(data.IsGroup) {
				this.isEditGroup = true;
				this.editGroupForm = {
					group_id:data.DepartmentId,
					group:data.DepartmentName
				}
			} else {
				console.log(data);
				this.isEditGroup = true;
				this.editGroupForm = {
					group_id:data.DepartmentId,
					group:data.DepartmentName,
					team:true
				}
			}
		},
		/* 保存编辑分组 */
	async	editGroupOver(){
		const res = this.editGroupForm.team ? await departInterence.editTeamGroup({
				TeamId:Number(this.editGroupForm.group_id),
				TeamName:this.editGroupForm.group,
			})	: await departInterence.editGroup({
				GroupId:Number(this.editGroupForm.group_id),
				GroupName:this.editGroupForm.group,
			})
			if(res.Ret === 200) {
					this.$message.success('编辑成功')
					this.isEditGroup = false;
					this.editGroupForm = {
						group_id:'',
						group:''
					}
					this.getDepartArr();
			}
		},
		// 新增节点分组
		addNode(data) {
			if(data.IsDepartment) {
				this.isAddGroup = true;
				this.groupForm = {
					title:"添加分组",
					depart:data.DepartmentName,
					depart_id:data.DepartmentId,
					group:data.Child||[]
				}
			}else if(data.IsGroup) {
				console.log(data);
				this.isAddGroup = true;
				this.groupForm = {
					title:"添加分组",
					depart:data.DepartmentName,
					depart_id:data.TopId,
					group_id:data.DepartmentId,
					group:data.Child||[],
					isGroup:data.IsGroup
				}
			}
		},
		// 点击删除分组
		handleClose(tag) {
        	this.groupForm.group.splice(this.groupForm.group.indexOf(tag), 1);
		},
		/* 点击添加 */
      showInput() {
        this.inputVisible = true;
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
		},
		// 输入完成
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
				let item = {
					DepartmentName:inputValue
				}
				this.groupForm.group.push(item);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
		/* 保存分组 */
		saveGroup() {
			this.$refs.groupForm.validate(async(valid) => {
				if (valid) {
					let groupArr = [];
					this.groupForm.group.forEach(item => {
						groupArr.push(item.DepartmentName)
					});
					 const res =  this.groupForm.isGroup ? await departInterence.addTeamGroup({
						DepartmentId:Number(this.groupForm.depart_id),
						GroupId:this.groupForm.group_id,
						TeamName:groupArr.join(',')
					 }): await departInterence.addGroup({
						DepartmentId:Number(this.groupForm.depart_id),
						GroupName:groupArr.join(',')
					})
						if(res.Ret === 200) {
							this.$message.success('添加成功')
							this.isAddGroup = false;
							this.groupForm = {
								title:"添加分组",
								depart:'',
								group:[],
								depart_id:'',
							};
							this.getDepartArr();
						}
				}
			})
		},
		/* 新建部门*/
		addDepart() {
			this.isAddDepart = true;
			this.departForm = {
				title:'新建部门',
				name:''
			}
		},
		/*保存部门*/
		saveDepart() {
			this.$refs.departForm.validate((valid) => {
				if (valid) {
					// alert('submit!');
					if(this.departForm.title == '新建部门') {
						departInterence.addDepart({
							DepartmentName:this.departForm.name
						}).then(res => {
							if(res.Ret === 200) {
								this.$message.success('新建成功')
								this.isAddDepart = false;
								this.departForm = {
									title:'新建部门',
									name:''
								}
								this.getDepartArr();
							}
						})
					}else {
						departInterence.editDepart({
							DepartmentId:Number(this.departForm.depart_id),
							DepartmentName:this.departForm.name
						}).then(res => {
							if(res.Ret === 200) {
								this.$message.success('编辑成功')
								this.isAddDepart = false;
								this.departForm = {
									title:'新建部门',
									name:''
								}
								this.getDepartArr();
							}
						})
					}
				}
			})			
		},
		/* 搜索用户 */
		searchHandle() {
			this.page_no = 1;
			this.initDepart();
		},
		/* 新建用户 */
		addUser() {
			this.isAddUser = true;
			this.hasEmployeeNo=false
			this.userForm = {
				title:'添加用户',
				account:'',
				pwd:'',
				employeeNumber:'',
				name:'',
				depart:'',
				role:'',
				direct:'',
				province:'',
				city:'',
				post:'',
				mobile:'',
				auth:0,
				status:1,
				email:'',
				areacode:'86',
			}
		},
		// 同步每刻
		synchronizationMEIKE(){
			departInterence.syncCompanyProfile().then(res=>{
				if(res.Ret == 200){
					this.$message.success('同步成功')
				}
			})
		},
		// 工作位置选择
		selectRegion(data) {
			this.userForm.province = data.province.value;
			this.userForm.city = data.city.value =='市'?'':data.city.value;
		},
		roleChange(value){
			if([2,6,18].includes(value)) return 
			this.$refs.userForm && this.$refs.userForm.clearValidate(['city'])
		},
		//切换省份时，市的值置为空
		provinceChange(){
			this.userForm.city=''
		},
		/* 保存用户 */
		saveUser() {
			console.log(this.userForm.depart);
			//转换研究方向字段数据,如果有
			let ResearchGroupIds = []
			if(this.userForm.direct){
				this.userForm.direct.forEach(item=>{
					ResearchGroupIds.push(item[item.length-1])
				})
			}
			this.$refs.addUserDialog.$refs.userForm.validate((valid) => {
				if (valid) {
					/* 新增 */
					if(this.userForm.title == '添加用户') {				
						let params = {
							AdminName: this.userForm.account,
							Password: new http.Base64().encode(this.userForm.pwd),
							EmployeeId:this.userForm.employeeNumber.replaceAll(' ',''),
							Authority: this.userForm.auth,
							DepartmentId: Number(this.userForm.depart[0]),
							GroupId:this.userForm.depart[1] ? Number(this.userForm.depart[1]) : 0,
							TeamId:this.userForm.depart[2] ? Number(this.userForm.depart[2]) : 0,
							Mobile: this.userForm.mobile,
							Position: this.userForm.post,
							RealName: this.userForm.name,
							RoleId: Number(this.userForm.role),
							Enabled:Number(this.userForm.status),
							ResearchGroupIds:ResearchGroupIds.join(','),
							Province:this.userForm.province,
							City:this.userForm.city,
							Email:this.userForm.email,
							TelAreaCode:this.userForm.areacode,
						}
						//console.log('testAdd',params)
						departInterence.addUser(params).then(res => {
							if(res.Ret === 200) {
								this.$message.success(res.Msg);
								this.isAddUser = false;
								this.userForm = {
									title:'添加用户',
									account:'',
									pwd:'',
									employeeNumber:'',
									name:'',
									depart:'',
									role:'',
									direct:'',
									province:'',
									city:'',
									post:'',
									mobile:'',
									auth:0,
									status:1,
									email:'',
									areacode:'86'
								}
								this.getTableUser();
							}
						})
					}else {
						/* 编辑 */
						/* 对密码加密处理之前校验是否已经是密文 */
						// let pwd = this.userForm.pwd===this.userForm.oldPwd ? this.userForm.pwd : md5.hex_md5(this.userForm.pwd);
						let pwd = new http.Base64().encode(this.userForm.pwd);
						// console.log(this.userForm,pwd)
						let params = {
							AdminId: Number(this.userForm.admin_id),
							AdminName: this.userForm.account,
							Password: pwd,
							EmployeeId:this.userForm.employeeNumber.replaceAll(' ',''),
							Authority: this.userForm.auth,
							DepartmentId: Number(this.userForm.depart[0]),
							GroupId: Number(this.userForm.depart[1]),
							TeamId:this.userForm.depart[2] ? Number(this.userForm.depart[2]) : 0,
							Mobile: this.userForm.mobile,
							Position: this.userForm.post,
							RealName: this.userForm.name,
							RoleId: Number(this.userForm.role),
							Enabled:Number(this.userForm.status),
							ResearchGroupIds:ResearchGroupIds.join(','),
							Province:this.userForm.province,
							City:this.userForm.city,
							Email:this.userForm.email,
							TelAreaCode:this.userForm.areacode||'86',
						}
						//console.log('testEdit',params)
						departInterence.editUser(params).then(res => {
							if(res.Ret === 200) {
								this.$message.success('编辑成功');
								this.isAddUser = false;
								this.userForm = {
									title:'添加用户',
									account:'',
									pwd:'',
									employeeNumber:'',
									name:'',
									depart:'',
									role:'',
									direct:'',
									province:'',
									city:'',
									post:'',
									mobile:'',
									auth:0,
									status:1,
									email:'',
									areacode:'86',
								}
								this.getTableUser();
							}
						})
					}
				}
			})
		},
		/*关闭弹窗*/
		cancelHandle(type) {
			if(type === 1) {
				this.departForm.name = '';
				this.$refs.departForm.resetFields();//重置校验
				this.isAddDepart = false;
			}else if(type === 2) {
				this.groupForm = {
					title:"添加分组",
					depart:'',
					depart_id:'',
					group:[],
				},
				this.$refs.groupForm.resetFields();//重置校验
				this.isAddGroup = false;
			}else if(type === 3) {
				this.userForm = {
					title:'添加用户',
					account:'',
					pwd:'',
					employeeNumber:'',
					name:'',
					depart:'',
					group:'',
					role:'',
					direct:'',
					province:'',
					city:'',
					post:'',
					mobile:'',
					auth:'无',
					status:1,
					email:'',
					areacode:'86',
				},
				this.$refs.addUserDialog.$refs.userForm.resetFields();//重置校验
				this.isAddUser = false;
			}else if(type === 4) {
				this.editGroupForm = {
					group_id:'',
					group:''
				}
				this.$refs.editGroupForm.resetFields();//重置校验
				this.isEditGroup = false;
			}
		},
		/* 页码改变 */
		handleCurrentChange(page) {
			this.page_no = page;
			this.getTableUser();
		},
		/* 点击表格行查看用户详情 */
		async getUserDetail(row) {
			let ResearchGroupIds = [] 
			const res = await departInterence.getResearchGroupByAdminId({
				AdminId:row.AdminId
			})
			if(res.Ret===200&&res.Data){
				res.Data.forEach(row=>{
					ResearchGroupIds.push(row.research_group_id)
				})
			}
			const direct = this.changeResearchGroupIdsToDirect(ResearchGroupIds,'tag_name')
			this.userObj = {
				name:row.RealName || '暂无',
				tel:row.Mobile || '暂无',
				depart:row.DepartmentGroup || '暂无',
				post:row.Position || '暂无',
				roleId:row.RoleId || 0,
				role:row.RoleName || '暂无',
				auth:row.Authority===2?'小组负责人':row.Authority===1?'部门负责人':'无',
				account:row.AdminName,
				pwd:row.Password,
				employeeNumber:row.EmployeeId || '暂无',
				direct:direct,
				province:row.Province,
				city:row.City,
			}
			this.click_roleId = row.RoleId;
			setTimeout(()=> {
				this.isShowUserdtl = true;
			})
		},
		/* 关闭信息弹窗 */
		closeShadow() {
			this.isShowUserdtl = false;
			this.$refs.userTable.setCurrentRow();
		},
		/* 编辑用户信息 */
		async editUser(item) {
			let departArr = [];
			departArr.push(item.DepartmentId)
			item.GroupId?departArr.push(item.GroupId):''
			item.TeamId ?departArr.push(item.TeamId):''
			let ResearchGroupIds = []
			const res = await departInterence.getResearchGroupByAdminId({
				AdminId:item.AdminId
			})
			if(res.Ret===200&&res.Data){
				res.Data.forEach(item=>{
					ResearchGroupIds.push(item.research_group_id)
				})
			}
			const direct = this.changeResearchGroupIdsToDirect(ResearchGroupIds,'tag_id')
		/* 	if(departArr[0]===1){
				this.isExtraUserFormItemShow = true
			}else{
				this.isExtraUserFormItemShow = false
			} */
			this.userForm = {
				title:'编辑用户',
				admin_id:item.AdminId,
				account:item.AdminName,
				pwd:item.Password,
				employeeNumber:item.EmployeeId,
				// oldPwd:item.Password,
				name:item.RealName,
				depart:departArr,
				role:item.RoleId,
				province:item.Province,
				city:item.City,
				post:item.Position,
				mobile:item.Mobile,
				auth:item.Authority,
				status:item.Enabled,
				direct:direct,
				email:item.Email,
				areacode:item.TelAreaCode||'86'
			}
			this.hasEmployeeNo=!!item.EmployeeId
			this.isAddUser = true;
		},
		/* 删除用户 */
		delUser(item) {
			this.$confirm(`是否确认删除用户【${item.AdminName}】`,'提示',{
				type:'warning'
			}).then(() => {
				departInterence.delUser({
					AdminId:item.AdminId
				}).then(res => {
					if(res.Ret === 200) {
						this.$message.success('删除成功')
						this.getTableUser();
					}
				})
			}).catch(() => {});
		},
	}
}
</script>
<style lang='scss'>
.depart_container {
	* {
		box-sizing: border-box;
	}
	.el-popper {
		padding: 20px !important;
	}
	.fade {
		transition: all 0.5s;
	}
	display: flex;
	align-items: space-between;
	background: #f5f7f9;
	// reset
	.el-form-item__label {
		font-size: 16px;
		padding-right: 20px !important;
	}
	.el-tag {
		font-size: 12px !important;
	}
	.el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
		content: '';
	}
	.el-tag {
		margin-right: 10px;
	}
	.el-cascader .el-input {
		width:100%;
	}
	.left_cont {
		width: 16%;
		min-width: 200px;
		margin-right: 20px;
		height: calc(100vh - 120px);
		overflow-y: auto;
		border-radius: 4px;
		background: #fff;
		padding: 20px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
		.company_top {
			display: flex;
			align-items:flex-end;
			font-size: 16px;
			color: #333;
			cursor: pointer;
			span {
				width: 100%;
				padding: 4px 10px 0;
				&:hover {
					background: #F5F7FA;
				}
			}
			.act {
				background: #F0F4FF;
			}
		}
		.depart_tree {
			font-size: 15px;
			color: #333;
			.custom-tree-node {
				display: flex !important;
				justify-content: space-between;
				align-items: center;
				display: block;
				flex: 1;
			}
			.el-tree-node__content {
				margin-bottom: 15px !important;
			}
			.el-tree-node__children {
				.el-tree-node {
					margin-bottom: 8px !important;
					padding-left: 18px;
				}
				.el-tree-node__content {
					margin-bottom: 5px !important;
					padding-left: 0 !important;
				}
			}
			.expanded.el-icon-caret-right:before {content: url("../../assets/img/set_m/down.png")!important;}
			.el-icon-caret-right:before {content: url("../../assets/img/set_m/slide.png")!important;}
			.el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before { content:""!important;}
			.el-tree-node__expand-icon.expanded {-webkit-transform: rotate(0deg);transform: rotate(0deg);}
			.el-tree-node.is-current > .el-tree-node__content {background-color: #F0F4FF !important;}
			.el-tree-node__content{padding-right:10px !important;}
		}
		.noDepart {
			margin-top: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #409EFF;
			font-size: 16px;
			cursor: pointer;
		}
	}
	.right_cont {
		width: 82%;
		background: #F5F7F9;
		// box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
		border-radius: 4px;
		.right_cont_top {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border: 1px solid #ECECEC;
			padding: 20px 30px;
			background: #fff;
			border-radius: 4px;
			box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
		}
		.right_cont_bot {
			height: calc(100vh - 222px);
			overflow-y: auto;
			padding: 20px 30px;
			background: #fff;
			margin-top: 20px;
			position: relative;
			border: 1px solid #ECECEC;
			border-radius: 4px;
			box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
			.right_shadow {
				width: 350px;
				background: #fff;
				position: absolute;
				right: 0;
				top: 0;
				bottom: 0;
				overflow-y: hidden;
				z-index: 2;
				box-shadow: -3px 0 6px rgba(0, 0, 0, 0.1);
				border: 1px solid #ececec;
				padding: 60px 30px;
				.shadow_top {
					display: flex;
					align-items: center;
				}
				.shadow_info {
					margin-top: 30px;
					margin-bottom: 40px;
					font-size: 16px;
					color: #333;
					height: calc(100% - 120px);
					overflow-y: auto;
					.info_item {
						margin-bottom: 20px;
						.item_tit {
							margin-bottom: 10px;
						}
					}
				}
				.close_btn {
					width: 16px;
					height: 16px;
					position: absolute;
					right: 20px;
					top: 20px;
				}
			}
		}
	}
}
</style>