<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="联系人" prop="contactUserName">
	    <el-input v-model="queryParams.contactUserName" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
	  </el-form-item>
	  <el-form-item label="联系电话" prop="contactPhone">
	    <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
	  </el-form-item>
	  <el-form-item label="名称" prop="companyName">
	    <el-input v-model="queryParams.companyName" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
	  </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:tenant: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:tenant: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:tenant: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:tenant: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="tenantList" @selection-change="handleSelectionChange">
		  <el-table-column type="selection" width="55" align="center" />
		  <el-table-column label="id" align="center" prop="id" v-if="false" />
		  <el-table-column label="租户编号" align="center" prop="tenantId" />
		  <el-table-column label="联系人" align="center" prop="contactUserName" />
		  <el-table-column label="联系电话" align="center" prop="contactPhone" />
		  <el-table-column label="名称" align="center" prop="companyName" />
		  <!-- <el-table-column label="社会信用代码" align="center" prop="licenseNumber" /> -->
		  <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
		    <template slot-scope="scope">
		      <span>{{scope.row.expireTime}}</span>
		    </template>
		  </el-table-column>
		  <el-table-column label="租户状态" align="center" prop="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 width="150" label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
		    <template slot-scope="scope">
		      <el-tooltip content="修改" placement="top">
		        <el-button link  size="mini"
            type="text"
            icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:tenant:edit']"></el-button>
		      </el-tooltip>
		      <el-tooltip content="同步套餐" placement="top">
		        <el-button link  size="mini"
            type="text"
            icon="el-icon-refresh" @click="handleSyncTenantPackage(scope.row)" v-hasPermi="['system:tenant:edit']">
		        </el-button>
		      </el-tooltip>
		      <el-tooltip content="删除" placement="top">
		        <el-button link  size="mini"
            type="text"
            icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:tenant:remove']"></el-button>
		      </el-tooltip>
		    </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="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="老师id" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入老师id" />
        </el-form-item> -->
		<el-row>
			<el-col :span="8">
				  <el-form-item label="名称" prop="companyName">
				    <el-input v-model="form.companyName" placeholder="请输入名称" />
				  </el-form-item>
			</el-col>
			<el-col :span="8">
				 <el-form-item label="联系人" prop="contactUserName">
				   <el-input v-model="form.contactUserName" placeholder="请输入联系人" />
				 </el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item label="联系电话" prop="contactPhone">
				  <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item v-if="!form.id" label="用户名" prop="username">
				  <el-input v-model="form.username" placeholder="请输入系统用户名" maxlength="30" />
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item v-if="!form.id" label="用户密码" prop="password">
				  <el-input type="password" v-model="form.password" placeholder="请输入系统用户密码" maxlength="20" />
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item label="租户套餐" prop="packageId">
				  <el-select v-model="form.packageId" :disabled="!!form.tenantId" placeholder="请选择租户套餐" clearable style="width: 100%">
				    <el-option v-for="item in packageList" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
				  </el-select>
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item label="过期时间" prop="expireTime">
					<el-date-picker clearable
					  v-model="form.expireTime"
					  type="datetime"
					  value-format="yyyy-MM-dd HH:mm:ss"
					  placeholder="请选择过期时间">
					</el-date-picker>
				  <!-- <el-date-picker clearable v-model="form.expireTime" type="datetime" value-format="yyyy-MM-DD HH:mm:ss" placeholder="请选择过期时间"> -->
				  </el-date-picker>
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item label="用户数量" prop="accountCount">
				  <el-input v-model="form.accountCount" placeholder="请输入用户数量" />
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item label="绑定域名" prop="domain">
				  <el-input v-model="form.domain" placeholder="请输入绑定域名" />
				</el-form-item>
			</el-col>
			<!-- <el-col :span="8">
				<el-form-item label="企业地址" prop="address">
				  <el-input v-model="form.address" placeholder="请输入企业地址" />
				</el-form-item>
			</el-col>
			<el-col :span="8">
				<el-form-item label="企业代码" prop="licenseNumber">
				  <el-input v-model="form.licenseNumber" placeholder="请输入统一社会信用代码" />
				</el-form-item>
			</el-col>
			<el-form-item label="企业简介" prop="intro">
			  <el-input type="textarea" v-model="form.intro" placeholder="请输入企业简介" />
			</el-form-item> -->
			<el-col :span="16">
				<el-form-item label="备注" prop="remark">
				  <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
				</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 { listTenant, getTenant, delTenant, addTenant, updateTenant, changeTenantStatus, syncTenantPackage } from '@/api/zhihuixy/tenant';
