<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_users.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 list" 
				 :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">用户名：{{ item.username }}</view>
					</view>
					<view class="row_box">
						<view class="text">昵称：{{ item.name }}</view>
					</view>
					<view class="row_box">
						<view class="text">部门：{{ item.department?item.department:'-' }}</view>
					</view>
					<view class="row_box">
						<view class="text">是否启用：{{item.is_enable==1?'是':'否'}}</view>
					</view>
					<view class="tag_status">
						<u-tag text="在职" v-if="item.status==1" type="success" size="mini"/>
						<u-tag text="离职" v-if="item.status==2" type="error" size="mini"/>
						<u-tag text="休假" v-if="item.status==3" type="info" size="mini"/>
					</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="setInfo.id">编辑账号</view>
					<view class="title" v-else>新增账号</view>
				</view>
				<scroll-view class="scroll-y" scroll-y="true">
					<view class="form_edit" style="padding-left: 50rpx;">
						<u-form>
							<u-form-item label="用户ID" label-width="140" v-if="setInfo.id">
								<view class="input_box bg_colorf8">
									<u-input v-model="setInfo.id" :disabled="true" />
								</view>
							</u-form-item>
							<u-form-item label="用户名" label-width="140" :required='true'>
								<view class="input_box">
									<u-input v-model="setInfo.username" />
								</view>
							</u-form-item>
							<u-form-item label="密码" v-if="!setInfo.id" label-width="140" :required='true'>
								<view class="input_box">
									<u-input v-model="setInfo.password" type="password"/>
								</view>
							</u-form-item>
							<u-form-item label="昵称" label-width="140" :required='true'>
								<view class="input_box">
									<u-input v-model="setInfo.name" />
								</view>
							</u-form-item>
							<u-form-item label="角色选择" label-width="140" :required='true'>
								<view class="input_box">
									<view class="u-select-list" @click="roleSelectFn()">
										<view class="value u-line-2" 
										v-if="setInfo.role_id">{{setInfo.role_name}}</view>
										<view class="placeholder" v-else>请选择</view>
										<view class="right">
											<u-icon name="arrow-right" color="#999" size="28"></u-icon>
										</view>
									</view>
								</view>
							</u-form-item>
							<u-form-item label="状态" label-width="140" :required='true'>
								<u-radio-group v-model="setInfo.status" 
								@change="radioGroupChange">
									<u-radio 
										v-for="(item, index) in statusList" :key="index" 
										:name="item.value">
										{{item.name}}
									</u-radio>
								</u-radio-group>
							</u-form-item>
							<u-form-item label="部门" label-width="140">
								<view class="input_box">
									<u-input v-model="setInfo.department" />
								</view>
							</u-form-item>
							<u-form-item label="手机号" label-width="140">
								<view class="input_box">
									<u-input v-model="setInfo.phone" type="number"/>
								</view>
							</u-form-item>
							<u-form-item label="基地数据" label-width="140">
								<view class="input_box">
									<view class="u-select-list select_multiple" @click="basePopupShow()">
										<view class="value u-line-2" 
										v-if="seletedShow">{{seletedShow}}</view>
										<view class="placeholder" v-else>请选择</view>
										<view class="right">
											<u-icon name="arrow-right" color="#999" size="28"></u-icon>
										</view>
									</view>
								</view>
							</u-form-item>
						</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 u-border-bottom">
					<view class="handle-btns">
						<view v-auth="['endpoint.admin_users.destroy']" class="btn_del" @click="deleteInfoId(formInfo.id)">删除</view>
						<view v-auth="['endpoint.admin_users.edit_password']" class="btn_edit" @click="editPwdPopup(formInfo.id)">修改密码</view>
						<view  v-if="formInfo.banned_at" v-auth="['super']" class="btn_edit" @click="unlock(formInfo.id)">解封</view>
						<view v-auth="['endpoint.admin_users.edit']" class="btn_edit" @click="editInfoId(formInfo.id)">编辑</view>
					</view>
				</view>
				<view class="section_c">
					
					<view class="plist u-border-bottom">
						<view class="label_t">用户名</view>
						<view class="flex-1">{{formInfo.username}}</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">昵称</view>
						<view class="flex-1">{{formInfo.name}}</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">电话</view>
						<view class="flex-1">{{formInfo.phone}}</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">部门</view>
						<view class="flex-1">{{formInfo.department?formInfo.department:'-' }}</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">封禁时间</view>
						<view class="flex-1">{{formInfo.banned_at?$u.date(formInfo.banned_at, 'yyyy-MM-dd hh:mm'):'-' }}</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">是否启用</view>
						<view class="flex-1 flex-row align-items-c">
							<view class="text" style="margin-right: 20rpx;">
								{{formInfo.is_enable==1?'是':'否'}}
							</view>
							<u-switch v-model="checked" size="34"
							@change="enableChange"></u-switch>
						</view>
					</view>
					<view class="plist u-border-bottom">
						<view class="label_t">状态</view>
						<view class="flex-1" v-if="formInfo.status==1">
							<u-tag text="在职" type="success" size="mini"/>
						</view>
						<view class="flex-1" v-if="formInfo.status==2">
							<u-tag text="离职" type="error" size="mini"/>
						</view>
						<view class="flex-1" v-if="formInfo.status==3">
							<u-tag text="休假" type="info" size="mini"/>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 基地数据 -->
		<u-popup v-model="popupShow2" border-radius="28" width="90%" height="60%"
		 mode="center" :closeable="true" :mask-close-able="false" z-index="920">
			<view class="popup-select-section">
				<view class="top_section">
					<view class="title">基地数据</view>
				</view>
				<scroll-view class="scrollY" scroll-y="true">
					<view class="info_cont">
						<view class="select-box">
							<view class="select-item" v-for="(item,index) in basicList" :key="index" 
							@click="selectedItem(item,index)" :class="[item.active?'active':'']">
								<view class="label">{{item.name}}</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="buttom_section">
					<u-button class="btn" type="default" @click="popupShow2 = false">取消</u-button>
					<u-button class="btn" @click="baseSelectedConfirm()" type="primary">确定</u-button>
				</view>
			</view>
		</u-popup>
		<!-- 修改密码 -->
		<u-popup v-model="editPwdShow" border-radius="28" width="92%" height="550rpx"
		 mode="center" :closeable="true" :mask-close-able="false" z-index="910">
			<view class="popup-form-ubox">
				<view class="top_box">
					<view class="title">修改密码</view>
				</view>
				<scroll-view class="scroll-y" scroll-y="true">
					<view class="form_edit" style="padding-left: 50rpx;">
						<u-form :model="form" ref="uFormPwd">
							<u-form-item label="密码" prop="password" label-width="160" :required='true'>
								<view class="input_box">
									<u-input v-model="form.password" type="password"/>
								</view>
							</u-form-item>
							<u-form-item label="确定密码" prop="password2" label-width="160" :required='true'>
								<view class="input_box">
									<u-input v-model="form.password2" type="password"/>
								</view>
							</u-form-item>
						</u-form>
					</view>
				</scroll-view>
				<view class="buttom_section">
					<u-button class="btn" type="default" @click="editPwdShow = false">取消</u-button>
					<u-button class="btn" @click="editPassword()" type="primary">确定</u-button>
				</view>
			</view>
		</u-popup>
		<u-select v-model="select2" :list="rolelist" :default-value="defaultRoleValue" mode="single-column"
		 @confirm="uselectConfirm"></u-select>
		 <u-loadmore :status="loading" margin-top="40"/>
	</view>
