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,
  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';
import qs from 'query-string';

//商品返回类型
type goodsType = InterDataType<listGoodsType>['list'];
//商品列表筛选类型
type goodsSearchParameters = Omit<InterReqType<listGoodsType>, 'goodsType'>;
const RentList = () => {
  //筛选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 [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={() => toRentGoodsDetail(id)}>
            详情
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<goodsType>([]);
  const [allRentGoods, setAllRentGoods] = 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>({ status: undefined });
  // 表格多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onTabChange = (key: string) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    query.status = key === '1' ? undefined : key === '2' ? 1 : 0;
    setSearchParams(
      qs.stringify({
        pageNo: 1,
        pageSize: 10,
        ...query,
        status: query.status === undefined ? 'all' : query.status,
      }),
    );
    getGoodsList(query);
    getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
    setQuery(query);
    setActiveTabKey(key);
  };
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.pageNo = pageNo;
    setSearchParams(
      qs.stringify({
        pageNo: pageNo,
        pageSize: pageSize,
        ...query,
        status: query.status === undefined ? 'all' : query.status,
      }),
    );
    getGoodsList(query);
    getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
  };
  //筛选
  const searchSuccess = (data: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setQuery({ ...filterObjAttr(data, ['time']), status: query.status });
    getGoodsList({ ...filterObjAttr(data, ['time']), status: query.status });
    getGoodsList(
      { ...filterObjAttr(data, ['time']), status: query.status, pageNo: 1, pageSize: 9999 },
      true,
    );
    setSearchParams(
      qs.stringify({
        pageNo: 1,
        pageSize: 10,
        ...filterObjAttr(data, ['time']),
        status: query.status === undefined ? 'all' : query.status,
      }),
    );
  };
  //商品列表
  const getGoodsList = (query?: goodsSearchParameters, isAll?: boolean) => {
    setLoading(true);
    GoodsAPI.getGoodsList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      goodsType: 1,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      if (isAll) {
        setAllRentGoods(result.list || []);
      } else {
        setTableData(result.list || []);
        pagination.totalCount = result.totalCount;
        pagination.totalPage = result.totalPage;
        setPagination(pagination);
      }
    });
  };
  //新增商品
  const toAddRentGoods = () => {
    navigate({ pathname: '/rentManage/rentGoods/add' });
  };
  //编辑商品
  const toEditGoods = (id: number) => {
    navigate({
      pathname: '/rentManage/rentGoods/edit',
      search: `id=${id}`,
    });
  };
  //商品详情
  const toRentGoodsDetail = (id: number) => {
    navigate({
      pathname: '/rentManage/rentGoods/detail',
      search: `id=${id}&isDetail=1`,
    });
  };
  // 表格多选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  //获取目录列表
  const getDirectoryList = () => {
    CategoryManageAPI.getDirectoryListClone({ type: 2 }).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('请先选择商品');
    }
    Modal.confirm({
      title: '提示',
      content: '删除后数据将会丢失，确定删除吗？',
      onOk() {
        GoodsAPI.batchRemoveWareInfo(selectedRowKeys as number[]).then(({ code }) => {
          if (code === '200') {
            if (pagination.pageNo !== 1 && tableData.length == 1) {
              pagination.pageNo -= 1;
            }
            message.success('删除成功');
            getGoodsList(query);
          }
        });
      },
    });
  };
  //上移
  const upGoodsRentClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择商品');
    } else if (selectedRowKeys.length > 1) {
      message.warning('最多选择一个商品');
    } else {
      const index = tableData.findIndex((v) => v.id === selectedRowKeys[0]);
      const allIndex = allRentGoods.findIndex((v) => v.id === selectedRowKeys[0]);
      if (index === 0 && pagination.pageNo === 1) {
        message.warning('位置已到最前列，无法上移');
      } else {
        const exReqData =
          index === 0
            ? allRentGoods
                .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.exchangeGoodsInfo({ 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,
                    status: query.status === undefined ? 'all' : query.status,
                  }),
                );
              }
              getGoodsList(query);
              getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
            }
          },
        );
      }
    }
  };
  //下移
  const downRentGoodsClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择商品');
    } else if (selectedRowKeys.length > 1) {
      message.warning('最多选择一个商品');
    } else {
      const index = tableData.findIndex((v) => v.id === selectedRowKeys[0]);
      const allIndex = allRentGoods.findIndex((v) => v.id === selectedRowKeys[0]);
      if (index === tableData.length - 1 && pagination.pageNo === pagination.totalPage) {
        message.warning('位置已到最后，无法下移');
      } else {
        const exReqData =
          index === tableData.length - 1
            ? allRentGoods
                .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.exchangeGoodsInfo({ 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,
                    status: query.status === undefined ? 'all' : query.status,
                  }),
                );
              }
              getGoodsList(query);
              getGoodsList({ ...query, pageNo: 1, pageSize: 9999 }, true);
            }
          },
        );
      }
    }
  };

  useEffect(() => {
    getDirectoryList();
    pagination.pageNo = Number(searchParams.get('pageNo') || 1);
    pagination.pageSize = Number(searchParams.get('pageSize') || 10);
    const queryObj = {
      goodsName: searchParams.get('goodsName') || undefined,
      directoryId: searchParams.get('directoryId')
        ? Number(searchParams.get('directoryId'))
        : undefined,
      startTime: searchParams.get('startTime') || undefined,
      endTime: searchParams.get('endTime') || undefined,
      status:
        searchParams.get('status') === 'all' || searchParams.get('status') === null
          ? undefined
          : Number(searchParams.get('status')),
    };
    getGoodsList(queryObj);
    getGoodsList({ ...queryObj, pageSize: 9999, pageNo: 1 }, true);
    setActiveTabKey(
      searchParams.get('status') === 'all' || searchParams.get('status') === null
        ? '1'
        : Number(searchParams.get('status')) === 1
        ? '2'
        : '3',
    );
    (searchRef.current as any).getForm().setFieldsValue({
      goodsName: searchParams.get('goodsName') || undefined,
      directoryId: searchParams.get('directoryId')
        ? Number(searchParams.get('directoryId'))
        : undefined,
      time: searchParams.get('startTime')
        ? [searchParams.get('startTime'), searchParams.get('endTime')]
        : undefined,
    });
  }, []);
  return (
    <div className='goods-list'>
      <SearchBox
        search={searchColumns}
        child={
          <Button type='primary' icon={<PlusOutlined />} onClick={toAddRentGoods}>
            新增商品
          </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={upGoodsRentClick}
          >
            上移
          </Button>
          <Button
            type='primary'
            style={{ marginRight: '10px' }}
            icon={<ArrowDownOutlined />}
            onClick={downRentGoodsClick}
          >
            下移
          </Button>
          {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 RentList;