import { listDepts,listDeptode} from "@/api/system/dept";
import { selectTenantPackage } from '@/api/zhihuixy/tenantPackage';
export default {
  name: "Class",
  dicts: ['sys_subject'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 注册-老师-班级（学科）表格数据
      tenantList: [],
	  packageList:[],
      // 弹出层标题
      title: "",
	  tableMaxHeight:400,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: '',
        contactUserName: '',
        contactPhone: '',
        companyName: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
       id: [{ required: true, message: "id不能为空", trigger: "blur" }],
       tenantId: [{ required: true, message: "租户编号不能为空", trigger: "blur" }],
       contactUserName: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
       contactPhone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
       companyName: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],
       username: [
         { required: true, message: "用户名不能为空", trigger: "blur" },
         { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
       ],
       password: [
         { required: true, message: "密码不能为空", trigger: "blur" },
         { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
       ]
      },
	  deptOptions:[],
	  kiuesegh:[],
	  kiueseghs:[],
	  fku:false
	  
    };
  },
  created() {
	  window.onresize = () => {
	            this.changeTableMaxHeight()
	          }
	          this.changeTableMaxHeight()
    this.getList();
	// this.getdept(0)
	this.getliet()
  },
  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;
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
	/** 查询所有租户套餐 */
	getliet(){
		this.loading = true;
		selectTenantPackage(this.queryParams).then(response => {
		  this.packageList = response.data;
		  // this.total = response.total;
		  this.loading = false;
		});
	},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        tenantId: undefined,
        contactUserName: '',
        contactPhone: '',
        username: '',
        password: '',
        companyName: '',
        licenseNumber: '',
        domain: '',
        address: '',
        intro: '',
        remark: '',
        packageId: '',
        expireTime: '',
        accountCount: 0,
        status: '0',
      };
      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.open = true;
      this.title = "添加信息";
	  this.form.schoolId =  this.$store.state.user.schoolId
	  this.fku = false
    },
	handleStatusChange(row){
		let text = row.status === "0" ? "启用" : "停用";
		this.$modal.confirm('确认要"' + text  + '"吗？').then(function() {
		  return changeTenantStatus(row.id, row.tenantId, row.status);
		}).then(() => {
		  this.$modal.msgSuccess(text + "成功");
		}).catch(function() {
		  row.status = row.status === "0" ? "1" : "0";
		});
		// let text = row.status === "0" ? "启用" : "停用";
		// changeTenantStatus(row.id, row.tenantId, row.status).then(response => {
		// 	this.$modal.msgSuccess("修改成功");
		// 	row.status = row.status === "0" ? "1" : "0";
		//  });
	},
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
     getTenant(id).then(response => {
		  // this.fku = true
        this.form = response.data;
		// this.form.
		// if(this.form.schoolId != null){
		// 	this.getdeptfr(this.form.schoolId)
		// }
        this.open = true;
        this.title = "修改信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTenant(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTenant(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
	  delTenant(ids).then(response => {
	  		this.getList();
	  		this.$modal.msgSuccess("删除成功");
	  });
      // this.$modal.confirm('是否确认删除注册-老师-班级（学科）编号为"' + ids + '"的数据项？').then(function() {
      //   return delClass(ids);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {});
    },
	/** 同步 */
	handleSyncTenantPackage(row) {
	  const ids = row.tenantId ;
	  // delTenant(ids).then(response => {
	  // 		this.getList();
	  // 		this.$modal.msgSuccess("删除成功");
	  // });
	  this.$modal.confirm('是否确认同步租户套餐租户"' + ids + '"的数据项？').then(function() {
	    return syncTenantPackage(ids,row.packageId);
	  }).then(() => {
	    this.getList();
	    this.$modal.msgSuccess("删除成功");
	  }).catch(() => {});
	},
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tenant/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)
	},
	// 获取屏幕高度
	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>
