<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addRole">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <!-- 添加角色 -->
    <UserModal ref="formRole" :formRoleValue="formRoleValue" />

    <!-- 分配角色 -->
    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      :title="editRoleTitle"
    >
      <n-form
        ref="formRef"
        :rules="rules"
        label-placement="left"
        label-width="auto"
        :model="formRoleValue"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="用户名">
          <n-input
            disabled
            v-model:value="formRoleValue.username"
            placeholder="请输入用户名"
          />
        </n-form-item>

        <n-form-item label="真实姓名">
          <n-input
            disabled
            v-model:value="formRoleValue.realname"
            placeholder="请输入真实姓名"
          />
        </n-form-item>

        <n-form-item label="角色" path="roleIds">
          <n-select
            label-field="roleName"
            value-field="id"
            multiple
            clearable
            v-model:value="formRoleValue.roleIds"
            :options="roleOptions"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button
            type="primary"
            :loading="formBtnLoading"
            @click="confirmForm"
            >提交</n-button
          >
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { BasicTable, TableAction } from "@/components/Table";

import { columns } from "./columns";
import { PlusOutlined } from "@vicons/antd";
import { getUserList, updateUser } from "@/api/system/user";
import { getRuleList } from "@/api/system/role";
import { saveUserRole } from "@/api/system/userrole";
const actionRef = ref();
const formRef = ref();
const formRole = ref();
const rules = {
  // roleIds: {
  //   type: "array",
  //   required: true,
  //   message: "请选择角色",
  //   trigger: ["blur", "change"],
  // },
};
const roleIds = ref([]);
const formRoleValue = reactive({
  id: null,
  username: "",
  realname: null,
  password: "123456",
  userType: 2,
  sex: 1,
  email: "",
  phone: "",
  status: 1,
  skinColor: "white",
  roleIds: [],
});

const roleOptions = ref([]);

const showModal = ref(false);
const formBtnLoading = ref(false);
const editRoleTitle = ref("");
const params = reactive({
  username: "",
});

const actionColumn = reactive({
  width: 250,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record) {
    return h(TableAction, {
      style: "button",
      actions: [
        {
          label: "配置角色",
          onClick: handleMenuAuth.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
        },
        {
          label: "编辑",
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
        },
        {
          label: "删除",
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
        },
      ],
    });
  },
});

// 新增按钮
const addRole = () => {
  formRole.value.init("add");
};

const loadDataTable = async (res: any) => {
  let _params = {
    ...unref(params),
    ...res,
  };
  const { data } = await getUserList(_params);
  return data;
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

async function confirmForm() {
  formRef.value.validate(async (errors: any) => {
    if (!errors) {
      formBtnLoading.value = true;

      const res = await saveUserRole({
        userId: formRoleValue.id,
        roleIds: formRoleValue.roleIds,
      });
      if (res.status === 200) {
        showModal.value = false;
        window["$message"].success("保存成功");
        reloadTable();
        formBtnLoading.value = false;
      }
    }
  });
}

function handleEdit(record: Recordable) {
  Object.assign(formRoleValue, record);
  formRole.value.init("edit");
}

function handleDelete(record: Recordable) {}

async function handleMenuAuth(record: Recordable) {
  editRoleTitle.value = `分配 ${record.realname} 的角色权限`;
  Object.assign(formRoleValue, record);
  showModal.value = true;
}

onMounted(async () => {
  const { data } = await getRuleList({ current: 1, size: 100 });
  roleOptions.value = data.records;
});
</script>

<style lang="less" scoped></style>
