import SearchBox, { searchColumns } from '~/components/search-box';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Card, Image, message, Table } from 'antd';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  DeleteOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import GoodsAPI from '~/api/modules/goodsAPI';
import { InterDataType, InterReqType, PaginationProps } from '~/api/interface';
import { listGoodsType } from '~/api/interface/goodsType';
import { CategoryManageAPI } from '~/api';
import { filterObjAttr } from '~/utils';

//商品返回类型
type goodsType = InterDataType<listGoodsType>['list'];
//商品列表筛选类型
type goodsSearchParameters = Omit<InterReqType<listGoodsType>, 'pageNo' | 'pageSize' | 'goodsType'>;

const GoodsList = () => {
  const navigate = useNavigate();
  const tabList = [
    {
      key: '1',
      tab: '全部',
    },
    {
      key: '2',
      tab: '上架中',
    },
    {
      key: '3',
      tab: '仓库中',
    },
  ];
  const [activeTabKey, setActiveTabKey] = useState<string>('1');
  const [searchColumns, setSearchColumns] = useState<searchColumns[]>([
    {
      label: '商品名称',
      placeholder: '请输入商品名称',
      name: 'goodsName',
      type: 'input',
    },
    {
      label: '所属目录',
      placeholder: '请选择所属目录',
      name: 'directoryId',
      type: 'select',
      options: [],
    },
    {
      label: '创建时间',
      placeholder: '请输入选择创建时间',
      name: 'time',
      type: 'rangePicker',
    },
  ]);
  const tableColumns: ColumnsType<goodsType[0]> = [
    {
      title: '序号',
      align: 'center',
      render: (_text: any, _record, index: number) =>
        (pagination.pageNo - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '图片',
      align: 'center',
      dataIndex: 'imgUrl',
      render: (text: string) => <Image src={text} width={50} height={50} />,
    },
    { title: '商品名称', align: 'center', dataIndex: 'goodsName' },
    { title: '所属目录', align: 'center', dataIndex: 'directoryName' },
    { title: '创建时间', align: 'center', dataIndex: 'createTime' },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      render: (text: number) => (text ? '上架' : '下架'),
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'id',
      render: (id: number) => (
        <>
          <Button type='link' onClick={() => toEditGoods(id)}>
            编辑
          </Button>
          <Button type='link' onClick={() => toGoodsDetail(id)}>
            详情
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<goodsType>([]);
  const [loading, setLoading] = useState<boolean>(false);
  //分页
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  //筛选
  const [query, setQuery] = useState<goodsSearchParameters>({ status: undefined });
  // 表格多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onTabChange = (key: string) => {
    pagination.pageNo = 1;
    query.status = key === '1' ? undefined : key === '2' ? 1 : 0;
    getGoodsList(query);
    setQuery(query);
    setActiveTabKey(key);
  };
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.pageNo = pageNo;
    getGoodsList(query);
  };
  //筛选
  const searchSuccess = (data: any) => {
    pagination.pageNo = 1;
    setQuery(filterObjAttr(data, ['time']));
    getGoodsList(filterObjAttr(data, ['time']));
  };
  //商品列表
  const getGoodsList = (query?: goodsSearchParameters) => {
    setLoading(true);
    GoodsAPI.getGoodsList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      goodsType: 0,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  //新增商品
  const toAddMallGoods = () => {
    navigate({ pathname: '/mallManage/mallGoods/add' });
  };
  //编辑商品
  const toEditGoods = (id: number) => {
    navigate({
      pathname: '/mallManage/mallGoods/add',
      search: `id=${id}`,
    });
  };
  //商品详情
  const toGoodsDetail = (id: number) => {
    navigate({
      pathname: '/mallManage/mallGoods/detail',
      search: `id=${id}&isDetail=1`,
    });
  };
  // 表格多选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  //获取目录列表
  const getDirectoryList = () => {
    CategoryManageAPI.getDirectoryListClone({ type: 4 }).then(({ result }) => {
      if (result) {
        const options = result.map((v) => ({ id: v.id, name: v.directoryName }));
        searchColumns[1].options = options;
        setSearchColumns(searchColumns);
      }
    });
  };
  //商品-批量上下架
  const batchOnShelfOrTakeDown = (status: number) => {
    if (selectedRowKeys.length === 0) {
      return message.warning('请先选择商品');
    }
    GoodsAPI.batchOnShelfOrTakeDown({ goodsIds: selectedRowKeys as number[], status }).then(
      ({ code }) => {
        if (code === '200') {
          message.success(status ? '上架成功' : '下架成功');
          getGoodsList(query);
        }
      },
    );
  };
  //商品-删除
  const deleteGoods = () => {
    if (selectedRowKeys.length === 0) {
      return message.warning('请先选择商品');
    }
    GoodsAPI.batchRemoveWareInfo(selectedRowKeys as number[]).then(({ code }) => {
      if (code === '200') {
        if (pagination.pageNo !== 1 && tableData.length == 1) {
          pagination.pageNo -= 1;
        }
        message.success('删除成功');
        getGoodsList(query);
      }
    });
  };
  useEffect(() => {
    getGoodsList();
    getDirectoryList();
  }, []);
  return (
    <div className='goods-list'>
      <SearchBox
        search={searchColumns}
        child={
          <Button type='primary' icon={<PlusOutlined />} onClick={toAddMallGoods}>
            新增商品
          </Button>
        }
        searchData={searchSuccess}
      />
      <Card tabList={tabList} activeTabKey={activeTabKey} onTabChange={onTabChange}>
        <div className='header-operate' style={{ marginBottom: '10px' }}>
          {activeTabKey !== '2' && (
            <Button
              type='primary'
              style={{ marginRight: '10px' }}
              icon={<ArrowUpOutlined />}
              onClick={() => batchOnShelfOrTakeDown(1)}
            >
              上架
            </Button>
          )}
          {activeTabKey !== '3' && (
            <Button
              type='primary'
              style={{ marginRight: '10px' }}
              icon={<ArrowDownOutlined />}
              onClick={() => batchOnShelfOrTakeDown(0)}
            >
              下架
            </Button>
          )}

          <Button danger icon={<DeleteOutlined />} onClick={deleteGoods}>
            删除
          </Button>
        </div>
        <Table
          columns={tableColumns}
          bordered
          dataSource={tableData}
          rowKey='id'
          rowSelection={{
            selectedRowKeys,
            onChange: onSelectChange,
          }}
          loading={loading}
          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} 条数据`,
          }}
        />
      </Card>
    </div>
  );
};
export default GoodsList;
