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, name } = 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.mealTypeList.map(m => m.code),
      saleDateList: item.saleDate,
      tabCateList: item.tabCate.map(t => ({ tabId: t })),
    }));
    const params = {
      enterpriseId: id,
      skuInfoList,
    };
    const res = await apiSaveVirtualGoodsList(params);
    if (res && res.success) {
      notification.success({ message: '添加成功' });
      onCancel();
    }
  };

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

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

  // 刷新列表数据
  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}>{name}</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="清选择"
                value={sleShopID}
                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}>
              <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"
            enterpriseId={id}
            productType={2}
            shopID={sleShopID}
            onSelectChange={setDataSource}
            handleClose={() => setVisibleSelectGoods(false)}
          />
        )}
      </div>
    </PageHeaderWrapper>
  );
};

export default VirtualGoodsInfo;
