<template>
	<el-container class="mainBox">
		<el-aside width="200px" v-loading="showGroupLoading">
			<el-container>
				<el-header>
					<el-input placeholder="输入关键字进行过滤" :size="size" v-model="groupFilterText" clearable></el-input>
				</el-header>
				<el-main class="treeMain nopadding">
					<el-tree ref="group" class="menu" node-key="id" :data="group" :current-node-key="''" :highlight-current="true" :expand-on-click-node="false" :filter-node-method="groupFilterNode" @node-click="groupClick">
						<template #default="{ node, data }">
							<span class="custom-tree-node userTree">
								<span>{{ node.label }}</span>
								<span class="btnBox" v-if="data.id!==''">
									<el-icon class="btn edit" size="14px" v-auth="'updateDept'" @click.stop="dept_edit(data)"><sc-icon-Edit/></el-icon>
									<el-icon class="btn del" size="14px" v-auth="'delDept'" @click.stop="dept_del(data)"><sc-icon-Delete/></el-icon>
								</span>
							</span>
						</template>
					</el-tree>
				</el-main>
			</el-container>
		</el-aside>
		<el-container class="mainHeaderNoBorderPadding">
			<el-header style="padding-left: 10px;">
				<div class="left-panel">
					<el-button type="primary" plain v-auth="'addDept'" :size="size" @click="addDept">新增分组</el-button>
					<el-button type="primary" v-auth="'userCreate'" :size="size" icon="el-icon-plus" @click="add">新增用户</el-button>
					<el-button type="danger" v-auth="'delUser'" plain :size="size" icon="el-icon-delete" :disabled="selection.length==0" @click="batch_del"></el-button>
					<el-button type="primary" v-auth="'addUserRoles'" plain :size="size" :disabled="selection.length==0" @click="role">分配角色</el-button>
					<el-button type="primary" plain :size="size" :disabled="selection.length==0" @click="rePwd">密码重置</el-button>
					<scImport ref="scImport" :size="size" :httpDisabled="httpDisabled" type="4" title="批量导入用户" @parentParams="importUpload" @importSuccess="importSuccess">
						<template #header>
							<el-button v-auth="'userImport'" type="primary" :size="size" plain @click="importFile">批量导入</el-button>
						</template>
						<template #download>
							<div v-auth="'userImportTemplate'" @click="importTemplate">下载导入模版</div>
						</template>
					</scImport>
				</div>
				<div class="right-panel">
					<div class="right-panel-search">
						<scExport :size="size" @exportData="exportData" @updateShow="exportChangeShow" :show="exportShow" type="7">
							<el-button :size="size" v-auth="'userExport'" icon="sc-icon-Download" :disabled="exportShow" @click="exportData">导出</el-button>
						</scExport>
					</div>
				</div>
			</el-header>
			<el-main class="nopadding">
				<div class="searchMain searchMainNoTop" style="padding-left: 10px;">
					<scSearch ref="scSearch" :searchList="searchList" @fetchSelectData="getSelectData"></scSearch>

					<div class="searchItem searchBtn">
						<el-button :size="size" :icon="searchShow?'el-icon-ArrowUpBold':'el-icon-ArrowDownBold'" @click="searchShowClick">{{searchShow?'收起':'更多'}}</el-button>
						<el-button :size="size" type="primary" icon="el-icon-search" @click="upSearch">查询</el-button>
						<el-button :size="size" type="info" icon="el-icon-RefreshRight" @click="reset">重置</el-button>
					</div>
				</div>
				<scTable ref="table" :apiObj="list.apiObj" :column="list.column" @selection-change="selectionChange" stripe border :size="size">
					<el-table-column type="selection" align="center" width="45"></el-table-column>
					<template #company_sort_name="scope">
						<span v-if="scope.row.company_info">
							{{scope.row.company_info.name}}
						</span>
					</template>
					<template #avatar="scope">
						<div class="userImg">
							<el-avatar :src="scope.row.avatar" size="small">
								<span v-if="scope.row.avatar== ''">
									{{scope.row.name.substring(0, 1)}}
								</span>
							</el-avatar>
						</div>
					</template>
					<template #roles="scope">
						<span v-if="scope.row.user_roles">
							<span v-for="(em,index) in scope.row.user_roles.role_names" :key="index">
								<span>{{em}}</span><span v-if="index+1<scope.row.user_roles.role_names.length">、</span>
							</span>
						</span>
					</template>
					<template #is_online="scope">
						<div class="userOnline">
							<span class="online" v-if="scope.row.online_info" :style="{color:`var(--el-order-color-2)`}"><span class="round" :style="{background:`var(--el-order-color-2)`}"></span> 在线</span>
							<span class="online" v-else :style="{color:`var(--el-order-color-0)`}"><span class="round" :style="{background:`var(--el-order-color-0)`}"></span> 离线</span>
							<span class="chat" @click="chatLink(scope.row)" v-if="scope.row.online_info"><el-icon size="16"><sc-icon-Chat/></el-icon> </span>
						</div>
					</template>
					<template #user_type="scope">
						<span v-for="(item,index) in userTypeList" :key="index">
							<span v-if="item.value == scope.row.user_type">{{item.label}}</span>
						</span>
					</template>
					<template #approve_status="scope">
						<span v-for="(item,index) in auditStatusList" :key="index">
							<span v-if="item.value == scope.row.approval_status" :style="{color: item.value==0?`var(--el-order-color-2)`: item.value==1?`var(--el-order-color-3)`:`var(--el-order-color-5)`}">{{item.label}}</span>
						</span>
					</template>
					<template #active_status="scope">
						<el-switch :size="size" v-model="scope.row.active_status" @change="changeSwitch($event, scope.row)" :loading="scope.row.$switch_status" :active-value="true" :inactive-value="false"></el-switch>
					</template>
					<el-table-column label="操作" fixed="right" align="center" width="160">
						<template #default="scope">
							<el-dropdown>
								<el-button class="noBorderBtn" icon="el-icon-more" :size="size"></el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item @click="table_show(scope.row, 'show')" icon="sc-icon-See">用户详情</el-dropdown-item>
										<div v-auth="'updateMe'">
											<el-dropdown-item @click="table_edit(scope.row, 'edit')" icon="sc-icon-Edit">编辑用户</el-dropdown-item>
										</div>
										<div v-auth="'userAudit'" v-if="scope.row.approval_status == 0">
											<el-dropdown-item @click="table_review(scope.row)" icon="sc-icon-OrderReview">审核用户</el-dropdown-item>
										</div>
										<div v-auth="'viewUserPermissions'">
											<el-dropdown-item @click="table_empower(scope.row)" icon="sc-icon-AbilityAuthorization" divided>查看权限</el-dropdown-item>
										</div>
										<div v-auth="'delUser'">
											<el-dropdown-item @click="table_del(scope.row, 'delete')" icon="sc-icon-Delete">删除用户</el-dropdown-item>
										</div>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</template>
					</el-table-column>
				</scTable>
			</el-main>
		</el-container>
	</el-container>

	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>
	<review-dialog v-if="dialog.review" ref="reviewDialog" @success="handleSuccess" @closed="dialog.review=false"></review-dialog>
	<re-pwd-dialog v-if="dialog.rePwdD" ref="rePwdDialog" @success="handleSuccess" @closed="dialog.rePwdD=false"></re-pwd-dialog>
	<dis-role-dialog v-if="dialog.role" ref="diRoleDialog" @success="handleSuccess" @closed="dialog.role=false"></dis-role-dialog>
	<dept-mag-dialog v-if="dialog.deptMsg" ref="deptMagDialog" @success="handleSuccess" @closed="dialog.deptMsg=false"></dept-mag-dialog>

