<template>
	<view class="column" style="height: calc(100% - 20rpx) ;">
		<view class="top " >
			<u-search placeholder="输入姓名/昵称搜索" bgColor='#F8F8FC'
			 v-model="searchContent" @custom="search()" @search="search()"></u-search>
			 <view class="justify-around  fs28">
			 	<view v-for="(item,index) in tabs" :key="index" :class="act==index?'active':'notact'" 
				@click="tabact(index)" class="flex-1 center ptb20">{{item}}</view>
				<view v-show="act==1" @click="selectact=!selectact" :class="selectact?'active':''"
				class="flex-1 center ptb20">批量</view>
			 </view>
		</view>
		<view v-if='list.length<1' class="center mt60" style="color: #666;">暂无用户</view>
		<scroll-view scroll-y class="indexes flex-1 pb60" :scroll-into-view="'indexes-'+ listCurID" :style="[{height:'calc(100vh - 300rpx)'}]"
		 :scroll-with-animation="true" :enable-back-to-top="true" >
			<view v-for="(item,index) in list" :key="index">
				<view :class="'indexItem-' + item.firstLetter" :id="'indexes-' + item.firstLetter" :data-index="item.firstLetter" @click.passive.stop>
					<view class="zm">{{item.firstLetter}}</view>
					<view class="user-list">
						<view class="user-item justify-start" v-for="(subitem,indexs) in item.list" 
						@click="navTo(subitem)" :key="indexs">
							<u-checkbox-group @change="changeitem(subitem.userId)" v-if="selectact">
								<u-checkbox :checked="subitem.checked" shape="circle" activeColor="#1773ff" :name="subitem.userId"
									labelColor="#1773ff" />
							</u-checkbox-group>
							<view class="bgf p20 radius16 flex-1">
								<view class="justify-between align-center">
									<view class="justify-start align-center">
										<view class="avatar" >
											<image class="img" :src="subitem.avatar?(baseUrl+subitem.avatar):avatar" mode="aspectFill"></image>
										</view> 
										<view class="content">
											<view class="name">
												{{subitem.nickName}}
											</view>
											<view class="dept justify-start align-center">
												<u-icon name="phone"></u-icon><view>{{subitem.phoneNumber}}</view> </view>
											<view class="dept">注册时间：{{subitem.registerTime}}</view>
										</view>
									</view>
									<view class="base-color fs24" v-if="subitem.status==0">未禁用</view>
									<view class="base-color-red fs24" v-else>禁用</view>
								</view>
								<view class="justify-between align-center mt10" @click.passive.stop>
									<view>
										<text class="base-color-9 ml10 fs24">部门：{{subitem.deptName?subitem.deptName:''}}</text>
										<view class="fs24 mt10 justify-start align-center" style="color: #115296;">
											<text class="base-color-9 ml10">岗位：{{subitem.postname?subitem.postname:''}}</text>
											<text class="base-color-9 ml20">角色：{{subitem.rolesname?subitem.rolesname:''}}</text>
										</view>
									</view>
									
									<!-- <view class="fs24 base-color-red mr10 bor-red
									base-bg-false plr20 radius40 ptb4">已禁用</view> -->
									<view class="fs24 base-color mr10 bor-blue h52 lh50
									base-bg-sure plr20 radius40 " style="width: fit-content;" v-if="subitem.isAudit==1">已审核</view>
									<view class="fs24 base-color-red mr10 bor-red h52 lh50
									base-bg-false plr20 radius40  " style="width: fit-content;z-index: 999;" @click="getidshen(subitem.userId)"
									 v-else-if="subitem.isAudit==0&&!selectact">待审核</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="indexBar" :style="[{height:'calc(100vh - 88rpx)'}]">
			<view class="indexBar-box" @touchstart="tStart" @touchend="tEnd" @touchmove.stop="tMove">
				<view class="indexBar-item" v-for="(item,index) in list" :key="index" :id="index" 
				@touchstart="getCur" @touchend="setCur"> {{item.firstLetter}}</view>
			</view>
		</view>
		<view class="justify-between base-bg-f foot-select " v-if="selectact">
			<view class="align-center justify-between " v-if="selectact">
				<u-checkbox-group @change="selectAll">
					<u-checkbox :checked="isSelectAll" shape="circle" activeColor="#1773ff" :name="true"
						label="全选" labelColor="#333" />
						<text class="fs24 base-color-9 ml12">已选{{ selectedUsers.length }}个</text>
						<!-- {{selectedCount}} -->
				</u-checkbox-group>
			</view>
			<view class="justify-center ">
				<button class="base-bg-f radius100 base-color-red h62 ml10 fs28 lh60"
					style="border: #ef4c50 solid 2rpx;" 
					@click="batchApprove">通过审核</button>
			</view>
		</view>
		<!--选择显示-->
		<view v-show="!hidden" class="indexToast">
			{{listCur}}
		</view>
		<u-popup :show="showcommpany" mode="center" round="16">
			<view class="bgf w600 h600 p40 radius16" style="max-height: 600rpx;">
				<view class="center bold fs32">设置销售员信息</view>
				<view class="justify-center align-center mtb30">
					<view class="mr40 fs32 base-color-6">部门：</view>
					<u-input
					   placeholder="选择部门"
					   border="surround"
					   v-model="valueb"
					   @focus="showbumen()"
					 ></u-input>
				</view>
				<view class="justify-center align-center mtb30">
					<view class="mr40 fs32 base-color-6">岗位：</view>
					 <view class="flex-1 u-border p16 radius8" @click="showgang=!showgang">
						 <view class="fs28" style="color: #000;">{{valuea}}</view>
						 <view class="fs28" style="color: #c0c4cc;" v-if="valueid.length==0">选择岗位</view>
					 </view>
				</view>
				<view class="justify-center align-center mtb30">
					<view class="mr40 fs32 base-color-6">角色：</view>
					 <view class="flex-1 u-border p16 radius8" @click="showjuese=!showjuese">
						 <view class="fs28" style="color: #000;">{{valuej}}</view>
						 <view class="fs28" style="color: #c0c4cc;" v-if="valuej.length==0">选择角色</view>
					 </view>
				</view>
				<view class="justify-around align-center mt50 ">
					<view class="quxiao" @click="showcommpany=!showcommpany">取消</view>
					<view class="queren" @click="confirmbchange">通过审核</view>
				</view>
				<tki-tree ref="tkitree" :range="columnb"  confirmColor="#4e8af7" :selectParent="true" @confirm="confirmb"/>
				<u-popup :show="showgang" @close="showgang=!showgang" :closeOnClickOverlay='true'>
					<view class="center bold fs36 pt40">请选择岗位</view>
					<view class="justify-start align-center warpbox mt40 p20">
						<view v-for="(item,index) in postlist" :key="item.postId" class="mlr10 mt10">
							<u-tag :text="item.postName" :plain="!item.checked" :name="index"
								@click="choosechangeTag"></u-tag>
						</view>
					</view>
					<view class="justify-around align-center mt50 ">
						<view class="quxiao" @click="showgang=!showgang">取消</view>
						<view class="queren" @click="postconfirm">确定</view>
					</view>
				</u-popup>
				<u-popup :show="showjuese" @close="showjuese=!showjuese" :closeOnClickOverlay='true'>
					<view class="center bold fs36 pt40">请选择角色</view>
					<view class="justify-start align-center warpbox mt40 p20">
						<view v-for="(item,index) in rolelist" :key="item.roleId" class="mlr10 mt10">
							<u-tag :text="item.roleName" :plain="!item.checked" :name="index"
								@click="choosechangerole"></u-tag>
						</view>
					</view>
					<view class="justify-around align-center mt50 ">
						<view class="quxiao" @click="showjuese=!showjuese">取消</view>
						<view class="queren" @click="roleconfirm">确定</view>
					</view>
				</u-popup>
			</view>
		</u-popup>
		<u-modal :show="showuser" title="提示" content='是否通过销售审核' :showCancelButton='true'
		@confirm='subsalesaudits' @cancel="showuser=!showuser"></u-modal>
		<u-loading-page :loading="viewload" iconSize="32" loadingColor="#3c9cff" fontSize="20"
		:loading-text="loadingtext" ></u-loading-page>
	</view>
