<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      label-position="left"
      label-width="100px"
    >
      <el-form-item label="租户名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          clearable
          placeholder="请输入租户名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="联系人" prop="contactUser">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.contactUser"-->
      <!--            clearable-->
      <!--            placeholder="请输入联系人"-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="联系方式" prop="contactPhone">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.contactPhone"-->
      <!--            clearable-->
      <!--            placeholder="请输入联系方式"-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="到期时间" prop="expireTime">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.expireTime"-->
      <!--            clearable-->
      <!--            placeholder="请输入到期时间"-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="登录用户ID" prop="loginUserId">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.loginUserId"-->
      <!--            clearable-->
      <!--            placeholder="请输入登录用户ID"-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="登录账户" prop="loginAccount">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.loginAccount"-->
      <!--            clearable-->
      <!--            placeholder="请输入登录账户"-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:tenant:add']"
          icon="Plus"
          plain
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:tenant:edit']"
          :disabled="single"
          icon="Edit"
          plain
          type="success"
          @click="handleUpdate"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:tenant:remove']"
          :disabled="multiple"
          icon="Delete"
          plain
          type="danger"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:tenant:export']"
          icon="Download"
          plain
          type="warning"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tenantList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <!--                    <el-table-column label="" align="center" prop="tenantId" />-->
      <el-table-column align="center" label="租户名称" prop="tenantName" />
      <el-table-column align="center" label="联系人" prop="contactUser" />
      <el-table-column align="center" label="联系方式" prop="contactPhone" />
      <el-table-column align="center" label="到期时间" prop="expireTime" />
      <el-table-column align="center" label="状态" prop="status">
        <template #default="{ row }">
          <dict-tag
            :options="tenantStatusOptions"
            :value="[row.status]"
            size="small"
          />
        </template>
      </el-table-column>
      <!--                    <el-table-column label="登录用户ID" align="center" prop="loginUserId" />-->
      <el-table-column align="center" label="登录账户" prop="loginAccount" />
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="scope">
          <el-button
            v-hasPermi="['sys:tenant:edit']"
            icon="Edit"
            link
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            v-hasPermi="['sys:tenant:remove']"
            icon="Delete"
            link
            type="primary"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
          <el-button
            v-if="!scope.row.loginUserId"
            icon="User"
            link
            type="primary"
            @click="handleCreateUser(scope.row)"
          >
            创建登录用户
          </el-button>
          <el-button
            v-if="scope.row.loginUserId"
            icon="User"
            link
            type="primary"
            @click="handleResetPassword(scope.row)"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改租户对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form
        ref="tenantRef"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input v-model="form.contactUser" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="到期时间" prop="expireTime">
          <!--          <el-input v-model="form.expireTime" placeholder="请输入到期时间"/>-->
          <el-date-picker
            v-model="form.expireTime"
            placeholder="请输入到期时间"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <!--        <el-form-item label="登录用户ID" prop="loginUserId">-->
        <!--          <el-input v-model="form.loginUserId" placeholder="请输入登录用户ID"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="登录账户" prop="loginAccount">-->
        <!--          <el-input v-model="form.loginAccount" placeholder="请输入登录账户"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showCreateUserDialog"
      append-to-body
      title="创建登录用户"
      width="500px"
    >
      <el-form
        ref="loginUserRef"
        :model="loginUserForm"
        :rules="loginUserRules"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="手机号码" prop="username">
          <el-input
            v-model="loginUserForm.username"
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <!--        <el-form-item label="邮箱" prop="email">-->
        <!--          <el-input v-model="loginUserForm.email" placeholder="请输入邮箱"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginUserForm.password"
            auto-complete="off"
            placeholder="请输入密码"
            type="password"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="repeatPassword">
          <el-input
            v-model="loginUserForm.repeatPassword"
            auto-complete="off"
            placeholder="请确认密码"
            type="password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitLoginUserForm"
            >确 定
          </el-button>
          <el-button @click="cancelCreateUser">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--重置密码对话框-->
    <el-dialog
      v-model="showResetPasswordDialog"
      append-to-body
      title="重置密码"
      width="420px"
    >
      <el-form
        ref="resetPasswordRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="resetPasswordForm.password"
            auto-complete="off"
            placeholder="请输入密码"
            type="password"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="repeatPassword">
          <el-input
            v-model="resetPasswordForm.repeatPassword"
            auto-complete="off"
            placeholder="请确认密码"
            type="password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitResetPasswordForm"
            >确 定
          </el-button>
          <el-button @click="cancelResetPassword">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Tenant" setup>
