<template>
  <div class="user">
    <div class="tree">
      <treeList :data="treeListData" v-model="sourceList.pagination.tenantId" node-key="id" @change="treeChange"> </treeList>
    </div>
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        searchKey="userName"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[
          {
            text: '添加用户',
            action: () => openModal('add'),
            disabled: !sourceList.pagination.tenantId,
          },
        ]"
        @get-list="getList">
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>
      </byTable>
    </div>
    <el-dialog :title="modalType == 'add' ? '添加用户' : '编辑用户'" v-if="dialogVisible" v-model="dialogVisible" width="500" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
        <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="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm('byform')" size="large" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="修改密码" v-model="roomDialogVisible" width="300" :before-close="handleClose" v-loading="loading">
      <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" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import treeList from "@/components/treeList/index";
import { computed, defineComponent, ref } from "vue";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
const validatePass = (rule, value, callback) => {
  if (!formData.data.password && modalType.value == "add") {
    callback(new Error("请输入账号和密码"));
  } else {
    callback();
  }
};
let 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 userId = ref("");
const { proxy } = getCurrentInstance();
const password = ref("");
const roomDialogVisible = ref(false);
const selectConfig = computed(() => {
  return [];
});
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: "300",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改密码",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              console.log(row);
              userId.value = row.userId;
              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((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeListData = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "treeSelect",
      prop: "deptId",
      label: "部门名称",
      data: [],
    },
    {
      type: "input",
      prop: "nickName",
      label: "姓名",
      required: true,
      itemWidth: 50,
      //disabled:true,
      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,
      //disabled:true,
      itemType: "text",
    },
    {
      type: "input",
      prop: "jobNumber",
      label: "工号",
      required: true,
      itemWidth: 50,
      //disabled:true,
      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 getTreeList = () => {
  proxy.post("/tenantInfo/list").then((message) => {
    message.map((item) => {
      item.label = item.enterpriseName;
      item.id = item.tenantId;
      item.children = [];
    });

    treeListData.value = message;
    console.log(treeListData.value);
  });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.get("/tenantUser/list", sourceList.value.pagination).then((message) => {
    message.rows.map((item) => {
      item.deptName = item.dept ? item.dept.deptName : item.dept;
    });
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

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,
      };
    });
  });
};

const treeChange = (e) => {
  console.log(e);
  sourceList.value.pagination.tenantId = e.id;
  getList({ tenantId: e.id });
  getUserList();
  getDept();
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    userType: 1,
  };
};
const TreetenantId = ref("");
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
  console.log(_selection.length);
};

const tree = ref(null);
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const method = modalType.value == "add" ? "POST" : "PUT";
    console.log(method);
    proxy
      .post(
        "/tenantUser",
        {
          ...formData.data,
          tenantId: sourceList.value.pagination.tenantId,
        },
        method
      )
      .then((res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
        getDept();
      });
  });
};
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("/tenantDept/list", {
      pageNum: 1,
      tenantId: sourceList.value.pagination.tenantId,
    })
    .then((message) => {
      recursive(message.data);
      formConfig.value[0].data = proxy.handleTree(message.data, "deptId");
      console.log(formConfig.value[0].data);
    });
};

const submitPassword = (password1) => {
  if (!password1) {
    ElMessage({
      message: "请输入新密码",
      type: "warning",
    });
    return;
  }
  proxy
    .post(
      "/tenantUser/resetPwd",
      {
        password: password1,
        userId: userId.value,
      },
      "PUT"
    )
    .then((res) => {
      ElMessage({
        message: "重置成功",
        type: "success",
      });
      roomDialogVisible.value = false;
      password.value = "";
    });
};

const getDtl = (row) => {
  //system/user/1
  proxy.get(`/tenantUser/${row.userId}`).then((res) => {
    console.log(res);
    formData.data = { ...row, roleIds: res.roleIds };
    modalType.value = "edit";
    console.log(modalType.value);
    dialogVisible.value = true;
  });
};
getTreeList();
getList();
</script>

<style lang="scss" scoped>
.user {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  background-color: white;
  .tree {
    width: 300px;
  }

  .content {
    width: calc(100% - 320px);
  }
}
</style>
