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 { jsonToArray } from '@/utils/utils';
import SaleDateModal from './components/SaleDateModal';
import GoodPriceModal from './components/GoodPriceModal';
import SaleSectionModal from './components/SaleSectionModal';
import SelectGoodsModal from './components/SelectGoodsModal';
import { apiSaveVirtualGoodsList, apiShopListByEnterpriseID, apiVirtualList } 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 [visiblePrice, setVisiblePrice] = useState(false); // 修改企业商品价格弹窗
  const [dataSource, setDataSource] = useState([]);
  const [shopList, setShopList] = useState({}); // 店铺列表
  const [sleShopID, setSelShopID] = useState(''); // 选中的店铺ID
  const [sleShopName, setSelShopName] = useState(''); // 选中的店铺名称
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [editItem, setEditItem] = useState({}); // 编辑信息

  // 取消
  const onCancel = () => {
    history.goBack();
  };
  // 打开选择商品弹窗
  const openSelectModal = () => {
    if (!sleShopID) {
      message.error('请选择店铺');
      return;
    }

    setVisibleSelectGoods(true);
  };

  // 提交
  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 = {
      enterpriseId: id,
      shopId: sleShopID,
      skuInfoList,
    };
    const res = await apiSaveVirtualGoodsList(params);
    if (res && res.success) {
      notification.success({ message: '添加成功' });
      onCancel();
    }
  };

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

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

  // 查询已选商品列表
  const getGoodsList = async shopId => {
    const data = {
      page: 1,
      size: 1000,
      data: {
        enterpriseId: id,
        shopId,
      },
    };
    const res = await apiVirtualList(data);
    if (res && res.data && res.data.records && res.data.records.length) {
      const keys = [];
      setDataSource(
        res.data.records.map(item => {
          item.saleDate = item.saleDateList.map(d => d.code);
          item.tabCate = item.tabCateList.map(c => c.tabId);
          item.enterprisePrice = item.activityPrice;
          item.salePrice = item.price;
          keys.push(item.skuId);
          return item;
        }),
      );
      setSelectedRowKeys(keys);
    } else {
      setDataSource([]);
    }
  };

  // 选中店铺
  const onSelectShop = sid => {
    setSelShopID(sid);
    setSelShopName(shopList[sid]);
    getGoodsList(sid);
  };

  // 刷新列表数据
  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);
  };

  useEffect(() => {
    getShopList();
  }, []);

  const options = {
    setVisibleSaleDate,
    setVisibleSaleSection,
    setEditItem,
    setVisiblePrice,
    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={jsonToArray(shopList)}
                className={style['info-box--select']}
                placeholder="清选择"
                value={sleShopID}
                onChange={e => onSelectShop(e)}
                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={openSelectModal}>
                选择商品
              </Button>
            </Col>
          </Row>
          <Row className={style['info-box--line']}>
            <Col span={24}>
              <Table rowKey="skuId" 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}
            item={editItem}
            type="saleDate"
            handleRefresh={v => refreshList('saleDate', v)}
            handleClose={() => setVisibleSaleDate(false)}
          />
        )}
        {/* 可售餐段弹窗 */}
        {visibleSaleSection && (
          <SaleSectionModal
            visible={visibleSaleSection}
            item={editItem}
            type="tabCate"
            enterpriseID={id}
            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}
            type="virtual"
            enterpriseId={id}
            productType={4}
            shopID={sleShopID}
            shopName={sleShopName}
            selectedRowKeys={selectedRowKeys}
            selectedRows={dataSource}
            onSelectChange={setDataSource}
            onSelectedRowKeys={setSelectedRowKeys}
            handleClose={() => setVisibleSelectGoods(false)}
          />
        )}
      </div>
    </PageHeaderWrapper>
  );
};

export default VirtualGoodsInfo;