import {
  addTenant,
  delTenant,
  getTenant,
  listTenant,
  registerUser,
  updateTenant,
} from "@/api/system/tenant";
import { resetUserPwd } from "@/api/system/user";
import { tenantStatusOptions } from "@/constant/dict";
import DictTag from "@/components/DictTag/index.vue";

const { proxy } = getCurrentInstance();

const tenantList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const showCreateUserDialog = ref(false);
const showResetPasswordDialog = ref(false);

// 创建用户时，验证确认密码
const validateRepeatPass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== loginUserForm.value.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

// 重置密码时，验证确认密码
const validateResetRepeatPass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== resetPasswordForm.value.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantName: null,
    contactUser: null,
    contactPhone: null,
    expireTime: null,
    status: null,
    loginUserId: null,
    loginAccount: null,
  },
  rules: {
    tenantName: [
      { required: true, message: "请输入租户名称", trigger: "blur" },
    ],
  },
  loginUserForm: {},
  loginUserRules: {
    username: [
      {
        required: true,
        message: "请输入手机号码",
        trigger: "blur",
      },
    ],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    repeatPassword: [
      {
        validator: validateRepeatPass,
        trigger: "change",
      },
    ],
  },
  resetPasswordForm: {},
  resetPasswordRules: {
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      {
        pattern: /^.{5,20}$/,
        message: "登录密码长度必须介于5到20之间",
        trigger: "blur",
      },
    ],
    repeatPassword: [
      {
        validator: validateResetRepeatPass,
        trigger: "change",
      },
    ],
  },
});

const {
  queryParams,
  form,
  rules,
  loginUserForm,
  loginUserRules,
  resetPasswordForm,
  resetPasswordRules,
} = toRefs(data);

/** 查询租户列表 */
function getList() {
  loading.value = true;
  listTenant(queryParams.value).then((response) => {
    tenantList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    tenantId: null,
    tenantName: null,
    contactUser: null,
    contactPhone: null,
    expireTime: null,
    status: null,
    createTime: null,
    createBy: null,
    loginUserId: null,
    loginAccount: null,
  };
  proxy.resetForm("tenantRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.tenantId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加租户";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _tenantId = row.tenantId || ids.value;
  getTenant(_tenantId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改租户";
  });
}

function resetLoginUser() {
  loginUserForm.value = {
    username: null,
    password: null,
    repeatPassword: null,
  };
  proxy.resetForm("loginUserRef");
}

function handleCreateUser(row) {
  resetLoginUser();
  loginUserForm.value.username = row.contactPhone;
  loginUserForm.value.tenantId = row.tenantId;
  showCreateUserDialog.value = true;
}

function cancelCreateUser() {
  showCreateUserDialog.value = false;
  resetLoginUser();
}

function resetResetPasswordForm() {
  resetPasswordForm.value = {
    password: null,
    repeatPassword: null,
  };
  proxy.resetForm("resetPasswordRef");
}

function handleResetPassword(row) {
  resetResetPasswordForm();
  resetPasswordForm.value.loginUserId = row.loginUserId;
  showResetPasswordDialog.value = true;
}

function cancelResetPassword() {
  resetResetPasswordForm();
  showResetPasswordDialog.value = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tenantRef"].validate((valid) => {
    if (valid) {
      if (form.value.tenantId != null) {
        updateTenant(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTenant(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function submitLoginUserForm() {
  proxy.$refs["loginUserRef"].validate((valid) => {
    if (valid) {
      registerUser(loginUserForm.value).then((response) => {
        proxy.$modal.msgSuccess("添加登录用户成功");
        showCreateUserDialog.value = false;
        getList();
      });
    }
  });
}

function submitResetPasswordForm() {
  proxy.$refs["resetPasswordRef"].validate((valid) => {
    if (valid) {
      resetUserPwd(
        resetPasswordForm.value.loginUserId,
        resetPasswordForm.value.password
      ).then((response) => {
        proxy.$modal.msgSuccess(
          "修改成功，新密码是：" + resetPasswordForm.value.password
        );
        showResetPasswordDialog.value = false;
        // resetResetPasswordForm()
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _tenantIds = row.tenantId || ids.value;
  proxy.$modal
    .confirm('是否确认删除租户编号为"' + _tenantIds + '"的数据项？')
    .then(function () {
      return delTenant(_tenantIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "sys/tenant/export",
    {
      ...queryParams.value,
    },
    `tenant_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
