import { Button, message, Modal } from 'antd';
import { inject, observer } from 'mobx-react';
import React, { useEffect, useState } from 'react';
import { lwjTable } from 'src/utils/quote';
import { columns, CouponsTypeTitle } from './info';
interface IProps {
  value?: { id: string; row: any; detail: any };
  onChange?: (value: { id: string; row: any; detail: any }) => void;
  coupons: any;
}
const ChooseCoupon: React.FC<IProps> = inject('coupons')(
  observer((props) => {
    const [visible, setVisible] = useState<boolean>(false);
    const [tp, setTp] = useState<any>(false);

    const open = async () => {
      const [tp] = lwjTable({
        entityName: 'coupon-list-in-use',
        defaultSelectedRowKeys: [props.value],
        rowSelectionType: 'radio',
        extraQueryParams: {
          flag: 2,
        },
      });
      setTp(tp);
      setVisible(true);
    };
    const close = () => {
      tp.getQueryPresenter()?.reset()
      setVisible(false);
    };
    useEffect(() => {
      tp?.setColumns?.(columns);
    }, [tp]);

    const submit = async () => {
      const { selectedRowKeys, selectedRows } = tp?.getSelection();
      if (!selectedRowKeys || selectedRowKeys.length === 0) {
        message.warn('请选择优惠券')
        return
      }
      const detail = await props.coupons.getCouponsDetail(selectedRowKeys[0]);
      props.onChange?.({
        id: selectedRowKeys[0],
        row: selectedRows[0],
        detail: detail,
      });
      close();
    };
    const getUnit = () => {
      let unit = '';
      switch (props.value?.detail?.discountType) {
        case 1:
          unit = '折';
        default:
          unit = '元';
      }
      return unit
    };
    const Table = tp ? tp.getComponent() : () => <></>;
    return (
      <>
        <Button type="primary" onClick={open}>
          {props.value?.detail?.name || '选择'}
        </Button>
        {props.value?.row && (
          <>
            <h3>名称：{props.value?.detail?.name}</h3>
            <h3>编码：{props.value?.detail?.couponCode}</h3>
            <h3>类型：{CouponsTypeTitle[props.value?.detail?.discountType]}</h3>
            <h3>优惠：{props.value?.detail?.faceValue}{getUnit()}</h3>
            <h3>描述：{props.value?.detail?.discountMsg}</h3>
          </>
        )}
        <Modal visible={visible} title={'选择优惠券'} width={1000} onCancel={close} onOk={submit}>
          <Table/>
        </Modal>
      </>
    );
  }),
);

export default ChooseCoupon;
