<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="联系人" prop="contactUserName">
        <el-input
          v-model="queryParams.contactUserName"
          placeholder="请输入联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="过期时间">
        <el-date-picker
          v-model="daterangeExpireTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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.common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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">
      <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>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <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="accountCount">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.accountCount === -1">不限制</el-tag>
          <el-tag v-else>{{ scope.row.accountCount }}人</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租户状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </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-key"
            @click="handleResetPassword(scope.row)"
            v-if="!(scope.row.tenantId === defaultTenantId)"
            v-hasPermi="['system:tenant:resetPassword']"
          >重置密码
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tenant:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="!(scope.row.tenantId === defaultTenantId)"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:tenant: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"
    />

    <!-- 添加或修改租户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" maxlength="50"
                    :disabled="form.tenantId !== null"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUserName">
          <el-input v-model="form.contactUserName" placeholder="请输入联系人" maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="关联套餐" prop="tenantPackageId" v-if="!(form.tenantId === defaultTenantId)">
          <el-select v-model="form.tenantPackageId" placeholder="请选择关联套餐" filterable clearable>
            <el-option
              v-for="item in listSysTenantPackage"
              :key="item.tenantPackageId"
              :label="item.name"
              :value="item.tenantPackageId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户账号" prop="userName"
                      v-if="!(form.tenantId === defaultTenantId) && form.tenantId === null">
          <el-input v-model="form.userName" placeholder="请输入用户账号" maxlength="30"
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="密码" prop="password"
                      v-if="!(form.tenantId === defaultTenantId) && form.tenantId === null">
          <el-input v-model="form.password" placeholder="请输入密码" maxlength="100" show-password
                    show-word-limit/>
        </el-form-item>
        <el-form-item label="企业简介" prop="intro">
          <el-input v-model="form.intro" type="textarea" placeholder="请输入企业简介" maxlength="255"
                    show-word-limit/>
        </el-form-item>
        <el-form-item>
          <el-link type="warning" :underline="false">注意：用户数量为-1时，用户数量不限制</el-link>
        </el-form-item>
        <el-form-item label="用户数量" prop="accountCount">
          <el-input-number v-model="form.accountCount" controls-position="right" :min="-1"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-link type="warning" :underline="false">注意：不选择过期时间时，租户过期时间不限制</el-link>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker clearable
                          v-model="form.expireTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="租户状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="255"
                    show-word-limit/>
        </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 {addTenant, delTenant, getTenant, listTenant, resetTenantPwd, updateTenant} from "@/api/system/tenant";
import {listSysTenantPackageVo} from "@/api/system/tenantPackage";

export default {
  name: "Tenant",
  dicts: ['common_status'],
  data() {
    return {
      // 默认租户
      defaultTenantId: '1876087600774053888',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户管理表格数据
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新者时间范围
      daterangeExpireTime: [],
      // 更新者时间范围
      daterangeCreateTime: [],
      // 更新者时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantPackageId: null,
        contactUserName: null,
        contactPhone: null,
        companyName: null,
        expireTime: null,
        status: null,
        creator: null,
        createTime: null,
        updater: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          {required: true, message: "请输入企业名称", trigger: "blur"}
        ],
        contactUserName: [
          {required: true, message: "请输入联系人", trigger: "blur"}
        ],
        contactPhone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'}
        ],
        tenantPackageId: [
          {required: true, message: "请选择关联套餐", trigger: "change"}
        ],
        userName: [
          {required: true, message: "请输入用户账号", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"}
        ]
      },
      // 租户套餐
      listSysTenantPackage: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询租户套餐列表 */
    listSysTenantPackageVoFun() {
      listSysTenantPackageVo().then(response => {
        this.listSysTenantPackage = response.data;
      })
    },

    /** 查询租户管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeExpireTime && '' != this.daterangeExpireTime) {
        this.queryParams.params["beginExpireTime"] = this.daterangeExpireTime[0];
        this.queryParams.params["endExpireTime"] = this.daterangeExpireTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tenantId: null,
        tenantPackageId: null,
        contactUserName: null,
        contactPhone: null,
        companyName: null,
        userName: null,
        password: null,
        intro: null,
        accountCount: -1,
        expireTime: null,
        status: '0',
        delFlag: null,
        remark: null,
        creator: null,
        createTime: null,
        updater: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeExpireTime = [];
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tenantId)
      this.single = selection.length !== 1

      for (let i = 0; i < selection.length; i++) {
        if (selection[i].tenantId === this.defaultTenantId) {
          this.multiple = true
          break
        } else {
          this.multiple = !selection.length
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.listSysTenantPackageVoFun()
      this.open = true;
      this.title = "添加租户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.listSysTenantPackageVoFun()
      const tenantId = row.tenantId || this.ids
      getTenant(tenantId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改租户管理";
      });
    },
    /**
     * 重置租户密码
     */
    handleResetPassword(row) {
      this.$prompt('请输入"' + row.companyName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {
        resetTenantPwd({tenantId: row.tenantId, password: value},).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tenantId != 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 tenantIds = row.tenantId || this.ids;
      this.$modal.confirm('是否确认删除租户管理编号为"' + tenantIds + '"的数据项？').then(function () {
        return delTenant(tenantIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>
