import React, { useEffect, useState } from "react";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import PageLayout from "../../../Common/Layout/PageLayout";
import PageHeader from "../../../Common/PageHeader/PageHeader";
import { getCostList } from "../../services";
import { CostItem } from "../../services/interface";
import { SORT, SORT_TYPE } from "../../constants";
import { sortTypeCode2Value } from "../../utils";

import type { Pagination, Sort } from "../../types";

const columns: GridColDef[] = [
  {
    field: "id",
    headerName: "账单号",
    width: 220,
    disableColumnMenu: true,
  },
  {
    field: "date",
    headerName: "交易时间",
    width: 130,
    disableColumnMenu: true,
  },
  {
    field: "transaction_type",
    headerName: "交易类型",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
  },
  {
    field: "transaction_source",
    headerName: "交易渠道",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
  },

  {
    field: "transaction_money",
    headerName: "交易金额/元",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
  },
  {
    field: "account_balance",
    headerName: "可用余额/元",
    sortable: false,
    // width: 130,
    disableColumnMenu: true,
  },
];

const CostHistory: React.FC = () => {
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchForm, setSearchForm] = useState<Sort>({
    sort: SORT.DESC.value,
  });
  const [list, setList] = useState<CostItem[]>([]);

  const getList = () => {
    getCostList({ ...searchForm, ...pagination }).then((res) => {
      setList(res.data.list || []);
      setPagination((state) => ({ ...state, total: res.data.total }));
    });
  };

  useEffect(() => {
    getList();
  }, [pagination.current, searchForm.sort]);

  const pageChangeHandler = (current: number) => {
    setPagination((state) => ({ ...state, current: current + 1 }));
  };
  const sortChangeHandler = (sorts) => {
    const item = sorts.find((item) => item.field === "date");
    let sort: SORT_TYPE = SORT.DESC.value;
    if (item) {
      sort = sortTypeCode2Value(item.sort);
    }
    setSearchForm((state) => ({
      ...state,
      sort,
    }));
  };
  return (
    <>
      <PageHeader label="交易记录"></PageHeader>
      <PageLayout>
        <DataGrid
          rows={list}
          columns={columns}
          paginationMode="server"
          isRowSelectable={() => false}
          page={pagination.current - 1}
          pageSize={pagination.pageSize}
          rowCount={pagination.total}
          rowsPerPageOptions={[pagination.pageSize]}
          autoHeight
          onPageChange={pageChangeHandler}
          onSortModelChange={sortChangeHandler}
        />
      </PageLayout>
    </>
  );
};

export default CostHistory;
