import React, { useState, useEffect } from 'react';
import { Select, Modal, Table, Input, Button, Pagination, notification } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { apiSelGoodsList, apiSelVirtualGoodsList, apiShopListByPickSelfID } from '../service';
import { getShopListByPickSelf } from '../service/bll';
import { SelectGoodsColumn, productType } from '../staticData/goods';
import style from '../style/index.less';
import { jsonToArray, deepClone } from '@/utils/utils';

const { Option } = Select;
const SaleDateModal = props => {
  const [searchType, setSearchType] = useState('1');
  const [searchKeyword, setSearchKeyword] = useState('');
  // const [goodsType, setGoodsType] = useState('1');
  const [shopId, setShopId] = useState();
  const [searchName, setSearchName] = useState('');
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [shopList, setShopList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);

  const searchList = async params => {
    console.log('params :>> ', params);
    console.log('searchType :>> ', searchType);
    console.log('shopId :>> ', shopId);
    const { enterpriseId } = props;
    const searchObj = {};
    if (searchKeyword && searchType && !params.search) {
      if (searchType === '1') {
        searchObj.name = searchKeyword;
      } else {
        searchObj.skuId = searchKeyword;
      }
    }
    const data = {
      page: params.current || page,
      size: params.pageSize || pageSize,
      data: Object.assign(
        {
          shopId,
          productType: props.productType,
          enterpriseId,
        },
        searchObj,
        params,
      ),
    };
    setLoading(true);
    let api = apiSelGoodsList;
    if (props.type === 'virtual') {
      api = apiSelVirtualGoodsList;
    }
    const res = await api(data);
    console.log('res :>> ', res);
    if (res && res.data && res.data.records) {
      setDataSource(res.data.records);
      setTotal(res.data.total);
    }
    setLoading(false);
  };

  // 点击搜索
  const onSearch = () => {
    setSearchKeyword(searchName);
    searchList({ [searchType === '1' ? 'name' : 'skuId']: searchName });
  };

  // 切换店铺
  const onChangeShop = v => {
    setShopId(v);
    searchList({
      shopId: v,
    });
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  // 关闭弹窗
  const handleCancel = () => {
    props.handleClose(false);
  };

  // 提交
  const handleConfirm = async () => {
    if (!selectedRows || selectedRows.length < 1) {
      notification.error({ message: '请选择要添加的商品' });
      return;
    }
    let shopName = '';
    if (shopList) {
      shopList.forEach(item => {
        if (+item.value === +shopId) {
          shopName = item.label;
        }
      });
    }
    const arr = deepClone(selectedRows).map(item => ({
      ...item,
      shopId,
      shopName,
    }));
    props.onSelectChange(arr);
    props.onChangeShop(shopId);
    handleCancel();
  };

  // 商品单选
  const onSelectChange = (record, selected) => {
    const { skuId } = record;
    if (selected) {
      const keys = [...selectedRowKeys, skuId];
      const arr = [...selectedRows, record];
      setSelectedRowKeys(keys);
      setSelectedRows(arr);
    } else {
      const rows = [];
      const keys = [];
      selectedRows.forEach(item => {
        if (item.skuId !== skuId) {
          rows.push(item);
          keys.push(item.skuId);
        }
      });
      setSelectedRowKeys(keys);
      setSelectedRows(rows);
    }
  };
  // 商品全选
  const onSelectAllChange = (selected, rows) => {
    const keys = [...selectedRowKeys];
    const arr = [...selectedRows];
    console.log('selected :>> ', selected);
    console.log('rows :>> ', rows);
    if (selected) {
      rows.forEach(item => {
        if (item && !keys.includes(item.skuId)) {
          keys.push(item.skuId);
          arr.push(item);
        }
      });
      setSelectedRowKeys(keys);
      setSelectedRows(arr);
    } else {
      dataSource.forEach(item => {
        const index = keys.findIndex(k => k === item.skuId);
        if (index > -1) {
          keys.splice(index, 1);
          arr.splice(index, 1);
        }
      });
      setSelectedRowKeys(keys);
      setSelectedRows(arr);
    }
  };

  // 切换页码
  const onPageChange = (current, size) => {
    setPage(current);
    setPageSize(size);
    searchList({
      current,
      pageSize: size,
    });
  };

  // 获取店铺列表
  const getShopList = async () => {
    const res = await apiShopListByPickSelfID({
      enterpriseId: props.enterpriseId,
      pickSelfIdList: props.pickSelfIdList,
    });
    if (res && res.data) {
      console.log('getShopList res :>> ', res);
      setShopList(
        res.data.map(item => ({
          label: item.name,
          value: item.id,
        })),
      );
      // searchList({});
    }
    // setShopList(res);
  };

  const rowSelection = {
    selectedRowKeys,
    onSelect: onSelectChange,
    onSelectAll: onSelectAllChange,
  };
  const selectBefore = (
    <Select defaultValue="1" onChange={setSearchType}>
      <Option value="1" key={1}>
        名称
      </Option>
      <Option value="2" key={2}>
        SKU
      </Option>
    </Select>
  );
  const selectAfter = <SearchOutlined onClick={onSearch} />;
  const footers = () => [
    <div className={style.footers} key="footer">
      <Pagination defaultCurrent={1} total={total} showQuickJumper onChange={onPageChange} />
      <div className={style['footers-btn']}>
        <div className={style['footers-desc']}>
          已选商品(<span className={style['footers-num']}>{selectedRows.length}</span>)
        </div>
        <Button key="back" onClick={handleCancel}>
          取消
        </Button>
        <Button key="submit" type="primary" loading={loading} onClick={handleConfirm}>
          确定
        </Button>
      </div>
    </div>,
  ];

  useEffect(() => {
    getShopList();
    // setGoodsType(props.productType);
  }, []);

  return (
    <Modal
      title="选择商品"
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="1000px"
      onOk={handleConfirm}
      onCancel={handleCancel}
      footer={footers()}
    >
      <div className={style['select-goods-box']}>
        <Select
          placeholder="请选择店铺"
          options={shopList}
          value={shopId}
          onChange={onChangeShop}
          className={style['select-goods-box--select']}
        />
        <Select
          placeholder="请选择商品类型"
          disabled
          value={`${props.productType}`}
          options={jsonToArray(productType)}
          className={style['select-goods-box--select']}
        />
        <Input
          addonBefore={selectBefore}
          addonAfter={selectAfter}
          onChange={e => setSearchName(e.target.value)}
          className={style['select-goods-box--txt']}
        />
      </div>
      <Table
        rowSelection={rowSelection}
        rowKey="skuId"
        columns={SelectGoodsColumn}
        pagination={false}
        dataSource={dataSource}
      />
    </Modal>
  );
};
export default SaleDateModal;
