<template>
  <div class="app-container">
    <el-form style="background-color: #fff; padding: 15px 5px; border-radius:10px;"  :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <p class="bgtan" style="margin-top: 0;">搜索条件</p>
	 <el-form-item label="客户端key" prop="clientKey">
	   <el-input v-model="queryParams.clientKey" placeholder="请输入客户端key" clearable @keyup.enter="handleQuery" />
	 </el-form-item>
	 <el-form-item label="客户端秘钥" prop="clientSecret">
	   <el-input v-model="queryParams.clientSecret" placeholder="请输入客户端秘钥" clearable @keyup.enter="handleQuery" />
	 </el-form-item>
	 <el-form-item label="状态" prop="status">
	   <el-select v-model="queryParams.status" placeholder="状态" clearable>
	     <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
	   </el-select>
	 </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style=" border-top-left-radius: 12px; border-top-right-radius: 12px; background-color: #fff;margin: 0;margin-top: 20px;padding: 10px 5px; ">
      <p class="bgtan" style="margin-top: 0;">客户端管理信息</p>
	  <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="[ 'system:client:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:client:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:client:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:client:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
     <div style="background-color: #fff; padding: 0 10px;  padding-bottom: 40px; border-bottom-left-radius: 12px; border-bottom-right-radius: 12px;">
		<el-table border :max-height="tableMaxHeight" v-loading="loading" :data="clientList" @selection-change="handleSelectionChange">
		  <el-table-column type="selection" width="55" align="center" />
		  <!-- <el-table-column label="ID" align="center" prop="id" /> -->
		 <el-table-column label="客户端id" align="center" prop="clientId" />
		 <el-table-column label="客户端key" align="center" prop="clientKey" />
		 <el-table-column label="客户端秘钥" align="center" prop="clientSecret" />
		 <el-table-column label="授权类型" align="center">
		   <template slot-scope="scope">
		     <div v-for="(type, index) in scope.row.grantTypeList" :key="index">
		         <dict-tag class="el-check-tag" :options="dict.type.sys_grant_type" :value="type" />
		     </div>
		   </template>
		 </el-table-column>
		 <el-table-column label="设备类型" align="center">
		   <template slot-scope="scope">
		     <dict-tag :options="dict.type.sys_device_type" :value="scope.row.deviceType" />
		   </template>
		 </el-table-column>
		 <el-table-column label="Token活跃超时时间" align="center" prop="activeTimeout" />
		 <el-table-column label="Token固定超时时间" align="center" prop="timeout" />
		 <el-table-column label="状态" align="center" key="status">
		   <template slot-scope="scope">
		     <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
		   </template>
		 </el-table-column>
		  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
		    <template slot-scope="scope">
		      <el-button
		        size="mini"
		        type="text"
		        icon="el-icon-edit"
		        @click="handleUpdate(scope.row)"
		        v-hasPermi="[ 'system:client:edit']"
		      >修改</el-button>
		      <el-button
		        size="mini"
		        type="text"
		        icon="el-icon-delete"
		        @click="handleDelete(scope.row)"
		        v-hasPermi="['system:client:remove']"
		      >删除</el-button>
		    </template>
		  </el-table-column>
		</el-table>
		
		<pagination
		  v-show="total>0"
		  :total="total"
		  :page.sync="queryParams.pageNum"
		  :limit.sync="queryParams.pageSize"
		  @pagination="getList"
		/> 
	 </div>
    

    <!-- 添加或修改注册-老师-班级（学科）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <!-- <el-form-item label="老师id" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入老师id" />
        </el-form-item> -->
		<el-row>
			<el-col :span="12">
				  <el-form-item label="客户端key" prop="clientKey">
				    <el-input v-model="form.clientKey" :disabled="form.id != null" placeholder="请输入客户端key" />
				  </el-form-item>
			</el-col>
			<el-col :span="12">
				  <el-form-item label="客户端秘钥" prop="clientSecret">
				    <el-input v-model="form.clientSecret" :disabled="form.id != null" placeholder="请输入客户端秘钥" />
				  </el-form-item>
			</el-col>
			<el-col :span="24">
				<el-col :span="12">
					 <el-form-item label="授权类型" prop="grantTypeList">
					   <el-select v-model="form.grantTypeList" multiple placeholder="请输入授权类型">
					     <el-option v-for="dict in dict.type.sys_grant_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
					   </el-select>
					 </el-form-item>
				</el-col>
				<el-col :span="12">
					 <el-form-item label="设备类型" prop="deviceType">
					   <el-select v-model="form.deviceType" placeholder="请输入设备类型">
					     <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
					   </el-select>
					 </el-form-item>
				</el-col>
			</el-col>
			
			<el-col :span="24">
				
				<el-col :span="12">
					  <el-form-item label="Token活跃超时时间" prop="activeTimeout" >
						<el-tooltip content="指定时间无操作则过期（单位：秒），默认30分钟（1800秒）" placement="top">
					    <el-input v-model="form.activeTimeout" placeholder="请输入Token活跃超时时间" />
						</el-tooltip>
					  </el-form-item>
				</el-col>
				<el-col :span="12">
					  <el-form-item label="Token固定超时时间" prop="timeout" >
						<el-tooltip content="指定时间必定过期（单位：秒），默认七天（604800秒）" placement="top">
					    <el-input v-model="form.timeout" placeholder="请输入Token固定超时时间" />
						</el-tooltip>
					  </el-form-item>
				</el-col>
			</el-col>
			
			

			<el-col :span="24">
				<el-form-item label="状态">
				  <el-radio-group v-model="form.status">
				    <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">
				      {{ dict.label }}
				    </el-radio>
				  </el-radio-group>
				</el-form-item>
			</el-col>
		</el-row>
        <!-- <el-form-item label="班级id" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入班级id" />
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listClient, getClient, delClient, addClient, updateClient, changeStatus
} from "@/api/system/client";
import { treeselect as menuTreeselect, tenantPackageMenuTreeselect } from "@/api/system/menu";
export default {
  name: "Class",
  dicts: ['sys_subject','sys_normal_disable','sys_grant_type','sys_device_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 注册-老师-班级（学科）表格数据
      clientList: [],
	  openDataScope: false,
	  menuExpand: false,
	  menuNodeAll: false,
	  deptExpand: true,
	  deptNodeAll: false,
	  // 菜单列表
	  menuOptions: [],
	  // 部门列表
	  deptOptions: [],
      // 弹出层标题
      title: "",
	  tableMaxHeight:400,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
       pageNum: 1,
       pageSize: 10,
       clientId: null,
       clientKey: null,
       clientSecret: null,
       grantType: null,
       deviceType: null,
       activeTimeout: null,
       timeout: null,
       status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
       id: [
         { required: true, message: "id不能为空", trigger: "blur" }
       ],
       clientId: [
         { required: true, message: "客户端id不能为空", trigger: "blur" }
       ],
       clientKey: [
         { required: true, message: "客户端key不能为空", trigger: "blur" }
       ],
       clientSecret: [
         { required: true, message: "客户端秘钥不能为空", trigger: "blur" }
       ],
       grantTypeList: [
         { required: true, message: "授权类型不能为空", trigger: "change" }
       ],
       deviceType: [
         { required: true, message: "设备类型不能为空", trigger: "change" }
       ],
      },
	  deptOptions:[],
	  kiuesegh:[],
	  kiueseghs:[],
	  fku:false
	  
    };
  },
  created() {
	  window.onresize = () => {
	            this.changeTableMaxHeight()
	          }
	          this.changeTableMaxHeight()
    this.getList();
	// this.getdept(0)
  },
  mounted() {
  	window.onresize = () => {
  	          this.changeTableMaxHeight()
  	        }
  	        this.changeTableMaxHeight()
  },
  methods: {
	  
	  getdept(val){
	  		  let kuesf=  {'parentId':val}
	  		  // this.kiuesegh = []
			  console.log(kuesf)
	  		listDepts(kuesf).then(response => {
	  		  this.deptOptions = this.handleTree(response.data, "deptId");
	  		  this.deptOptions.filter(rou =>{
	  			  if(rou.children != undefined){
	  			  	rou.children.filter(rour =>{
	  			  					  this.kiuesegh.push(rour)
	  			  	})		  
	  			  }
	  			  // this.kiuesegh = rou.children
	  			  // this.kiuesegh.push(rou.children)
	  			  console.log(rou.children)
	  		  })
	  		  this.kiueseghs = this.kiuesegh
	  		  // this.deptOptions = response.data
	  		  console.log(this.kiuesegh)
	  		});  
	  },
	  getdeptfr(val){
	  		  let kuesf=  {'parentId':val}
	  		  // this.kiuesegh = []
	  			  console.log(kuesf)
	  		this.kiuesegh = []
	  		listDeptode(kuesf).then(response => {
	  		  this.kiuesegh = this.handleTree(response.data, "deptId");
	  		  console.log(this.kiuesegh)
	  		});  
	  },
    /** 查询注册-老师-班级（学科）列表 */
    getList() {
      this.loading = true;
      listClient(this.queryParams).then(response => {
        this.clientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
		this.form={
			id: undefined,
			clientId: undefined,
			clientKey: undefined,
			clientSecret: undefined,
			grantTypeList: undefined,
			deviceType: undefined,
			activeTimeout: undefined,
			timeout: undefined,
			status: undefined,
		}
    
     this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
	  this.getMenuTreeselect();
      this.open = true;
      this.title = "添加租户套餐";
	  this.form.schoolId =  this.$store.state.user.schoolId
	  this.fku = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
	 const roleId = row.id || this.ids
	 // const roleMenu = this.getPackageMenuTreeselect(roleId);
	 getClient(roleId).then(response => {
	   this.form = response.data;
	   this.open = true;
	   
	   this.title = "修改信息";
	 });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            // this.form.menuIds = this.getMenuAllCheckedKeys();
            updateClient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // this.form.menuIds = this.getMenuAllCheckedKeys();
            addClient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
	/** 修改状态 */
	handleStatusChange(row) {
		let text = row.status === "0" ? "启用" : "停用";
	  const ids = row.id || this.ids;
	  // delClass(ids).then(response => {
	  // 		this.getList();
	  // 		this.$modal.msgSuccess("删除成功");
	  // });
	  this.$modal.confirm("确认要\"" + text + "\"\"" + row.packageName + "\"套餐吗？").then(function() {
	    return changeStatus(row.packageId, row.status);
	  }).then(() => {
	    this.getList();
	    this.$modal.msgSuccess("操作成功");
	  }).catch(() => {
		  row.status = row.status === "0" ? "1" : "0";
	  });
	},
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
	  // delClass(ids).then(response => {
	  // 		this.getList();
	  // 		this.$modal.msgSuccess("删除成功");
	  // });
      this.$modal.confirm('是否确认删除"' + ids + '"的数据项？').then(function() {
        return delClient(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/client/export', {
        ...this.queryParams
      }, `class_${new Date().getTime()}.xlsx`)
    },
	mjyhess(val){
		this.form.className = val.deptName
	},
	mjyhes(val){
		console.log(val,this.form.schoolName)
		this.form.schoolName = val.deptName
		this.kiuesegh = []
		let kuesf= {'parentId':val.deptId} 
		listDeptode(kuesf).then(response => {
		  this.kiuesegh = this.handleTree(response.data, "deptId");
		  console.log(this.kiuesegh)
		});  
		// this.getdept(val.deptId)
	},
	/** 查询菜单树结构 */
	getMenuTreeselect() {
	  menuTreeselect().then(response => {
	    this.menuOptions = response.data;
	  });
	},
	// 所有菜单节点数据
	getMenuAllCheckedKeys() {
	  // 目前被选中的菜单节点
	  let checkedKeys = this.$refs.menuTreeRef.getCheckedKeys();
	  // 半选中的菜单节点
	  let halfCheckedKeys = this.$refs.menuTreeRef.getHalfCheckedKeys();
	  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
	  return checkedKeys;
	},
	/** 根据角色ID查询菜单树结构 */
	getPackageMenuTreeselect(packageId) {
	  return tenantPackageMenuTreeselect(packageId).then(response => {
	    this.menuOptions = response.data.menus;
	    return response;
	  });
	},
	// 所有部门节点数据
	getDeptAllCheckedKeys() {
	  // 目前被选中的部门节点
	  let checkedKeys = this.$refs.dept.getCheckedKeys();
	  // 半选中的部门节点
	  let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
	  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
	  return checkedKeys;
	},
	// 树权限（展开/折叠）
	handleCheckedTreeExpand(value, type) {
	  if (type == 'menu') {
	    let treeList = this.menuOptions;
	    for (let i = 0; i < treeList.length; i++) {
	      this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
	    }
	  } else if (type == 'dept') {
	    let treeList = this.deptOptions;
	    for (let i = 0; i < treeList.length; i++) {
	      this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
	    }
	  }
	},
	// 树权限（全选/全不选）
	handleCheckedTreeNodeAll(value, type) {
	  if (type == 'menu') {
	    this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
	  } else if (type == 'dept') {
	    this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
	  }
	},
	// 树权限（父子联动）
	handleCheckedTreeConnect(value, type) {
	  if (type == 'menu') {
	    this.form.menuCheckStrictly = value ? true: false;
	  } else if (type == 'dept') {
	    this.form.deptCheckStrictly = value ? true: false;
	  }
	},
	// 获取屏幕高度
	showFilterForm () {
	      this.filterActive = !this.filterActive
	      this.changeTableMaxHeight()
	    },
	
	    changeTableMaxHeight () {
	      let height = document.body.offsetHeight // 网页可视区域高度
	      // if (this.filterActive) {
	      //   this.tableMaxHeight = height - 320
	      // } else {
	        this.tableMaxHeight = height - 250
	      // }
	      console.log(height)
	    }
	
  }
};
</script>

<style scoped lang="scss">
	.bgtan{
		border-left: 3px solid #4775EA;
		padding-left: 10px;
	}
	
	.app-container{
		background-color: #f6f6f6;
		// height: 100vh;
	}
</style>
