import React, { useState, useEffect, useRef } from 'react';
import { Spin, Table, Pagination, message, notification } from 'antd';
import { unstable_batchedUpdates } from 'react-dom';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';
import { GOOD_MANAGE } from '@/../config/permission.config';
import PubSub from 'pubsub-js';
import GoodsGroup from './components/GoodsGroup';
import {
  apiTakeawayGoods,
  apiGoodsActionBatch,
  apiSortTakeawayGoods,
  apiTopTakeawayGoods,
} from '../service';
import styles from '../style.less';
import { takeawayColumn } from '../staticdata';
// import VirtualTable from './components/VirtualTable';
import ActionBar from './components/ActionBar';
import WeekTime from './components/WeekTime';
import StockModal from './components/StockModal';
import SendModal from './components/SendModal';
import MinimumPurchaseModal from './components/MinimumPurchase';
import SwitchGroupModal from './components/SwitchGroupModal';

const Takeaway = options => {
  const [tableData, setTableData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [shopId, setShopId] = useState(0);
  const [groupId, setGroupId] = useState(0);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(50);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);
  const [visibleWeekTime, setVisibleWeekTime] = useState(false);
  const [visibleStock, setVisibleStock] = useState(false);
  const [visibleBuy, setVisibleBuy] = useState(false);
  const [visibleSend, setVisibleSend] = useState(false);
  const [visibleSwitchGroup, setVisibleSwitchGroup] = useState(false);
  const [scribeToken, setScribeToken] = useState('');

  const groupRef = useRef(null);

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const getDataList = async (page = pageNo, size = pageSize, storageRackId = groupId) => {
    setLoading(true);
    const params = Object.assign({}, options.searchValue, {
      pageNo: page || pageNo,
      productType: 5,
      pageSize: size || pageSize,
      storageRackId,
    });
    const productCategoryId = options.searchValue?.productCategoryId || [];
    params.productCategoryId =
      (productCategoryId.length && productCategoryId[productCategoryId.length - 1]) || '';
    const res = await apiTakeawayGoods(params);
    setLoading(false);
    if (res && res.data) {
      setTableData(res.data.records || []);
      setTotal(res.data.total || 0);
    }
  };
  const onPageChange = (page, size) => {
    unstable_batchedUpdates(() => {
      setPageNo(page);
      setPageSize(size);
    });
    getDataList(page, size);
  };

  const onSortEnd = async ({ oldIndex, newIndex }) => {
    if (oldIndex !== newIndex) {
      const sourceGoods = tableData[oldIndex];
      const targetGoods = tableData[newIndex];
      // const newData = arrayMoveImmutable(tableData.slice(), oldIndex, newIndex).filter(el => !!el);
      // const skuSorts = newData.map((item, index) => ({
      //   skuId: item.skuId,
      //   sort: pageSize * (pageNo - 1) + index + 1,
      // }));
      if (sourceGoods && sourceGoods.skuId && targetGoods && targetGoods.skuId) {
        const params = {
          storageRackId: groupId,
          shopId,
          sourceSkuId: sourceGoods.skuId,
          targetSkuId: targetGoods.skuId,
        };
        await apiSortTakeawayGoods(params);
        getDataList(pageNo, pageSize);
      }
    }
  };

  const SortableItem = SortableElement(props => <tr {...props} />);
  const SortableBody = SortableContainer(props => <tbody {...props} />);

  const DraggableContainer = props => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass={styles['row-dragging']}
      onSortEnd={onSortEnd}
      {...props}
    />
  );

  const DraggableBodyRow = ({ className, style, ...restProps }) => {
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = tableData.findIndex(x => x.skuId === restProps['data-row-key']);
    return <SortableItem index={index} {...restProps} />;
  };

  // 批量操作 type 1-是否列出 2-修改上下架   3-改货架  4-售卖时间更新  5-调整商品起购数量 6-调整商品是否单点不送   7-修改库存
  const handleBatchAction = async params => {
    const json = {
      skuIds: selectedRowKeys,
      shopId,
    };
    setActionLoading(true);
    const res = await apiGoodsActionBatch(Object.assign({}, json, params));
    setActionLoading(false);
    if (res.businessCode === '0000' && res.code === '0000') {
      message.success('处理成功！');
      unstable_batchedUpdates(() => {
        setActionLoading(false);
        setVisibleWeekTime(false);
        setVisibleStock(false);
        setVisibleSwitchGroup(false);
        setVisibleBuy(false);
        setVisibleSend(false);
      });
      getDataList(pageNo, pageSize);
    }
  };

  // 显示弹窗
  const openModal = type => {
    type === 'time' && setVisibleWeekTime(true);
    type === 'stock' && setVisibleStock(true);
    type === 'group' && setVisibleSwitchGroup(true);
    type === 'buy' && setVisibleBuy(true);
    type === 'send' && setVisibleSend(true);
  };

  // 单商品修改库存
  const onShowStockModal = ({ skuId }) => {
    setSelectedRowKeys([skuId]);
    openModal('stock');
  };
  // 编辑
  const onEdit = ({ spuId, skuId }) => {
    options.handleEdit({
      shopId,
      spuId,
      skuId,
    });
  };
  // 新建商品
  const onNew = () => {
    options.handleEdit({
      shopId,
      groupId,
    });
  };
  // 置顶
  const toTop = async ({ skuId }) => {
    // onSortEnd({ oldIndex, newIndex: 0 });
    const res = await apiTopTakeawayGoods({
      productItemId: skuId,
      shopId,
      storageRackId: groupId,
    });
    if (res.businessCode === '0000' && res.code === '0000') {
      getDataList(pageNo, pageSize);
      message.success('处理成功！');
    }
  };

  useEffect(() => {
    if (groupId) {
      setPageNo(1);
      getDataList(1, pageSize);
    } else {
      setTableData([]);
    }
  }, [groupId, options.refresh]);

  useEffect(() => {
    const stoken = PubSub.subscribe('refreshTakeAway', (_, data) => {
      console.log('refreshTakeAway :>> ', data);
      if (data.groupId && groupId !== data.groupId) {
        setGroupId(data.groupId);
        if (groupRef.current) {
          groupRef.current.setSelected(`${data.groupId}`);
        }
      }
    });
    setScribeToken(stoken);

    return () => {
      PubSub.unsubscribe(scribeToken);
    };
  }, []);

  const actions = {
    onShowStockModal,
    toTop,
    onEdit,
    getDataList,
    shopId,
    pageNo,
  };

  const canAddTakeaway = options.permissions[GOOD_MANAGE.ADD_TAKEAWAY_GOODS];

  return (
    <div className={styles.takeawayBox}>
      <Spin spinning={loading}>
        <GoodsGroup
          ref={groupRef}
          shopId={shopId}
          changeShop={setShopId}
          changeGroup={setGroupId}
        />
        {(shopId && (
          <ActionBar
            selectedRowKeys={selectedRowKeys}
            shopId={shopId}
            canAddTakeaway={canAddTakeaway}
            handleSearch={getDataList}
            openModal={openModal}
            newGoods={onNew}
          />
        )) ||
          ''}
        <Table
          dataSource={tableData}
          bordered
          columns={takeawayColumn(actions)}
          rowKey={record => record.skuId}
          pagination={false}
          scroll={{ x: '100%', y: 500 }}
          rowSelection={rowSelection}
          components={{
            body: {
              wrapper: DraggableContainer,
              row: DraggableBodyRow,
            },
          }}
        />
        <br />
        {(tableData && (
          <Pagination
            className={styles['takeawayBox--page']}
            onChange={onPageChange}
            total={total}
            showTotal={o => `共${o}条`}
            current={pageNo}
            pageSize={pageSize}
            showSizeChanger
            onShowSizeChange={onPageChange}
          />
        )) ||
          ''}
      </Spin>
      <WeekTime
        visible={visibleWeekTime}
        loading={actionLoading}
        confirm={handleBatchAction}
        cancel={setVisibleWeekTime}
      />
      <StockModal
        visible={visibleStock}
        loading={actionLoading}
        skuIds={selectedRowKeys}
        shopId={shopId}
        confirm={handleBatchAction}
        cancel={setVisibleStock}
      />
      <SendModal
        visible={visibleSend}
        loading={actionLoading}
        confirm={handleBatchAction}
        cancel={setVisibleSend}
      />
      <MinimumPurchaseModal
        visible={visibleBuy}
        loading={actionLoading}
        confirm={handleBatchAction}
        cancel={setVisibleBuy}
      />
      <SwitchGroupModal
        visible={visibleSwitchGroup}
        loading={actionLoading}
        confirm={handleBatchAction}
        cancel={setVisibleSwitchGroup}
      />
    </div>
  );
};

export default Takeaway;
