<template>
	<div v-if="isRouterAlive">
		<div class="container">
			<div class="handle-box">
				<selectoption></selectoption>
				<el-input v-model="query.name" size="small" placeholder="登录账号" class="handle-input mr10"
					:clearable="true">
				</el-input>
				<el-button type="primary" size="small" class="my-2" icon="el-icon-search" @click="handleSearch" style="background: #FA8E00; border: none;">搜索</el-button>
				<el-button type="primary" size="small" class="my-2" @click="handleEdit1" style="background: #FA8E00; border: none;">添加账户</el-button>
				<el-button type="primary" size="small" class="my-2" @click="createEnterprise" style="background: #FA8E00; border: none;">添加部门</el-button>
				<el-button type="primary" size="small" class="my-2" @click="historicalAccount" v-if="userInfo.type==0" style="background: #FA8E00; border: none;">历史账户
				</el-button>
			</div>
			<div>
				<el-row :gutter="20">
					<el-col :span="colNum_6">
						<el-card shadow="nerver" class="h600 cardbg">
							<el-tree :data="zNodes" node-key="id" node-click="onClick" default-expand-all
								:expand-on-click-node="false" :props="defaultProps" @node-click="handleNodeClick"
								class="el-tree">
								<span class="custom-tree-node" slot-scope="{ node, data }">
									<span>{{ node.label }}</span>
									<span>
										<el-button type="text" size="mini" @click="() => modifyEnterprise(node, data)">
											编辑
										</el-button>
										<el-button type="text" size="mini" @click="() => remove(node, data)">
											删除
										</el-button>
									</span>
								</span>
							</el-tree>
						</el-card>
					</el-col>
					<el-col :span="colNum_18">
						<el-table :data="tableData" border class="table" ref="multipleTable" height="600"
							header-cell-class-name="table-header" @selection-change="handleSelectionChange">
              <el-table-column label="序号" type="index" width="80">
                <template slot-scope="scope">
                  {{pageTotal - (($store.state.currentPage-1)*pageSize) - scope.$index}}
                </template>
              </el-table-column>
							<el-table-column prop="username" label="登录账号"></el-table-column>
							<el-table-column prop="phone" label="电话"></el-table-column>
							<el-table-column prop="enterpriseName" label="所属部门"></el-table-column>
							<el-table-column label="操作" width="200" align="center">
								<template #default="scope">
									<el-button type="text" @click="handleEdit(scope.$index, scope.row)">操作</el-button>
									<el-button type="text" class="red" @click="handleDelete(scope.$index, scope.row)">删除
									</el-button>
									<el-button type="text" class="red" @click="forceDeletion(scope.$index, scope.row)"
										v-if="userInfo.type==0">强制删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<div class="pagination">
							<el-pagination background layout="total, prev, pager, next"
								:current-page="$store.state.currentPage" :page-size="pageSize" :total="pageTotal"
								@current-change="handlePageChange"></el-pagination>
						</div>
					</el-col>
				</el-row>
			</div>
			<!-- 添加用户弹出框 -->
			<el-dialog title="编辑" :visible.sync="editVisible1" width="30%">
				<el-form ref="addform" :model="addform" :rules="rules" label-width="100px" class="demo-ruleForm">
					<el-form-item label="登录账号" prop="username">
						<el-input v-model="addform.username" :clearable="true"></el-input>
					</el-form-item>
					<el-form-item label="密码" prop="password">
						<el-input v-model="addform.password" :clearable="true"></el-input>
					</el-form-item>
					<el-form-item label="电话" prop="phone">
						<el-input v-model="addform.phone" :clearable="true"></el-input>
					</el-form-item>
					<el-form-item label="部门" prop="enterpriseName">
						<el-select v-model="addform.enterpriseName" placeholder="请选择" @change="enterfun">
							<el-option v-for="item in enterpriselist" :key="item.id" :label="item.name"
								:value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="用户类型" prop="userType">
						<el-select v-model="userType" placeholder="请选择">
							<el-option :key="0" label="超级管理员" :value="0" v-if="userInfo.type==0">
							</el-option>
							<el-option v-for="item in yhlxlist" :key="item.value" :label="item.label"
								:value="item.value" v-if="userInfo.type<=item.value">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="角色">
						<el-cascader :options="rololist" v-model="roleIds" :props="{multiple: true }"
							@change="getCheckNode1" clearable></el-cascader>
					</el-form-item>
				</el-form>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="editVisible1 = false">取 消</el-button>
						<el-button type="primary" @click="saveEdit1">保 存</el-button>
					</span>
				</template>
			</el-dialog>
		</div>

		<!-- 编辑弹出框 -->
		<el-dialog title="操作" :visible.sync="editVisible" width="50%">
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="修改权限" name="first">
					<el-form ref="jurisdiction" :model="jurisdiction" label-width="70px">
						<el-form-item label="部门" prop="enterpriseName">
							<el-select v-model="jurisdiction.enterpriseName" placeholder="请选择" @change="enterfun">
								<el-option v-for="item in enterpriselist" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="用户类型" prop="userType">
							<el-select v-model="jurisdiction.userType" placeholder="请选择">
                <el-option :key="0" label="超级管理员" :value="0" v-if="userInfo.type==0">
                </el-option>
								<el-option v-for="item in yhlxlist" :key="item.value" :label="item.label"
									:value="item.value" v-if="userInfo.type<=item.value">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="角色">
							<el-cascader :options="rololist" v-model="jurisdiction.roleId" :props="{multiple: true }"
								@change="getCheckNode" clearable></el-cascader>
						</el-form-item>
					</el-form>
				</el-tab-pane>
				<el-tab-pane label="修改密码" name="second">
					<el-form ref="form" :model="form" label-width="70px">
						<el-form-item label="旧密码">
							<el-input v-model="modifyfrom.oldPassword" :clearable="true" show-password></el-input>
						</el-form-item>
						<el-form-item label="新密码">
							<el-input v-model="modifyfrom.newPassword" :clearable="true" show-password></el-input>
						</el-form-item>
						<el-form-item label="确认密码">
							<el-input v-model="modifyfrom.confirmPassword" :clearable="true" show-password></el-input>
						</el-form-item>
					</el-form>
				</el-tab-pane>
			</el-tabs>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveEdit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 历史账户 -->
		<el-dialog title="历史账户" :visible.sync="historyUser" width="50%">
			<el-table ref="multipleTable1" :data="historyData" tooltip-effect="dark" style="width: 100%"
				@selection-change="handleSelectionChange1" height="400">
				<el-table-column prop="id" label="ID" width="70" align="center"></el-table-column>
				<el-table-column prop="username" label="登录账号"></el-table-column>
				<el-table-column prop="phone" label="电话"></el-table-column>
				<el-table-column prop="enterpriseName" label="所属部门"></el-table-column>
				<el-table-column label="操作" width="200" align="center">
					<template #default="scope">
						<el-button type="text" class="red" @click="forceDeletion(scope.$index, scope.row)"
							v-if="userInfo.type==0">
							强制删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background layout="total,sizes, prev, pager, next" @size-change="handleSizeChange"
				:page-sizes="[10, 20, 100, 200]" :current-page="pageNum1" :page-size="pageSize1" :total="pageTotal1"
				@current-change="handlePageChange1"></el-pagination>
		</el-dialog>
		<!-- 创建企业 -->
		<el-dialog title="创建部门" :visible.sync="enterpriseidedit" width="50%">
			<el-form ref="form" :model="Enterprise" label-width="70px">
				<el-form-item label="所属机构">
					<el-select v-model="ssjg" placeholder="请选择" @change="ssselectFun1">
						<el-option v-for="item in enterpriselist" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="部门名字">
					<el-input v-model="Enterprise.name" :clearable="true"></el-input>
				</el-form-item>
				<el-form-item label="允许接入">
					<el-input v-model="Enterprise.quota" :clearable="true"></el-input>
				</el-form-item>
				<el-form-item label="坐标">
					<el-input v-model="Enterprise.address" :disabled="true" :clearable="true">
						<el-button slot="append" icon="el-icon-location"></el-button>
					</el-input>
					<el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="center" :events="events">
					</el-amap>
				</el-form-item>
				<el-form-item label="绑定房间">
					<div class="eltree">
						<el-tree :data="roomlist" show-checkbox node-key="id" ref="tree" @check="handleCheckChange"
							:props="defaultProps"></el-tree>
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="enterpriseidedit = false">取 消</el-button>
					<el-button type="primary" @click="addEnterprise">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 编辑部门 -->
		<el-dialog title="编辑部门" :visible.sync="enterpriseidedit1" width="30%">
			<el-form ref="form1" :model="Enterprise1" label-width="70px">
				<el-form-item label="部门名称">
					<el-select v-model="ssjg" placeholder="请选择" @change="ssselectFun">
						<el-option v-for="item in enterpriselist" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="修改名称">
					<el-input v-model="Enterprise1.name" :clearable="true"></el-input>
				</el-form-item>
				<el-form-item label="房源">
            <el-cascader style="width: 100%;" size="middle" v-model="selectKeyList" :options="roomlist"  ref="tree1" collapse-tags clearable
                  @change="handleCheckChange1" :props="{ multiple: true }"></el-cascader>
				</el-form-item>
        <el-form-item label="接收类型">
          <el-select v-model="Enterprise1.atAlert" multiple collapse-tags placeholder="请选择">
            <el-option
              v-for="item in atAlertList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信通知">
          <el-select v-model="Enterprise1.sendItem" multiple collapse-tags placeholder="请选择">
            <el-option
              v-for="item in sendItemList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="坐标">
					<el-input v-model="Enterprise1.address" :disabled="true" :clearable="true">
						<el-button slot="append" icon="el-icon-location"></el-button>
					</el-input>
					<el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="center" :events="events">
					</el-amap>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="enterpriseidedit1 = false">取 消</el-button>
					<el-button type="primary" @click="addEnterprise1">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog title="选择地址" :visible.sync="addresstc" width="30%">
		</el-dialog>
	</div>
