import { stringify } from 'qs';
import { useEffect, useState } from 'react';
import { FooterPagination } from '@/components/PaginationPlugin';
import type { ColumnsTypeUltra } from '@/components/TableColumnsFilterPlugin';
import { TablePlugin } from '@/components/TablePlugin';
import { statusObj } from '@/configs/adminLogConfig';
import type { IAjaxDataBase, IParamsBase } from '@/interfaces/common';
import { AdminLogServices } from '@/services/AdminLogServices';
import { tableFixedByPhone, toArray } from '@/utils/common';
import { useRequest } from '@/utils/useRequest';

interface IAjaxData extends IAjaxDataBase {
  data: any[];
}
type IParams = IParamsBase & {
  create_dateL?: string;
  create_dateU?: string;
  admin_id?: number;
};

/** 操作日志页面 */
const AdminSysLogForm: React.FC = () => {
  const [params] = useState<IParams>({
    curr_page: 1,
    page_count: 20,
    admin_id: Number(localStorage.getItem('admin_id')) || undefined,
  });
  const [ajaxData, setAjaxData] = useState<IAjaxData>({ count: 0, data: [] });

  const { loading: listLoading, request: listRequest } = useRequest(AdminLogServices.getAdminSysLogAjaxList, {
    onSuccessCodeZero: (res) => {
      setAjaxData({
        count: res.count || 0,
        data: toArray(res.data),
      });
    },
  });

  const columns: ColumnsTypeUltra<any> = [
    {
      title: '#',
      width: 20,
      fixed: tableFixedByPhone('left'),
      align: 'center',
      render(_value, _record, index) {
        return index + 1;
      },
    },
    { title: '操作账号', dataIndex: 'username', width: 50 },
    { title: '操作IP', dataIndex: 'ip', width: 100 },
    { title: '菜单', dataIndex: 'menu_ch_name', width: 80 },
    { title: '权限', dataIndex: 'function_ch_name', width: 60 },
    { title: '操作时间', dataIndex: 'create_date', width: 120 },
    { title: '状态', dataIndex: 'status', width: 60, render: (value) => statusObj[value] },
  ];

  function page(curr: number) {
    if (!listLoading) {
      params.curr_page = curr;
      listRequest(stringify(params));
    }
  }

  useEffect(() => {
    page(1);
  }, []);

  return (
    <>
      <TablePlugin
        loading={listLoading}
        onChange={(_p, _f, sort: any) => {
          page(1);
        }}
        dataSource={ajaxData.data}
        columns={columns}
        scroll={{ x: true }}
        rowKey={'sys_id'}
      />

      <FooterPagination
        current={params.curr_page}
        pageSize={params.page_count}
        total={ajaxData.count}
        onChange={(curr, pageSize) => {
          params.page_count = pageSize;
          page(curr);
        }}
      />
    </>
  );
};

/** 操作日志页面 */
export default AdminSysLogForm;
