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

const AddModal = props => {
  const [form] = Form.useForm();
  const { addVisible, enterpriseId, name, onCancel } = props;
  const [selectList, setSelectList] = useState([]);
  const [options, setOptions] = useState([]);
  const handleCancel = status => {
    form.resetFields();
    onCancel(status, 'add');
  };
  const handleChange = value => {
    setSelectList(value);
  };
  const onOk = async () => {
    if (!selectList.length) {
      notification.error({
        message: $t('add.micro.store'),
      });
      return;
    }
    const res = await apiShopAdd({ enterpriseId, shopIds: selectList });
    if (res.businessCode === '0000') {
      notification.success({
        message: $t('added.successfully'),
      });
      handleCancel(true);
    }
  };
  const getSelectList = async () => {
    const res = await apiSelectList({ enterpriseId });
    if (res.businessCode === '0000') {
      const optionData = res.data.map(item => ({
        value: item.shopId,
        label: item.shopName,
      }));
      setOptions(optionData);
    }
  };

  useEffect(() => {
    if (addVisible) {
      getSelectList();
    }
  }, [addVisible]);
  return (
    <>
      <Modal title={$t('add.enterprise.store')} onOk={onOk} visible={addVisible} onCancel={handleCancel}>
        <Form form={form}>
          <Form.Item label={$t('enterprise.name')}>
            <span>{name}</span>
          </Form.Item>
          <Form.Item label={$t('add.micro.store')} name="shopIds">
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder={$t('select.micro.store')}
              onChange={handleChange}
              options={options}
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item label={$t('food.type')}>
            <span>{$t('instore')}</span>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddModal;
