<template>
  <div>
    <el-row>
      <baseTableHeader
        title="用户管理"
        @resetSearch="resetSearch"
        @search="search">
        <template #content>
          <el-form :model="searchForm" :inline="true" label-position="right">
            <el-form-item label="姓名：">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别：">
              <el-radio-group v-model="searchForm.sex">
                <el-radio value="男">男</el-radio>
                <el-radio value="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号：">
              <el-input
                v-model="searchForm.phone"
                placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template #operateBtns>
          <el-button size="small" type="primary" @click="add">
            <template #icon>
              <el-icon>
                <CirclePlus />
              </el-icon> </template
            >新增</el-button
          >
        </template>
      </baseTableHeader>
    </el-row>
    <el-card style="margin-top: 8px">
      <base-table :option="tableOption" ref="table">
        <template #colunm>
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="180"
            align="center" />
          <el-table-column prop="sex" label="性别" align="center" />
          <el-table-column prop="role" label="所属角色" align="center">
            <template #default="scope">
              {{
                roleList?.find(
                  (item) => Number(item.id) === Number(scope.row.role)
                )?.name || "无"
              }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.userState"
                size="large"
                width="65px"
                inline-prompt
                active-text="启用"
                @change="stateVal => userStatChange(stateVal as boolean, scope.row)"
                :active-value="1"
                :inactive-value="0"
                inactive-text="禁用" />
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column
            prop="createDate"
            label="创建时间"
            width="180"
            align="center" />
          <el-table-column #default="scope" width="300">
            <el-button size="small" type="primary" @click="view(scope.row)"
              >查看</el-button
            >
            <el-button size="small" type="warning" @click="edit(scope.row)"
              >修改</el-button
            >
            <el-button size="small" type="danger" @click="deleteData(scope.row)"
              >删除</el-button
            >
            <el-button size="small" type="danger" @click="resetPwd(scope.row)"
              >重置密码</el-button
            >
          </el-table-column>
        </template>
      </base-table>
    </el-card>

    <base-curd-dialog
      v-model="pageVisibleState.show2LevelPage.value"
      :title="pageVisibleState.dialogTitle.value"
      width="50%"
      :before-close="handleDialogClose"
      @addConfim="addConfim"
      @editConfim="editConfim"
      @closeConfirm="handleDialogClose"
      :showPageType="pageVisibleState.showPageType">
      <template #content>
        <userAddOrEdit
          :executeType="pageVisibleState.executeType.value"
          v-if="
            pageVisibleState.showPageType.edit ||
            pageVisibleState.showPageType.add
          "
          :data="(currentUser as userType)"
          @updateData="getUserData">
        </userAddOrEdit>
        <userView
          v-if="pageVisibleState.showPageType.view"
          :data="(currentUser as userType)">
        </userView>
      </template>
    </base-curd-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { resetParams } from "@/util/globalMethods";
import { userType } from "@/types/user";
import { globalState } from "@/store";
import userAddOrEdit from "./page/userAddOrEdit.vue";
import userView from "@/pages/publicPages/user/userView.vue";
import api from "@/lib/request";
import pageVisible from "@/components/curdDialog/pageVisibleState";
import { roleDataList } from "@/lib/api/publicApiList";
import { roleType } from "@/types/role";
import { tableOptionType } from "@/types/table";
const pageVisibleState = new pageVisible({
  add: "新增用户",
  edit: "用户编辑",
  view: "信息查看",
});

const globalStateStore = globalState();
const searchForm = reactive({
  name: "",
  sex: "",
  phone: "",
});

let currentUser = ref<userType>({});
let roleList = ref<roleType[]>();
let table = ref();
let tableOption = ref<tableOptionType>({
  url: "/user/list",
  searchUrl: "/user/query",
  searchParams: searchForm,
  executeType: "list",
});

onMounted(async () => {
  roleList.value = await roleDataList();
});

function view(row: userType) {
  pageVisibleState.showPageType.view = true;
  currentUser.value = row;
}
function edit(row: userType) {
  pageVisibleState.showPageType.edit = true;

  currentUser.value = row;
}
function add() {
  pageVisibleState.showPageType.add = true;
}

function addConfim() {
  ElMessageBox.confirm("确定新增该条信息吗？", "提示", {
    type: "warning",
  }).then(() => {
    globalStateStore.setGlobalLoadingShow(true, "正在提交信息...");
    api()
      .post("/user/add", { ...currentUser.value })
      .then((res) => {
        if (res.code === 200) {
          pageVisibleState.showPageType.add = false;
          pageVisibleState.show2LevelPage.value = false;
          ElMessage.success("新增成功！");
          table.value.methods.setDataType("list");
        } else {
          ElMessage.error(res.msg);
        }
        globalStateStore.setGlobalLoadingShow(false);
      });
  });
}

function getUserData(newVal: any) {
  currentUser.value = { ...newVal.value };
}

function editConfim() {
  ElMessageBox.confirm("确定更改数据吗？", "提示", { type: "warning" }).then(
    () => {
      api()
        .post("/user/update", currentUser.value)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("更改成功！");
            pageVisibleState.show2LevelPage.value = false;
            table.value.methods.setDataType("list");
          }
        });
    }
  );
}

function deleteData(row: userType) {
  ElMessageBox.confirm("确定要删除该用户吗？", "警告", {
    type: "error",
  }).then(() => {
    api()
      .get("/user/delete?id=" + row.id)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success(` ${row.name}  删除成功！`);
          table.value.methods.setDataType("list");
        } else {
          ElMessage.warning(res.msg);
        }
      });
  });
}
function search() {
  table.value.methods.setDataType("search");
}

function resetSearch() {
  resetParams(searchForm);
  table.value.methods.setDataType("reset");
  ElMessage.success("重置成功！");
}

function resetPwd(row: userType) {
  ElMessageBox.confirm("确定要重置该用户的密码吗？", "警告", {
    type: "error",
  }).then(() => {
    api()
      .get("/user/resetPwd?id=" + row.id)
      .then((res) => {
        if (res.code === 200) {
          ElMessageBox.confirm(
            ` ${row.name}  的密码重置成功为123456，请告知用户！`,
            "提示",
            { type: "success" }
          );
        } else {
          ElMessage.error(res.msg);
        }
      });
    ElMessage.success("密码重置成功！");
  });
}
function handleDialogClose() {
  pageVisibleState.show2LevelPage.value = false;
}
function userStatChange(state: boolean, data: userType) {
  api()
    .post("/user/update", {
      userState: state ? 1 : 0,
      id: data.id,
    })
    .then(() => {
      ElMessage.success("用户状态更改成功！");
      table.value.methods.setDataType("list");
    });
}
</script>
<style lang="scss" scoped></style>
