<template>
	<view class="role-page bg-page">
		<u-sticky :h5NavHeight="h5NavHeightP">
		<view class="top-title-box">
			<view class="title">角色列表</view>
			<view class="handle-option">
				<u-button v-auth="['endpoint.admin_roles.create']" class="btn" size="medium"
				 @click="addBtn()" type="primary">新增</u-button>
			</view>
		</view>
		</u-sticky>
		<view class="content-box">
			<u-swipe-action class="tb_swipe_list" 
				 v-for="(item, index) in rolelist" 
				 :show="item.show" :index="index"  :key="item.id" 
				@click="click"
				@open="open"
				:options="options"
				>
				<view class="tb_body" @click="showInfo(index)">
					<!-- <view class="row_box">
						<view class="text">序号：{{ index+1 }}</view>
					</view> -->
					<view class="row_box">
						<view class="text">角色名称：{{ item.name }}</view>
					</view>
					<view class="row_box">
						<view class="text">角色编码：{{ item.slug }}</view>
					</view>
				</view>
			</u-swipe-action>
		</view>
		<!-- 编辑 -->
		<u-popup v-model="editShow" border-radius="28" width="92%" height="70%"
		 mode="center" :closeable="true" :mask-close-able="false" z-index="910">
			<view class="popup-form-ubox">
				<view class="top_box">
					<view class="title" v-if="formInfo.id">编辑角色</view>
					<view class="title" v-else>新增角色</view>
				</view>
				<scroll-view class="scroll-y" scroll-y="true">
					<view class="form_edit">
						<u-form :model="formInfo">
							<u-form-item label="角色ID" v-if="formInfo.id" label-width="140">
								<view class="input_box bg_colorf8">
									<u-input v-model="formInfo.id" :disabled="true" />
								</view>
							</u-form-item>
							<u-form-item label="角色名称" label-width="140">
								<view class="input_box">
									<u-input v-model="formInfo.name" />
								</view>
							</u-form-item>
							<u-form-item label="角色编码" label-width="140">
								<view class="input_box">
									<u-input v-model="formInfo.slug" />
								</view>
							</u-form-item>
							<view class="label_tit">菜单分配</view>
							<DaTreeVue2
							  v-if="isgetInfo"
							  ref="DaTreeRef"
							  :data="permissionsList"
							  labelField="label"
							  valueField="id"
							  showCheckbox
							  :defaultCheckedKeys="defaultCheckedKeysValue"
							  @change="handleTreeChange"
							  @expand="handleExpandChange" />
							  
						</u-form>
						
					</view>
				</scroll-view>
				<view class="buttom_section">
					<u-button class="btn" type="default" @click="editShow = false">取消</u-button>
					<u-button class="btn" @click="editInfoBtn()" type="primary">确定</u-button>
				</view>
			</view>
		</u-popup>
		<u-popup v-model="popupShow" mode="bottom" border-radius="28" z-index="900">
			<view class="popup-form-info">
				<view class="top_box">
					<view class="handle-btns">
						<view v-auth="['endpoint.admin_roles.destroy']" class="btn_del" @click="deleteRoleId(info.id)">删除</view>
						<view v-auth="['endpoint.admin_roles.edit']" class="btn_edit" @click="editRoleId(info.id)">编辑</view>
					</view>
				</view>
				<view class="section_c">
					
					<view class="plist u-border-bottom">
						<view class="label_t">角色名称</view>
						<view class="flex-1">{{info.name}}</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">角色编码</view>
						<view class="flex-1">{{info.slug}}</view>
					</view>
				</view>
			</view>
		</u-popup>
		<u-loadmore :status="loading" margin-top="40"/>
	</view>
</template>

