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 GoodPriceModal from './components/GoodPriceModal';
import SaleSectionModal from './components/SaleSectionModal';
import SelectGoodsModal from './components/SelectGoodsModal';
import { apiSelPickSelfList, apiPickSelfList, apiSaveGoodsList } from './service';

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

const TakeawayGoodsInfo = 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 [visiblePrice, setVisiblePrice] = useState(false); // 修改企业商品价格弹窗
  const [dataSource, setDataSource] = useState([]);
  const [pickSelfList, setPickSelfList] = useState([]); // 取餐点列表
  const [slePickSelf, setSelPickSelf] = useState([]); // 选中的取餐点列表
  const [editItem, setEditItem] = useState({}); // 编辑信息
  const [shopId, setShopId] = useState(''); // 店铺ID

  // 取消
  const onCancel = () => {
    history.goBack();
  };
  // 提交
  const onSubmit = async () => {
    if (!dataSource || dataSource.length < 1) {
      message.error('请添加商品');
      return;
    }
    const skuInfoList = [];
    try {
      dataSource.forEach(item => {
        if (!item.mealTypeList || item.mealTypeList.length < 1) {
          throw Error('请添加餐品类型！');
        }
        if (!item.enterprisePrice || `${item.enterprisePrice}`.length < 1) {
          throw Error('请添加企业价格！');
        }
        if (!item.saleDate || item.saleDate.length < 1) {
          throw Error('请添加可售日期！');
        }
        if (!item.tabCate || item.tabCate.length < 1) {
          throw Error('请添加可售餐段！');
        }
        const json = {
          skuId: item.skuId,
          enterprisePrice: item.enterprisePrice,
          mealTypeList: item.mealTypeList.map(m => m.code),
          saleDateList: item.saleDate,
          tabCateList: item.tabCate.map(t => ({ tabId: t })),
        };
        skuInfoList.push(json);
      });
    } catch (e) {
      message.error(e.message);
      return;
    }
    const params = {
      shopId,
      enterpriseId: id,
      pickSelfIdList: slePickSelf,
      skuInfoList,
    };
    console.log('params :>> ', params);
    const res = await apiSaveGoodsList(params);
    if (res && res.success) {
      notification.success({ message: '添加成功' });
      onCancel();
    }
  };

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

  // 根据企业ID获取取餐点
  const getPickSelf = async () => {
    const res = await apiPickSelfList();
    if (res && res.data && res.data.records) {
      setPickSelfList(
        res.data.records.map(item => ({
          value: item.id,
          label: item.pickselfName,
        })),
      );
    }
  };
  // 根据企业ID获取已选取餐点
  const getSelPickSelf = async () => {
    const res = await apiSelPickSelfList({
      enterpriseId: id,
    });
    if (res && res.data) {
      setSelPickSelf(res.data.map(item => item.pickSelfId));
    }
  };

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

  // 显示选择商品弹窗
  const onShowSelect = () => {
    if (!slePickSelf || slePickSelf.length < 1) {
      message.error('请选择取餐点!');
      return;
    }
    setVisibleSelectGoods(true);
  };

  useEffect(() => {
    getPickSelf();
    getSelPickSelf();
  }, []);

  const options = {
    setVisibleSaleDate,
    setVisibleSaleSection,
    setEditItem,
    onDel,
    setVisiblePrice,
  };

  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
                mode="multiple"
                showSearch
                options={pickSelfList}
                className={style['info-box--select']}
                placeholder="清选择"
                value={slePickSelf}
                onChange={setSelPickSelf}
                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={() => onShowSelect()}>
                选择商品
              </Button>
            </Col>
          </Row>
          <Row className={style['info-box--line']}>
            <Col span={24}>
              <div className={style['info-box--batch-btn']}>
                <Button
                  onClick={() => {
                    setEditItem({});
                    setVisibleSaleDate(true);
                  }}
                >
                  批量配置日期
                </Button>
                <Button
                  onClick={() => {
                    setEditItem({});
                    setVisibleSaleSection(true);
                  }}
                >
                  批量配置餐段
                </Button>
              </div>
              <Table
                columns={GoodsInfoColumn(options)}
                pagination={false}
                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}
            item={editItem}
            handleRefresh={v => refreshList('saleDate', v)}
            handleClose={() => setVisibleSaleDate(false)}
          />
        )}
        {/* 可售餐段弹窗 */}
        {visibleSaleSection && (
          <SaleSectionModal
            visible={visibleSaleSection}
            item={editItem}
            handleRefresh={v => refreshList('tabCate', v)}
            handleClose={() => setVisibleSaleSection(false)}
          />
        )}
        {/* 修改企业商品价格弹窗 */}
        {visiblePrice && (
          <GoodPriceModal
            visible={visiblePrice}
            item={editItem}
            handleRefresh={v => refreshList('enterprisePrice', v)}
            handleClose={() => setVisiblePrice(false)}
          />
        )}
        {/* 选择商品弹窗 */}
        {visibleSelectGoods && (
          <SelectGoodsModal
            visible={visibleSelectGoods}
            enterpriseId={id}
            productType={5}
            pickSelfIdList={slePickSelf}
            shopID={shopId}
            item={editItem}
            onChangeShop={setShopId}
            onSelectChange={setDataSource}
            handleClose={() => setVisibleSelectGoods(false)}
          />
        )}
      </div>
    </PageHeaderWrapper>
  );
};

export default TakeawayGoodsInfo;
