<template>
	<div class="admin-user">
		<el-form :inline="true">
			<el-form-item v-if="$permission('/admin/user/check')">
				<el-input
					v-model="queryParams.name"
					size="small"
					placeholder="请输入"
				></el-input>
			</el-form-item>
			<el-form-item class="tenant" v-if="userinfo.rList?(userinfo.rList.filter(item=>item.roleId==1))[0]:''">
        		<el-select v-model="queryParams.tenant"  @change="getList2" clearable placeholder="根据租户查询">
					<el-option
						v-for="item in tenantList"
						:key="item.id"
						:label="item.name"
						:value="item.id">
					</el-option>
				</el-select>
      </el-form-item>
			
			<!-- <el-form-item label="用户名">
        <el-input v-model="queryParams.name" size="small" placeholder="请输入用户名"></el-input>
      </el-form-item> -->
			<el-form-item>
				<el-button type="" size="small" @click="getList2" v-if="$permission('/admin/user/check')">查询</el-button>
				<el-button type="primary" size="small" @click="handleAdd()" v-if="$permission('/admin/user/add')">新增</el-button
				>
			</el-form-item>
		</el-form>
		<el-table
			v-loading="loading"
			:data="tableData"
			border
			header-row-class-name="custom-table-header"
		>
			<el-table-column
				type="index"
				label="#"
				width="55"
				align="center"
			>
			<template slot-scope="scope">
          <span>{{ (scope.$index + 1) + ((queryParams.current - 1) * queryParams.size) }}</span>
        </template>
			</el-table-column>
			<el-table-column
				prop="name"
				label="姓名"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column
				prop="username"
				label="账号"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column label="性别" align="center" show-overflow-tooltip>
				<template slot-scope="scope">
					<span>{{ genderObj[scope.row.gender] }}</span>
				</template>
			</el-table-column>
			<el-table-column
				prop="email"
				label="邮箱"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column
				prop="mobile"
				label="联系方式"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column
				prop="tenantName"
				label="所属租户"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column label="是否启用" align="center" show-overflow-tooltip>
				<template slot-scope="scope">
					<span v-if="scope.row.state == 0">否</span>
					<span v-if="scope.row.state == 1">是</span>
				</template>
			</el-table-column>
			<el-table-column
				prop="remark"
				label="备注"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column label="操作" align="center" width="150">
				<template slot-scope="scope">
					<el-dropdown split-button type="primary" size="small" >
						<p @click="handleEdit(scope.row)" v-if="$permission('/admin/user/modify')">编辑</p>
						<p v-else :disabled="true">编辑</p>
						<el-dropdown-menu slot="dropdown" class="text-align_center">
							<!-- <el-dropdown-item @click.native="handleDetails(scope.row)" divided  v-if="$permission('/admin/user/detail')">人员详情</el-dropdown-item> -->
							<el-dropdown-item @click.native="handleReset(scope.row)" v-if="$permission('/admin/user/reset')">重置密码</el-dropdown-item>
							<el-dropdown-item class="color-red" @click.native="handleDelete(scope.row)" divided  v-if="$permission('/admin/user/delete')">删除</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination">
			<el-pagination
				:current-page.sync="queryParams.current"
				:page-size="queryParams.size"
				:total="total"
				@current-change="handleCurrentChange"
				layout="total, prev, pager, next, jumper"
				background
			></el-pagination>
		</div>
		<el-dialog
			:title="title"
			:visible.sync="visible"
			width="700px"
			:before-close="close"
		>
			<el-form
				v-if="visible"
				:model="ruleForm"
				:rules="rules"
				ref="ruleForm"
				label-width="100px"
				label-position="left"
			>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input
								v-model="ruleForm.name"
								placeholder="请输入姓名"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="性别" prop="gender">
							<el-select
								v-model="ruleForm.gender"
								class="width_100"
								placeholder="请选择"
							>
								<el-option
									v-for="(item, key) in genderObj" :key="key"
									:label="item"
									:value="parseInt(key)"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="邮箱" prop="email">
							<el-input
								v-model="ruleForm.email"
								placeholder="请输入邮箱"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系方式" prop="mobile">
							<el-input
								v-model="ruleForm.mobile"
								placeholder="请输入联系方式"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="QQ号" prop="qqNumber">
							<el-input
								type="text"
								v-model="ruleForm.qqNumber"
								placeholder="请输入QQ号"
								@input="change($event)"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="微信号" prop="wechat">
							<el-input
								v-model="ruleForm.wechat"
								placeholder="请输入微信号"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="钉钉号" prop="nail">
							<el-input
								v-model="ruleForm.nail"
								placeholder="请输入钉钉号"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="所属租户" prop="tenant">
							<!-- <el-tooltip
								class="item"
								effect="dark"
								:disabled="!ruleForm.tenantName"
								:content="ruleForm.tenantName"
								placement="top-start"
							>
								<el-input
									v-model="ruleForm.tenantName"
									placeholder="请输入所属租户"
									:readonly="true"
								></el-input>
							
							</el-tooltip> -->
								<el-select v-model="ruleForm.tenant" :disabled="(userinfo.rList?!(userinfo.rList.filter(item=>item.roleId==1))[0]:'')||disabled" placeholder="请选择">
										<el-option
										v-for="item in tenantList"
										:key="item.id"
										:label="item.name"
										:value="item.id">
										</el-option>
									</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="24">
					<el-col :span="24">
						<el-form-item label="职位[部门]" prop="nail">
							<template>
								<el-col :span="11" style="padding-left: 0">
									<el-form-item label-width="0" prop="position">
										<el-tooltip
											class="item"
											effect="dark"
											:disabled="!labelVal"
											:content="labelVal"
											placement="top-start"
										>
											<el-cascader
												ref="deptIdCascader"
												v-model="positionAndDepartment.department"
												:options="departmentList"
												:show-all-levels="false"
												:props="{
													checkStrictly: true,
													value: 'id',
													label: 'name',
												}"
												clearable
												@change="handleChange"
												placeholder="请选择部门"
											>
											</el-cascader>
										</el-tooltip>
									</el-form-item>
								</el-col>

								<el-col :span="11" style="padding-left: 0">
									<el-form-item
										label-width="0"
										label-height="82"
										label-line-height="82px"
										prop="position"
									>
										<el-select
											v-model="positionAndDepartment.position"
											filterable
											placeholder="请选择职位"
										>
											<el-option
												v-for="item in positionList"
												:key="item.name"
												:label="item.position"
												:value="item.id"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="2">
									<el-button
										type="primary"
										size="mini"
										@click="showInputLabel"
										circle
										icon="el-icon-plus"
									></el-button>
								</el-col>
								<el-col :span="24" style="padding-left: 0; margin: 10px 0 0 0">
									<template>
										<div
											style="
												width: 100%;
												height: 75px;
												border: 1px solid #c0c0c0;
												border-radius: 4px;
												overflow: auto;
											"
										>
											<el-tag
												v-for="(tag, index) in ruleForm.positions"
												:key="index"
												closable
												:disable-transitions="false"
												@close="handleClose(index)"
											>
												<span
													>{{ tag.positionName }}<span v-if="tag.departmentName">[{{
														tag.departmentName
													}}]</span></span
												>
											</el-tag>
										</div>
									</template>
								</el-col>
							</template>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="所属用户组" prop="group">
							<el-select
								v-model="ruleForm.group"
								multiple
								collapse-tags
								placeholder="请选择用户组"
							>
								<el-option
									v-for="item in groupList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="所属角色" prop="role" class="role">
							<el-select
								v-model="ruleForm.role"
								multiple
								collapse-tags	
								placeholder="请选择所属角色"
							>
								<el-option
									v-for="item in roleList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
									:disabled="item.disabled"
								>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="24">
					<el-col :span="12">
						<el-form-item label="账号" prop="username">
							<el-input
								v-model="ruleForm.username"
								placeholder="请输入账号"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item v-if="pswdshow" label="密码" prop="password">
							<el-input
								v-model="ruleForm.password"
								placeholder="请输入密码"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否启用" prop="state">
							<el-switch
								:active-value="1"
								:inactive-value="0"
								v-model="ruleForm.state"
								active-color="#13ce66"
								inactive-color="#ff4949"
							>
							</el-switch>
							<!-- <el-input v-model="ruleForm.state" placeholder="请输入状态" type="textarea"></el-input> -->
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="备注" prop="remark">
					<el-input
						v-model="ruleForm.remark"
						placeholder="请输入备注"
						type="textarea"
						maxlength="100"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="close">取 消</el-button>
				<el-button type="primary" @click="submit" :loading="btnLoading"
					>确 定</el-button
				>
			</div>
		</el-dialog>

		<el-dialog
			:title="title"
			:visible.sync="showvisible"
			width="700px"
			class="my-dialog-name"
			contentStyle="width:400px;"
			:before-close="close"
			v-if="ruleForm.apply != null"
		>
			<el-form
				label-position="left"
				class="demo-table-expand"
				label-width="80px"
			>
				<el-form-item label="账号 :" class="marginB">
					<span>{{ ruleForm.apply.username }}</span>
				</el-form-item>
				<el-form-item label="姓名 :" class="marginB">
					<span>{{ ruleForm.apply.remark }}</span>
				</el-form-item>
				<el-form-item label="性别 :" class="marginB">
					<span>{{ ruleForm.apply.gender === 1 ? "男" : "女" }}</span>
				</el-form-item>
				<el-form-item label="邮箱 :" class="marginB">
					<span>{{ ruleForm.apply.email }}</span>
				</el-form-item>
				<el-form-item label="联系方式 :" class="marginB">
					<span>{{ ruleForm.apply.mobile }}</span>
				</el-form-item>
				<el-form-item label="QQ号 :" class="marginB">
					<span>{{ ruleForm.apply.qqNumber }}</span>
				</el-form-item>
				<el-form-item label="微信号 :" class="marginB">
					<span>{{ ruleForm.apply.mobile }}</span>
				</el-form-item>
				<el-form-item label="钉钉号 :" class="marginB">
					<span>{{ ruleForm.apply.nail }}</span>
				</el-form-item>
        <el-form-item label="所属租户 :" class="marginB">
					<span>{{ ruleForm.apply.tenantName }}</span>
				</el-form-item>
        <el-form-item label="用户组 :" class="marginB">
					<span v-for="item in ruleForm.apply.groupList">{{ item.name }}</span>
				</el-form-item>
        <el-form-item label="所属角色 :" class="marginB">
					<span v-for="item in ruleForm.apply.roleList">{{ item.name }}</span>
				</el-form-item>
        <!-- <el-form-item label="账号 :" class="marginB">
					<span>{{ ruleForm.apply.nail }}</span>
				</el-form-item> -->
				<el-form-item label="是否启用 :" class="marginB">
					<span>{{ ruleForm.apply.state === 1 ? "已启用" : "未启用" }}</span>
				</el-form-item>
				<el-form-item label="备注 :" class="marginB">
					<span>{{ ruleForm.apply.remark }}</span>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
	import Treeselect from "@riophae/vue-treeselect"
	import "@riophae/vue-treeselect/dist/vue-treeselect.css"
	export default {
		components: {
			Treeselect
		},
		
		data() {
      const isMobile = (rule, value, callback) => {
        if (value) {
          var reg = /(^((\+86)|(86))?(1[3-9])\d{9}$)|(^(0\d{2,3})-?(\d{7,8})$)/
          var re = new RegExp(reg)
          if (re.test(value)) {
            callback()
          } else {
            callback(new Error('输入的手机号码格式不正确，请重新输入'))
          }
        } else {
          callback()
        }
      };
      const isPassword = (rule, value, callback) => {
        if (value) {
          let reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[`~!#$%^&*()_\-+=<>?:\"{}|,.\/;'\\[\]·！@￥……（）——【】、：；‘’“”，。/《》？ ]).{6,}$/
          let re = new RegExp(reg)
          if (re.test(value)) {
            callback()
          } else {
            callback(new Error('密码必须包含大小写字母、数字、特殊字符且长度至少为六位的组合'))
          }
        } else {
          callback(new Error('请输入密码'))
        }
      };
			return {
				disabled:false,
				pswdshow: false,
				showvisible: false,
				visible: false,
				loading: false,
				btnLoading: false,
				total: 0,
				tableData: [],
				tenantList:[],
				title: "",
				roleList: [
					{
						value: "选项1",
						label: "黄金糕",
					},
					{
						value: "选项2",
						label: "双皮奶",
					},
					{
						value: "选项3",
						label: "蚵仔煎",
					},
					{
						value: "选项4",
						label: "龙须面",
					},
					{
						value: "选项5",
						label: "北京烤鸭",
					},
				],
				queryParams: {
					size: 10,
					current: 1,
					// username: '',
          departmentIds: [],
          positionIds:[],
					name: "",
					tenant:''
				},
				labelVal: "",
				departmentList: [],
				positionList: [],
				groupList: [],
				roleList: [],
				genderObj: {
					0: "女",
					1: "男",
				},
				positionAndDepartment: {},
				// departmentList: [],
				ruleForm: {},
				rules: {
					name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
					username: [{ required: true, message: "请输入账号", trigger: "blur" }],
					password: [{ required: true, validator:isPassword, trigger: "blur" }],
					mobile: [
						{ required: false, validator:isMobile, trigger: "blur" },
						// {
						// 	pattern:
						// 		/(^((\+86)|(86))?(1[3-9])\d{9}$)|(^(0\d{2,3})-?(\d{7,8})$)/,
						// 	message: "输入的手机号码格式不正确，请重新输入",
						// 	trigger: "blur",
						// },
					],
					email: [
						{ required: true, message: "请输入邮箱", trigger: "blur" },
						{
							pattern:
								/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9_\.\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
							message: "请输入正确的邮箱格式",
							trigger: "blur",
						},
					],
					sex: [{ required: true, message: "请选择性别", trigger: "change" }],
					// position: [{ required: true, message: '请选择职位', trigger: 'change' },],
					// department: [{ required: true, message: '请选择部门', trigger: 'change' },],
					state: [{ required: true, message: "请选择", trigger: "change" }],
					tenant:[{ required: true, message: "请选择", trigger: "change" }],
				},
			};
		},
		watch: {
			"positionAndDepartment.department"() {
				if (this.$refs.deptIdCascader) {
					this.$refs.deptIdCascader.dropDownVisible = false;
				}
			},
			"ruleForm.email"(val) {
				// console.log(val)
				if (val.indexOf("@qq.com") != -1) {
					var index = val.indexOf("@qq.com");
					var str = val.substring(0, index);
					this.ruleForm.qqNumber = str;
				} else if (val.indexOf("@qq.com") == -1) {
				}
			},
		},
		computed: {
			userinfo() {
				
				return this.$store.state.admin.userinfo;
			},
		},
		mounted() {
			this.getList();
			this.getDepartment();
			this.getPositionList();
			this.getGroupList();
			this.getRoleList();
			this.getTenantList()
		},
		methods: {
			 //根据条件查询
			 getList2(){
				this.queryParams.current=1
				this.getList()
			},
			change(e) {
				this.$forceUpdate();
			},
			// getqqNumber(val){
			//   if(val.indexOf('@qq.com')){
			//     var index = val.indexOf('@qq.com')
			//     var str = val.substring(0,index)
			//     this.ruleForm.qqNumber=str
			//     console.log(this.ruleForm.qqNumber,str)
			//   }else{
			//     this.ruleForm.qqNumber=''
			//   }
			// },
			handleClose(index) {
				this.ruleForm.positions.splice(index, 1);
			},
			handleChange(val) {
				// console.log(val)
				let res = this.getVal(val, this.departmentList, []);
				this.labelVal = res.join("/");
			},
			getVal(data, options, arr) {
				options.forEach((e) => {
					if(data){
						data.forEach((i) => {
						if (i == e.id) {
							arr.push(e.name || e.position);
							return;
						} else {
							if (e.children) {
								this.getVal([i], e.children, arr);
							} else {
								return;
							}
						}
					});
					}
					
				});
				return arr;
			},
			normalizer(node) {
				if (node.children && !node.children.length) {
					delete node.children;
				}
				return {
					id: node.id,
					label: node.name,
					children: node.children,
				};
			},
			handleAdd() {
				this.disabled=false
				this.title = "新增人员";
				this.pswdshow = true;
				this.visible = true;
				this.ruleForm = {
					tenant:this.userinfo.tenantId,
					gender: 0,
					state: 1,
					positions: [],
					email:''
				};
			},
			handleEdit(row) {
				this.disabled=true
				this.title = "编辑人员";
				this.pswdshow = false;
				this.visible = true;
				// this.ruleForm = { ...row };
				this.ruleForm =JSON.parse(JSON.stringify(row));
			},
			handleDetails(row) {
				this.title = "人员详情";
				this.showvisible = true;
				this.ruleForm.apply = row;
			},
			close() {
				this.positionAndDepartment = {};
				this.pswdshow = false;
				this.visible = false;
				this.showvisible = false;
			},
			getDepartment() {
				this.$api.getAllDepartmentList().then((response) => {
					this.departmentList = response.data;
				});
			},
			getPositionList() {
				this.$api.getAllPositionList().then((response) => {
					this.positionList = response.data;
				});
			},
			getGroupList() {
				this.$api.getAllUserGroupList().then((response) => {
					this.groupList = response.data;
				});
			},
			getTenantList(){
				this.$api.getAllTenantList().then(response => {
						this.tenantList = response.data
					})
			},
			getRoleList() {
        this.$api.getAllRoleList().then((response) => {
          this.roleList = response.data;
          var a = this.userinfo.rList.findIndex((item) => {
              return item.roleId == 1;
              });
              if(a == -1){
                var b = this.roleList.findIndex(i=>{
                  return i.id == 1
                })
                if(b !=-1){
                  this.roleList[b].disabled=true
                }
                
              }else{
                this.roleList[0].disabled=false
              }
        });
      },
			showInputLabel() {
				// console.log(this.positionAndDepartment.hasOwnProperty('department'))
				if(this.positionAndDepartment.hasOwnProperty('department')==true){
					var departmentName = this.getVal(
					[
						this.positionAndDepartment.department[
							this.positionAndDepartment.department.length - 1
						],
					],
					this.departmentList,
					[]
				);
				}else{
					this.positionAndDepartment.department=[''],
					 departmentName=['']
				}
				
				var positionName = this.getVal(
					[this.positionAndDepartment.position],
					this.positionList,
					[]
				);
				this.ruleForm.positions.push({
					position: this.positionAndDepartment.position,
					positionName: positionName[0],
					department:
						this.positionAndDepartment.department[
							this.positionAndDepartment.department.length - 1
						],
					departmentName: departmentName[departmentName.length - 1],
				});
				
				this.positionAndDepartment = {};
				this.labelVal = "";
			},
			getList() {
				this.loading = true;
				this.$api
					.getPersonnelList(this.queryParams)
					.then((response) => {
            			this.tableData = response.data;
						this.total = response.pageColumn.total;
						this.loading = false;
					})
					.catch((error) => {
						this.loading = false;
					});
			},
			handleCurrentChange(val) {
				this.queryParams.current = val;
				this.getList();
			},
			submit() {
				this.$refs.ruleForm.validate((valid) => {
					if (valid) {
						this.btnLoading = true;
						if (this.ruleForm.id) {
							this.$api
								.editPersonnel(this.ruleForm)
								.then((response) => {
									this.$message.success("编辑成功");
									this.btnLoading = false;
									this.getList();
									this.close();
								})
								.catch((error) => {
									this.btnLoading = false;
								});
						} else {
							// this.ruleForm.tenant = this.userinfo.tenantId;
							this.$api
								.addPersonnel(this.ruleForm)
								.then((response) => {
									if(response.code == 200){
										this.$message.success("新增成功");
									}else if(response.code == 0){
										this.$message.error("新增失败")
									}
									// console.log(1212)
									this.btnLoading = false;
									this.getList();
									this.close();
								})
								.catch((error) => {
									this.btnLoading = false;
								});
						}
					} else {
						// console.log("error submit!!");
						return false;
					}
				});
			},
			handleReset(row) {
				this.$confirm("确认将用户密码重置吗？", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				}).then(() => {
					this.loading = true;
					this.$api
						.ResetPassword({ userId: row.id })
						.then((response) => {
							this.$message.success("重置成功");
							this.loading = false;
							this.getList();
						})
						.catch((error) => {
							this.loading = false;
						});
				});
			},
			handleDelete(row) {
				this.$confirm("确认删除本条数据吗？", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				}).then(() => {
					this.loading = true;
					this.$api
						.deletePersonnel({ id: row.id })
						.then((response) => {
							this.$message.success("删除成功");
							this.loading = false;
							this.getList();
						})
						.catch((error) => {
							this.loading = false;
						});
				});
			},
		},
	};
</script>
<style>
	
</style>
<style lang="scss" scoped>
	.el-tag + .el-tag {
		margin-left: 10px;
	}
	.admin-user {
	}
	.marginB {
		margin-bottom: 0;
	}
	
</style>