<template>
  <div class="app-container">
    <Filter
      v-model="filterData"
      :config="filterConfig"
      @handleAction="handleFilterData"
      @updateSchool="hanldeUpdateSchool"
    />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >添加</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          :disabled="multiple"
          plain
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <!-- 表格 -->
    <Table
      :xbTable="xbTable"
      @tablePageChange="handleTablePageChange"
      @selectionChange="handleSelectionChange"
    >
      <template v-slot:operation="scope">
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleUpdate(scope.row)"
          >编辑</el-button
        >
        <el-button
          link
          type="primary"
          icon="Edit"
          @click="handleResetPwd(scope.row)"
          >重置密码</el-button
        >
        <el-button
          link
          type="danger"
          icon="Delete"
          @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </Table>
    <!-- 编辑新增用户信息 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="diaRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="useUserStore().showAllTenant" label="学校名称">
          <SchoolSelect
            v-model="form.tenantId"
            @updateData="hanldeUpdateFormSchool"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input
            v-model="form.nickName"
            placeholder="请输入"
            clearable
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="所属角色" prop="roleIds">
          <el-select
            v-model="form.roleIds"
            placeholder="请选择"
            multiple
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in formConfig.roleOption"
              :key="dict.roleId"
              :label="dict.roleName"
              :value="dict.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            placeholder="请输入"
            clearable
            maxlength="50"
          />
        </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>
  </div>
</template>

<script setup name="userManage">
import Filter from "@/views/smartCampus/components/Filter/index.vue";
import Table from "@/views/smartCampus/components/Table/index.vue";
import { validatePhone } from "@/utils/validate";
import {
  getRoleListApi,
  getUserListApi,
  addUserApi,
  updateUserApi,
  deleteUserApi,
  getUserDetailsApi,
  resetUserPwdApi,
  exportUserApi,
} from "@/api/smartCampus/index";
import useUserStore from "@/store/modules/user";
import { download } from "@/hooks/download";
const { proxy } = getCurrentInstance();
const selectConfig = ref({
  roleOption: [],
});
const formConfig = ref({
  roleOption: [],
});
const filterData = ref({}); //过滤
const filterConfig = computed(() => {
  return [
    {
      comName: "admin",
      label: "学校名称",
      prop: "tenantId",
      placeholder: "请选择",
      clearable: true,
    },
    {
      comName: "el-input",
      label: "姓名",
      placeholder: "请输入",
      prop: "nickName",
      clearable: true,
    },
    {
      comName: "el-select",
      label: "所属角色",
      prop: "roleId",
      clearable: true,
      options: selectConfig.value.roleOption,
      selectConfig: {
        label: "roleName",
        value: "roleId",
      },
    },
    {
      comName: "el-input",
      label: "联系电话",
      placeholder: "请输入",
      prop: "phonenumber",
      clearable: true,
    },
  ];
});
const title = ref(""); //弹窗标题
const open = ref(false); //弹窗开关
// 弹窗数据
const data = reactive({
  form: {},
  rules: {
    tenantId: [
      { required: true, message: "学校名称不能为空", trigger: "change" },
    ],
    nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    phonenumber: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      {
        required: true,
        validator: validatePhone,
        trigger: "blur",
      },
    ],
    roleIds: [
      { required: true, message: "所属角色不能为空", trigger: "change" },
    ],
  },
});
const { form, rules } = toRefs(data);
const multiple = ref(true); //批量删除
const exportId = ref([]); //批量导出的id
const xbTable = ref({
  loading: false,
  columns: [
    { type: "selection" },
    { prop: "nickName", label: "姓名" },
    { prop: "roleString", label: "所属角色" },
    { prop: "phonenumber", label: "联系电话" },
    { prop: "remark", label: "备注" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
/** 查询列表 */
function getList() {
  xbTable.value.loading = true;
  xbTable.value.tableData = [];
  getUserListApi({ ...xbTable.value.pagination, ...filterData.value }).then(
    (res) => {
      let data = res.rows;
      xbTable.value.loading = false;
      xbTable.value.pagination.total = res.total;
      if (data.length > 0) {
        for (let i in data) {
          let roleList = data[i].roles;
          let roleArray = roleList.length
            ? roleList.map(function (item) {
                return item.roleName;
              })
            : [];
          let roleString = roleArray.length ? roleArray.join(",") : "-";
          xbTable.value.tableData.push({ ...data[i], roleString: roleString });
        }
      }
    }
  );
}
// 过滤按钮
function handleFilterData(type) {
  switch (type.value) {
    case "search":
      getList();
      break;
    case "reset":
      xbTable.value.pagination.pageNum = 1;
      getList();
      break;
  }
}
// 更新学校
function hanldeUpdateSchool() {
  filterData.value.roleId = "";
  getSelectOption(filterData.value.tenantId);
}
// 表单内学校
function hanldeUpdateFormSchool() {
  form.value.roleIds = [];
  getSelectOption(form.value.tenantId);
}

// 下拉框数据
function getSelectOption(tenantId) {
  // 角色
  getRoleListApi({ tenantId }).then((res) => {
    if (res.code === 200) {
      if (open.value) {
        formConfig.value.roleOption = res.rows;
      } else {
        selectConfig.value.roleOption = res.rows;
      }
    }
  });
}
/** 表单重置 */
function reset() {
  form.value = {
    nickName: undefined,
    phonenumber: undefined,
    remark: undefined,
    roleIds: [],
  };
  proxy.resetForm("diaRef");
}
// 添加按钮
function handleAdd() {
  reset();
  title.value = "平台用户管理/添加";
  open.value = true;
  getSelectOption(form.value.tenantId);
}
// 导出
function handleExport() {
  let exportIdString = JSON.stringify(exportId.value);
  exportUserApi(exportIdString).then((res) => {
    download(res, `user_template_${new Date().getTime()}.xlsx`);
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  form.value.tenantId = "";
  reset();
}
// 表格勾选
function handleSelectionChange(val) {
  exportId.value = val.map((item) => item.userId);
  multiple.value = !val.length;
}
// 表格分页
function handleTablePageChange(val) {
  xbTable.value.pagination.pageSize = val.limit;
  xbTable.value.pagination.pageNum = val.page;
  getList();
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  title.value = "平台用户管理/编辑";
  getUserDetailsApi(row.userId).then((res) => {
    if (res.code === 200) {
      open.value = true;
      form.value = res.data.user;
      form.value.roleIds = res.data.roleIds;
      getSelectOption(form.value.tenantId);
    }
  });
}
// 重置密码
function handleResetPwd(row) {
  proxy.$modal
    .confirm("确定重置该用户的登录密码吗？")
    .then(() => {
      return resetUserPwdApi(row);
    })
    .then(() => {
      proxy.$modal.msgSuccess("重置成功");
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const deleteId = row.userId;
  proxy.$modal
    .confirm("是否确认删除？")
    .then(() => {
      xbTable.value.loading = true;
      return deleteUserApi(deleteId);
    })
    .then(() => {
      xbTable.value.loading = false;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .finally(() => {
      xbTable.value.loading = false;
    });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["diaRef"].validate((valid) => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUserApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUserApi(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 超管
function handleAdminRole() {
  if (useUserStore().showAllTenant) {
    xbTable.value.columns.splice(1, 0, {
      prop: "tenantName",
      label: "学校名称",
    });
  }
}
handleAdminRole();
getList();
getSelectOption();
</script>
<style lang="scss" scoped></style>