</template>

<script>
	import {getAllUsers,querydepartment,querypost,modifysaleNews,queryrole} from '@/api/user.js';
	import {subsalesaudit} from '@/api/courseManage.js';
	import tkiTree from "@/components/tki-tree/tki-tree.vue"
	export default {
		components: {tkiTree},
		data() {
			return {
				viewload:true,
				loadingtext:"数据加载中...",
				baseUrl:uni.getStorageSync('requestPath'),
				avatar:this.$store.state.imgpath+"/app/images/default.png",
				CustomBar: 0,
				hidden: true,
				listCurID: '',
				list: [],
				listCur: '',
				searchContent:"",
				tabs:['已审核','未审核'],
				act:0,
				selectact:false,
				isSelectAll:false,
				selectedUsers:[],
				isAudits:1,
				ids:'',
				showcommpany:false,
				columnb: [
				    ['11', '22', '33']
				],
				postlist:{},
				showgang:false,
				showjuese:false,
				valuea:'',
				valueb:'',
				actpost:[],
				valueid:'',
				valueidbu:'',
				xuanid:[],
				valuej:'',
				rolelist:[],
				roleid:[],
				seluserids:[],
				showuser:false
			}
		},
		onLoad() {
			this.getUser();
			this.getdepartment()
			this.getpostlist()
			this.getrolelist()
		},
		onReady() {
			let that = this;
			uni.createSelectorQuery().select('.indexBar-box').boundingClientRect(function(res) {
				that.boxTop = res.top
			}).exec();
			uni.createSelectorQuery().select('.indexes').boundingClientRect(function(res) {
				that.barTop = res.top
			}).exec()
		},
		methods: {
			roleconfirm(){
				this.roleid = this.rolelist.filter(item => item.checked).map(v => v.roleId).join(",")
				this.valuej = this.rolelist.filter(item => item.checked).map(v => v.roleName).join('，')
				this.showjuese=!this.showjuese
			},
			choosechangerole(i){
				this.rolelist[i].checked = !this.rolelist[i].checked
			},
			showbumen(){
				this.$refs.tkitree._show();
			},
			confirmbchange(){
				console.log(this.valueb.length,this.xuanid)
				if(this.valueb.length==0){
					uni.showToast({
						icon: 'none',
						title: '请选择部门'
					})
					return
				}
				if(this.xuanid.length==0){
					uni.showToast({
						icon: 'none',
						title: '请选择部门'
					})
					return
				}
				if(this.valuej.length==0){
					uni.showToast({
						icon: 'none',
						title: '请选择角色'
					})
					return
				}
				const data={
					companyUserIds:this.ids,
					deptId:this.valueidbu,
					postIds:this.valueid,
					roleIds:this.roleid
				}
				modifysaleNews(data).then(res=>{
					console.log('设置信息',res)
					if(res.code==200){
						// uni.showToast({
						// 	icon: 'none',
						// 	title: '成功'
						// })
						this.xuanid=[]
						setTimeout(()=>{
							this.subsalesaudits()
						},100)
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
					}
				})
			},
			getallList(){
				this.valueidbu=[]
				this.valueid=[]
				this.valueb=''
				this.valuea=''
				this.ids=''
			},
			postconfirm(){
				this.xuanid=this.postlist.filter(item => item.checked).map(v => v.postId)
				this.valueid = this.postlist.filter(item => item.checked).map(v => v.postId).join(",")
				this.valuea = this.postlist.filter(item => item.checked).map(v => v.postName).join('，')
				this.showgang=!this.showgang
			},
			choosechangeTag(i) {
				console.log(this.postlist[i].checked )
				this.postlist[i].checked = !this.postlist[i].checked
			},
			getdepartment(){
				querydepartment().then(res=>{
					if(res.code==200){
						this.columnb=res.data
						// console.log('部门',res)
					}
				})
			},
			getpostlist(){
				querypost().then(res=>{
					if(res.code==200){
						this.postlist = res.data.map(item => {
							return {
								...item,
								checked: false,
							}
						})
						console.log('岗位',res)
					}
				})
			},
			getrolelist(){
				queryrole().then(res=>{
					if(res.code==200){
						this.rolelist = res.data.map(item => {
							return {
								...item,
								checked: false,
							}
						})
						// console.log('岗位',res)
					}
				})
			},
			confirma(e){
				this.showgang = !this.showgang
				this.valuea=e.value[0]
				console.log(e)
			},
			confirmb(e){
				this.valueb=e[0].label
				this.valueidbu=e[0].id
				console.log(e[0])
			},
			getidshen(id){
				console.log(id)
				this.getallList()
				this.ids=id
				this.seluserids[0]=id
				this.showuser=!this.showuser
				// this.showcommpany=!this.showcommpany
			},
			batchApprove(){
				 if (this.selectedUsers.length === 0) {
					  uni.showToast({
						title: '请先选择用户',
						icon: 'none',
					  });
					  return;
				}
				
				this.ids=this.selectedUsers.join(',')
				this.seluserids=this.selectedUsers
				// this.showcommpany=!this.showcommpany
				this.showuser=!this.showuser
				// this.subsalesaudits()
				// this.confirmbchange()
			},
			subsalesaudits(){
				const data={
					 userIds:this.seluserids
				}
				subsalesaudit(this.seluserids).then(res=>{
					console.log("subsalesaudits=====",res)
					if(res.code==200){
						uni.showToast({
							title: "用户通过审核，成为销售！",
							icon: 'none',
						});
						
						this.valueidbu=[]
						this.valueid=[]
						this.valueb=[]
						this.valuea=''
						this.valuej=''
						this.roleid=[]
						this.ids=''
						this.showuser=!this.showuser
						this.seluserids=[]
						// this.showcommpany=!this.showcommpany
						this.getUser()
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
					}
				})
			},
			// 全选
			selectAll() {
				this.isSelectAll = !this.isSelectAll;
				this.selectedUsers = []; // 清空已选列表
				 // 遍历所有用户项，更新 checked 状态
				    this.list = this.list.map(group => {
				      group.list = group.list.map(user => {
				        if (this.isSelectAll) {
				          this.selectedUsers.push(user.userId); // 添加用户ID到选中列表
				        }
				        return {
				          ...user,
				          checked: this.isSelectAll,
				        };
				      });
				      return group;
				    });
				// 如果取消全选，清空 selectedUsers
					if (!this.isSelectAll) {
					  this.selectedUsers = [];
					}
			},
			// 单选 /反选 
			changeitem(userId) {
				const index = this.selectedUsers.indexOf(userId);
				if (index === -1) {
				  this.selectedUsers.push(userId); // 选中
				} else {
				  this.selectedUsers.splice(index, 1); // 取消选中
				}
				// 更新全选状态
				this.isSelectAll = this.selectedUsers.length === this.getTotalUsers();
			},
			// 计算总用户数
			  getTotalUsers() {
			    return this.list.reduce((total, group) => total + group.list.length, 0);
			  },
			tabact(index){
				this.list=[]
				this.act=index
				if(this.act==0){
					this.selectact=false
					this.isAudits=1
					this.getUser();
				}else if(this.act==1){
					this.isAudits=0
					this.getUser();
				}
			},
			getUser(){
				
				var data = {
					searchKey:this.searchContent,
					isAudit:this.isAudits
					};
				var that=this;
				getAllUsers(data).then(
					res => {
						if(res.code==200){
							this.viewload=false
							 that.list=res.users;
							this.list=this.list.map(group=>{
								group.list = group.list.map(user => {
								   return {
									 ...user,
									 checked: this.isSelectAll,
									 postname:user.post.map(item=>item.postName).join(","),
									 rolesname:user.roles.map(item=>item.roleName).join(",")
								   };
								})
								return group;
							})
						}
					},
					rej => {}
				);
			},
			//获取文字信息
			getCur(e) {
				this.hidden = false;
				this.listCur = this.list[e.target.id].firstLetter;
			},
			setCur(e) {
				this.hidden = true;
				this.listCur = this.listCur
			},
			//滑动选择Item
			tMove(e) {
				let y = e.touches[0].clientY,
					offsettop = this.boxTop,
					that = this;
				//判断选择区域,只有在选择区才会生效
				if (y > offsettop) {
					let num = parseInt((y - offsettop) / 20);
					console.log(num);
					if(num<that.list.length){
						this.listCur = that.list[num].firstLetter
					}
				};
			},
			
			//触发全部开始选择
			tStart() {
				this.hidden = false
			},
			
			//触发结束选择
			tEnd() {
				this.hidden = true;
				this.listCurID = this.listCur
			},
			indexSelect(e) {
				let that = this;
				let barHeight = this.barHeight;
				let list = this.list;
				let scrollY = Math.ceil(list.length * e.detail.y / barHeight);
				for (let i = 0; i < list.length; i++) {
					if (scrollY < i + 1) {
						that.listCur = list[i].firstLetter;
						that.movableY = i * 20
						return false
					}
				}
			},
			navTo(subitem){
				uni.navigateTo({
					url: './userInfo?userId='+subitem.userId
				})
			},
			search(){
				this.getUser()
			}
			
		}
	}
