<template>
  <div>
    <BasicTable
      ref="tableRef"
      @register="registerTable"
      rowKey="id"
      showTableSetting
      :canResize="true"
      :pagination="{
        pageSize: 10,
        defaultPageSize: 10,
        showSizeChanger: false,
      }"
    >
      <template #toolbar>
        <a-button type="primary" @click="addRole"> 添加 </a-button>
        <a-button type="danger" @click="deleteBatches"> 删除 </a-button>
      </template>
      <template #form-custom> custom-slot </template>
      <template #action="{ record }">
        <TableAction :actions="createActions(record)" />
      </template>
    </BasicTable>
    <Popup @register="addRegister" :popupData="popupData" @saveData="saveData" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, reactive, ref, unref } from 'vue';
  import Popup from './popup.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { getFormConfig, columns } from './data';
  import {
    getUserList,
    addUser,
    editUser,
    deleteUser,
    getGroupTree,
    deleteBatchesUser,
  } from '/@/api/sys/user';
  import { useUserStore } from '/@/store/modules/user';
  import {
    BasicTable,
    useTable,
    TableAction,
    ActionItem,
    EditRecordRow,
    TableActionType,
  } from '/@/components/Table';

  interface PopupData {
    title: string;
    treeData: object[];
  }

  export default defineComponent({
    components: { BasicTable, TableAction, Popup },
    setup() {
      init();
      const { createMessage } = useMessage();
      const { success, error } = createMessage;
      const tableRef = ref<Nullable<TableActionType>>(null);
      const currentEditKeyRef = ref('');
      const popupData = reactive<PopupData>({
        title: '添加',
        treeData: [],
      });
      const [registerTable] = useTable({
        title: '管理员管理',
        titleHelpMessage: '一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成',
        rowSelection: { type: 'checkbox' },
        columns: columns,
        clickToRowSelect: false, // 点击行不勾选
        api: getUserList,
        useSearchForm: true,
        beforeFetch: beforeFetch,
        afterFetch: afterFetch,
        formConfig: getFormConfig(),
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        showIndexColumn: false,
        bordered: true,
      });
      const userStore = useUserStore();
      const [addRegister, { openModal: openAdd }] = useModal();
      const id = userStore.getUserInfo?.id;
      function getTableAction() {
        // 获取组件
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      }

      function getSelectRowList() {
        // 获取选中行
        console.log(getTableAction().getSelectRows());
      }
      // 请求之前处理参数
      function beforeFetch(params) {
        console.log(params);
        console.log('==========before========');
        // params['op'] = {};
        for (let k in params) {
          if (!params[k]) {
            delete params[k];
          }
        }

        console.log(params);

        if (params.logintime) {
          params.logintime[0] = params.logintime[0].replace(
            /([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/g,
            '00:00:00'
          );
          params.logintime[1] = params.logintime[1].replace(
            /([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/g,
            '23:59:59'
          );
        }

        params.offset = params.page;
        params.limit = params.pageSize;
        delete params.page;
        delete params.pageSize;
      }
      function afterFetch(result) {
        result.map((item) => {
          if (item.groups) {
            item.groups_value = [];
            item.groups.map((item_group) => {
              item.groups_value.push({ lable: item_group.name, value: item_group.id });
            });
          } else {
            item.groups = []; //null
            item.groups_text = [];
          }
        });
        console.log(`result`, result);
      }

      async function init() {
        const GroupTree = await getGroupTree();
        popupData.treeData = GroupTree.tree;
      }

      function getSelectRowKeyList() {
        // 获取选中行的key --- id
        console.log(getTableAction().getSelectRowKeys());
      }

      function addRole() {
        if (!popupData.treeData[0]) {
          error('没有访问权限!');
          return;
        }
        popupData.title = '添加';
        openAdd(true, {
          id: null,
          username: '',
          nickname: '',
          email: '',
          groups_value: [],
          status: 'normal',
        });
      }

      function handleEdit(record: EditRecordRow) {
        if (!popupData.treeData[0]) {
          error('没有访问权限!');
          return;
        }
        currentEditKeyRef.value = record.id; // record.key
        popupData.title = '编辑';
        const data = getTableAction().getDataSource();
        data.map((item) => {
          if (item.id === record.id) {
            record = item;
          }
        });
        console.log('================record=======');
        console.log(record);
        openAdd(true, record);
      }

      async function handleDelete(record: Recordable) {
        console.log(record);
        await deleteUser({ id: record.id }).then((res) => {
          console.log(res);
          getTableAction().reload();
          success('删除成功!');
        });
        // const data = getTableAction().getDataSource()
        // console.log(data)
        // getTableAction().setTableData(data.filter(item => item.id !== record.id))
      }

      async function deleteBatches() {
        const id = getTableAction().getSelectRowKeys().toString();
        if (!id) {
          return;
        }
        await deleteBatchesUser({ id }).then((res) => {
          console.log(res);
          getTableAction().reload();
          success('删除成功!');
          getTableAction().setSelectedRowKeys([]);
        });
      }

      async function saveData(params: any) {
        const data = params.data;
        data.groups = [];
        if (data.groups_value) {
          data.groups_value.map((item) => {
            data.groups.push(item.value);
          });
        }
        const closeModel = params.closeModal;
        if (data.groups) {
          data.groups = data.groups.toString();
        } else {
          data.groups = data.groups_text = '';
        }
        delete data.groups_value;
        console.log(`data`, data);
        if (!data.id) {
          await addUser(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            success('创建成功!');
          });
          console.log('----------add---');
        } else {
          await editUser(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            success('修改成功!');
          });
          console.log('----------edit---');
        }
      }

      function createActions(record: EditRecordRow): ActionItem[] {
        if (id === record.id) {
          return [
            {
              label: '',
            },
          ];
        }
        return [
          {
            label: '编辑',
            icon: 'ant-design:edit-outlined',
            color: 'warning',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            color: 'error',
            icon: 'ic:outline-delete-outline',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
            },
          },
        ];
      }
      onMounted(() => {
        console.log(getTableAction());
      });
      return {
        popupData,
        tableRef,
        registerTable,
        addRole,
        handleEdit,
        deleteBatches,
        createActions,
        getTableAction,
        getSelectRowList,
        getSelectRowKeyList,
        addRegister,
        saveData,
        getUserList,
      };
    },
  });
</script>
<style>
  .ant-calendar-picker {
    width: 100%;
  }
</style>
