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

import { GetActivityConfiguration, GetCouponCanUseCountAndLimit, GetGoodsInfo, GetCosRequestURL } from '../service';
import axios from 'axios';
const CreateForm = (props) => {

  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 [imgurl, setimgUrl] = useState(props.values.activityImg ? props.values.activityImg : null);
  const [goodsPrice, SetGoodsPrice] = useState([]);



  const children = [];
  for (let i = 10; i < 36; i++) {
    children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
  }


  const tailFormItemLayout = {
    wrapperCol: {
      sm: {
        span: 500,
        offset: 1,
      },
    },
  };
  //每次触发
  useEffect(() => {

    return () => {
      if (!props.createModalVisible) {
        setimgUrl(null);
      }
    }
  })

  //初始化数据
  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;
            }
          });
          // SetGoodsPrice(arr??[]);
          return arr[key] ? (arr[key].price ? arr[key].price : 0) : 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;
  };
  const uploadProp = {
    name: 'file',
    showUploadList: false,
    multiple: false,
    accept: '.png, .jpg, .jpeg, .gif',
    // 这里需要指定文件上传的content-type
    headers: {
      'Content-Type': 'application/octet-stream',
    },
    customRequest({
      action,
      file,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {

      //覆盖action 上传之前获取上传地址
      var index = file.name.lastIndexOf(".");
      var ext = file.name.substr(index + 1);

      let fileData = null;
      GetCosRequestURL({ directory: "activity", fileExtension: ext, method: "PUT" }).then((r) => {
        action = r.allUrl;
        var index = file.name.lastIndexOf(".");
        //获取后缀
        var ext = file.name.substr(index + 1);
        const reader = new FileReader();

        if (['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext) == -1) {
          message.error(`${file.name} 不是图片文件`);
          return;
        }

        reader.readAsArrayBuffer(file);
        reader.onload = (e) => {
          fileData = e.target.result;
          // 使用 axios 进行文件上传的请求
          axios.put(action, fileData, {
            withCredentials,
            headers,
            onUploadProgress: ({ total, loaded }) => {
              // 进行上传进度输出，更加直观
              onProgress({ percent: Math.round(loaded / total * 100).toFixed(2) }, file);
            },
          }).then(response => {
            props.form.setFieldsValue({ activityImg: r.seeUrl });
            if (response.status == 200 || response.statusText == 'OK') {
              setimgUrl(r.seeUrl)
            }
            // onSuccess(response, file);
          })
            .catch(onError);
        };
      });
      // return {
      //   abort() {
      //     console.log('upload progress is aborted.');
      //   },
      // };
    },
    //defaultFileList: props.location.query.values ? props.location.query.values : null

  };
  return (
    <Modal
      title={props.values.id ? '编辑优活动' : '新建活动'}
      width={700}
      visible={props.createModalVisible}
      footer={null} //底部内容
      onCancel={() => {
        props.onCancel();
      }}
      //关闭时销毁 Modal 里的子元素
      destroyOnClose={true}
    >
      <Form
        preserve={false}
        form={props.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="activityImg1" label="请输入活动图片" rules={[{ required: true }]}
          >
            <Upload
              {...uploadProp}
            >
              {imgurl ? <img src={imgurl} alt="avatar" style={{ width: '30px', height: '40px' }} /> : <Button icon={<UploadOutlined />}>上传</Button>}

            </Upload>
          </Form.Item>
          <Form.Item name="activityImg" label="请输入活动图片" hidden={true} >
            <Input placeholder="请输入活动图片" />
          </Form.Item>
          <Form.Item
            name="activityType"
            label="活动类型"
            defaultValue={props.values.activityType}
            rules={[{ required: true }]}
          >
            <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择活动类型"
            >
              <Option key={1} value={1}>
                {'送券'}
              </Option>
              <Option key={2} value={2}>
                {'买满减现'}
              </Option>
              <Option key={3} value={3}>
                {'特价商品'}
              </Option>
              <Option key={4} value={4}>
                {'买满赠送(优惠券)'}
              </Option>
              <Option key={5} value={5}>
                {'买满赠送(商品)'}
              </Option>
              <Option key={6} value={6}>
                {'累计消费换购(阶梯)'}
              </Option>
              <Option key={7} value={7}>
                {'累计消费换购(循环)'}
              </Option >
              <Option key={8} value={8}>
                {'加价换购'}
              </Option>
            </Select >
          </Form.Item >

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.activityType !== currentValues.activityType
            }  >
            {({ getFieldValue }) =>
              (getFieldValue('activityType') == '6' || getFieldValue('activityType') == '7') ? (
                <Form.Item>
                  <Form.Item
                    name="isGiftGoodsParticipate"
                    label="赠送商品是否参与活动"
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                  >
                    <Select
                      showSearch
                      optionFilterProp="children"
                      filterOption={(input, option) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      placeholder="请选活动消费类型"
                    >
                      <Option key={1} value={1}>
                        {'是'}
                      </Option>
                      <Option key={0} value={0}>
                        {'否'}
                      </Option>
                    </Select >
                  </Form.Item>
                  <Form.Item
                    name="consumptionType"
                    label="活动消费类型"
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                  >
                    <Select
                      showSearch
                      optionFilterProp="children"
                      filterOption={(input, option) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      placeholder="请选活动消费类型"
                    >
                      <Option key={1} value={1}>
                        {'钱（元）'}
                      </Option>
                      <Option key={2} value={2}>
                        {'数量（杯/碗/盒/个/.....）'}
                      </Option>
                    </Select >
                  </Form.Item>
                </Form.Item>

              ) : null
            }
          </Form.Item>



          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.activityType !== currentValues.activityType
            }  >
            {({ getFieldValue }) =>
              // (getFieldValue('activityType') == '6' || getFieldValue('activityType') == '7') ? (

              //   <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: '消费次数' }]}
              //               >
              //                 <InputNumber />
              //               </Form.Item>
              //               &nbsp;&nbsp;
              //               {`根据店铺实际情况奖励`}
              //               <MinusCircleOutlined onClick={() => remove(name)} />
              //             </Space>
              //           ))}
              //           <Form.Item>
              //             <Button type="dashed" onClick={() => {

              //               if (getFieldValue('activityType') == '7') {
              //                 if (!getFieldValue('activityRewards')||getFieldValue('activityRewards').length < 1) {
              //                   add();
              //                 }else{
              //                   message.warning('添加数量已达到上限');
              //                 }
              //               } else {
              //                 add();
              //               }


              //             }} block icon={<PlusOutlined />}>
              //               添加
              //             </Button>
              //           </Form.Item>
              //         </>
              //       )}
              //     </Form.List>
              //   </Form.Item>
              // ) :
              (getFieldValue('activityType') == '2' ||
                getFieldValue('activityType') == '4' ||
                getFieldValue('activityType') == '5' ||
                getFieldValue('activityType') == '6' ||
                getFieldValue('activityType') == '8' ||
                getFieldValue('activityType') == '7') ? (

                <Form.Item label={getFieldValue('activityType') == '6' || getFieldValue('activityType') == '7' ? '消费次数' :
                  (getFieldValue('activityType') == '8' ? '加购价格' : '消费金额')}>

                  <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: '请输入消费金额' }]}
                            >
                              <InputNumber />
                            </Form.Item>
                            &nbsp;&nbsp;
                            <Form.Item
                              {...restField}
                              label={getFieldValue('activityType') == '6' || getFieldValue('activityType') == '7' || getFieldValue('activityType') == '4' ? "赠送优惠券" :
                                (getFieldValue('activityType') == '5' || getFieldValue('activityType') == '8') ? "赠送商品" : "赠送金额"}

                              name={[name, 'value']}
                              fieldKey={[fieldKey, 'value']}
                              rules={[{ required: true, message: '请选择' }]} >
                              {
                                [4, 6, 7].includes(getFieldValue('activityType')) ? (
                                  <Select style={{ width: 200 }}
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) =>
                                      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    } >
                                    {couponInfo.map((item, index) => {
                                      return (
                                        <Option
                                          index={index}
                                          value={item.couponId}
                                          key={item.couponId}
                                        >
                                          {item.couponName}
                                        </Option>
                                      );
                                    })}
                                  </Select>) :
                                  (getFieldValue('activityType') == '5' || getFieldValue('activityType') == '8') ? (
                                    <Select style={{ width: 200 }}
                                      showSearch
                                      optionFilterProp="children"
                                      filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                      } >
                                      {goodsInfo.map((item, index) => {
                                        return (
                                          <Option index={index} value={item.id} key={item.id}>
                                            {item.name}
                                          </Option>
                                        );
                                      })}
                                    </Select>
                                  ) :
                                    (<InputNumber />)
                              }

                            </Form.Item>
                            <MinusCircleOutlined onClick={() => remove(name)} />
                          </Space >
                        ))
                        }
                        <Form.Item>
                          <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                            添加
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List >
                </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, 'value']}
                                fieldKey={[fieldKey, 'value']}
                                rules={[{ required: true, message: '请输入促销价' }]} >
                                <Select mode="tags" style={{ width: '160px' }} placeholder="请输入促销价" maxTagCount='responsive'>
                                  {[]}
                                </Select>
                              </Form.Item>
                              <MinusCircleOutlined onClick={() => remove(name)} />
                            </Space>
                          ))}
                          <Form.Item>
                            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                              添加
                            </Button>
                          </Form.Item>
                        </>
                      )}
                    </Form.List>
                  </Form.Item>
                </>
                //  --------------end特价商品end--------------
              ) : (
                //  --------------优惠券--------------
                <>
                  <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, 'value']}
                                fieldKey={[fieldKey, 'value']}
                                rules={[
                                  { required: true, message: getFieldValue('activityType') == 4 ? "请输入兑换值" : "请输入发送数量" },
                                  {
                                    type: 'number',
                                    min: 0,
                                    max: parseInt(
                                      getFieldValue('activityType') == 4 ? 999999999 : canUseCountOrlimit(key, props.values.activityRewards, 1),
                                    ),
                                    message: '超出领取限制',
                                  },
                                ]}
                              >
                                <InputNumber
                                  min={0}
                                  max={getFieldValue('activityType') == 4 ? 999999999 : canUseCountOrlimit(key, props.values.activityRewards, 1)}
                                  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>
                </>
                //--------------end优惠券end--------------
              )
            }
          </Form.Item >

          <Form.Item noStyle>
            <Form.Item {...tailFormItemLayout} style={{ height: 32 }}>
              <Form.Item
                name="activityStartTime"
                label="开始时间"
                style={{ float: 'left' }}
                rules={[{ required: true }]}
              >
                <DatePicker placeholder="开始时间"
                  disabledDate={(current) => {
                    return current && current > props.form.getFieldValue('activityEndTime');
                  }} />
              </Form.Item>
              <Form.Item
                name="activityEndTime"
                label="结束时间"
                style={{ float: 'left', marginLeft: 20 }}
                rules={[{ required: true }]}
              >
                <DatePicker placeholder="结束时间"
                  disabledDate={(current) => {

                    return current && current < props.form.getFieldValue('activityStartTime');
                  }} />
              </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;