</template>

<script>
	import zTree from "../components/zTree2.vue";
	import zTree1 from "../components/zTree.vue";
	import zTreeOne from "../components/zTree2.vue";
	import {
		httpGet,
		httpPost
	} from "../api/index";
	import {
		ztreeToElementTree,
		recursion,
		uniqueArray
	} from "../utils/index";
  import utils from "../utils/util.js"
	export default {
		inject: ['reload'],
		name: "basetable",
		data() {
			const self = this;
			return {
        atAlertList:[
          {
            value: 1,
            label: '撬锁报警'
          },
          {
            value: 2,
            label: '强行开门报警'
          },
          {
            value: 7,
            label: '低电量报警'
          },
          {
            value: 9,
            label: '胁迫开锁报警'
          }
        ],
        sendItemList:[
          {
            value: 1,
            label: '充值短信'
          },
          {
            value: 2,
            label: '交租成功'
          },
          {
            value: 3,
            label: '提醒交租'
          },
          {
            value: 4,
            label: '签约成功'
          }
        ],
				historyUser: false,
				selectoption: [],
				selectoptionValue: '',
				historySelection: [],
				pageNum1: 1,
				pageSize1: 10,
				pageTotal1: 0,
				historyData: [],
				addresstc: false,
				center: [114.064552, 22.548457],
				jurisdiction: {
					roleId: '',
					userType: '',
					identity: '',
					enterpriseName: ''
				},
				lng: 0,
				lat: 0,
				loaded: false,
				events: {
					click(e) {
						self.center = [e.lnglat.lng, e.lnglat.lat];
						self.Enterprise.address = JSON.stringify([e.lnglat.lng, e.lnglat.lat])
						self.Enterprise1.address = JSON.stringify([e.lnglat.lng, e.lnglat.lat])
					}
				},
				plugin: [{
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 100, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: true, //显示定位按钮，默认：true
					buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
					showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
					extensions: 'all',
					pName: 'Geolocation',
					events: {
						init(o) {
							// o 是高德地图定位插件实例
							o.getCurrentPosition((status, result) => {
								if (result && result.position) {
									self.lng = result.position.lng;
									self.lat = result.position.lat;
									self.center = [self.lng, self.lat];
									self.loaded = true;
									self.$nextTick();
								}
							});
						},
						click(e) {
							console.log(e)
						}
					}
				}],
				sele: true,
				selTreestatus: true,
				SelectedList: [],
				defaultProps: {
					children: "children",
					label: "name",
				},
				zNodes: [],
				setting1: {
					edit: {
						enable: true,
						editNameSelectAll: true,
						drag: {
							isMove: false,
						},
						showRemoveBtn: false,
						showRenameBtn: true,
						renameTitle: "修改",
					},
					check: {
						enable: true,
					},
					data: {
						simpleData: {
							enable: true,
							pIdKey: "pid",
						},
					},
					view: {
						showIcon: false,
						addHoverDom: this.addHoverDom,
						removeHoverDom: this.removeHoverDom,
					},
				},
				setting: {
					edit: {
						enable: true,
						editNameSelectAll: true,
						drag: {
							isMove: false,
						},
						showRemoveBtn: false,
						showRenameBtn: true,
						renameTitle: "修改",
					},
					check: {
						enable: false,
					},
					data: {
						simpleData: {
							enable: true,
							pIdKey: "parentId",
						},
					},
					view: {
						showIcon: false,
						addHoverDom: this.addHoverDom,
						removeHoverDom: this.removeHoverDom,
					},
				},
				ssjg: "",
				addHoverDom: true,
				modifyfrom: {
					oldPassword: "",
					newPassword: "",
					confirmPassword: ""
				},
				isRouterAlive: true,
				identity: "",
				userType: "",
				enterpriselist: [],
				Enterprise: {
					name: "",
					quota: '',
				},
				Enterprise1: {
					name: "",
					address: '',
          atAlert:'',
          sendItem:''
				},
				rololist: [],
				enterpriseidedit: false,
				yhsflist: [{
					value: 1,
					label: "高级管理员"
				}, {
					value: 2,
					label: "中级管理员"
				}, {
					value: 3,
					label: "低级管理员"
				}, ],
				yhlxlist: [{
					value: 1,
					label: "管理员"
				}, {
					value: 2,
					label: "子用户"
				}, {
					value: 3,
					label: "小程序用户"
				}, ],
				pageSize: 10,
				pageIndex: 1,
				query: {
					address: "",
					name: "",
					pageIndex: 1,
					pageSize: 10,
					options: [],
				},
				tableData: [],
				multipleSelection: [],
				delList: [],
				editVisible: false,
				pageTotal: 0,
				form: {},
				addform: {
					username: "",
					password: "",
					enterpriseName: "",
					identity: "0",
					userType: "",
					roleId: '',
					enterpriseId: "",
				},
				rules: {
					username: [{
						required: true,
						message: "请输入名称",
						trigger: "blur"
					}],
					phone: [{
						required: true,
						message: "请输入电话",
						trigger: "blur"
					}, {
						min: 11,
						max: 11,
						message: "长度为 11 个字符",
						trigger: "blur"
					}, ],
					password: [{
						required: true,
						message: "请输入密码",
						trigger: "blur"
					}],
					enterpriseName: [{
						required: true,
						message: "请选择部门",
						trigger: "blur"
					}, ],
					userType: [{
						required: true,
						message: "请选择用户类型",
						trigger: "blur"
					}, ],
				},
				idx: -1,
				id: -1,
				editVisible1: false,
				enterpriseidedit1: false,
				enterpriseId: "",
				enterpriseId1: "",
				roomtable: [],
				activeName: "first",
				roomstatus: true,
				zNodes1: [],
				roomlist1: [],
				pid: 1,
				roomlist: [],
				selectkey: [],
				selectkey1: [],
				enterpriseId2: '',
				userInfo: {
					type: ''
				},
				roleIds: [],
				tenantId: '',
        selectKeyList:[],
        colNum_6:6,
        colNum_18:18
			};
		},
		components: {
			zTree,
			zTree1,
			zTreeOne
		},
		beforeCreate() {
			// this.$store.commit('getselectoption')
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem('info'))
			this.enterpriseId = this.userInfo.enterpriseId
			this.getEnterprise();
			this.selectoption = JSON.parse(localStorage.getItem('selectoption'))
			this.selectoptionValue = localStorage.getItem('tenantId')

      if(document.documentElement.clientWidth<1080){
        this.colNum_6 = 24
        this.colNum_18 = 24
      }else{
        this.colNum_6 = 6
        this.colNum_18 = 18
      }
		},
		mounted() {
			this.getUserID();
			this.getUserList();
			this.addRoom();
			if (this.userInfo.type == 0) {
				this.getDeletes()
			}
		},
		methods: {
			selectTenantId(e) {
				localStorage.setItem('tenantId', e)
				this.reload()
			},
			// 获取选中角色权限
			getCheckNode(e) {
				var list = []
				e.map(li => {
					list.push(li[0])
				})
				this.jurisdiction.roleId = list
			},
			getCheckNode1(e) {
				var list = []
				e.map(li => {
					list.push(li[0])
				})
				this.roleIds = list
			},
			// 权限选择
			jurisdictionFun() {

			},
			getDeletes() {
				var data = {
					pageNum: this.pageNum1,
					pageSize: this.pageSize1
				}
				httpGet(data, this.$api.getDeletes).then(res => {
					if (res.success) {
						this.historyData = res.data.list
						this.pageTotal1 = res.data.total
					} else {
						this.$message.error('获取历史账户失败')
					}
				})
			},
			historicalAccount() {
				this.historyUser = true
			},
			// 强制删除登录用户
			forceDeletion(index, row) {
				this.$confirm("确定要删除吗？", "提示", {
						type: "warning",
					})
					.then(() => {
						var data = {
							user: row.username
						}
						httpGet(data, this.$api.orderKill).then(res => {
							if (res.success) {
								this.getUserList();
								this.getDeletes()
								this.$message.success('删除成功')
							} else {
								this.$message.error('删除失败')
							}
						})
					})
			},
			initMap(e) {
				// init(o) {
				// o 是高德地图定位插件实例
				e.getCurrentPosition((status, result) => {
					if (result && result.position) {
						self.lng = result.position.lng;
						self.lat = result.position.lat;
						self.center = [self.lng, self.lat];
						self.loaded = true;
						self.$nextTick();
					}
				});
				// }
			},
			selectAddress() {
				this.addresstc = true
			},
			//编辑节点
			modifyFun(node, data) {
				console.log(node, data);
			},
			remove(node, data) {
				var list = [];
				list.push(data);
				var data = recursion(list)
				this.$confirm("确定要删除吗？", "提示", {
					type: "warning",
				}).then(() => {
					httpPost(data, this.$api.deleteEnterprise).then((res) => {
						if (res.success) {
							this.getEnterprise();
							this.$message.success("删除成功");
						} else {
							this.getEnterprise();
							this.$message.error("删除失败");
						}
					});
				});
			},
			// 绑定房间
			bindsave() {},
			handleCheckChange1(e) {
        // console.log(e,this.selectkey1)
				var SelectedList = this.$refs.tree1.getCheckedNodes();
        var arr=[]
        SelectedList.map(li=>{
          arr.push(li.value)
        })
        this.SelectedList=arr
        this.selectKeyList=e
			},
			//所选房源
			handleCheckChange() {
				this.selectkey = this.$refs.tree.getCheckedKeys();
			},
			//添加房源
			addRoom() {
				var data = {};
				httpGet(data, this.$api.getSiteList).then((res) => {
					var array = uniqueArray(res.data.list, 'id')
					this.roomlist = ztreeToElementTree(array, {});
				});
			},
			ssselectFun1(e) {
				this.enterpriseId2 = e;
			},
			ssselectFun(e) {
				this.enterpriseId1 = e;
				this.ssjg = e
				var q = {
					enterpriseId: e,
				}
				this.SelectedList = []
				var data = {
					q: JSON.stringify(q),
				};
				httpGet(data, this.$api.getSiteList).then((res) => {
					// this.selectkey
					var array = uniqueArray(res.data.list, 'id')
					this.zNodes1 = ztreeToElementTree(array, {});
					var array1 = []
					array.map(li => {
						array1.push(li.id)
					})
          var selectKeyList=[],selectkey1=[]
          res.data.list.forEach(item=>{
            var name = utils.findIndexArrayOne(this.roomlist, item.id, [])
            if (name) {
              selectKeyList.push(name)
            }
            selectkey1.push(item.id)
          })
          this.selectKeyList=selectKeyList
           this.selectkey1=selectkey1
					this.sele = false
					this.$nextTick(function() {
						this.SelectedList = array1
						this.sele = true
					})
				});
			},
			loadNode(node, resolve) {
				if (node.childNodes) {
					var q = {};
					if (node.level) {
						q = {
							pid: node.level,
						};
					} else {
						q = {
							pid: this.pid,
						};
					}
					var data = {
						q: JSON.stringify(q),
					};
					httpGet(data, this.$api.getTree).then((res) => {
						// if (res.data.length > 1) {
						//   res.data.splice(0, 1);
						// }
						return resolve(arr);
					});
				} else {
					this.$message.error("暂无更多数据");
				}
			},
			getroomperson() {
				var q = {
					enterpriseId: this.form.enterpriseId,
				};
				var data = {
					q: JSON.stringify(q),
				};
				httpGet(data, this.$api.getSiteList).then((res) => {
					var roomtable = [];
					var array = uniqueArray(res.data.list, 'id')
					array.map((li) => {
						if (li.acreage && li.layout) {
							roomtable.push(li);
						}
					});
					this.roomtable = roomtable;
				});
			},
			// 添加绑定房间
			bindroom() {
				this.roomstatus = !this.roomstatus;
			},
			//操作切换
			handleClick(tab, event) {
				// console.log(tab, event);
			},
			onMouseDown(evt, treeId, treeNode) {
				this.Enterprise1 = treeId;
				this.enterpriseidedit1 = true;
				this.getroom();
			},
			getroom() {
				var q = {
					enterpriseId: this.Enterprise1.id,
				};
				var data = {
					q: JSON.stringify(q),
				};
				httpGet(data, this.$api.getSiteList).then((res) => {
					var array = uniqueArray(res.data.list, 'id')
					this.zNodes1 = array;
				});
			},
			// 部门手风琴点击事件
			handleNodeClick(data) {
				this.enterpriseId = data.id;
				this.getUserList();
			},
			// 获取角色id
			getUserID() {
				var data = {
					pageNum: 1,
					pageSize: 100,
				};
				httpGet(data, this.$api.getRoleList).then((res) => {
					var rololist = []
					res.data.list.map(li => {
						var obj = {
							value: li.id,
							label: li.name,
						}
						rololist.push(obj)
					})
					this.rololist = rololist;
				});
			},
			enterfun(e) {
				this.enterpriseId = e;
				this.getUserList();
				this.enterpriselist.map((li) => {
					if (li.id == e) {
						this.addform.enterpriseName = li.name;
						this.addform.enterpriseId = li.id;
					}
				});
			},
			getEnterprise() {
				httpGet("", this.$api.getEnterprise).then((res) => {
					this.enterpriselist = res.data.list;
					if (res.data.list.length > 0) {
						this.enterpriseId = res.data.list[0].id;
					}
					res.data.list.map((li) => {
						li.pid = li.parentId;
					});
					this.zNodes = []
					this.zNodes = ztreeToElementTree(res.data.list, {}); //res.data.list;
				});
			},
			// 部门编辑确
			addEnterprise1() {
				if (this.enterpriseId1 == "") {
					this.$message.error("请选择要编辑的部门");
				} else {
					var idlist1 =[...new Set(this.selectkey1.concat(this.SelectedList))]
          if(this.selectkey1.length>0){
            if (idlist1.length > 0) {
              var datalistll=[]
              this.selectkey1.map((li) => {
                var ary = {
                  itemId: li,
                  orderId: this.enterpriseId1,
                };
                datalistll.push(ary)
              });
              httpPost(datalistll, this.$api.removeAssign).then((res) => {
                if (res.success) {
                  var idlist = [];
                  this.SelectedList.map((li) => {
                    var ary = {
                      itemId: li,
                      orderId: this.enterpriseId1,
                    };
                    idlist.push(ary);
                  });
                  if (idlist.length != 0) {
                    setTimeout(()=>{
                      httpPost(idlist, this.$api.assignSite).then((res) => {});
                    },500)
                  }
                }
              });
            }
          }else{
            var idlist = [];
            this.SelectedList.map((li) => {
              var ary = {
                itemId: li,
                orderId: this.enterpriseId1,
              };
              idlist.push(ary);
            });
            if (idlist.length != 0) {
              httpPost(idlist, this.$api.assignSite).then((res) => {});
            }
          }
					if (this.Enterprise1.name != "" || this.Enterprise1.address != "") {
						var data = {
							list: [{
								name: this.Enterprise1.name,
								id: this.enterpriseId1,
								coordinate: JSON.stringify(this.Enterprise1.address),
                atAlert:JSON.stringify(this.Enterprise1.atAlert),
                sendItem:JSON.stringify(this.Enterprise1.sendItem)
							}],
						};
						httpPost(data, this.$api.updateEnterprise).then((res) => {
							if (res.success) {
								this.getEnterprise();
								this.$message.success("修改成功");
							} else {
								this.$message.error("修改部门失败");
							}
						});
					} else {
						this.getEnterprise();
						this.$message.success("修改成功");
					}
					this.enterpriseidedit1 = false;
				}
			},
			addEnterprise() {
				if (this.ssjg == "") {
					this.$message.error("请选择所属部门");
				} else if (this.Enterprise.name == "") {
					this.$message.error("输入部门名称");
				} else if (this.Enterprise.quota == "") {
					this.$message.error("请输入允许接入设备数量");
				} else {
					var data = {
						name: this.Enterprise.name,
						parentId: this.ssjg,
						coordinate: JSON.stringify(this.Enterprise.address),
						quota: this.Enterprise.quota
					};
					httpPost(data, this.$api.addEnterprise).then((res) => {
						if (res.success) {
							this.$message.success("创建成功");
							var idlist = [];
							this.selectkey.map((li) => {
								var ary = {
									itemId: li,
									orderId: res.data,
								};
								idlist.push(ary);
							});
							if (idlist.length != 0) {
								httpPost(idlist, this.$api.assignSite).then((res1) => {
									if (res1.success) {
										this.$message.success("绑定成功");
										this.enterpriseidedit = false;
										this.getEnterprise();
									}
								});
							}
						} else {
							if (res.message == "Exceeded quota") {
								this.$message.error("超出配额");
							} else {
								this.$message.error(res.message);
							}
						}
					});
				}
			},
			modifyEnterprise(node, data) {
				this.enterpriseidedit1 = true;
				this.ssjg = data.id
				this.enterpriseId1 = data.id
				this.Enterprise1.address = JSON.parse(data.coordinate)
        this.Enterprise1.atAlert = JSON.parse(data.atAlert)
        this.Enterprise1.sendItem = JSON.parse(data.sendItem)
				this.getshsite(data.id);
			},
      getArr (dataSource, id) { // dataSource 这个是选择器的数据源  id 是 目标id
        const arrRes = []
        dataSource.some(item => {
          if (item.value == id) {
            arrRes.unshift(item.value)
            return true
          } else {
            if (item.children) {
              item.children.some(item1 => {
                if (item1.value == id) {
                  arrRes.unshift(item1.value)
                  arrRes.unshift(item.value)
                  return true
                } else {
                  if (item1.children) { // item1.children 判断 防止不存在对应的三级数据
                    item1.children.some(item2 => {
                      if (item2.value == id) {
                        arrRes.unshift(item2.value)
                        arrRes.unshift(item1.value)
                        arrRes.unshift(item.value)
                        return true
                      }
                    })
                  }
                }
              })
            }
          }
        })
        return arrRes // 返回最终根据id查找出来的数组
      },
			getshsite(id) {
				this.SelectedList = []
				var q = {
					enterpriseId: id,
				};
				var data = {
					q: JSON.stringify(q),
				};
				httpGet(data, this.$api.getSiteList).then((res) => {
					var SelectedList = []
					if (res.data.list.length > 0) {
						var array = uniqueArray(res.data.list, 'id')
						SelectedList = recursion(array);
					} else {
						SelectedList = []
					}
          var selectKeyList=[],selectkey1=[]
          res.data.list.forEach(item=>{
            var name = utils.findIndexArrayOne(this.roomlist, item.id, [])
            if (name) {
              selectKeyList.push(name)
            }
            selectkey1.push(item.id)
          })
          this.selectKeyList=selectKeyList
           this.selectkey1=selectkey1
					this.sele = false;
					this.$nextTick(() => {
						var str=this.familyTree(this.roomlist)
						let newArr = SelectedList.filter((x) => !str.some((item) => x === item));
						this.SelectedList = newArr;
						this.sele = true;
					});
				});
			},
			 familyTree(arr) {
			      var temp = [];
			      var forFn = function (list) {
			        for (var i = 0; i < list.length; i++) {
			          var item = list[i];
			          if (item.children) {
			            temp.push(item.id);
			            forFn(item.children);
			          }
			        }
			      };
			      forFn(arr);
			      return temp;
			    },
			createEnterprise() {
				this.enterpriseidedit = true;
			},
			// 获取用户列表
			getUserList() {
				var data = {
					pageNum: this.pageNum1,
					pageSize: this.pageSize1,
					q: JSON.stringify({
						enterpriseId: this.enterpriseId,
					}),
				};
				httpGet(data, this.$api.getUserList).then((res) => {
					res.data.list.map((li) => {
              var name = utils.findIndexArray(this.enterpriselist, li.enterpriseId, [])
              var path = ''
              if (name) {
                path = name.join('/')
                li.enterpriseName=path
              }
					});
					this.tableData = res.data.list;
					this.pageTotal = res.data.total;
				});
			},
			// 编辑操作
			handleEdit1() {
				this.editVisible1 = true;
			},
			// 保存编辑  添加用户
			saveEdit1() {
				this.addform.identity = this.userType;
				this.addform.userType = this.userType;
				var roleIds = this.roleIds
				this.addform.roleId = roleIds[0]
				if (
					this.addform.username == "" ||
					this.addform.phone == "" ||
					this.addform.password == "" ||
					this.addform.userType === ""
				) {
					this.$message.error("请填写完整信息");
				} else if (this.addform.phone.length != 11) {
					this.$message.error("请填写正确手机号");
				} else {
					var addform = this.addform
					addform['tenantId'] = this.$store.state.tenantId
					httpPost(this.addform, this.$api.addUser).then((res) => {
						if (res.success) {
							var data = {
								roleIds: roleIds,
								userId: res.data,
							}
							httpPost(data, this.$api.bindRole).then((res1) => {
								if (res1.success) {
									this.$message.success('绑定角色成功')
								} else {
									this.$message.error('绑定角色失败')
								}
							})
							this.$message.success("添加成功");
							this.editVisible1 = false;
							this.isRouterAlive = false;
							this.getUserList();
							this.$nextTick(function() {
								this.isRouterAlive = true;
							});
						} else {
							this.$message.error("添加失败");
						}
					});
				}
			},
			handleChange(value) {
				console.log(value);
			},
			// 触发搜索按钮
			handleSearch() {
				// this.$set(this.query, "pageIndex", 1);
				this.getUserList1(1, 10);
				this.$store.commit('increment', 1)
			},
			// 删除操作
			handleDelete(index, row) {
				// 二次确认删除
				this.$confirm("确定要删除吗？", "提示", {
						type: "warning",
					})
					.then(() => {
						var data = [row.id];
						httpPost(data, this.$api.deleteUser).then((res) => {
							if (res.success) {
								this.$message.success("删除成功");
								this.getUserList();
							} else {
								this.$message.error("删除失败");
							}
						});
					})
					.catch(() => {});
			},
			// 多选操作
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			// 多选操作
			handleSelectionChange1(val) {
				this.historySelection = val;
			},
			delAllSelection() {
				const length = this.multipleSelection.length;
				let str = "";
				this.delList = this.delList.concat(this.multipleSelection);
				for (let i = 0; i < length; i++) {
					str += this.multipleSelection[i].name + " ";
				}
				this.$message.error(`删除了${str}`);
				this.multipleSelection = [];
			},
			// 编辑操作
			handleEdit(index, row) {
				this.idx = index;
				this.form = row;
				this.editVisible = true;
				this.jurisdiction.userType = row.type
				// this.jurisdiction.roleId = row.identity
				this.jurisdiction.enterpriseName = row.enterpriseId
				this.getroomperson();
				this.getroleId(row.id)
			},
			// 获取绑定角色
			getroleId(id) {
				var data = {
					userId: id
				};
				httpGet(data, this.$api.getRolesByUser).then((res) => {
					if (res.success) {
						if (res.data.length > 0) {
							var defaultkeys = []
							res.data.map(li => {
								defaultkeys.push(li.id)
							})
							this.jurisdiction.roleId = defaultkeys
							this.form.identity = defaultkeys
						}
					} else {
						this.$message.error('获取绑定角色失败')
					}
				})
			},
			scalarArrayEquals(array1, array2) {
				if (array2) {
					return array1.length == array2.length && array1.every(function(v, i) {
						return v === array2[i]
					});
				} else {
					return false
				}
			},
			// 保存编辑
			saveEdit() {
				if (this.activeName == 'first') {
					var jurisdiction = this.jurisdiction
					if (jurisdiction.enterpriseName != this.form.enterpriseId) {
						var data = {
							id: this.form.id,
							enterpriseId: jurisdiction.enterpriseName
						};
						httpPost(data, this.$api.editUserEnterprise).then((res) => {
							if (res.success) {
								this.getUserList1(1, 10);
								this.$message.success("修改成功");
							} else {
								this.$message.error("修改失败");
							}
						});

					}
					if (!this.scalarArrayEquals(jurisdiction.roleId, this.form.identity)) {
						var data = {
							roleIds: jurisdiction.roleId,
							userId: this.form.id
						}
						httpPost(data, this.$api.bindRole).then((res) => {
							if (res.success) {
								this.getUserList1(1, 10);
								this.$message.success('修改成功')
							} else {
								this.$message.error('修改失败')
							}
						})
					}
					if (jurisdiction.userType != this.form.type) {
						var data = {
							type: jurisdiction.userType,
							id: this.form.id
						}
						httpPost(data, this.$api.editType).then((res) => {
							if (res.success) {
								this.getUserList1(1, 10);
								this.$message.success('修改成功')
							} else {
								this.$message.error('修改失败')
							}
						})
					}
					this.editVisible = false;
				} else if (this.activeName == 'second') {
					if (this.modifyfrom.confirmPassword != this.modifyfrom.newPassword) {
						this.$message.error("确认密码输入错误！");
					} else if (this.modifyfrom.confirmPassword == '' || this.modifyfrom.newPassword == '') {
						this.$message.error("请输入修改的密码");
					} else {
						var data = {
							userId: this.form.id,
							new: this.modifyfrom.newPassword,
							old: this.modifyfrom.oldPassword,
						};
						httpPost(data, this.$api.editPassword).then((res) => {
							if (res.success) {
								this.getUserList1(1, 10);
								this.$message.success("修改成功！");
								this.editVisible = false;
							} else {
								this.$message.error("修改失败，请输入正确的旧密码！");
							}
						});
					}
				}
			},
			// 分页导航
			handlePageChange(val) {
				// this.$set(this.query, "pageIndex", val);
				console.log(val);
				this.getUserList1(val, 10);
			},
			handleSizeChange(val) {
				this.pageSize1 = val
				this.getHistoryList(this.pageNum1, val)
			},
			// 分页导航
			handlePageChange1(val) {
				this.getHistoryList(val, this.pageSize1);
			},
			getHistoryList(pageNum, pageSize) {
				var data = {
					pageNum: pageNum,
					pageSize: pageSize
				}
				httpGet(data, this.$api.getDeletes).then(res => {
					if (res.success) {
						this.historyData = res.data.list
					} else {
						this.$message.error('获取历史账户失败')
					}
				})
			},
			getUserList1(pageNum, pageSize) {
				var q = {
					username: this.query.name,
					enterpriseId: this.enterpriseId,
				};
				var data = {
					pageNum: pageNum,
					pageSize: pageSize,
					q: JSON.stringify(q),
				};
				httpGet(data, this.$api.getUserList).then((res) => {
					res.data.list.map((li) => {
            var name = utils.findIndexArray(this.enterpriselist, li.enterpriseId, [])
            var path = ''
            if (name) {
              path = name.join('/')
              li.enterpriseName=path
            }
					});
					this.tableData = res.data.list;
					this.pageTotal = res.data.total;
				});
			},
		},
	};
