<template>
  <div class="tenant">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      highlight-current-row
      :action-list="[
        {
          text: '添加用户',
          action: () => openModal(),
        },
      ]"
      @get-list="getList">
    </byTable>

    <el-dialog :title="modalType == 'add' ? '添加用户' : '编辑用户'" v-if="dialogVisible" v-model="dialogVisible" width="600" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #deptId>
          <div style="width: 100%">
            <el-tree-select
              v-model="formData.data.deptId"
              :data="deptList.data"
              check-strictly
              :render-after-expand="false"
              node-key="deptId"
              :props="defaultProps" />
          </div>
        </template>
        <template #account>
          <el-input style="width: 150px; margin-right: 10px" v-model="formData.data.userName" @change="changeUserName" placeholder="请输入用户名"></el-input>
          <el-input style="width: 150px; margin-right: 10px" v-model="formData.data.password" @change="changePassword" placeholder="密码"></el-input>
          <span style="color: #409eff; cursor: pointer" @click="newPassword">随机生成</span>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改密码" v-if="roomDialogVisible" v-model="roomDialogVisible" width="300" v-loading="loading">
      <template #footer>
        <el-input v-model="password" placeholder="请输入新密码" @change="changePassword2" style="margin-bottom: 20px" />
        <el-button @click="roomDialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitPassword(password)" size="large" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const defaultProps = {
  children: "children",
  label: "deptName",
};
const deptList = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    tenantId: useUserStore().user.tenantId,
  },
});
const loading = ref(false);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "部门",
        prop: "deptName",
      },
    },
    {
      attrs: {
        label: "姓名",
        prop: "nickName",
        align: "left",
      },
    },
    {
      attrs: {
        label: "用户名",
        prop: "userName",
      },
    },
    {
      attrs: {
        label: "系统用户",
        prop: "userType",
      },
      render(userType) {
        return userType == 1 ? "是" : "否";
      },
    },
    {
      attrs: {
        label: "手机号",
        prop: "phonenumber",
      },
    },
    {
      attrs: {
        label: "工号",
        prop: "jobNumber",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改密码",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              userId.value = row.userId;
              password.value = "";
              roomDialogVisible.value = true;
            },
          },
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              if (!sourceList.value.pagination.tenantId) {
                ElMessage({
                  message: "请选择租户",
                  type: "warning",
                });
                return;
              }
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                proxy
                  .post(
                    "/tenantUser/" + row.userId,
                    {
                      id: row.userId,
                    },
                    "delete"
                  )
                  .then(() => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy.get("/tenantDept/list", { pageNum: 1, pageSize: 10000, tenantId: useUserStore().user.tenantId }).then((res) => {
    deptList.value.data = proxy.handleTree(res.data, "deptId");
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.get("/tenantUser/list", sourceList.value.pagination).then((res) => {
    res.rows.map((item) => {
      item.deptName = item.dept ? item.dept.deptName : item.dept;
    });
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      type: "slot",
      prop: "deptId",
      slotName: "deptId",
      label: "部门名称",
    },
    {
      type: "input",
      prop: "nickName",
      label: "姓名",
    },
    {
      type: "slot",
      prop: "userName",
      slotName: "account",
      label: "账户信息",
    },
    {
      type: "radio",
      prop: "userType",
      label: "系统用户",
      required: true,
      disabled: true,
      border: true,
      data: [
        {
          label: "是",
          id: 1,
        },
        {
          label: "否",
          id: 0,
        },
      ],
    },
    {
      type: "select",
      label: "角色",
      prop: "roleIds",
      multiple: true,
      data: [],
    },
    {
      type: "input",
      prop: "phonenumber",
      label: "手机号",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "input",
      prop: "jobNumber",
      label: "工号",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
  ];
});
const rules = ref({
  deptId: [{ required: true, message: "请选择部门名称", trigger: "change" }],
  nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
  phonenumber: [{ required: true, message: "请输入手机号", trigger: "blur" }],
});
const getUserList = () => {
  proxy.get(`/tenantRole/list?pageNum=1&pageSize=10000&tenantId=${sourceList.value.pagination.tenantId}`).then((message) => {
    formConfig.value[4].data = message.rows.map((item) => {
      return {
        ...item,
        id: item.roleId,
        label: item.roleName,
      };
    });
  });
};
getUserList();
const openModal = () => {
  modalType.value = "add";
  formData.data = {
    userType: 1,
    tenantId: useUserStore().user.tenantId,
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.password && formData.data.password.length < 5) {
      return ElMessage("密码长度不得低于五位");
    }
    const method = modalType.value == "add" ? "POST" : "PUT";
    proxy.post("/tenantUser", formData.data, method).then(() => {
      if (formData.data.password && formData.data.userId) {
        proxy.post("/tenantUser/resetPwd", { password: formData.data.password, userId: formData.data.userId }, "PUT").then();
      }
      ElMessage({
        message: modalType.value == "add" ? "添加成功" : "编辑成功",
        type: "success",
      });
      dialogVisible.value = false;
      getList();
    });
  });
};
const getDtl = (row) => {
  dialogVisible.value = true;
  proxy.get(`/tenantUser/${row.userId}`).then((res) => {
    formData.data = { ...row, roleIds: res.roleIds };
    modalType.value = "edit";
  });
};
const newPassword = () => {
  formData.data.password = generatePassword();
};
const generatePassword = () => {
  var length = 12,
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    password = "";
  for (var i = 0, n = charset.length; i < length; ++i) {
    password += charset.charAt(Math.floor(Math.random() * n));
  }
  return password;
};
const userId = ref("");
const password = ref("");
const roomDialogVisible = ref(false);
const submitPassword = (password1) => {
  if (!password1) {
    ElMessage({
      message: "请输入新密码",
      type: "warning",
    });
    return;
  }
  if (password1.length < 5) {
    return ElMessage("密码长度不得低于五位");
  }
  proxy
    .post(
      "/tenantUser/resetPwd",
      {
        password: password1,
        userId: userId.value,
      },
      "PUT"
    )
    .then(() => {
      ElMessage({
        message: "重置成功",
        type: "success",
      });
      roomDialogVisible.value = false;
      password.value = "";
    });
};
const changeUserName = (val) => {
  formData.data.userName = val.trim();
};
const changePassword = (val) => {
  formData.data.password = val.trim();
};
const changePassword2 = (val) => {
  password.value = val.trim();
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
