import React, { useState, useEffect, forwardRef, useRef, useImperativeHandle } from 'react';
import { Button, Modal, Select, Form, notification } from 'antd';
import styles from '../index.less';
import { apiSelectedList, apiSelectList, apiShopAdd } from '../service.js';

const AddModal = props => {
  const { addVisible, enterpriseId, name } = props;
  const [selectList, setSelectList] = useState([]);
  const [options, setOptions] = useState([]);
  const handleCancel = () => {
    props.onCancel(false);
  };
  const handleChange = value => {
    setSelectList(value);
  };
  const onOk = async () => {
    if (!selectList.length) {
      notification.error({
        message: '请添加微店',
      });
      return;
    }
    const res = await apiShopAdd({ enterpriseId, shopIds: selectList });
    if (res.businessCode === '0000') {
      notification.success({
        message: '添加成功',
      });
      props.onCancel(true);
    }
  };
  const getSelectedList = async () => {
    const res = await apiSelectedList({ enterpriseId });
    if (res.businessCode === '0000') {
      const { data } = res;
      const list = [];
      data.forEach(item => {
        list.push(item.id);
      });
      setSelectList(list);
    }
  };
  const getSelectList = async () => {
    const res = await apiSelectList({ id: enterpriseId });
    if (res.businessCode === '0000') {
      const optionData = res.data.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setOptions(optionData);
    }
  };

  useEffect(() => {
    if (addVisible) {
      getSelectedList();
    }
  }, [addVisible]);
  return (
    <>
      <Modal title="添加企业店铺" onOk={onOk} visible={addVisible} onCancel={() => handleCancel}>
        <Form>
          <Form.Item label="企业名称">
            <span>{name}</span>
          </Form.Item>
          <Form.Item label="添加微店" name="shopIds" initialValue={selectList}>
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder="请选择微店"
              onChange={handleChange}
              options={options}
            />
          </Form.Item>
          <Form.Item label="餐饮类型">
            <span>到店</span>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddModal;
