<template>
	
	<view class="index-container" :style="{ height: `${windowHeight}px` }" @touchmove.stop.prevent="() => {}">
		<z-paging class="paging" ref="paging" use-virtual-list @query="queryList" bg-color="#F3F3F3"
			:loading-more-enabled="false">
			<template #top>
				<custom-nav-bar :left="true"  title="用户管理">
					<template v-slot:right>
						<view class="fixed">
							<view align="right" class="iconfont icon-jia icon" v-hasPermi="['system:user:add']" @click="onAdd"></view>
						</view>
					</template>
				</custom-nav-bar>
				<!--搜索框-->
				<view class="search">
					<u-search placeholder="请输入姓名" @search="onSearchValue" @custom="onSearchValue"
						@clear="onSearchValue(null)" shape="square"></u-search>
					<uni-forms ref="form" :model="form" labelWidth="0px" style="margin-top: 5px;">
						<uni-forms-item label="" name="">
							<cxk-dropdown-tree :dataOptions="treeList" labelField="label" valueField="id"
								:defaultCheckedKeys="defaultCheckedKeys" @change="handleTreeChange"
								style="width: 78%;float: left;margin-right: 2px;"></cxk-dropdown-tree>
							<u-checkbox-group style="width: 20%;float: right;" icon-placement="left"
								@change="handleChange">
								<u-checkbox active-color="#35842E" label="查全部" name="all"></u-checkbox>
							</u-checkbox-group>
						</uni-forms-item>
					</uni-forms>
				</view>
				<u-gap height="1" bgColor="#F3F3F3"></u-gap>
				<view class="list-size">
					<view v-show="list.length > 0">用户数量：({{ list.length }}人)</view>
				</view>
			</template>
			<template #cell="{ item }">
				<view class="index-container" style="background: white">
					<view class="user" @click="clickMore(item)">
						<!--头像-->
						<view>
							<u--image :showLoading="true" shape="square" radius="5px"
								:src="item.avatar ? item.avatar : ''" width="70px" height="70px"></u--image>
						</view>
						<!--信息-->
						<view class="user-info">
							<view class="info">
								<view style="font-size: 15px; color: #939393; font-weight: bold">姓名：</view>
								<u--text :text="item.userName"></u--text>
							</view>
							<view class="info">
								<view style="font-size: 15px; color: #939393; font-weight: bold">角色：</view>
								<u--text :text="item.role.roleName"></u--text>
							</view>
							<view class="info">
								<view style="font-size: 15px; color: #939393; font-weight: bold">电话：</view>
								<u--text :text="item.mobilePhone"></u--text>
							</view>
							<view class="info">
								<view style="font-size: 15px; color: #939393; font-weight: bold">公司：</view>
								<u--text :text="item.companyGroup.companyFullName" v-if="item.companyGroup && item.companyGroup.companyFullName"></u--text>
							</view>
						</view>
						<!--启用禁用标签-->
						<u-tag style="align-self: flex-start; font-size: 15px; margin-right: 10px"
							:text="item.status == 0 ? '启用' : '禁用'" :type="item.status == 0 ? 'success' : 'error'"
							size="mini" plain plainFill></u-tag>
						<u-icon style="margin-top: 20px" name="arrow-right"></u-icon>
					</view>
					<view class="bottom">
						<!--打电话-->
						<view>
							<u--text text="打电话" color="#009933" iconStyle="margin-right:5px"
								prefixIcon="../../../static/images/work/user/user-index-phone-icon.png"
								@click="onClickPhone(item.mobilePhone)" v-if="item.userId>2"></u--text>
						</view>
						<!--编辑-->
						<view>
							<u--text text="编辑" color="#009933" iconStyle="margin-right:5px"
								prefixIcon="../../../static/images/work/user/user-index-edit-icon.png"
								@click="onEditClick(item.userId)" v-hasPermi="['system:user:edit']"
								v-if="item.userId>2"></u--text>
						</view>
						<view>
							<u--text text="修改密码" color="#009933" iconStyle="margin-right:5px"
								prefixIcon="../../../static/images/work/user/editpassword.png"
								@click="onEditPassWordClick(item)" v-hasPermi="['system:user:edit']"
								v-if="item.userId>2"></u--text>
						</view>
						<!--删除-->
						<view>
							<u--text text="删除" color="#009933" iconStyle="margin-right:5px"
								prefixIcon="../../../static/images/work/user/user-index-del-icon.png"
								@click="onDeleteClick(item.userId)" v-hasPermi="['system:user:remove']"
								v-if="item.userId>2"></u--text>
						</view>
					</view>
				</view>
			</template>
		</z-paging>
		<u-modal title='修改密码' :show="showModal" showCancelButton buttonReverse height="180"
			@confirm="confirmUpdatePassWord" @cancel="() => showModal = false">
			<view class="slot-content">
				<u--form labelPosition="left" :model="userForm" ref="form">
					<u-form-item label="新密码" labelWidth="100px" required>
						<uni-easyinput v-model="userForm.passWord" style="width: 200px;" min></uni-easyinput>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
	</view>