</template>

<script>
	import {showLoading,hideLoading} from '@/com/utils.js'
	import checkPermission from '@/utils/permission.js'
	import md5 from 'js-md5'
	export default {
		data() {
			return {
				per_page:10,
				page:1,
				list:[],
				loading:'loadmore',
				popupShow:false,
				cindex:-1,//操作的索引
				editShow:false,
				formInfo:{},
				basicList:[],//基地数据
				popupShow2:false,//选择基地数据
				seletedBaseList:[],
				statusList:[
					{
						name: '在职',
						value:1
					},
					{
						name: '离职',
						value:2
					},
					{
						name: '休假',
						value:3
					}
				],
				setInfo:{
					id:'',
					username:'',
					name:'',
					password:'',
					role_id:'',
					role_name:'',
					status:'',
					department:'',
					phone:'',
					base_ids:[]
				},
				rolelist:[],
				select2:false,
				checked:false,
				editPwdShow:false,
				form: {
					id:'',
					password:'',
					password2:'',
				},
				rules: {
					password: [
						{
							required: true,
							message: '请输入密码',
							trigger: ['blur', 'change']
						}
					],
					password2: [
						{
							required: true,
							message: '请输入密码',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return value==this.form.password;
							},
							message: '两次密码不一致',
							trigger: ['blur'],
						}
					]
				}
			};
		},
		computed:{
			options() {
      return [
        {
          text: '编辑',
          opt: 'edit',
          permission: ['endpoint.device.edit'],
          style: {
            backgroundColor: '#007aff',
          },
        },
        {
          text: '删除',
          opt: 'delete',
          permission: ['endpoint.device.destroy'],
          style: {
            backgroundColor: '#dd524d',
          },
        },
      ].filter((e) => checkPermission(e.permission))
    },
			seletedShow(){
				let arrName = [];
				for(let item of this.seletedBaseList){
					arrName.push(item.name);
				}
				let showName = arrName.length?arrName.join(','):'';
				return showName;
			},
			defaultRoleValue(){
				let def_val = [0];
				let roleId = this.setInfo.role_id;
				if(roleId){
					for(let i=0;i< this.rolelist.length;i++){
						if(this.rolelist[i].id==roleId){
							def_val = [i];
							break;
						}
					}
				}
				
				return def_val;
			}
		},
		onLoad() {
			this.queryDataList();
			this.getAgriculturalBasic();
			this.getRoles();
		},
		methods: {
			enableChange(val){
				this.formInfo.is_enable = val?1:0;
				let id = this.formInfo.id;
				if(id){
					this.$http.put(`/api/admin-users/${id}/enable`).then(({data})=>{
					})
				}
				
			},
			addBtn(){
				this.setInfoKeys('add');
				this.editShow = true;
			},
			roleSelectFn(){
				this.select2 = true;
			},
			uselectConfirm(e){
				console.log(e)
				this.setInfo.role_id = e[0].value;
				this.setInfo.role_name = e[0].label;
			},
			radioGroupChange(e){
				console.log(e)
			},
			basePopupShow(){
				let seletIds = this.setInfo.base_ids;
				this.basicList.forEach((item)=>{item.active = false;})
				for(let base of this.basicList){
					for(let id of seletIds){
						if(base.id==id){
							base.active = true;
						}
					}
				}
				this.popupShow2 = true;
			},
			showInfo(index){
				this.cindex = index;
				let _id = this.list[index].id;
				this.queryInfo(_id);
				this.formInfo = this.list[index];
				this.checked = this.formInfo.is_enable==1?true:false;
				this.popupShow = true;
				
			},
			open(index){
				this.list[index].show = true;
			},
			click(index, index1) {
				console.log(index,index1,this.list[index])
				if(index1 == 1) {
					this.cindex = index;
					let _id = this.list[index].id;
					this.deleteInfoId(_id);
				} else {//编辑
					let _id = this.list[index].id;
					this.queryInfo(_id);
					this.formInfo = this.list[index];
					this.setInfoKeys();
					this.editShow = true;
					this.list[index].show = false;
					
				}
				
			},
			queryDataList(refresh){
				if(refresh){
					this.loading = 'loadmore';
					this.page = 1;
					this.list = [];
				}
				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-users',{params:params}).then(({data})=>{
					console.log(data)
					// if(refresh){
					// 	this.list = [];
					// }
					this.loading = 'loadmore';
					if(data.code==200){
						let _list = data.data|| [];
						for(let item of _list){
							item.show = false;
						}
						this.list = this.list.concat(_list);
						console.log(this.list);
						if(this.list.length>= data.meta.total){
							this.loading ='nomore';
						}
					}
				}).catch(()=>{
					this.loading = 'loadmore';
				})
			},
			//修改
			editInfoBtn(){
				let {id,username,name,role_id,status,department,phone,base_ids,password} = this.setInfo;
				let params = {
					name:name,
					username:username,
					role_id:role_id,
					status:status,
					base_ids:base_ids,
					phone:phone,
					department:department,
				}
				if (username=='') {
					uni.showToast({ title: '请填写用户名', icon: 'none' });
					return;
				}
				if (name=='') {
					uni.showToast({ title: '请填写昵称', icon: 'none' });
					return;
				}
				if (role_id=='') {
					uni.showToast({ title: '请选择角色', icon: 'none' });
					return;
				}
				if (status=='') {
					uni.showToast({ title: '请选择状态', icon: 'none' });
					return;
				}
				showLoading('请稍等...');
				if(id){params['id'] = id;}
				if(params['id']){
					this.$http.put(`/api/admin-users/${id}`,params).then(({data})=>{
						hideLoading();
						if(data.code==200){
							this.editShow = false;
							this.queryDataList(true);
							
						}
						uni.showToast({ title: data.message, icon: 'none' });
					}).catch(()=>{
						hideLoading();
					})
				}else{
					if (!password) {
						uni.showToast({ title: '请填写密码', icon: 'none' });
						return;
					}
					params['password'] = md5(password);
					this.$http.post(`/api/admin-users`,params).then(({data})=>{
						hideLoading();
						if(data.code==200){
							this.editShow = false;
							this.queryDataList(true);
							
						}
						uni.showToast({ title: data.message, icon: 'none' });
					}).catch(()=>{
						hideLoading();
					})
				}
				
			},
			editInfoId(id){
				// this.queryInfo(id);

				this.setInfoKeys();
				this.editShow = true;
				this.popupShow = false;
			},
			setInfoKeys(type){
				let info = {
					id:'',
					username:'',
					name:'',
					password:'',
					role_id:'',
					role_name:'',
					status:'',
					department:'',
					phone:'',
					base_ids:[],
					base_names:[],
				}
				if(type=='add'){
					this.seletedBaseList = [];
					this.setInfo = info;
				}else{
					let {id,name,username,status,department,phone,bases,roles} = this.formInfo;
					info['id'] = id;
					info['username'] = username;
					info['name'] = name;
					info['status'] = status;
					info['department'] = department;
					info['phone'] = phone;
					if(roles&&roles[0]&&roles[0].id){
						info['role_id'] = roles[0].id;
						info['role_name'] = roles[0].name;
					}
					if(bases&&bases.length){
						let arr = [];
						for(let b of bases){
							arr.push(b.id);
						}
						info['base_ids'] = arr;
						this.seletedBaseList = bases;
					}else{
						info['base_ids'] = [];
						this.seletedBaseList = [];
					}
					this.setInfo = info;
				}
			},
			//删除deleteInfoId
			deleteInfoId(id){
				uni.showModal({
					title: '提示',
					content: '是否确定删除？',
					success:  (res)=> {
						if (res.confirm) {
							console.log('用户点击确定');
							showLoading('请稍等...');
							this.$http.delete(`/api/admin-users/${id}`).then(({data})=>{
								hideLoading();
								if(data.code==200){
									this.formInfo = {};//重置删除
									this.popupShow = false;
									this.list.splice(this.cindex,1);
									uni.showToast({ title: data.message, icon: 'none' });
								}
							}).catch(()=>{
								hideLoading();
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				
			},
			editPwdPopup(id){
				this.form.id = id;
				this.editPwdShow = true;
				setTimeout(()=>{
					this.$refs.uFormPwd.setRules(this.rules);
				},600)
				
			},
			unlock(id){
				uni.showModal({
					title: '提示',
					content: '是否确定解封？',
					success:  (res)=> {
						if (res.confirm) {
							console.log('用户点击确定');
							showLoading('请稍等...');
							this.$http.put(`/api/admin-users/${id}/unban`).then(({data})=>{
								hideLoading();
								if(data.code==200){
									this.popupShow = false;
									uni.showToast({ title: data.message, icon: 'none' });
								}
							}).catch(()=>{
								hideLoading();
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				
			},
			//修改密码
			editPassword(){
				this.$refs.uFormPwd.validate(valid => {
					if (valid) {
						console.log('验证通过');
						let params = {
							password:md5(this.form.password),
							password_confirmation:md5(this.form.password2)
						}
						this.$http.put(`/api/admin-users/${this.form.id}/edit-password`,params).then(({data})=>{
							if(data.code==200){
								this.editPwdShow = false;
								uni.showToast({ title: data.message, icon: 'none' });
							}
						}).catch(()=>{
							
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			queryInfo(id){
				this.$http.get(`/api/admin-users/${id}`).then(({data})=>{
					console.log(data,'queryInfo===')
					if(data.code==200){
						this.formInfo = data.data;
						this.setInfoKeys();
					}
				}).catch((err)=>{
					
				})
			},
			//选择
			selectedItem(item,index){
				this.basicList[index].active = !this.basicList[index].active;
			},
			//基础数据
			baseSelectedConfirm(){
				let seleteds = [];
				let ids = [];
				console.log(this.basicList)
				for(let item of this.basicList){
					if(item.active){
						seleteds.push(item);
						ids.push(item.id);
					}
				}
				this.seletedBaseList = seleteds;
				this.setInfo.base_ids = ids;
				this.popupShow2 = false;
			},
			//基地数据
			getAgriculturalBasic(){
				let params = { type: 1, per_page: 9999, page: 1 }
				this.$http.get(`/api/agricultural-basic`,{params:params}).then(({data})=>{
					if(data.code==200){
						let list = data.data;
						for(let item of list){
							item.active = false;
						}
						this.basicList = JSON.parse(JSON.stringify(list));
					}
				}).catch(()=>{
					
				})
			},
			getRoles(){
				let params = { type: 1, per_page: 999, page: 1 }
				this.$http.get(`/api/admin-roles`,{params:params}).then(({data})=>{
					if(data.code==200){
						let list = data.data;
						for(let item of list){
							item.label = item.name;
							item.value = item.id
						}
						this.rolelist = JSON.parse(JSON.stringify(list));
					}
				}).catch(()=>{
					
				})
			},
		},
		//触底加载
		onReachBottom() {
			if(this.loading=='loadmore'){
				this.queryDataList();
			}
		},
	}
</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>
