import SearchBox, { searchColumns } from '~/components/search-box';
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Card, Image, message, Modal, Table } from 'antd';
import { ArrowDownOutlined, ArrowUpOutlined, 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 { listPageGoodsInfoType } from '~/api/interface/goodsType';
import { filterObjAttr } from '~/utils';
import qs from 'query-string';
import { CategoryManageAPI } from '~/api';
import { categoryListRespType } from '~/api/interface/categoryManage';

//商品返回类型
type goodsType = InterDataType<listPageGoodsInfoType>['list'];
//商品列表筛选类型
type goodsSearchParameters = InterReqType<listPageGoodsInfoType>;
//分类返回类型
type categoryType = InterDataType<categoryListRespType>['list'];

const GoodsList = () => {
  //筛选ref
  const searchRef = useRef();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const tabList = [
    {
      key: '1',
      tab: '全部',
    },
    {
      key: '2',
      tab: '上架中',
    },
    {
      key: '3',
      tab: '仓库中',
    },
  ];
  const [activeTabKey, setActiveTabKey] = useState<string>('1');
  //分类列表
  const [categoryList, setCategoryList] = useState<categoryType>([]);
  const [searchColumns, setSearchColumns] = useState<searchColumns[]>([
    {
      label: '商品名称',
      placeholder: '请输入商品名称',
      name: 'goodsName',
      type: 'input',
    },
    {
      label: '商品类型',
      placeholder: '请选择商品类别',
      name: 'categoryPrimaryId',
      type: 'select',
      options: [],
    },
  ]);
  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: 'resourcesList',
      render: (text: goodsType[0]['resourcesList']) => (
        <Image src={text.find((v) => v.type === 0)?.url || ''} width={50} height={50} />
      ),
    },
    { title: '商品名称', align: 'center', dataIndex: 'tradeName' },
    {
      title: '商品类别',
      align: 'center',
      render: (_text: string, record: goodsType[0]) => getCategoryStr(record),
    },
    { title: '创建时间', align: 'center', dataIndex: 'createTime' },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'shelfStatus',
      render: (text: number) => (text ? '上架' : '下架'),
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'id',
      render: (id: number, record: goodsType[0]) => (
        <>
          <Button type='link' onClick={() => toEditGoods(id)}>
            编辑
          </Button>
          <Button type='link' onClick={() => toGoodsDetail(id)}>
            详情
          </Button>
          <Button type='link' onClick={() => upOrDownShelf(1, id)} disabled={!!record.shelfStatus}>
            上架
          </Button>
          <Button type='link' onClick={() => upOrDownShelf(0, id)} disabled={!record.shelfStatus}>
            下架
          </Button>
          <Button type='link' danger onClick={() => removeMallGoods(id)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<goodsType>([]);
  const [allGoods, setAllGoods] = useState<goodsType>([]);
  const [loading, setLoading] = useState<boolean>(false);
  //分页
  const [pagination, setPagination] = useState<
    PaginationProps & { totalCount: number; totalPage: number }
  >({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 1,
  });
  //筛选
  const [query, setQuery] = useState<goodsSearchParameters>({ shelfStatus: undefined });
  // 表格多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onTabChange = (key: string) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    query.shelfStatus = key === '1' ? undefined : key === '2' ? 1 : 0;
    setSearchParams(
      qs.stringify({
        pageNo: 1,
        pageSize: 10,
        ...query,
        shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
      }),
    );
    getGoodsList(query);
    getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
    setQuery(query);
    setActiveTabKey(key);
  };
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    setSearchParams(
      qs.stringify({
        pageNo: pageNo,
        pageSize: pageSize,
        ...query,
        shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
      }),
    );
    getGoodsList(query);
    getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
  };
  //筛选
  const searchSuccess = (data: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setQuery({ ...data, shelfStatus: query.shelfStatus });
    getGoodsList({ ...data, shelfStatus: query.shelfStatus });
    getGoodsList({ ...data, shelfStatus: query.shelfStatus, pageSize: 9999, pageNo: 1 }, true);
    setSearchParams(
      qs.stringify({
        pageNo: 1,
        pageSize: 10,
        ...filterObjAttr(data, ['time']),
        shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
      }),
    );
  };
  //商品列表
  const getGoodsList = (query?: goodsSearchParameters, isAll?: boolean) => {
    setLoading(true);
    GoodsAPI.getListPageGoodsInfo({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      if (isAll) {
        setAllGoods(result.list || []);
      } else {
        setTableData(result.list || []);
        pagination.totalCount = result.totalCount;
        pagination.totalPage = result.totalPage;
        setPagination(pagination);
      }
    });
  };
  //新增商品
  const toAddMallGoods = () => {
    navigate({ pathname: '/mallManage/mallGoods/add' });
  };
  //编辑商品
  const toEditGoods = (id: number) => {
    navigate({
      pathname: '/mallManage/mallGoods/edit',
      search: `id=${id}`,
    });
  };
  //商品详情
  const toGoodsDetail = (id: number) => {
    navigate({
      pathname: '/mallManage/mallGoods/detail',
      search: `id=${id}`,
    });
  };
  // 表格多选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  //商品-单个上下架
  const upOrDownShelf = (status: number, id: number) => {
    Modal.confirm({
      title: '提示',
      content: `确认${status ? '上架' : '下架'}该商品？`,
      onOk: () => {
        GoodsAPI.upOrDownShelf({ id, status }).then(({ code }) => {
          if (code === '200') {
            message.success(status ? '上架成功' : '下架成功');
            getGoodsList(query);
            setSelectedRowKeys([]);
          }
        });
      },
    });
  };
  //商品-删除
  const removeMallGoods = (id: number) => {
    Modal.confirm({
      title: '提示',
      content: '删除后数据将会丢失，确定删除吗？',
      onOk() {
        GoodsAPI.removeMallGoods({ id }).then(({ code }) => {
          if (code === '200') {
            if (pagination.pageNo !== 1 && tableData.length == 1) {
              pagination.pageNo -= 1;
            }
            message.success('删除成功');
            getGoodsList(query);
            setSelectedRowKeys([]);
          }
        });
      },
    });
  };
  //上移
  const upGoodsClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择商品');
    } else {
      const index = tableData.findIndex((v) => v.id === selectedRowKeys[0]);
      const allIndex = allGoods.findIndex((v) => v.id === selectedRowKeys[0]);
      if (index === 0 && pagination.pageNo === 1) {
        message.warning('位置已到最前列，无法上移');
      } else {
        const exReqData =
          index === 0
            ? allGoods
                .filter((_v, index) => index === allIndex - 1 || index === allIndex)
                .map((v) => ({ id: v.id }))
            : tableData
                .filter((_v, i) => index - 1 === i || index === i)
                .map((v) => ({ id: v.id }));
        GoodsAPI.exchange({ firstId: exReqData[0].id, secondId: exReqData[1].id }).then(
          ({ code }) => {
            if (code === '200') {
              message.success('上移成功');
              if (index === 0 && pagination.pageNo !== 1) {
                pagination.pageNo -= 1;
                setSearchParams(
                  qs.stringify({
                    pageNo: pagination.pageNo,
                    pageSize: pagination.pageSize,
                    ...query,
                    shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
                  }),
                );
              }
              getGoodsList(query);
              getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
            }
          },
        );
      }
    }
  };
  //下移
  const downGoodsClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择商品');
    } else {
      const index = tableData.findIndex((v) => v.id === selectedRowKeys[0]);
      const allIndex = allGoods.findIndex((v) => v.id === selectedRowKeys[0]);
      if (index === tableData.length - 1 && pagination.pageNo === pagination.totalPage) {
        message.warning('位置已到最后，无法下移');
      } else {
        const exReqData =
          index === tableData.length - 1
            ? allGoods
                .filter((_v, index) => index === allIndex + 1 || index === allIndex)
                .map((v) => ({ id: v.id }))
            : tableData
                .filter((_v, i) => index + 1 === i || index === i)
                .map((v) => ({ id: v.id }));
        GoodsAPI.exchange({ firstId: exReqData[0].id, secondId: exReqData[1].id }).then(
          ({ code }) => {
            if (code === '200') {
              message.success('下移成功');
              if (index === tableData.length - 1 && pagination.pageNo !== pagination.totalPage) {
                pagination.pageNo += 1;
                setSearchParams(
                  qs.stringify({
                    pageNo: pagination.pageNo,
                    pageSize: pagination.pageSize,
                    ...query,
                    shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
                  }),
                );
              }
              getGoodsList(query);
              getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
            }
          },
        );
      }
    }
  };
  //分类列表
  const getCategoryList = () => {
    CategoryManageAPI.getCategoryRespList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      searchColumns[1].options = (result.list || []).map((v) => ({ id: v.id, name: v.name }));
      setSearchColumns([...searchColumns]);
      setCategoryList(result.list || []);
    });
  };
  //商品列表，分类组合
  const getCategoryStr = (record: goodsType[0]) => {
    return categoryList
      .reduce((pre: string[], cur) => {
        if (cur.id === record.categoryPrimaryId) {
          pre.push(cur.name);
          if (record.categorySubId) {
            pre.push(cur.subDTOList.find((v) => v.id === record.categorySubId)?.name || '');
          }
        }
        return pre;
      }, [])
      .join('/');
  };

  useEffect(() => {
    getCategoryList();
    pagination.pageNo = Number(searchParams.get('pageNo') || 1);
    pagination.pageSize = Number(searchParams.get('pageSize') || 10);
    const queryObj = {
      tradeName: searchParams.get('goodsName') || undefined,
      shelfStatus:
        searchParams.get('shelfStatus') === 'all' || searchParams.get('shelfStatus') === null
          ? undefined
          : Number(searchParams.get('shelfStatus')),
    };
    getGoodsList(queryObj);
    getGoodsList({ ...queryObj, pageNo: 1, pageSize: 9999 }, true);
    setActiveTabKey(
      searchParams.get('shelfStatus') === 'all' || searchParams.get('shelfStatus') === null
        ? '1'
        : Number(searchParams.get('shelfStatus')) === 1
        ? '2'
        : '3',
    );
    (searchRef.current as any).getForm().setFieldsValue({
      tradeName: searchParams.get('goodsName') || undefined,
    });
  }, []);

  return (
    <div className='goods-list'>
      <SearchBox
        search={searchColumns}
        child={
          <Button type='primary' icon={<PlusOutlined />} onClick={toAddMallGoods}>
            新增商品
          </Button>
        }
        searchData={searchSuccess}
        baseRef={searchRef}
      />
      <Card tabList={tabList} activeTabKey={activeTabKey} onTabChange={onTabChange}>
        <div className='header-operate' style={{ marginBottom: '10px' }}>
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            icon={<ArrowUpOutlined />}
            onClick={upGoodsClick}
          >
            上移
          </Button>
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            icon={<ArrowDownOutlined />}
            onClick={downGoodsClick}
          >
            下移
          </Button>
        </div>
        <Table
          columns={tableColumns}
          bordered
          dataSource={tableData}
          rowKey='id'
          rowSelection={{
            selectedRowKeys,
            onChange: onSelectChange,
            type: 'radio',
            hideSelectAll: true,
          }}
          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;