</template>
<script>
	import store from "@/store"
	import {
		updateUserPwd
	} from "@/api/system/user"
	import {
		checkPermi
	} from "@/utils/permission"
	import plugin from "@/plugins"
	export default {
		data() {
			return {
				isFirst:true,
				user: store.state.user.user,
				defaultCheckedKeys: "",
				list: [],
				windowHeight: null,
				paging: null,
				all: false,
				form: null,
				treeList: [],
				companyGroupId: null,
				query: {
					companyGroupIds: "",
					userName: null
				},
				selectCompanyObj: {},
				showModal: false,
				selectItem: {},
				userForm: {
					passWord: null
				}
			}
		},
		created() {
			this.windowHeight = uni.getSystemInfoSync().windowHeight;
		},
		onLoad(){
			this.getCompanyTree();
		},
		onShow() {
			if (this.paging != null) {
				this.$refs.paging.reload()
			}
			this.queryList();
		},
		onNavigationBarButtonTap(e) {
			//如果点击了添加地块
			if (e.index == 0) {
				if (!this.query.companyId) {
					plugin.modal.msgError("请选择要添加用户的公司")
					return;
				}
				if (checkPermi(["system:user:add"])) {
					let companyObj = this.selectCompanyObj.originItem.node;
					uni.navigateTo({
						url: "/pages/work/user/create-user?companyObj=" + encodeURIComponent(JSON.stringify(
							companyObj))
					})
				} else {
					plugin.modal.msgError("抱歉暂无权限")
				}
			}
		},
		methods: {
			/** 查询公司下拉树结构 */
			getCompanyTree() {
				const obj = {
					status: 0,
					delFlag: "0",
					companyTypes: [1, 2, 3],
				}
				store
					.dispatch("companyTreeSelect", obj)
					.then(res => {
						this.treeList = res.data;
						if (this.treeList && this.treeList.length) {
							let cache_companyId = uni.getStorageSync("app_companyId")
							if(cache_companyId){
								this.defaultCheckedKeys = cache_companyId + "";
							}else{
								let companyList = this.treeList[0].children.filter(x => x.id != 100);
								if (companyList && companyList.length) {
									this.defaultCheckedKeys = companyList[0].id + "";
								}
							}
						}
					})
					.catch(error => {
						plugin.modal.msgError(error)
					})
					.finally(() => {
						plugin.modal.closeLoading()
					})
			},
			queryList() {
				if (!checkPermi(["system:user:list"])) {
					plugin.modal.msgError("抱歉暂无权限")
					return
				}
				if (!this.query.companyGroupIds || this.query.companyGroupIds == "" || this.query.companyGroupIds ==
					"101") {
					return;
				}
				plugin.modal.loading("获取用户列表...")
				if (this.query.userName == null || this.query.userName == "") {
					delete this.query["userName"]
				}
				store
					.dispatch("getUserList", this.query)
					.then(res => {
						this.list = res.data;
						this.$refs.paging.complete(this.list)
					})
					.catch(error => {
						plugin.modal.msgError(error)
					})
					.finally(() => {
						plugin.modal.closeLoading()
					})
			},
			onAdd(){
				if (!this.selectCompanyObj) {
					plugin.modal.msgError("请选择要添加地块的公司")
					return;
				}
				if (checkPermi(["system:user:add"])) {
					let companyObj = this.selectCompanyObj.originItem.node;
					uni.navigateTo({
						url: "/pages/work/user/create-user?companyObj=" + encodeURIComponent(JSON.stringify(
							companyObj))
					})
				} else {
					plugin.modal.msgError("抱歉暂无权限")
				}
			},
			onItemClick(item) {
				uni.navigateTo({
					url: "/pages/work/land/index-detail?item=" + encodeURIComponent(JSON.stringify(item))
				})
			},
			onSearchValue(e) {
				this.query.userName = e;
				this.queryList();
			},
			handleTreeChange(values, currentItem) {
				this.query.companyGroupIds = "";
				this.companyGroupId = values;
				if(!this.isFirst){
					uni.setStorageSync("app_companyId", this.companyGroupId)
				}
				this.selectCompanyObj = currentItem;
				if (this.all) {
					this.getCompanyGroupIds();
				}
				this.query.companyGroupIds += values;
				this.queryList();
			},
			getCompanyGroupIds() {
				if (this.selectCompanyObj && this.selectCompanyObj.childrenKeys) {
					this.selectCompanyObj.childrenKeys.forEach(property => {
						if (property) {
							this.query.companyGroupIds += property + ",";
						}
					});
				}
			},
			onEditClick(userId) {
				if (checkPermi(["system:user:edit"])) {
					uni.navigateTo({
						url: `/pages/work/user/create-user?edit=true&id=${userId}`
					})
				} else {
					plugin.modal.msgError("抱歉暂无权限")
				}
			},
			onClickPhone(phone) {
				plugin.modal.confirm("是否拨打电话?").then(res => {
					//#ifdef APP-PLUS
					plus.device.dial(phone, true)
					//#endif
					//#ifdef MP-WEIXIN
					uni.makePhoneCall({
						phoneNumber: phone,
						fail: res => {
							console.log(res)
						},
						success: res => {
							console.log("success" + res)
						}
					})
					//#endif
				})
			},
			onEditPassWordClick(item) {
				this.selectItem = item;
				this.showModal = true;
			},
			confirmUpdatePassWord() {
				if (!this.userForm.passWord || this.userForm.passWord == "") {
					plugin.modal.msgError("请输入的新密码！")
					return
				}
				if (this.userForm.passWord.length < 5 || this.userForm.passWord.length > 20) {
					plugin.modal.msgError("用户密码长度必须介于 5 和 20 之间！")
					return
				}
				let user = {};
				user.userId = selectItem.value.userId;
				user.password = userForm.value.passWord;
				updateUserPwd(user)
					.then(res => {
						this.showModal = false;
						this.userForm.passWord = null;
						plugin.modal.msgSuccess("修改成功！")
					})
			},
			onDeleteClick(userId) {
				let ids = [];
				ids.push(userId)
				plugin.modal.confirm("确定删除用户吗?").then(res => {
					store
						.dispatch("delUser", ids)
						.then(res => {
							plugin.modal.msgSuccess("删除成功")
							//重新刷新列表
							this.queryList()
						})
						.catch(error => {
							plugin.modal.msgError(error)
						})
						.finally(() => {
							plugin.modal.closeLoading()
						})
				})
			},
			clickMore(item) {
				plugin.tab.navigateTo(`/pages/work/user/ground?userInfo=${encodeURIComponent(JSON.stringify(item))}`)
			},
			handleChange(e) {
				this.all = e && e.length ? true : false;
				this.query.companyGroupIds = "";
				if (this.all) {
					this.getCompanyGroupIds();
				}
				if (this.companyGroupId) {
					this.query.companyGroupIds += this.companyGroupId;
				}
				this.queryList();
			},
			// 缓存数据
			setStorage(type, data) {
				uni.setStorageSync(type, {
					userId: this.user.userId,
					data: data,
				});
			}
		}
	}
