import SearchBox, { searchColumns as searchColumnsType } from '~/components/search-box';
import { Button, Card, Image, message, Modal, Table } from 'antd';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  DeleteOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { useEffect, useRef, useState } from 'react';
import { ColumnsType } from 'antd/es/table';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { RentManageAPI } from '../../../../api';
import { InterDataType, InterReqListType, PaginationProps } from '../../../../api/interface';
import { leaseGoodsListType } from '../../../../api/interface/rentManageType';
import './index.scss';
import qs from 'query-string';
import { useSelector } from 'react-redux';

//租赁列表返回类型
type rentGoodsType = InterDataType<leaseGoodsListType>['list'];
//租赁列表参数类型
type rentGoodsParametersType = Exclude<InterReqListType<leaseGoodsListType>, undefined>;

const RentList = () => {
  const searchRef = useRef<any>();

  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  //类型下拉列表
  const [rentTypeSelectList, setRentTypeSelectList] = useState<{ label: string; value: number }[]>(
    [],
  );
  //品牌下拉列表
  const [brandInfoList, setBrandInfoList] = useState<{ label: string; value: number }[]>([]);

  const searchColumns: searchColumnsType[] = [
    {
      label: '商品名称',
      name: 'tradeName',
      type: 'input',
      placeholder: '请输入商品名称',
    },
    {
      label: '商品类型',
      name: 'productTypeId',
      type: 'Select',
      placeholder: '请选择商品类型',
      options: rentTypeSelectList,
    },
    {
      label: '商品品牌',
      name: 'brandInfoId',
      type: 'Select',
      placeholder: '请选择商品品牌',
      options: brandInfoList,
    },
  ];

  const tabList = [
    {
      key: '1',
      tab: '全部',
    },
    {
      key: '2',
      tab: '上架中',
    },
    {
      key: '3',
      tab: '仓库中',
    },
  ];
  const [activeTabKey, setActiveTabKey] = useState<string>('1');
  const tableColumns: ColumnsType<rentGoodsType[0]> = [
    {
      title: '商品名称',
      width: '30%',
      onHeaderCell: () => ({
        style: {
          textAlign: 'center',
        },
      }),
      render: (_: any, record) => (
        <div className='rent-goods-info'>
          <div className='goods-img'>
            <Image
              src={record.resourcesList.find((v) => v.type === 0)?.url}
              width={50}
              height={50}
            />
          </div>
          <div className='info-meta'>
            <div className='title'>{record.tradeName}</div>
            <div className='type'>
              {rentTypeSelectList.find((v) => v.value === record.productTypeId)?.label}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '押金范围',
      align: 'center',
      dataIndex: 'cashPledgeRange',
    },
    {
      title: '租金范围（日）',
      align: 'center',
      dataIndex: 'rentalRange',
    },
    {
      title: '库存',
      align: 'center',
      dataIndex: 'stock',
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'shelfStatus',
      render: (text: number) => (text ? '上架' : '下架'),
    },
    {
      title: '操作',
      align: 'center',
      width: '20%',
      render: (_: any, record) => (
        <>
          <Button type='link' onClick={() => toRentEdit(record)}>
            编辑
          </Button>
          <Button type='link' onClick={() => toRentDetail(record)}>
            详情
          </Button>
          <Button
            type='link'
            disabled={!!record.shelfStatus}
            onClick={() => batchOnShelfOrTakeDownRequest([record.id], 1)}
          >
            上架
          </Button>
          <Button
            type='link'
            disabled={!record.shelfStatus}
            onClick={() => batchOnShelfOrTakeDownRequest([record.id], 0)}
          >
            下架
          </Button>
          <Button type='link' danger onClick={() => batchRemoveWareInfoRequest([record.id])}>
            删除
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<rentGoodsType>([]);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [query, setQuery] = useState<rentGoodsParametersType>({
    shelfStatus: undefined,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onTabChange = (key: string) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setActiveTabKey(key);
    query.shelfStatus = key === '1' ? undefined : key === '2' ? 1 : 0;
    setSearchParams(
      qs.stringify({
        pageNo: 1,
        pageSize: 10,
        ...query,
        shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
      }),
    );
    setQuery(query);
    getRentGoodsList(query);
  };

  //租赁商品列表
  const getRentGoodsList = (query?: rentGoodsParametersType) => {
    RentManageAPI.getLeaseGoodsList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      pagination.totalCount = result.totalCount;
      setPagination({ ...pagination });
      setTableData(result.list || []);
    });
  };
  //新增，编辑租赁商品
  const addOrEditClick = () => {
    navigate({ pathname: '/rentManage/rentGoods/add' });
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getRentGoodsList(query);
    setSearchParams(
      qs.stringify({
        pageNo,
        pageSize,
        ...query,
        shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
      }),
    );
  };
  //筛选
  const searchSuccess = (value: rentGoodsParametersType) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setSearchParams(
      qs.stringify({
        pageNo: 1,
        pageSize: 10,
        ...value,
        shelfStatus: query.shelfStatus === undefined ? 'all' : query.shelfStatus,
      }),
    );
    setQuery(value);
    getRentGoodsList(value);
  };

  //获取类型列表
  const getRentTypeList = () => {
    RentManageAPI.getTypeList({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      if (result.list) {
        setRentTypeSelectList(result.list.map((v) => ({ value: v.id, label: v.name })));
      }
    });
  };
  //品牌列表
  const getRentMakeList = () => {
    RentManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      if (result.list) {
        const optionList = result.list.map((v) => ({ label: v.brandName, value: v.id }));
        setBrandInfoList(optionList);
      }
    });
  };
  //跳转租赁商品编辑
  const toRentEdit = (record: rentGoodsType[0]) => {
    navigate({ pathname: '/rentManage/rentGoods/edit', search: `id=${record.id}` });
  };
  //跳转租赁详情
  const toRentDetail = (record: rentGoodsType[0]) => {
    navigate({ pathname: '/rentManage/rentGoods/detail', search: `id=${record.id}` });
  };
  //批量上下架操作
  const batchOnShelfOrTakeDownClick = (status: number) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择租赁商品');
    } else {
      batchOnShelfOrTakeDownRequest(selectedRowKeys as number[], status);
    }
  };
  //批量上下架请求
  const batchOnShelfOrTakeDownRequest = (goodsIds: number[], status: number) => {
    Modal.confirm({
      title: '提示',
      content: status
        ? '是否确认上架？商品上架后,请到出租中的商品查看并管理。'
        : '是否确认下架？商品下架后请到仓库中的商品查看并管理',
      onOk: () => {
        RentManageAPI.batchOnShelfOrTakeDown({ goodsIds, status }).then(({ code }) => {
          if (code === '200') {
            message.success(`${status ? '上架' : '下架'}成功`);
            getRentGoodsList(query);
            setSelectedRowKeys([]);
          }
        });
      },
    });
  };
  //批量删除操作
  const batchRemoveWareInfoClick = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择租赁商品');
    } else {
      batchRemoveWareInfoRequest(selectedRowKeys as number[]);
    }
  };
  //批量删除请求
  const batchRemoveWareInfoRequest = (ids: number[]) => {
    Modal.confirm({
      title: '提示',
      content: `确认删除${ids.length > 1 ? '这些' : '该'}商品`,
      onOk: () => {
        RentManageAPI.batchRemoveWareInfo(ids).then(({ code }) => {
          if (code === '200') {
            if (ids.length === tableData.length && pagination.pageNo !== 1) {
              pagination.pageNo -= 1;
            }
            getRentGoodsList(query);
            message.success('删除成功');
          }
        });
      },
    });
  };
  //表格-选择
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  useEffect(() => {
    pagination.pageNo = Number(searchParams.get('pageNo')) || 1;
    pagination.pageSize = Number(searchParams.get('pageSize')) || 10;
    const searchData = {
      tradeName: searchParams.get('tradeName') || undefined,
      productTypeId: searchParams.get('productTypeId')
        ? Number(searchParams.get('productTypeId'))
        : undefined,
      brandInfoId: searchParams.get('brandInfoId')
        ? Number(searchParams.get('brandInfoId'))
        : undefined,
      shelfStatus: searchParams.get('shelfStatus')
        ? searchParams.get('shelfStatus') === 'all'
          ? undefined
          : Number(searchParams.get('shelfStatus'))
        : undefined,
    };
    searchRef.current.getForm().setFieldsValue(searchData);
    setActiveTabKey(
      searchParams.get('shelfStatus')
        ? searchParams.get('shelfStatus') === 'all'
          ? '1'
          : Number(searchParams.get('shelfStatus')) === 1
          ? '2'
          : '3'
        : '1',
    );
    setQuery(searchData);
    getRentGoodsList(searchData);
    getRentTypeList();
    getRentMakeList();
  }, []);

  return (
    <div className='rent-list'>
      <SearchBox
        search={searchColumns}
        child={
          <>
            <Button
              icon={<PlusOutlined />}
              type='primary'
              onClick={addOrEditClick}
              disabled={!!userInfo.roleInfo.superAdmin}
            >
              新增商品
            </Button>
          </>
        }
        searchData={searchSuccess}
        baseRef={searchRef}
      />
      <Card tabList={tabList} activeTabKey={activeTabKey} onTabChange={onTabChange}>
        <div className='table-operate' style={{ marginBottom: '10px' }}>
          <Button
            type='primary'
            icon={<ArrowUpOutlined />}
            style={{ marginRight: '10px' }}
            onClick={() => batchOnShelfOrTakeDownClick(1)}
          >
            批量上架
          </Button>
          <Button
            type='primary'
            icon={<ArrowDownOutlined />}
            style={{ marginRight: '10px' }}
            onClick={() => batchOnShelfOrTakeDownClick(0)}
          >
            批量下架
          </Button>
          <Button
            type='primary'
            danger
            icon={<DeleteOutlined />}
            onClick={batchRemoveWareInfoClick}
          >
            批量删除
          </Button>
        </div>
        <Table
          columns={tableColumns}
          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} 条数据`,
          }}
          rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
        />
      </Card>
    </div>
  );
};
export default RentList;