</template>

<script>
	import saveDialog from './save'
	import reviewDialog from './review'
	import rePwdDialog from './rePwd'
	import disRoleDialog from './role'
	import deptMagDialog from '/src/views/setting/deptMag/save'

	export default {
		name:"userMag",
		components: {
			saveDialog, rePwdDialog, disRoleDialog, reviewDialog, deptMagDialog
		},
		data() {
			return {
				size:'small',
				httpDisabled:false,
				dialog: {
					save: false,
					review: false,
					rePwdD: false,
					role: false,
					deptMsg:false,
				},
				showGroupLoading: false,
				groupFilterText: '',
				group: [],
				auditStatusList:[],
				userTypeList:[],
				list:{
					apiObj: this.$API.system.user.list,
					column:[]
				},
				selection: [],
				exportShow:false,
				searchShow:false,
				searchList:[
					{name:'创建日期',type:'date',code:'activation_date',show:true},
					{name:'状态',type:'select',code:'active_status', data:[], placeholder:"请选择状态",show:true},
					{name:'联系方式',type:'text',code:['mobile'],placeholder:"请输入手机号",isOpen:true,show:false},
					{name:'姓名',type:'text',code:['name'],placeholder:"请输入姓名",isOpen:true,show:false},
					{name:'关键字',type:'text',code:['login_name','roles','department'],keyword:true,show:true},
				],
				params: {},
			}
		},
		watch: {
			groupFilterText(val) {
				this.$refs.group.filter(val);
			}
		},
		provide(){
			return{
				columnHeaderParams:false,
			}
		},
		mounted() {
			this.getGroup()
			this.auditStatus();
			this.userType();
		},
		methods: {
			searchShowClick(){
				this.searchShow = !this.searchShow;
				this.searchList.forEach(item=>{
					if(item.isOpen){
						item.show = this.searchShow
					}
				})
			},
			getSelectData(item){
				let {data,params} = item;
				this.params = params;
				if(data.code == "active_status"){
					this.getStatusList(data,params);
				}
			},
			async getStatusList(data,params) {
				const res = await this.$API.oss.status.post(params);
				if(res.code == 200){
					this.searchList.forEach(item=>{
						if(item.code == data.code){
							item.data = res.data;
						}
					})
				}
			},

			rePwd() {
				this.dialog.rePwdD = true
				this.$nextTick(() => {
					const id = this.selection[0]['id']
					this.$refs.rePwdDialog.open('add', id)
				})
			},
			role() {
				this.dialog.role = true
				this.$nextTick(() => {
					const data = this.selection;
					const row = {
						id: data[0]['id'],
						login_name: data[0]['login_name'],
						name: data[0]['name'],
						group: data[0]['user_roles'],
						mobile: data[0]['mobile'],
						avatar:data[0]['avatar']
					}
					this.$refs.diRoleDialog.open().setData(row)
				})
			},
			//添加部门分组
			addDept(){
				this.dialog.deptMsg = true
				this.$nextTick(() => {
					this.$refs.deptMagDialog.open()
				})
			},
			dept_edit(row){
				this.dialog.deptMsg = true
				this.$nextTick(() => {
					this.$refs.deptMagDialog.open('edit').setData(row)
				})
			},
			dept_del(row){
				this.$confirm(`确定删除 ${row.name} 吗？`, '提示', {
					type: 'warning'
				}).then(async () => {
					const reqData = {ids: [row.id]};
					const res = await this.$API.system.dept.delete.post(reqData);
					if(res.code == 200){
						await this.getGroup();
						this.$message.success("删除成功")
					}
				}).catch(()=>{})
			},
			//添加
			add(){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open()
				})
			},

			// 批量导入
			importFile(){
				this.$nextTick(()=>{
					this.$refs.scImport.importFile();
				})
			},
			async importTemplate() {
				const res = await this.$API.system.user.template.post();
				const blob = new Blob([res]);
				const text = new Date().getTime();
				const eLink = document.createElement('a');
				eLink.download = "用户导入模版_"+text+'.xlsx';
				eLink.style.display = 'none';
				eLink.href = URL.createObjectURL(blob);
				document.body.appendChild(eLink);
				eLink.click();
				URL.revokeObjectURL(eLink.href);
				document.body.removeChild(eLink);
			},
			async importUpload(params) {
				this.httpDisabled = true;
				const res = await this.$API.system.user.import.post(params);
				if(res.code == 200){
					this.$refs.scImport.setAnalysisShow(true);
					this.$message.success('上传成功，开始导入数据');
				}
			},
			importSuccess(refresh){
				this.httpDisabled = false;
				if(!refresh){
					this.$refs.table.refresh()
				}
			},

			//编辑
			table_edit(row){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open('edit').setData(row)
				})
			},
			//查看
			table_show(row){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open('show').setData(row)
				})
			},
			//删除
			async table_del(row){
				this.$confirm(`确定删除 ${row.login_name} 吗？`, '提示', {
					type: 'warning'
				}).then(async () => {
					const reqData = {ids: [row.id]};
					const res = await this.$API.system.user.delete.post(reqData);
					if(res.code == 200){
						this.$refs.table.refresh();
						this.$message.success("删除成功")
					}
				}).catch(()=>{})
			},
			//批量删除
			async batch_del(){
				this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
					type: 'warning'
				}).then(async () => {
					const loading = this.$loading();
					const params = {ids: this.selection.map(em => em.id)};
					const res = await this.$API.system.user.delete.post(params);
					if (res.code == 200) {
						this.$refs.table.refresh();
						this.$message.success("删除成功");
					}
					loading.close();
				}).catch(() => {

				})
			},
			// 审核用户
			table_review(row){
				this.dialog.review = true
				this.$nextTick(() => {
					this.$refs.reviewDialog.open('show').setData(row)
				})
			},
			// 查看用户权限
			table_empower(row){
				this.$router.push({
					path: '/setting/user/view-permission',
					query: {
						id: row.id,
						name:row.name,
					}
				})
			},
			//表格选择后回调事件
			selectionChange(selection){
				this.selection = selection;
			},
			// 加载用户审核常量
			async auditStatus() {
				const res = await this.$API.system.user.auditStatus.post();
				if(res.code == 200){
					this.auditStatusList = res.data;
				}
			},
			// 加载用户类型常量
			async userType() {
				const res = await this.$API.system.user.userType.post();
				if (res.code == 200) {
					this.userTypeList = res.data;
				}
			},
			//加载树数据
			async getGroup(){
				this.showGroupLoading = true;
				const res = await this.$API.system.dept.active.post();
				if(res.code == 200){
					const allNode = {id: '', label: '所有'};
					res.data.unshift(allNode);
					this.group = res.data;
				}
				this.showGroupLoading = false;
			},
			//树过滤
			groupFilterNode(value, data){
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			//树点击事件
			groupClick(data){
				const params = {
					groupId: data.id
				};
				this.$refs.table.reload(params)
			},
			// 状态
			changeSwitch(val, row) {
				row.$switch_yx = true;
				setTimeout(async () => {
					let params = {
						id: row.id,
						status: row.active_status,
					};
					const res = await this.$API.system.user.status.post(params);
					if(res.code !=200){
						row.active_status = !row.active_status;
					}
					delete row.$switch_status;
					delete row.$switch_yx;
				}, 500);
			},
			// 下载导出
			exportChangeShow(params){
				if(params.type == 7){
					this.exportShow = params.status==0?true:false
				}
			},
			async exportData() {
				if(this.exportShow) return
				const res = await this.$API.system.user.export.post();
				if(res.code == 200){
					this.exportShow = true;
					this.$message.success('开始导出');
				}
			},
			//搜索
			upSearch(){
				this.$refs.table.upData(this.params)
			},
			reset(){
				this.params = {};
				this.$refs.scSearch.reload();
				this.$refs.table.reload();
			},
			//本地更新数据
			handleSuccess(data, mode){
				if(mode=='add'){
					this.getGroup();
				}else if(mode=='edit'){
					this.$refs.table.tableData.filter(item => item.id===data.id ).forEach(item => {
						Object.assign(item, data)
					});
					this.getGroup();
				}
				this.$refs.table.refresh();
			},
			chatLink(item){
				this.$router.replace({
					name:"infoQuery",
				})
				this.$TOOL.data.set('CHAT_PARAMS',JSON.stringify(item));
			}
		}
	}
</script>

<style lang="scss" scoped>
	.userOnline{
		display: flex;align-items: center;
	}
	.online{
		display: flex;align-items: center;
		.round{width: 10px;height: 10px;display: inline-block;border-radius: 50%;margin-right: 4px;}
	}
	.chat{
		display: flex;align-items: center;margin-left: 6px;
		color: var(--el-color-success);
		cursor: pointer;
	}
	.userTree{
		position: relative;
		width: 100%;
		font-size: var(--el-font-size-small);
		.btnBox{
			position: absolute;right: 10px;top: 2px;
			.btn{margin: 0 3px;}
			.btn.edit{color: var(--el-color-primary)}
			.btn.del{color: var(--el-color-danger)}
		}
	}
</style>