<script>
	import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
	import {showLoading,hideLoading} from '@/com/utils.js'
	import checkPermission from '@/utils/permission.js'
	export default {
		components: { DaTreeVue2 },
		data() {
			return {
				per_page:10,
				page:1,
				rolelist:[],
				loading:'loadmore',
				popupShow:false,
				info:{},//详情
				cindex:-1,//操作的索引
				editShow:false,
				formInfo:{
					id:'',
					name:'',
					slug:'',
					permissions:'',
					get_permissions:false
				},
				isgetInfo:false,
				permissionsList:[],
				defaultCheckedKeysValue: [],
			};
		},
		computed: {
    options() {
      return [
        {
          text: '编辑',
          opt: 'edit',
          permission: ['endpoint.admin_roles.edit'],
          style: {
            backgroundColor: '#007aff',
          },
        },
        {
          text: '删除',
          opt: 'delete',
          permission: ['endpoint.admin_roles.destroy'],
          style: {
            backgroundColor: '#dd524d',
          },
        },
      ].filter((e) => checkPermission(e.permission))
    },
  },
		onLoad() {
			this.queryAdminRoleList();
			this.queryPermissions();
			
		},
		methods: {
			addBtn(){
				this.resetForm();
				this.isgetInfo = true;
				this.editShow = true;
			},
			handleTreeChange(allSelectedKeys, currentItem) {
			  console.log('handleTreeChange ==>', allSelectedKeys, currentItem);
			  this.formInfo.permissions = allSelectedKeys;
			},
			handleExpandChange(expand, currentItem) {
			  console.log('handleExpandChange ==>', expand, currentItem)
			},
			showInfo(index){
				this.cindex = index;
				this.info = this.rolelist[index];
				this.popupShow = true;
			},
			open(index){
				this.rolelist[index].show = true;
			},
			click(index, index1) {
				console.log(index,index1,this.rolelist[index])
				if(index1 == 1) {
					this.cindex = index;
					let _id = this.rolelist[index].id;
					this.deleteRoleId(_id);
				} else {
					let _id = this.rolelist[index].id;
					this.queryRoleInfo(_id);
					this.formInfo = this.rolelist[index];
					this.editShow = true;
					this.rolelist[index].show = false;
					
				}
				
			},
			
			queryAdminRoleList(refresh){
				if(refresh){
					this.loading = 'loadmore';
					this.rolelist = [];
					this.page = 1;
				}
				if(this.loading=='nomore'){//超出最大页
					return false;
				}
				let params = {
					per_page:this.per_page,
					page: this.page ++,
					_t: new Date().getTime()
				}
				this.loading = 'loading';
				this.$http.get('/api/admin-roles',{params:params}).then(({data})=>{
					
					console.log(data)
					this.loading = 'loadmore';
					if(data.code==200){
						let _list = data.data|| [];
						for(let item of _list){
							item.show = false;
						}
						this.rolelist = this.rolelist.concat(_list);
						console.log(this.rolelist);
						if(this.rolelist.length>= data.meta.total){
							this.loading ='nomore';
						}
					}
				}).catch(()=>{
					this.loading = 'loadmore';
				})
			},
			//修改
			editInfoBtn(){
				if(!this.isgetInfo){
					return false
				}
				let params = {
					name:this.formInfo.name,
					slug:this.formInfo.slug,
					permission_ids:this.formInfo.permissions
				}
				let id = this.formInfo.id;
				if (params.name=='') {
					uni.showToast({ title: '请填写角色名称', icon: 'none' });
					return;
				}
				if (params.slug=='') {
					uni.showToast({ title: '请填写角色编码', icon: 'none' });
					return;
				}
				showLoading('请稍等...');
				if(id){
					this.$http.put(`/api/admin-roles/${id}`,params).then(({data})=>{
						hideLoading();
						if(data.code==200){
							this.editShow = false;
						}
						uni.showToast({ title: data.message, icon: 'none' });
					}).catch(()=>{
						hideLoading();
					})
				}else{
					this.$http.post(`/api/admin-roles`,params).then(({data})=>{
						hideLoading();
						if(data.code==200){
							this.queryAdminRoleList(true);
							this.editShow = false;
						}
						uni.showToast({ title: data.message, icon: 'none' });
					}).catch(()=>{
						hideLoading();
					})
				}
			},
			editRoleId(id){
				this.queryRoleInfo(id);
				this.formInfo = this.info;
				this.editShow = true;
			},
			//删除角色
			deleteRoleId(id){
				uni.showModal({
					title: '提示',
					content: '是否确定删除？',
					success:  (res)=> {
						if (res.confirm) {
							console.log('用户点击确定');
							showLoading('请稍等...');
							this.$http.delete(`/api/admin-roles/${id}`).then(({data})=>{
								hideLoading();
								if(data.code==200){
									this.formInfo = {};//重置删除
									this.popupShow = false;
									this.rolelist.splice(this.cindex,1);
									uni.showToast({ title: data.message, icon: 'none' });
								}
							}).catch(()=>{
								hideLoading();
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				
			},
			//权限数据列表
			queryPermissions(){
				this.$http.get('/api/permissions').then(({data})=>{
					if(data.code==200){
						this.permissionsList = data.data;
					}
				}).catch((err)=>{
					
				})
			},
			queryRoleInfo(id){
				this.isgetInfo = false;
				this.$http.get(`/api/admin-roles/${id}`).then(({data})=>{
					console.log(data,'queryRoleInfo===')
					if(data.code==200){
						this.formInfo.permissions = data.data.permissions;
						this.defaultCheckedKeysValue = data.data.permissions;
						this.isgetInfo = true;
						console.log(this.defaultCheckedKeysValue,'queryRoleInfo===')
					}
				}).catch((err)=>{
					
				})
			},
			resetForm(){
				this.formInfo = {
					id:'',
					name:'',
					slug:'',
					permissions:'',
					get_permissions:false
				};
				this.defaultCheckedKeysValue = [];
			}
		},
		//触底加载
		onReachBottom() {
			if(this.loading=='loadmore'){
				this.queryAdminRoleList();
			}
		},
	}
</script>

<style lang="scss" scoped>
.role-page{
	.content-box{
		padding: 30rpx;
	}
}

.input_box{
	width: 100%;
	padding: 0 12rpx;
}
.top-title-box{
	display: flex;
	align-items: center;
	padding: 24rpx 30rpx;
	background-color: #fff;
	justify-content: space-between;
	border-top: 12rpx solid #eeeeef;
	.title{
		font-size: 32rpx;
		font-weight: bold;
	}
	.handle-option{
		.btn{
			font-size: 32rpx;
			height: 60rpx;
			padding: 0 40rpx;
			background-color: rgb(42, 125, 201);
		}
	}
}
</style>
