import React, { useRef,useState, useEffect } from 'react';
import { Modal, Form, Input, Button, Select, InputNumber, Divider, Space,message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { GetPaperCouponType,AddPaperCouponType } from '../../service';
import GoodsList from '../GoodsList'
let index = 0;
const CreateForm = (props) => {
  const[form]=Form.useForm();
  const [items, setItems] = useState();
  const [visiblegoods, setvisiblegoods] = useState(false);
  const inputRef = useRef(null);
  const [name, setName] = useState('');
  const [checkgoods,setcheckgoods]=useState([]);
  //初始化数据
  useEffect(() => {
    //form.resetFields();
    initcouponType();
  }, []);

  useEffect(()=>{
    form.setFieldsValue(props.values);
  },[props.values])
  const initcouponType = async () => {
    var data = await GetPaperCouponType();
    var op=[]
    data.data.map((item) => (
      op.push({label:item.value,value:item.key})
    ));
    setItems(op)
  };
  const formItemLayout = {
    labelCol: {
      sm: { span: 4 },
    },
    wrapperCol: {},
  };
  const tailFormItemLayout = {
    wrapperCol: {
      sm: {
        span: 500,
        offset: 1,
      },
    },
  };
  const onNameChange = (event) => {
    setName(event.target.value);
  };
  const addItem = async (e) => {
    e.preventDefault();
    setItems([...items, {label:name,value:index++} || `New item ${index++}`]);
    setName('');
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
   
    await AddPaperCouponType(JSON.stringify({Name:name})).then((r) => {
        if (r.data) {
            message.success('添加成功');
            initcouponType();
          } else {
            message.error('添加失败请重试！');
          }
    })
  };
  const ongoodsopen= () => {
    setvisiblegoods(true);
  }
  const oncheck=(data)=>{
    console.log(data)
    setcheckgoods(data)
  }
  return <>
    <Modal
      maskClosable={false}
      title={props.values.id ? '编辑优惠卷' : '新建优惠卷'}
      width={700}
      visible={props.createModalVisible}
      // bodyStyle={{ padding: '32px 40px 48px' }}
      footer={null} //底部内容
      //取消
      onCancel={() => {
        props.onCancel();
      }}
      //关闭时销毁 Modal 里的子元素
      destroyOnClose
    >
      <Form
        {...formItemLayout}
        layout="Horizontal"
        preserve={false}
        form={form}
        onFinish={props.onFinish}
      >
        <Form.Item name="id" hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item name="storeId" hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item name="goodsId" hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item name="goodsName" label="商品" rules={[{ required: true, max: 200 }]}>
          <Input placeholder="请选择商品名称" onClick={ongoodsopen} />
        </Form.Item>
        <Form.Item name="title" label="优惠卷标题"  rules={[{ required: true, max: 200 }]}>
          <Input placeholder="请输入优惠卷标题" />
        </Form.Item>
        <Form.Item
          name="cTypeId"
          label="优惠卷类型"
          defaultValue={props.values.cTypeId}
          rules={[{ required: true }]}
        >
          <Select placeholder="请选择优惠卷类型"
          dropdownRender={(menu) => (
            <>
              {menu}
              <Divider
                style={{
                  margin: '8px 0',
                }}
              />
              <Space
                style={{
                  padding: '0 8px 4px',
                }}
              >
                <Input
                  placeholder="请输入选项"
                  ref={inputRef}
                  value={name}
                  onChange={onNameChange}
                />
                <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
                  新增
                </Button>
              </Space>
            </>
          )}
          options={items}
          >
            {/* <OptGroup>{options}</OptGroup> */}
          </Select>
        </Form.Item>
        <Form.Item {...tailFormItemLayout} style={{ height: 32 }}>
          <Form.Item label="原始金额" style={{ float: 'left' }}  rules={[{ required: true }]}>
            <Form.Item name="money" noStyle>
              <InputNumber placeholder="金额"  min={0} precision={2}    />
            </Form.Item>
          </Form.Item>
        </Form.Item>
        <Form.Item {...tailFormItemLayout} style={{ height: 32 }}>
          <Form.Item label="平台金额" style={{ float: 'left' }}  rules={[{ required: true }]}>
            <Form.Item name="soureMoney" noStyle>
              <InputNumber placeholder="金额"  min={0} precision={2}    />
            </Form.Item>
          </Form.Item>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ float: 'right' }}>
            保存
          </Button>
        </Form.Item>
      </Form>
    </Modal>
    <Modal title="商品列表" destroyOnClose maskClosable={false} visible={visiblegoods} width={900} onCancel={() => {
      setvisiblegoods(false)
      }} onOk={()=>{
        var na="";
        var naid="";
        var money=0.00;
        var storeid="";
        checkgoods.forEach((item,index)=>{
          na=na+item.goods_Name
          naid=naid+item.goodsId;
          money=item.price;
          storeid=item.storeId;
          if(index<checkgoods.length-1){
            na=na+",";
            naid=naid+",";
          }
        })
        form.setFieldsValue({
          goodsName: na,
          goodsId:naid,
          money:money,
          storeId:storeid
        });
        setvisiblegoods(false);
        setcheckgoods([])
      }}  >
        <GoodsList oncheck={oncheck}></GoodsList>
    </Modal>
    </>
};

export default CreateForm;
