import React, { useState, useEffect } from 'react';
import {
  InputNumber,
  Row,
  Col,
  Checkbox,
  Space,
  Steps,
  message,
  Modal,
  Form,
  Input,
  Button,
  Select,
  DatePicker,
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

import { GetActivityConfiguration, GetCouponCanUseCountAndLimit, GetGoodsInfo } from '../service';

const CreateForm = (props) => {
  const [form] = Form.useForm();
  const { Option, OptGroup } = Select;
  const [options, setoptions] = useState();
  const [current, setCurrent] = React.useState(0);
  const [firstItem, SetFirstItem] = useState();
  const [secondItem, SetSecondItem] = useState();
  const [isFormShow, SetisFormShow] = useState(true);
  const [couponInfo, SetCouponInfo] = useState([]);
  const [goodsInfo, SetGoodsInfo] = useState([]);
  const [isCouponModalVisible, SetIsCouponModalVisible] = useState(false);
  const [selectCoupon, SetselectCoupon] = useState(false);
  const [quantityLimit, SetQuantityLimit] = useState([]);

  const [goodsPrice, SetGoodsPrice] = useState([]);

  const tailFormItemLayout = {
    wrapperCol: {
      sm: {
        span: 500,
        offset: 1,
      },
    },
  };

  //初始化数据
  useEffect(() => {
    const initcouponType = async (value) => {
      var data = (await GetCouponCanUseCountAndLimit()).data;
      if (data != undefined) {
        SetCouponInfo(data);
      }
    };
    const initGoodsInfoType = async (value) => {
      var data = (await GetGoodsInfo()).data;
      if (data) {
        SetGoodsInfo(data);
      }
    };
    initcouponType();
    initGoodsInfoType();
  }, []);

  const canUseCountOrlimit = (key, value, type) => {
    var result = 0;
    if (value) {
      if (type == 3) {
        if (goodsPrice[key]) {
          return goodsPrice[key].price;
        } else {
          const arr = [[...goodsPrice]]; //克隆的时候改变地址
          goodsInfo.filter((item) => {
            if (item.id == value[key]?.rewardValue) {
              arr[key] = item;
            }
          });
          var vv = arr;
          // SetGoodsPrice(arr??[]);
          return arr[key] ? arr[key].price : 0;
        }
      } else {
        var rewardValue = value[key];
        var count = 0;
        couponInfo.filter((item) => {
          if (rewardValue && item.couponId == rewardValue?.rewardValue) {
            if (type == 1) {
              count = item.canUseCount;
            } else {
              count = item.limit;
            }
          }
        });
      }

      if (type == 1) {
        result = parseInt(
          quantityLimit[key] ? JSON.stringify(quantityLimit[key].canUseCount) : count,
        );
      } else {
        result = parseInt(quantityLimit[key] ? JSON.stringify(quantityLimit[key].limit) : count);
      }
    } else if (quantityLimit[key]) {
      if (type == 1) {
        result = quantityLimit[key].canUseCount;
      } else {
        result = quantityLimit[key].limit;
      }
    }
    return result;
  };

  return (
    <Modal
      title={props.values.id ? '编辑优活动' : '新建活动'}
      width={700}
      visible={props.createModalVisible}
      footer={null} //底部内容
      onCancel={() => {
        props.onCancel();
      }}
      //关闭时销毁 Modal 里的子元素
      destroyOnClose={true}
    >
      <Form
        preserve={false}
        // form={form}
        labelCol={{ span: 4 }}
        layout="Horizontal"
        initialValues={props.values}
        onFinish={props.onFinish}
      >
        <span style={{ display: isFormShow ? 'block' : 'none' }}>
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>

          <Form.Item name="activityName" label="活动名称" rules={[{ required: true, max: 64 }]}>
            <Input placeholder="请输入活动名称" />
          </Form.Item>
          <Form.Item name="activityImg" label="活动图片" rules={[{ required: true, max: 500 }]}>
            <Input placeholder="请输入活动图片" />
          </Form.Item>
          <Form.Item
            name="activityType"
            label="活动类型"
            defaultValue={props.values.activityType}
            rules={[{ required: true }]}
          >
            <Select
              onChange={() => {
                // form.setFieldsValue({ activityValue: undefined });
              }}
              allowClear
              placeholder="请选择活动类型"
            >
              <OptGroup>
                <Select.Option key={1} value={1}>
                  {'送券'}
                </Select.Option>
                <Select.Option key={2} value={2}>
                  {' 其他'}
                </Select.Option>
                <Select.Option key={3} value={3}>
                  {'商品促销'}
                </Select.Option>
                <Select.Option key={4} value={4}>
                  {'商城优惠券'}
                </Select.Option>
              </OptGroup>
            </Select>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.activityType !== currentValues.activityType
            }
          >
            {({ getFieldValue }) =>
              getFieldValue('activityType') == '2' ? (
                <Form.Item name="activityValue" label="活动值" rules={[{ required: true }]}>
                  <Form.Item name="activityValue" noStyle>
                    <Input placeholder="请输入活动值" />
                  </Form.Item>
                </Form.Item>
              ) : getFieldValue('activityType') == '3' ? (
                <Form.Item label="商品信息">
                  <Form.List name="activityRewards">
                    {(fields, { add, remove }) => (
                      <>
                        {fields.map(({ key, name, fieldKey, ...restField }) => (
                          <Space
                            key={key}
                            style={{ display: 'flex', marginBottom: 8 }}
                            align="baseline"
                          >
                            <Form.Item
                              {...restField}
                              name={[name, 'rewardValue']}
                              fieldKey={[fieldKey, 'rewardValue']}
                              rules={[{ required: true, message: '请选择商品' }]}
                            >
                              <Select
                                style={{ width: 200 }}
                                onChange={(value) => {
                                  const arr = [...goodsPrice]; //克隆的时候改变地址
                                  goodsInfo.filter((item) => {
                                    if (item.id == value) {
                                      arr[key] = item;
                                    }
                                  });
                                  SetGoodsPrice(arr);
                                }}
                              >
                                {goodsInfo.map((item, index) => {
                                  return (
                                    <Select.Option index={index} value={item.id} key={item.id}>
                                      {item.name}
                                    </Select.Option>
                                  );
                                })}
                              </Select>
                            </Form.Item>
                            {/* {`原价:${goodsPrice[key]?.price}`} */}
                            {`原价:${canUseCountOrlimit(key, props.values.activityRewards, 3)}`}
                            &nbsp;&nbsp;
                            <Form.Item
                              {...restField}
                              label="促销价"
                              name={[name, 'sendNum']}
                              fieldKey={[fieldKey, 'sendNum']}
                              rules={[{ required: true, message: '请输入促销价' }]}
                            >
                              <InputNumber min={0} placeholder="促销价" />
                            </Form.Item>
                            <MinusCircleOutlined onClick={() => remove(name)} />
                          </Space>
                        ))}
                        <Form.Item>
                          <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                            添加
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                </Form.Item>
              ) : (
                <Form.Item label="优惠券">
                  <Form.List name="activityRewards">
                    {(fields, { add, remove }) => (
                      <>
                        {fields.map(({ key, name, fieldKey, ...restField }) => (
                          <Space
                            key={key}
                            style={{ display: 'flex', marginBottom: 8 }}
                            align="baseline"
                          >
                            <Form.Item
                              {...restField}
                              name={[name, 'rewardValue']}
                              fieldKey={[fieldKey, 'rewardValue']}
                              rules={[{ required: true, message: '请选择优惠券' }]}
                            >
                              <Select
                                style={{ width: 200 }}
                                onChange={(value) => {
                                  const arr = [...quantityLimit]; //克隆的时候改变地址
                                  couponInfo.filter((item) => {
                                    if (item.couponId == value) {
                                      arr[key] = item;
                                    }
                                  });
                                  SetQuantityLimit(arr);
                                }}
                              >
                                {couponInfo.map((item, index) => {
                                  return (
                                    <Select.Option
                                      index={index}
                                      value={item.couponId}
                                      key={item.couponId}
                                    >
                                      {item.couponName}
                                    </Select.Option>
                                  );
                                })}
                              </Select>
                            </Form.Item>
                            {`可用数量:${canUseCountOrlimit(key, props.values.activityRewards, 1)}`}
                            &nbsp;&nbsp;
                            <Form.Item
                              {...restField}
                              label={getFieldValue('activityType')==4?"兑换值":"每次领取数量"} 
                              name={[name, 'sendNum']}
                              fieldKey={[fieldKey, 'sendNum']}
                              rules={[
                                { required: true, message: getFieldValue('activityType')==4?"请输入兑换值":"请输入发送数量"},
                                {
                                  type: 'number',
                                  min: 0,
                                  max: parseInt(
                                    getFieldValue('activityType')==4?999999999:canUseCountOrlimit(key, props.values.activityRewards, 2),
                                  ),
                                  message: '超出领取限制',
                                },
                              ]}
                            >
                              <InputNumber
                                min={0}
                                max={getFieldValue('activityType')==4?999999999:canUseCountOrlimit(key, props.values.activityRewards, 2)}
                                placeholder={getFieldValue('activityType')==4?"兑换值":"每次领取数量"}
                              />
                            </Form.Item>
                            <MinusCircleOutlined onClick={() => remove(name)} />
                          </Space>
                        ))}
                        <Form.Item>
                          <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                            添加
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                </Form.Item>
              )
            }
          </Form.Item>

          <Form.Item noStyle>
            <Form.Item {...tailFormItemLayout} style={{ height: 32 }}>
              <Form.Item
                name="activityStartTime"
                label="开始时间"
                style={{ float: 'left' }}
                rules={[{ required: true }]}
              >
                <DatePicker placeholder="开始时间" />
              </Form.Item>
              <Form.Item
                name="activityEndTime"
                label="结束时间"
                style={{ float: 'left', marginLeft: 20 }}
                rules={[{ required: true }]}
              >
                <DatePicker placeholder="结束时间" />
              </Form.Item>
            </Form.Item>
          </Form.Item>
          <Form.Item name="remark" label="备注" rules={[{ required: true, max: 200 }]}>
            <Input placeholder="请输入备注" />
          </Form.Item>
          <Form.Item name="activityRule" label="规则说明" rules={[{ required: true, max: 500 }]}>
            <Input placeholder="请输入规则说明" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ float: 'right' }}>
              保存
            </Button>
          </Form.Item>
        </span>
      </Form>
    </Modal>
  );
};

export default CreateForm;
