<template>
  <div class="system-manage-container user-manage" v-loading="loading">
    <div class="system-manage-header">
      <div class="header-left">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="关键字查询">
            <el-input
              v-model="searchForm.name"
              clearable
              @keydown.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="header-right">
        <el-form>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增用户</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="system-manage-content manage-content">
      <common-table
        :autoHeight="true"
        :data="tableData"
        :columns="tableColumns"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        title=""
        :index="true"
        :border="true"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentPageChange"
      >
        <template #departs="{ row }">
          <div>{{ row.departs?.map((item) => item.name).join(",") }}</div>
        </template>
        <template #positions="{ row }">
          <div>{{ row.positions?.map((item) => item.name).join(",") }}</div>
        </template>
        <template #roles="{ row }">
          <div>{{ row.roles?.map((item) => item.name).join(",") }}</div>
        </template>
        <template #enable="{ row }">
          <el-switch
            :model-value="row.enable === 0 ? true : false"
            @change="handleStatusChange($event, row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>

        <template #operations="{ row, index }">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleEdit(row, index)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(row, index)"
          >
            删除
          </el-button>
        </template>
      </common-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="cancelUserForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="userFormData"
        ref="userForm"
        :rules="userRules"
        label-width="100"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="userFormData.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="userFormData.mobile"
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-tree-select
            v-model="userFormData.departs"
            :data="departmentData"
            node-key="id"
            :props="{ label: 'name' }"
            placeholder="请选择所属部门"
            multiple
            :render-after-expand="false"
          />
        </el-form-item>
        <!-- <el-form-item label="岗位">
            <el-select v-model="userFormData.positions"
              multiple
              placeholder="请选择岗位" no-data-text="暂无数据"
            >
                <el-option v-for="item in positionsData" :key="item.id"
                    :label="item.name" :value="item.id"
                ></el-option>
            </el-select>
        </el-form-item> -->
        <el-form-item label="角色">
          <el-select
            v-model="userFormData.roles"
            multiple
            placeholder="请选择角色"
            no-data-text="暂无数据"
          >
            <el-option
              v-for="item in rolesData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="userFormData.enable">
            <el-radio :value="0">启用</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUserForm">取消</el-button>
          <el-button type="primary" @click="saveUserForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import CommonTable from "@/components/common/commonTable.vue";

const { proxy } = getCurrentInstance();
const loading = ref(false);

// 查询表单数据
const searchForm = ref({});
// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 表格列配置
const tableColumns = [
  {
    prop: "name",
    label: "用户姓名",
    minWidth: 100,
    showOverflowTooltip: true,
  },
  {
    prop: "mobile",
    label: "手机号码",
    minWidth: 100,
  },
  {
    prop: "departs",
    label: "所属部门",
    minWidth: 120,
    slot: "departs",
    showOverflowTooltip: true,
  },
  // {
  //   prop: "positions",
  //   label: "岗位",
  //   minWidth: 100,
  //   slot: "positions",
  //   showOverflowTooltip: true,
  // },
  {
    prop: "roles",
    label: "角色",
    minWidth: 100,
    slot: "roles",
    showOverflowTooltip: true,
  },
  // {
  //   prop: "createdAt",
  //   label: "创建时间",
  //   minWidth: 160,
  // },
  {
    prop: "enable",
    label: "状态",
    width: 100,
    slot: "enable",
    align: "center",
  },
  {
    prop: "operations",
    label: "操作",
    width: 120,
    slot: "operations",
    fixed: "right",
    align: "center",
  },
];

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增用户");

// 用户表单数据
const userForm = ref();
const userFormData = ref({
  enable: 0,
});
const departmentData = ref([]);
const rolesData = ref([]);

const loadDepartmentData = () => {
  proxy.$post({
    url: "/api/user/depart/treeDepart",
    data: {},
    callback: (data) => {
      departmentData.value = data;
    },
    error: (err) => {},
  });
};

// 角色下拉数据
const loadRolesData = () => {
  proxy.$post({
    url: "/api/user/role/listRole",
    data: {
      page: 1,
      pageSize: 10,
    },
    callback: (data) => {
      rolesData.value = data.rows;
    },
    error: (err) => {},
  });
};
// 表单验证规则
const userRules = {
  name: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],
  mobile: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
};

// 事件处理函数
const handleSearch = (formData) => {
  currentPage.value = 1;
  loadTableData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadTableData();
};

const handleCurrentPageChange = (page) => {
  currentPage.value = page;
  loadTableData();
};

// 新增用户
const handleAdd = () => {
  dialogTitle.value = "新增用户";
  dialogVisible.value = true;
};
// 编辑
const handleEdit = (row, index) => {
  dialogTitle.value = "编辑用户";
  proxy.$post({
    url: "/api/user/manage/getUserInfo",
    data: { id: row.id },
    callback: (data) => {
      userFormData.value = { ...data };
      userFormData.value.departs = data.departs.map((item) => item.id);
      userFormData.value.roles = data.roles.map((item) => item.id);
    },
    error: (err) => {
      ElMessage.error("编辑失败:", err);
    },
  });
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row, index) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户"${row.name}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    proxy.$post({
      url: "/api/user/manage/deleteUser",
      data: { id: row.id },
      callback: (data) => {
        loadTableData();
        ElMessage.success("删除成功");
      },
      error: (err) => {
        ElMessage.error("删除失败:", err);
      },
    });
  } catch {}
};

const saveUserForm = () => {
  userForm.value.validate((valid) => {
    if (valid) {
      let url = userFormData.value.id ? "updateUser" : "createUser";
      proxy.$post({
        url: "/api/user/manage/" + url,
        data: userFormData.value,
        callback: (data) => {
          dialogVisible.value = false;
          loadTableData();
          ElMessage.success(dialogTitle.value + "成功");
        },
        error: (err) => {
          ElMessage.error(dialogTitle.value + "失败:", err);
        },
      });
    }
  });
};
const cancelUserForm = () => {
  userFormData.value = {};
  userForm.value.resetFields();
  dialogVisible.value = false;
};

// 处理状态切换
const handleStatusChange = (newValue, row) => {
  const newEnableValue = newValue ? "0" : "1";

  proxy.$post({
    url: "/api/user/manage/updateUser",
    data: {
      id: row.id,
      enable: newEnableValue,
    },
    callback: (data) => {
      loadTableData();
      ElMessage.success(
        `用户状态已${newEnableValue === "0" ? "启用" : "停用"}`,
      );
    },
    error: (err) => {
      ElMessage.error("状态更新失败");
    },
  });
};

// 表格数据
const loadTableData = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/user/manage/listUser",
    data: {
      ...searchForm.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    },
    callback: (data) => {
      tableData.value = data.rows;
      total.value = data.count;
      loading.value = false;
    },
    error: (err) => {
      loading.value = false;
      ElMessage.error("加载数据失败");
    },
  });
};

onMounted(() => {
  loadTableData();
  loadDepartmentData();
  // loadPositionsData();
  loadRolesData();
});
</script>

<style scoped lang="less">
@import "@/styles/manage.less";
</style>
