import React, { useRef, useState, useEffect } from 'react';
import { Button, notification, Spin, Select, Row, Col, Table, message } from 'antd';
import { useHistory } from 'react-router-dom';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { GoodsInfoColumn } from './staticData/goods';
import SaleDateModal from './components/SaleDateModal';
import SaleSectionModal from './components/SaleSectionModal';
import SelectGoodsModal from './components/SelectGoodsModal';
import { apiSaveVirtualGoodsList, apiShopListByEnterpriseID } from './service';

import style from './style/index.less';

const VirtualGoodsInfo = props => {
  const { id } = props.location.query;
  const history = useHistory();
  const [loading, setLoading] = useState(false);
  const [visibleSaleDate, setVisibleSaleDate] = useState(false); // 可售日期弹窗
  const [visibleSaleSection, setVisibleSaleSection] = useState(false); // 可售餐段弹窗
  const [visibleSelectGoods, setVisibleSelectGoods] = useState(false); // 选择商品弹窗
  const [dataSource, setDataSource] = useState([]);
  const [shopList, setShopList] = useState([]); // 店铺列表
  const [sleShopID, setSelShopID] = useState(''); // 选中的店铺
  const [editID, setEditID] = useState(''); // 编辑ID

  // 取消
  const onCancel = () => {
    history.goBack();
  };
  // 提交
  const onSubmit = async () => {
    if (!dataSource || dataSource.length < 1) {
      message.error('请添加商品');
      return;
    }
    const skuInfoList = dataSource.map(item => ({
      skuId: item.skuId,
      enterprisePrice: item.enterprisePrice,
      mealTypeList: item.mealType,
      saleDateList: item.saleDate,
    }));
    const params = {
      shopId: sleShopID,
      enterpriseId: id,
      skuInfoList,
    };
    await apiSaveVirtualGoodsList(params);
    notification.success({ message: '添加成功' });
    onCancel();
  };

  // 删除
  const onDel = i => {
    const arr = dataSource.splice(i, 1);
    setDataSource(arr);
  };

  // 根据企业ID获取店铺列表
  const getShopList = async () => {
    const res = await apiShopListByEnterpriseID({
      enterpriseId: id,
    });
    setShopList(
      res.map(item => ({
        key: item.id,
        label: <span>{item.name}</span>,
      })),
    );
  };

  // 刷新列表数据
  const refreshList = (type, v) => {
    const arr = dataSource.map(item => {
      if (editID) {
        if (item.skuId === editID) {
          item[type] = v;
        }
      } else {
        item[type] = v;
      }
      return item;
    });
    setDataSource(arr);
  };

  // const initData = async () => {
  //   setLoading(true);
  // };
  useEffect(() => {
    getShopList();
  }, []);

  const options = {
    setVisibleSaleDate,
    setVisibleSaleSection,
    setEditID,
    onDel,
  };

  return (
    <PageHeaderWrapper title="添加企业严选商品">
      <div className={style['info-box']}>
        <Spin spinning={loading}>
          <Row className={style['info-box--line']}>
            <Col span={3} className={style['info-box--label']}>
              企业名称：
            </Col>
            <Col span={20}>企业名称111</Col>
          </Row>
          <Row className={style['info-box--line']}>
            <Col span={3} className={style['info-box--label']}>
              选择店铺：
            </Col>
            <Col span={20}>
              <Select
                showSearch
                options={shopList}
                className={style['info-box--select']}
                placeholder="清选择"
                onChange={setSelShopID}
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
              />
            </Col>
          </Row>
          <Row className={style['info-box--line']}>
            <Col span={3} className={style['info-box--label']}>
              添加商品：
            </Col>
            <Col span={20}>
              <Button type="primary" onClick={() => setVisibleSelectGoods(true)}>
                选择商品
              </Button>
            </Col>
          </Row>
          <Row className={style['info-box--line']}>
            <Col span={24}>
              <div className={style['info-box--batch-btn']}>
                <Button
                  onClick={() => {
                    setEditID('');
                    setVisibleSaleDate(true);
                  }}
                >
                  批量配置日期
                </Button>
                <Button
                  onClick={() => {
                    setEditID('');
                    setVisibleSaleSection(true);
                  }}
                >
                  批量配置餐段
                </Button>
              </div>
              <Table columns={GoodsInfoColumn(options)} dataSource={dataSource} />
            </Col>
          </Row>
          <Row className={style['info-box--btns']}>
            <Col span={4} />
            <Col span={20}>
              <Button
                type="primary"
                onClick={onSubmit}
                className={style['info-box--btns__confirm']}
              >
                确定
              </Button>
              <Button onClick={onCancel}>取消</Button>
            </Col>
          </Row>
        </Spin>
        {/* 可售日期弹窗 */}
        {visibleSaleDate && (
          <SaleDateModal
            visible={visibleSaleDate}
            handleRefresh={v => refreshList('saleDate', v)}
            handleClose={() => setVisibleSaleDate(false)}
          />
        )}
        {/* 可售餐段弹窗 */}
        {visibleSaleSection && (
          <SaleSectionModal
            visible={visibleSaleSection}
            handleRefresh={v => refreshList('mealType', v)}
            handleClose={() => setVisibleSaleSection(false)}
          />
        )}
        {/* 选择商品弹窗 */}
        {visibleSelectGoods && (
          <SelectGoodsModal
            visible={visibleSelectGoods}
            type="virtual"
            onSelectChange={setDataSource}
            handleClose={() => setVisibleSelectGoods(false)}
          />
        )}
      </div>
    </PageHeaderWrapper>
  );
};

export default VirtualGoodsInfo;
