<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"></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" 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 :size="size" title="批量导入用户" @parentParams="importUpload" @importSuccess="importSuccess">
						<div v-auth="'userImportTemplate'" @click="importTemplate">下载导入模版</div>
					</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-auths="'userExport'" icon="sc-icon-Download" @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 :size="size">
					<el-table-column type="selection" align="center" width="45"></el-table-column>
					<sc-table-column label="序号" align="center" type="index"></sc-table-column>
					<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 #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="'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>
	<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>

</template>

<script>
	import saveDialog from './save'
	import rePwdDialog from './rePwd'
	import disRoleDialog from './role'

	export default {
		components: {
			saveDialog, rePwdDialog, disRoleDialog
		},
		data() {
			return {
				size:'small',
				dialog: {
					save: false,
					rePwdD: false,
					role: false
				},
				showGroupLoading: false,
				groupFilterText: '',
				group: [],
				list:{
					apiObj: this.$API.system.user.list,
					column:[]
				},
				selection: [],
				exportShow:false,
				searchShow:false,
				searchList:[
					{name:'创建日期',type:'date',code:'activation_date'},
					{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);
			}
		},
		mounted() {
			this.getGroup()
		},
		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)
				})
			},
			//添加
			add(){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open()
				})
			},

			// 批量导入
			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) {
				const res = await this.$API.system.user.import.post(params);
				if(res.code == 200){
					this.$message.success('上传成功，开始导入数据');
				}
			},
			importSuccess(){
				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_empower(row){
				this.$router.push({
					path: '/setting/user/view-permission',
					query: {
						id: row.id,
						name:row.name,
					}
				})
			},
			//表格选择后回调事件
			selectionChange(selection){
				this.selection = selection;
			},
			//加载树数据
			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.$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.$refs.table.refresh();
				}else if(mode=='edit'){
					this.$refs.table.tableData.filter(item => item.id===data.id ).forEach(item => {
						Object.assign(item, data)
					})
				}
				this.$refs.table.refresh();
			}
		}
	}
</script>

<style>
</style>
