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 { 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 [dataSource, setDataSource] = useState([]);
  const [pickSelfList, setPickSelfList] = useState([]); // 取餐点列表
  const [slePickSelf, setSelPickSelf] = 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: id,
      enterpriseId: id,
      pickSelfIdList: slePickSelf,
      skuInfoList,
    };
    await apiSaveGoodsList(params);
    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.map(item => item.pickSelfId));
    }
  };

  // 刷新列表数据
  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 onShowSelect = () => {
    if (!slePickSelf || slePickSelf.length < 1) {
      message.error('请选择取餐点!');
      return;
    }
    setVisibleSelectGoods(true);
  };

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

  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
                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={() => {
                    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}
            enterpriseId={id}
            productType={5}
            pickSelfIdList={slePickSelf}
            onSelectChange={setDataSource}
            handleClose={() => setVisibleSelectGoods(false)}
          />
        )}
      </div>
    </PageHeaderWrapper>
  );
};

export default TakeawayGoodsInfo;
