import React, {useEffect, useState} from 'react';
import {Modal, Button, Select, message} from 'antd';
import useInitail from "@/hooks/useInitail";
import {getDealerApi} from "@/common/api";

interface Props {
  onCancel: () => any,
  visible: boolean,
  dealerList: any[],
  onOk: (dealer: any) => any
}
const {Option} = Select;
export default function Index({ onCancel, visible, onOk, dealerList = [] }: Props) {
  const [dealer, setDealer] = useState<any>({ settleDealerId: null, settleDealerName: null});
  const { data: dealers } = useInitail<CommonApi.OptionVO[], CommonApi.DealerParam>(getDealerApi, [], {});
  const suIds = dealerList.map(it => it.settleDealerId);

  useEffect(() => {
    if (!visible) {
      setDealer({});
    }
  }, [visible]);

  const handSave = () => {
    if (!dealer.settleDealerId) {
      message.error('请选择采购商家');
      return;
    }
    onOk && onOk(dealer);
    onCancel && onCancel();
  };

  return (
    <Modal
      width={400}
      visible={visible}
      title="采购商家"
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>取消</Button>,
        <Button
          key="submit"
          disabled={!dealer.settleDealerId}
          onClick={handSave}
          type="primary"
          htmlType="submit"
        >
          确认
        </Button>
      ]}
    >
      <div style={{display: 'flex', flexDirection: 'row', alignItems: 'center', marginBottom: 10}}>
        <span>商家：</span>
        <Select
          value={dealer.settleDealerId}
          style={{ width: 250 }}
          placeholder="请选择商家"
          showSearch
          optionFilterProp="children"
          onChange={(settleDealerId) => {
            const d = dealers.find(it => it.id == settleDealerId) || {};
            setDealer({ settleDealerId, settleDealerName: d.name});
          }}
        >
          {dealers.filter(it => !suIds.includes(it.id)).map((b) => (
            <Option value={b.id || -1} key={b.id}>{b.name || ''}</Option>
          ))}
        </Select>
      </div>
    </Modal>
  );
}
