<template>
  <div>
    <el-card class="box-card">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :action-list="[
          {
            text: '添加账号',
            action: () => clickAdd(),
          },
        ]"
        @get-list="getList"
        @clickReset="clickReset">
        <template #code="{ item }">
          <div>
            <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickCode(item)">{{ item.code }}</a>
          </div>
        </template>
      </byTable>
    </el-card>

    <el-dialog :title="modalType == 'add' ? '添加账号' : '编辑账号'" v-if="openDialog" v-model="openDialog" width="600">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #account>
          <el-input style="width: 150px; margin-right: 10px" v-model="formData.data.userName" placeholder="请输入用户名"></el-input>
          <el-input style="width: 150px; margin-right: 10px" v-model="formData.data.password" placeholder="密码"></el-input>
          <span style="color: #409eff; cursor: pointer" @click="newPassword">随机生成</span>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openDialog = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large" v-preReClick>确 定</el-button>
      </template>
    </el-dialog>

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

<script setup>
import byTable from "/src/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "/src/components/byForm/index";

const { proxy } = getCurrentInstance();
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    tenantId: "000000",
  },
});
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: "sysRoleList",
      },
      render(sysRoleList) {
        return sysRoleList.map((item) => item.roleName).join(",");
      },
    },
    {
      attrs: {
        label: "手机号",
        prop: "phonenumber",
      },
    },
    {
      attrs: {
        label: "工号",
        prop: "jobNumber",
      },
    },
    {
      attrs: {
        label: "操作",
        width: 220,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改密码",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              userId.value = row.userId;
              roomDialogVisible.value = true;
            },
          },
          {
            attrs: {
              label: "编辑",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickUpdate(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 getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
      tenantId: "000000",
    };
  } else {
    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);
  });
};
getList();
const clickReset = () => {
  getList("", true);
};
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.deptId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};
const getDept = () => {
  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,
      };
    });
  });
  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      tenantId: sourceList.value.pagination.tenantId,
    })
    .then((message) => {
      recursive(message.data);
      formConfig.value[0].data = proxy.handleTree(message.data, "deptId");
    });
};
getDept();
const formOption = reactive({
  inline: true,
  labelWidth: "100px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {},
  treeData: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "treeSelect",
      prop: "deptId",
      label: "部门名称",
      data: [],
    },
    {
      type: "input",
      prop: "nickName",
      label: "姓名",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      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 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 validatePass = (rule, value, callback) => {
  if (!formData.data.password && modalType.value == "add") {
    callback(new Error("请输入账号和密码"));
  } else {
    callback();
  }
};
const rules = ref({
  roleKey: [{ required: true, message: "请选择部门", trigger: "blur" }],
  nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  userName: [{ validator: validatePass, required: true, message: "请输入账号和密码", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
});
const openDialog = ref(false);
const modalType = ref("add");
const submit = ref(null);
const clickAdd = () => {
  modalType.value = "add";
  formData.data = {
    userType: 1,
    tenantId: "000000",
  };
  openDialog.value = true;
};
const clickUpdate = (item) => {
  proxy.get(`/tenantUser/${item.userId}`).then((res) => {
    formData.data = { ...item, roleIds: res.roleIds };
    modalType.value = "edit";
    openDialog.value = true;
  });
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    const method = modalType.value == "add" ? "POST" : "PUT";
    proxy.post("/tenantUser", formData.data, method).then(() => {
      ElMessage({
        message: modalType.value == "add" ? "添加成功" : "编辑成功",
        type: "success",
      });
      openDialog.value = false;
      getList();
    });
  });
};
const userId = ref("");
const password = ref("");
const roomDialogVisible = ref(false);
const submitPassword = (password1) => {
  if (!password1) {
    ElMessage({
      message: "请输入新密码",
      type: "warning",
    });
    return;
  }
  proxy
    .post(
      "/tenantUser/resetPwd",
      {
        password: password1,
        userId: userId.value,
      },
      "PUT"
    )
    .then(() => {
      ElMessage({ message: "重置成功", type: "success" });
      roomDialogVisible.value = false;
      password.value = "";
    });
};
</script>

<style lang="scss" scoped>
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
</style>
