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 { SelectGoodsColumn, productType, weekOptions } 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 [shopId, setShopId] = useState(props.shopID || null);
  const [shopName, setShopName] = 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(props.selectedRowKeys || []);
  const [selectedRows, setSelectedRows] = useState(props.selectedRows || []);

  const searchList = async params => {
    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);
    const arr =
      res?.data?.records?.map(item => {
        item.enterprisePrice = item.salePrice;
        return item;
      }) || [];
    setDataSource(arr);
    setTotal(res?.data?.total || 0);
    setLoading(false);
  };

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

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

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

  // 提交
  const handleConfirm = async () => {
    if (!selectedRows || selectedRows.length < 1) {
      notification.error({ message: $t('select.products.to.add') });
      return;
    }
    let sName = '';
    if (shopList && shopList.length) {
      shopList.forEach(item => {
        if (+item.value === +shopId) {
          sName = item.label;
        }
      });
    } else {
      sName = shopName;
    }
    const arr = deepClone(selectedRows).map(item => ({
      ...item,
      shopId,
      saleDate:
        !item.saleDate || item.saleDate.length < 1 ? Object.keys(weekOptions) : item.saleDate,
      shopName: sName,
    }));
    props.onSelectChange(arr);
    if (!props.shopID) {
      props.onChangeShop(shopId);
    }
    if (props.onSelectedRowKeys) {
      props.onSelectedRowKeys(selectedRowKeys);
    }
    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];
    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) {
      setShopList(
        res.data.map(item => ({
          label: item.name,
          value: item.id,
        })),
      );
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onSelect: onSelectChange,
    onSelectAll: onSelectAllChange,
    getCheckboxProps: record => ({
      disabled: !!record.selected,
    }),
  };
  const onChangeSearchType = v => {
    setSearchType(v);
    setSearchName('');
  };
  const selectBefore = (
    <Select defaultValue="1" onChange={onChangeSearchType}>
      <Option value="1" key={1}>{$t('name')}</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']}>{$t('selected')}<span className={style['footers-num']}>{selectedRowKeys.length}</span>)
        </div>
        <Button key="back" onClick={handleCancel}>{$t('cancel')}</Button>
        <Button key="submit" type="primary" loading={loading} onClick={handleConfirm}>{$t('confirm')}</Button>
      </div>
    </div>,
  ];

  useEffect(() => {
    if (+props.productType === 5) {
      setShopId(null);
      getShopList();
    } else {
      setShopId(props.shopID);
      setShopName(props.shopName);
      searchList({});
    }
  }, []);

  return (
    <Modal
      title={$t('select.products')}
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="1000px"
      onOk={handleConfirm}
      onCancel={handleCancel}
      footer={footers()}
    >
      <div className={style['select-goods-box']}>
        {props.productType === 5 ? (
          <Select
            placeholder={$t('select.store')}
            options={shopList}
            value={shopId}
            onChange={onChangeShop}
            className={style['select-goods-box--select']}
          />
        ) : (
          <Input disabled value={shopName} className={style['select-goods-box--txt']} />
        )}
        <Select
          placeholder={$t('select.product.type')}
          disabled
          value={`${props.productType}`}
          options={jsonToArray(productType)}
          className={style['select-goods-box--select']}
        />
        <Input
          addonBefore={selectBefore}
          addonAfter={selectAfter}
          value={searchName}
          allowClear
          type={+searchType === 2 ? 'number' : 'text'}
          onChange={e => setSearchName(e.target.value)}
          onPressEnter={onSearch}
          className={style['select-goods-box--txt']}
        />
      </div>
      <Table
        rowSelection={rowSelection}
        rowKey="skuId"
        columns={SelectGoodsColumn}
        pagination={false}
        dataSource={dataSource}
      />
    </Modal>
  );
};
export default SaleDateModal;
