import React, { useState, useEffect, createRef } from "react";
import { Box, Button, TextField, Alert, MenuItem } from "@mui/material";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import PageLayout from "../../../Common/Layout/PageLayout";
import PageHeader from "../../../Common/PageHeader/PageHeader";
import Drawer from "../../components/Drawer";
import type { Pagination } from "../../types";
import { applyInvoice, getInvoiceList } from "../../services";
import { ApplyInvoiceRequestBody, InvoiceItem } from "../../services/interface";
import { INVOICE, INVOICE_STATUS_TYPE } from "../../constants";
import message from "../../../../../utils/message";

type TableItem = InvoiceItem;

type FormValue = ApplyInvoiceRequestBody;

const columns: GridColDef<TableItem>[] = [
  {
    field: "id",
    headerName: "ID",
    disableColumnMenu: true,
  },
  {
    field: "title",
    headerName: "发票抬头",
    width: 130,
    disableColumnMenu: true,
    sortable: false,
  },
  {
    field: "type",
    headerName: "发票类型",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
    renderCell(params) {
      return Object.values(INVOICE).find((i) => i.value === params.value).cname;
    },
  },
  {
    field: "address_name",
    headerName: "收件人姓名",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
  },

  {
    field: "address",
    headerName: "邮寄地址",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
  },
  {
    field: "phone",
    headerName: "联系方式",
    sortable: false,
    width: 130,
    disableColumnMenu: true,
  },
  {
    field: "desc",
    headerName: "发票备注",
    sortable: false,
    // width: 130,
    disableColumnMenu: true,
  },
  {
    field: "status",
    headerName: "状态",
    sortable: false,
    // width: 130,
    disableColumnMenu: true,
  },
];

class InvoiceDrawer {
  visible: boolean = false;
  form: FormValue = {
    title: "",
    type: INVOICE.VAT_NORMAL.value,
    address_name: "",
    address: "",
    phone: "",
    desc: "",
  };
}

const Invoice: React.FC = () => {
  const [drawer, setDrawer] = useState<InvoiceDrawer>(new InvoiceDrawer());
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [list, setList] = useState<TableItem[]>([]);
  const formRef = createRef<HTMLFormElement>();

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

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

  const pageChangeHandler = (page: number) => {
    setPagination((state) => ({ ...state, page: page + 1 }));
  };

  const drawerHideHandler = () => {
    setDrawer(new InvoiceDrawer());
  };
  const drawerShowHandler = () => {
    setDrawer((state) => ({ ...state, visible: true }));
  };

  const createFieldProps = (
    name: keyof FormValue
  ): React.ComponentProps<typeof TextField> => {
    return {
      fullWidth: true,
      margin: "normal",
      name,
      value: drawer.form[name],
      onChange: (e) => {
        setDrawer((state) => ({
          ...state,
          form: {
            ...state.form,
            [name]: e.target.value,
          },
        }));
      },
    };
  };

  const submitHandler = (e: React.FormEvent) => {
    e.preventDefault();
    applyInvoice(drawer.form).then((res) => {
      message.success("提交成功");
      drawerHideHandler();
      if (pagination.current === 1) {
        getList();
      } else {
        setPagination((state) => ({ ...state, current: 1 }));
      }
    });
  };

  return (
    <>
      <PageHeader label="发票管理"></PageHeader>
      <PageLayout>
        <div>
          <Button variant="contained" onClick={drawerShowHandler}>
            申请开票
          </Button>
        </div>
        <br />
        <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}
        />
      </PageLayout>
      <Drawer
        visible={drawer.visible}
        onCancel={drawerHideHandler}
        title="申请开票"
        onConfirm={() => {
          formRef.current.requestSubmit();
        }}
      >
        <Box component="form" ref={formRef} onSubmit={submitHandler}>
          <Alert color="warning" icon={false}>
            土星云仅提供纸质发票，我们将在收到申请后 7
            个工作日内为您开具并用快递邮寄给您。
          </Alert>
          <TextField
            required
            label="发票抬头"
            {...createFieldProps("title")}
          ></TextField>
          <TextField
            required
            label="发票类型"
            {...createFieldProps("type")}
            select
          >
            {Object.values(INVOICE).map((option) => (
              <MenuItem key={option.value} value={option.value}>
                {option.cname}
              </MenuItem>
            ))}
          </TextField>
          <TextField
            required
            label="收件人姓名"
            {...createFieldProps("address_name")}
          ></TextField>
          <TextField
            required
            label="邮寄地址"
            {...createFieldProps("address")}
          ></TextField>
          <TextField
            required
            label="联系方式"
            {...createFieldProps("phone")}
          ></TextField>
          <TextField
            label="发票备注"
            {...createFieldProps("desc")}
            multiline
            minRows={3}
          ></TextField>
        </Box>
      </Drawer>
    </>
  );
};

export default Invoice;
