import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Button, Select, Tag } from 'antd';
import { DndProvider } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import styles from '../../style.less';
import DragTag from './DragTag';
import InsertTag from './InsertTag';
import GroupInfo from './GroupInfo';
import { apiDelStorage, apiSortStorage, apiStorageList, apiSupplierShopList } from '../../service';

const GoodsGroup = forwardRef((options, ref) => {
  const [groupEdit, setGroupEdit] = useState(false);
  const [selected, setSelected] = useState(0);
  const [storageId, setStorageId] = useState(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [shops, setShops] = useState([]);
  const [tags, setTags] = useState([]);

  const getShopList = async () => {
    const res = await apiSupplierShopList({
      state: 1,
      productBusiness: 1,
    });
    if (res && res.data && res.data.length > 0) {
      setShops(
        res.data.map(item => ({
          label: item.name,
          value: +item.id,
        })),
      );
      options.changeShop(+res.data[0].id);
    } else {
      options.changeShop(0);
    }
  };

  const getGroupList = async () => {
    if (options.shopId) {
      const res = await apiStorageList({
        shopId: options.shopId,
      });
      if (res && res.data && res.data.length > 0) {
        const arr = res.data
          .sort((x, y) => x.priority - y.priority)
          .map(item => ({
            text: item.name,
            id: item.rackId,
          }));
        setTags(arr);
        setSelected(res.data[0].rackId);
      } else {
        setTags([]);
        setSelected(0);
      }
    } else {
      setTags([]);
      setSelected(0);
    }
  };

  const handleEdit = async id => {
    setStorageId(id || 0);
    setIsModalOpen(true);
  };
  const handleDelete = async id => {
    const res = await apiDelStorage({
      shopId: options.shopId,
      id,
    });
    if (res.businessCode === '0000' && res.code === '0000') {
      getGroupList();
    }
  };

  // 更换位置
  const changePosition = async (dIndex, hIndex) => {
    const data = tags.slice();
    const temp = data[dIndex];
    // 交换位置
    data[dIndex] = data[hIndex];
    data[hIndex] = temp;
    setTags(data);
  };
  const endChangePosition = async () => {
    const data = tags.slice();
    const storageRankList = data.map((item, i) => ({
      id: item.id,
      priority: i + 1,
    }));
    const params = {
      shopId: options.shopId,
      storageRankList,
    };
    await apiSortStorage(params);
    getGroupList();
  };

  const onSelect = i => {
    setSelected(i);
  };

  useEffect(() => {
    if (options.shopId) {
      getGroupList();
    }
  }, [options.shopId]);
  useEffect(() => {
    getShopList();
  }, []);
  useEffect(() => {
    options.changeGroup(selected);
  }, [selected]);

  useImperativeHandle(ref, () => ({
    setSelected,
  }));

  return (
    <div className={styles.groupBox}>
      {(shops && shops.length && (
        <>
          <div className={styles['groupBox-title']}>
            <div className={styles['groupBox-title--name']}>所属门店</div>
            <Select
              showSearch
              value={options.shopId}
              placeholder="请选择所属门店"
              onChange={options.changeShop}
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={shops}
            />
          </div>
          <div className={styles['groupBox-title']}>
            <div className={styles['groupBox-title--name']}>商品分组</div>
            <Button onClick={() => setGroupEdit(!groupEdit)}>
              {groupEdit ? '完成' : '编辑分组'}
            </Button>
          </div>
          <div className={styles['groupBox-body']}>
            {groupEdit ? (
              <DndProvider backend={HTML5Backend}>
                <div className={styles['groupBox-body--dragbox']}>
                  {tags.map((item, index) => (
                    <DragTag
                      changePosition={changePosition}
                      endChangePosition={endChangePosition}
                      index={index}
                      {...item}
                      selected={selected}
                      edit={handleEdit}
                      del={handleDelete}
                      key={item.id}
                    />
                  ))}
                  <InsertTag handleOpen={handleEdit} />
                </div>
              </DndProvider>
            ) : (
              <div className={styles['groupBox-body--dragbox']}>
                {tags.map(item => (
                  <Tag
                    key={item.id}
                    onClick={() => onSelect(item.id)}
                    className={[
                      styles['groupBox-body--tag-normal'],
                      selected === item.id ? styles['groupBox-body--tag__cur'] : '',
                    ]}
                  >
                    <span className={styles['groupBox-body--tag__text']}>{item.text}</span>
                  </Tag>
                ))}
                <InsertTag key="insert" handleOpen={handleEdit} />
              </div>
            )}
          </div>
        </>
      )) ||
        ''}
      <GroupInfo
        isModalOpen={isModalOpen}
        id={storageId}
        shopId={options.shopId}
        search={getGroupList}
        handleClose={setIsModalOpen}
      />
    </div>
  );
});

export default GoodsGroup;
