import { useEffect, useState } from 'react';
import { Button, message, Modal, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import AddOrEditMakeModal from './components/addOrEditMakeModal';
import { MakeManageAPI } from '~/api';
import { MakeItemEntity } from '~/api/interface/makeManage';
import { PaginationProps } from '~/api/interface';

const MakeManage = () => {
  const columns: ColumnsType<MakeItemEntity> = [
    {
      title: '品牌名称',
      align: 'center',
      dataIndex: 'brandName',
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      align: 'center',
      render: (_text: string, record: MakeItemEntity) => (
        <>
          <Button type='link' onClick={() => editMake(record)}>
            编辑
          </Button>
          <Button type='link' danger onClick={() => deleteMake(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<MakeItemEntity[]>([]);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  // add or edit modal is show
  const [currentMakeItem, setCurrentMakeItem] = useState<MakeItemEntity>();
  const [addOrEditModalShow, setAddOrEditModalShow] = useState<boolean>(false);

  // 新建
  const addMakeClick = () => {
    setAddOrEditModalShow(true);
  };
  // add or edit modal event
  const addOrEditModalOk = () => {
    getListBrandInfo({
      pageSize: pagination.pageSize,
      pageNo: pagination.pageNo,
    });
    setAddOrEditModalShow(false);
    setCurrentMakeItem(undefined);
  };
  const addOrEditModalCancel = () => {
    setCurrentMakeItem(undefined);
    setAddOrEditModalShow(false);
  };
  // 品牌-列表
  const getListBrandInfo = (data: Pick<PaginationProps, 'pageSize' | 'pageNo'>) => {
    MakeManageAPI.getListBrandInfo(data).then(({ result }) => {
      setTableData(result.list || []);
      pagination.pageNo = data.pageNo;
      pagination.pageSize = data.pageSize;
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getListBrandInfo({
      pageSize,
      pageNo,
    });
  };
  // edit
  const editMake = (record: MakeItemEntity) => {
    setCurrentMakeItem(record);
    setAddOrEditModalShow(true);
  };
  // delete
  const deleteMake = (record: MakeItemEntity) => {
    Modal.confirm({
      content: '是否删除该品牌？',
      onOk: () => {
        MakeManageAPI.deleteBrandInfo({ id: record.id }).then(({ code, message: msg }) => {
          if (code === '200') {
            message.success('删除成功');
            if (tableData.length === 1 && pagination.pageNo !== 1) {
              pagination.pageNo--;
            }
            getListBrandInfo({
              pageSize: pagination.pageSize,
              pageNo: pagination.pageNo,
            });
          } else {
            message.error(msg);
          }
        });
      },
    });
  };

  useEffect(() => {
    getListBrandInfo({
      pageSize: pagination.pageSize,
      pageNo: pagination.pageNo,
    });
  }, []);
  return (
    <div className='make-manage'>
      <Button
        icon={<PlusOutlined />}
        type='primary'
        onClick={addMakeClick}
        style={{ marginBottom: '10px' }}
      >
        新建
      </Button>

      <Table
        columns={columns}
        bordered
        rowKey='id'
        dataSource={tableData}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <AddOrEditMakeModal
        open={addOrEditModalShow}
        onOk={addOrEditModalOk}
        handleCancel={addOrEditModalCancel}
        title={currentMakeItem ? '编辑品牌' : '新建品牌'}
        makeItem={currentMakeItem}
      />
    </div>
  );
};
export default MakeManage;
