<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">
						<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>
				<view class="tip-intel">
					<view v-show="list.length > 0">用户数量：({{ list.length }}人)</view>
				</view>
			</template>
			<template #cell="{ item }">
				<view class="card">
					<view class="cards-content" @click="clickMore(item)">
						<view class="txt-list" >
							<view class="left">
								<view>
									<u--image :showLoading="true" shape="square" radius="5px" width="70px" height="70px"
										:src="item.avatar" v-if="item.avatar" />
									<u--image :showLoading="true" shape="square" radius="5px" width="70px" height="70px"
										src="../../../static/images/login/userAvatar.png" v-else />
								</view>

							</view>
							<view class="left" style="flex: 1 1 0%;padding-left: 10px;">
								<view>
									<view>姓名：</view>
									<u--text :text="item.userName"></u--text>
								</view>
								<view>
									<view>角色：</view>
									<u--text :text="item.role.roleName"></u--text>
								</view>
								<view>
									<view>电话：</view>
									<u--text :text="item.mobilePhone"></u--text>
								</view>
								<view>
									<view>公司：</view>
									<u--text :text="item.companyGroup.companyFullName"
										v-if="item.companyGroup && item.companyGroup.companyFullName"></u--text>
								</view>
							</view>
							<view class="right">
								<view class="iconfont icon-you">
								</view>
							</view>
							<!--启用禁用标签-->
							<view style="position: absolute;right: 20px;">
								<uni-tag :text="item.status == 0 ? '启用' : '禁用'" :circle="true"
									:type="item.status == 0 ? 'success' : 'error'" v-if="item.status == 0"></uni-tag>
							</view>

						</view>
					</view>
					<view class="card-view">
						<!--打电话-->
						<!-- <view @click="onClickPhone(item.mobilePhone)" v-if="item.userId>2">
							<view class="iconfont icon-hover"></view>打电话
						</view> -->
						<!--编辑-->
						<view @click="onEditClick(item.userId)" v-hasPermi="['system:user:edit']" v-if="item.userId>2">
							<view class="iconfont icon-a-bianji6"></view>编辑
						</view>
						<!--修改密码-->
						<view @click="onEditPassWordClick(item)" v-hasPermi="['system:user:edit']" v-if="item.userId>2">
							<view class="iconfont icon-mima"></view>修改密码
						</view>
						<!--删除-->
						<view @click="onDeleteClick(item.userId)" v-hasPermi="['system:user:remove']"
							v-if="item.userId>2">
							<view class="iconfont icon-shanchu1"></view>删除
						</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 {
		userResetPwd
	} from "@/api/system/user"
	import {
		checkPermi
	} from "@/utils/permission"
	import plugin from "@/plugins"
	// 引入插件包
	import {
		requestPermissions
	} from "@/js_sdk/yu-app-permission/yu-app-permission.js"
	// 前往设置页面  兼容安卓以及IOS
	import {
		goSetting
	} from "@/js_sdk/yu-app-permission/yu-app-permission.js"

	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() {
			let companyId = null;
			if (getApp().ijs.land) {
				companyId = getApp().ijs.land.companyGroup.companyId
			}
			this.getCompanyTree(companyId);
		},
		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(companyId) {
				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) {
							if (companyId) {
								this.defaultCheckedKeys = 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;
				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("抱歉暂无权限")
				}
			},
			async onClickPhone(phone) {
				// //安卓手机手动设置一个showActionSheet
				// uni.showActionSheet({
				// 	itemList: ['phone', '呼叫'],
				// 	success: function(res) {
				// 		if (res.tapIndex == 1) {
				// 			uni.makePhoneCall({
				// 				phoneNumber: phone,
				// 			})
				// 		}
				// 	}
				// })

				plugin.modal.confirm("是否拨打电话?").then(res => {

					// #ifdef APP-PLUS
					//手机端的这样写
					plus.device.dial("+86" + phone, true);
					//#endif
					// uni.makePhoneCall({
					// 	phoneNumber: phone
					// });

					// //#ifdef APP-PLUS
					// plus.device.dial(phone, true)
					// //#endif
					// //#ifdef MP-WEIXIN
					// uni.makePhoneCall({
					// 	phoneNumber: phone,
					// 	fail: res => {},
					// 	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 = this.selectItem.userId;
				user.password = this.userForm.passWord;
				userResetPwd(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" scoped>
	.txt-list .left uni-text:first-child {
		width: auto;
	}

	.txt-list .left .u-text {
		margin-left: 10px !important;
	}

	// 表单
	::v-deep.uni-forms-item__label {
		display: none !important;
	}

	.u-search {
		padding: 10px 10px 0 10px;
	}

	.u-checkbox {
		margin: 0 !important;
		height: 35px;
	}

	::v-deep.u-search__action--active {
		width: 20% !important;
		text-align: left !important;
	}
	.uni-forms-item.is-direction-left {
		margin: 0 !important;
	}
</style>