</script>

<style lang="scss">
	.index-container {
		background-color: white;
		height: 100%;

		.search {
			background-color: white;
			padding: 10px;
		}

		.list-size {
			display: flex;
			padding: 5px 5px;
			background: white;
			justify-content: center;
		}

		.list {
			margin: 10px 10px;

			work-user-index-item {
				background-color: white;
			}
		}

		.index-container {
			margin: 10px 0px;
			padding: 20px 0px;
			background-color: #fff;
			border-radius: 10px;
			box-shadow: 1px 1px 2px 2px rgba(0, 0, 0, 0.05);

			.user {
				margin: 0px 20px;
				display: flex;
				align-items: center;

				.user-info {
					margin-left: 10px;
					width: 100%;

					.info {
						margin: 10px 0px;
						display: flex;
					}
				}
			}

			.bottom {
				margin: 10px 30px 0px 30px;
				display: flex;
				justify-content: space-between;
			}
		}
	}

	.left-pop {
		margin: 10px 5px;
		display: flex;
		align-items: center;
		font-size: 12px;
		padding: 0 4px;
	}

	.already-selected {
		position: relative;
	}

	.already-selected ::before {
		content: "";
		width: 6px;
		height: 60%;
		background-color: #ff7300;
		position: absolute;
		left: -8px;
		top: 50%;
		transform: translateY(-50%);
		border-radius: 4px;
	}
</style>