<template>
  <div class="user-page">
    <UserQuery />
    <div class="user-list">
      <BasicTable
        :columns="columns"
        :data-source="userList"
        :row-key="(row) => row.userId"
        ref="basicTableRef"
        :pagination="{ total: totalCount, pageSize: pageSize, hideOnSinglePage: false }"
        :actionColumn="actionColumn"
        :tableSetting="{
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        @update:checked-row-keys="onCheckedRow"
        virtual-scroll
        @page-num-change="handlePageNumChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #tableTitle>
          <el-space align="center">
            <el-button type="primary" @click="openAddSingleDrawer">
              <template #icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
              添加用户
            </el-button>
            <el-button @click="openAddAdminDrawer" v-if="userStore?.info?.username === ROOT_USER">
              <template #icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
              添加租户管理员
            </el-button>
            <el-button
              color="#1890FF"
              @click="openAddMultipleDrawer"
              style="margin-left: 18px"
              plain
            >
              <template #icon>
                <el-icon>
                  <DocumentAdd />
                </el-icon>
              </template>
              批量导入
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </div>
    <CreateDrawer ref="createDrawerRef" :title="drawerTitle" @change="reloadTable" />
    <CreateAdminDrawer
      ref="createAdminDrawer"
      :title="createAdminTitle"
      @change="reloadTable"
      :editType="createAdminType"
    />
    <AddUser
      v-if="showAddPopover"
      v-model="showAddPopover"
      class="add-popover"
      @change="reloadTable"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, onMounted } from 'vue';
  import { BasicTable, BasicColumn } from '@/components/Table';
  import { Plus, DocumentAdd } from '@element-plus/icons-vue';
  import { roleAllList } from '@/api/system/role';
  import editIcon from '@/assets/images/table/table-edit.png';
  import deleteIcon from '@/assets/images/table/table-delete.png';
  import { useUserStore } from '@/store/modules/user';
  import CreateDrawer from './CreateDrawer.vue';
  import CreateAdminDrawer from './CreateAdminDrawer.vue';
  import { columns } from './columns';
  import ActionColomns from './component/ActionColomns.vue';
  import AddUser from './component/AddUser.vue';
  // import { Search } from '@element-plus/icons-vue';
  import UserQuery from './component/UserQuery.vue';
  import useUser from './hooks/use-user';
  import { storeToRefs } from 'pinia';
  import { EditType } from './types';
  import { ROOT_USER } from './types';

  const useUserDetail = useUser();
  const { userList, page, pageSize, totalCount } = storeToRefs(useUserDetail);
  const { conditionSearch, userDel } = useUserDetail;

  const userStore = useUserStore();

  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref([]);
  const tableData = ref();
  const createDrawerRef = ref();
  const createAdminDrawer = ref();
  const drawerTitle = ref('添加用户');
  const createAdminTitle = ref('添加租户管理员');
  const roleData = ref([]);

  const createAdminType = ref(EditType.create);

  const handlePageNumChange = (pageNum) => {
    console.log('pageNum', pageNum);

    page.value = pageNum;
    conditionSearch();
  };
  const handlePageSizeChange = (size) => {
    page.value = 1;
    pageSize.value = size;
    conditionSearch();
  };

  const actionColumn: BasicColumn = reactive({
    width: 150,
    title: '操作',
    prop: 'action',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(ActionColomns as any, {
        space: 20,
        color: '#629bf9',
        style: 'img',
        size: 16,
        actionIcons: [
          {
            label: '编辑',
            icon: editIcon,
            onClick: handleEdit.bind(null, record.row),
          },
          {
            label: '删除',
            icon: deleteIcon,
            onClick: handleDelete.bind(null, record.row),
          },
        ],
      });
    },
  });

  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value
      .filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.username;
      })
      .join('，');
  }

  function reloadTable() {
    conditionSearch();
  }

  const openAddSingleDrawer = () => {
    drawerTitle.value = '添加用户';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  };
  const openAddAdminDrawer = () => {
    createAdminTitle.value = '添加租户管理员';
    const { openDrawer } = createAdminDrawer.value;
    openDrawer();
  };

  const showAddPopover = ref<boolean>(false);

  const openAddMultipleDrawer = () => {
    showAddPopover.value = true;
    console.log('showAddPopover', showAddPopover.value);
  };

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    drawerTitle.value = '编辑用户';
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.userId);
  }

  function handleDelete(record: Recordable) {
    const delDetail = {
      userId: record.userId,
      nickname: record.nickname,
      username: record.username,
    };
    userDel(delDetail);
  }

  onMounted(async () => {
    const res = await roleAllList();
    roleData.value = res.list.map((item: any) => {
      return {
        value: item.roleId,
        label: item.roleName,
      };
    });
  });
</script>
<style scoped>
  .user-page {
    position: relative;
    height: calc(100vh - 64px - 12px);
    background-color: #ffffff;
  }

  .user-list {
    padding: 0 21px;
  }

  .add-popover {
    position: absolute;
    width: 593px;
    height: 435px;
    left: 50%;
    top: 50%;
    margin-top: -218px;
    margin-left: -297px;
    z-index: 99;
  }
</style>