</script>

<style scoped>
	.handle-box {
		margin-bottom: 20px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 300px;
		display: inline-block;
	}

	.table {
		width: 100%;
		font-size: 14px;
	}

	.red {
		color: #ff0000;
	}

	.mr10 {
		margin-right: 10px;
	}

	.mright {
		margin-right: 10px;
		display: inline-block;
	}

	.table-td-thumb {
		display: block;
		margin: auto;
		width: 40px;
		height: 40px;
	}

	.elrow {
		margin-bottom: 20px;
	}

	.grid-content {
		position: relative;
		z-index: 99;
		display: flex;
		align-items: center;
		overflow: hidden;
		justify-content: space-around;
		-webkit-box-align: center;
	}

	/* 加的 */

	.colposition {
		display: flex;
		align-items: center;
		position: relative;
		box-sizing: border-box;
		border: 2px solid hsla(0, 0%, 100%, 0.2);
		/* width: 100%; */
	}

	.grid-cont-right {
		flex: 1;
		text-align: left;
		padding-left: 20px;
		box-sizing: border-box;
		font-size: 16px;
		color: #666;
		font-size: 14px;
		line-height: 32px;
	}

	.grid-num {
		font-size: 24px;
	}

	.grid-con-icon {
		font-size: 50px;
		width: 100px;
		height: 100px;
		text-align: center;
		line-height: 100px;
		color: #fff;
	}

	.grid-con-1 {
		position: relative;
	}

	.grid-con-1::before {
		position: absolute;
		content: "";
		top: 50%;
		right: 0;
		width: 1px;
		transform: translateY(-50%);
		height: 70px;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		border-left: 1px dashed #666;
	}

	.grid-con-1 .grid-con-icon {
		background: rgb(45, 140, 240);
	}

	.grid-con-1 .grid-num {
		/* color: rgb(45, 140, 240); */
		color: #333;
	}

	.grid-con-2 .grid-con-icon {
		background: rgb(100, 213, 114);
	}

	.grid-con-2 .grid-num {
		/* color: rgb(45, 140, 240); */
		color: #333;
	}

	.grid-con-3 .grid-con-icon {
		background: rgb(242, 94, 67);
	}

	.grid-con-3 .grid-num {
		color: rgb(242, 94, 67);
	}

	.h600 {
		height: 600px;
		overflow: auto;
	}

	.cardbg {
		background: #fff;
		padding: 0;
	}

	.eltree {
		height: 200px;
		overflow: auto;
		padding-top: 8px;
		box-sizing: border-box;
	}

	.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 8px;
	}

	.el-tree>>>.custom-tree-node>span:first-child {
		width: 160px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.amap-demo {
		height: 300px;
	}

  .handle-box .el-button+.el-button,.handle-box .el-checkbox.is-bordered+.el-checkbox.is-bordered{
    margin-left: 0;
  }

  @media only screen and (max-width: 1024px){
    .h600{
      height: 300px;
    }
  }
</style>