</script>
<style  lang="scss">
	.quxiao{
		width: 40%;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		background-color: #F8F8FC;
		border: 2rpx solid #cacaca;
		color: #999;
		border-radius: 50rpx;
	}
	.queren{
		width: 40%;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		background-color: #1773ff;
		color: #fff;
		border-radius: 50rpx;
	}
	::v-deep {
		.foot-select {
			 position: fixed;
			  bottom: 0;
			  width: 100%;
			  padding: 20rpx;
			  background: #fff;
			  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
			  z-index: 1000;
		}
	}
	 .active{
		 color: #1773ff;
		 font-weight: bold;
	 }
	 .notact{
		 color: #888;
	 }
	page {
		background-color: #F8F8FC; 
	}
	.top{
		/* height: 88rpx; */
		background-color: #fff;
		padding: 0rpx 15rpx;
		padding-top: 20rpx;
	}
	.indexes {
		position: relative;
	}

	.indexBar {
		position: fixed;
		right: 0px;
		bottom: 0px;
		padding: 20upx 20upx 20upx 60upx;
		display: flex;
		align-items: center;
	}

	.indexBar .indexBar-box {
		width: 40upx;
		height: auto;
		background: #fff;
		display: flex;
		flex-direction: column;
		box-shadow: 0 0 20upx rgba(0, 0, 0, 0.1);
		border-radius: 10upx;
	}

	.indexBar-item {
		flex: 1;
		width: 40upx;
		height: 40upx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24upx;
		color: #888;
	}

	movable-view.indexBar-item {
		width: 40upx;
		height: 40upx;
		z-index: 9;
		position: relative;
	}

	movable-view.indexBar-item::before {
		content: "";
		display: block;
		position: absolute;
		left: 0;
		top: 10upx;
		height: 20upx;
		width: 4upx;
		background-color: #f37b1d;
	}

	.indexToast {
		position: fixed;
		top: 0;
		right: 80upx;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		width: 100upx;
		height: 100upx;
		border-radius: 10upx;
		margin: auto;
		color: #fff;
		line-height: 100upx;
		text-align: center;
		font-size: 48upx;
	}
	.zm{
		height:30rpx;
		padding: 0rpx 20rpx;
		font-size: 24rpx;
		color: #888;
		background: #F8F8FC;
	}
	.user-list{
		 margin: 20rpx;
		 border-radius: 20rpx;
	}
	.user-item{
		width: 100%;
		margin: 12rpx 0;
	}
	.user-item .avatar{
		width: 100upx;
		height: 100upx;
	}
	.user-item .avatar .img{
		border-radius: 50%;
		width: 100%;
		height: 100%;
	}
	.user-item .content{
		margin-left: 15rpx;
	}
	.user-item .content .name{
		font-size: 26rpx;
		color: #111;
	}
	.user-item .content .dept{
		font-size: 24rpx;
		color: #888;
		margin-top: 15rpx;
		
	}
</style>
