import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Checkbox,
  Space,
  Steps,
  message,
  Modal,
  Form,
  Input,
  Button,
  Select,
  DatePicker,
} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { GetActivityConfiguration, GetCoupon, AddactivityConfiguration, goodsType, GetStoreInfos } from '../service';
const key = 'message';
const CreateConfigForm = (props) => {
  const [form] = Form.useForm();
  const { Option, OptGroup } = Select;
  const [isFormShow, SetisFormShow] = useState(true);
  const [GoodsType, SetGoodsType] = useState([]);
  const [Shops, Setshops] = useState([]);

  //初始化数据
  useEffect(() => {
    const initgoodsType = async (value) => {
      var data = await goodsType({ current: 1, pageSize: 100 });
      if (data != undefined) {
        SetGoodsType(data.data);
      }
    };
    const initShops = async (value) => {
      var data = await GetStoreInfos({ current: 1, pageSize: 100 });
      if (data) {
        Setshops(data.data);
      }
    };
    initgoodsType();
    initShops();
  }, []);

  const tailFormItemLayout = {
    wrapperCol: {
      sm: {
        span: 500,
        offset: 1,
      },
    },
  };
  let numChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']

  const GetSelectVal = (info) => {
    let value = [];
    if (info.configurationName == "星期限制") {
      for (let i = 0; i < 7; i++) {
        value.push({
          label: `星期${i == 0 ? "日" : numChar[i]}`,
          value: i.toString(),
        });
      }
    }

    if (info.configurationName == "商品种类限制") {
      GoodsType.data.forEach(element => {
        value.push({
          label: element.goodsType_Name,
          value: element.id,
        });
      });
    }
    if (info.configurationName == "门店限制") {
      Shops.data.forEach(element => {
        value.push({
          label: element.storeName,
          value: element.storeId,
        });
      });
    }

    return value;
  }

  //新增
  const onFinish = async (values) => {
    message.loading('正在添加...', key);
    try {
      if (values.users) {
        values.users.forEach(element => {
          element.activity_Id = props.activityId;
        });

      }
      await AddactivityConfiguration(JSON.stringify(values.users)).then((r) => {
        message.destroy(key);
        if (r.data) {
          props.onCancel();
          message.success('添加成功');
        } else {
          message.error('添加失败请重试！');
        }
      });
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('添加失败请重试！');
      return false;
    }
  };




  return (
    <Modal
      title={'活动配置'}
      width={700}
      visible={props.createModalVisible}
      footer={null} //底部内容
      onCancel={() => {
        props.onCancel();
      }}
      //关闭时销毁 Modal 里的子元素
      destroyOnClose >
      {/* ----------------------------------------------------------------------------------------- */}

      <Form name="dynamic_form_nest_item" autoComplete="off" onFinish={onFinish}
        initialValues={{
          "users": props.config
        }}
      >
        <Form.List name="users">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, fieldKey, ...restField }) => (
                <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">

                  <Form.Item
                    {...restField}
                    name={[name, 'valueType']}
                    fieldKey={[fieldKey, 'valueType']}
                    hidden={true}>
                    <Input style={{ width: 80 }} size='Small' />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'configId']}
                    fieldKey={[fieldKey, 'configId']}>
                    <Checkbox.Group >
                      <Row>
                        <Col span={32} >
                          <Checkbox value={props.config[key].configuration_Id} style={{ lineHeight: '32px' }}>
                            {props.config[key].configurationName}
                          </Checkbox>
                        </Col>
                      </Row>
                    </Checkbox.Group>
                  </Form.Item>
                  <span>条件：{props.config[key].configurationRule}</span>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.activityType !== currentValues.activityType
                    }  >
                    {({ getFieldValue }) =>
                      props.config[key].configurationValueCount != 0 ? (
                        <Form.Item
                          {...restField}
                          name={[name, 'operator']}
                          fieldKey={[fieldKey, 'operator']}
                        // rules={[{ required:  true, message: '请输入判定符' }]}
                        >
                          <Select style={{ width: 80 }} size='Small'  >
                            <Option value=">">大于</Option>
                            <Option value="<">小于</Option>
                            <Option value="==">等于</Option>
                            <Option value=">=and<=">包含</Option>
                          </Select>
                        </Form.Item>
                      ) : (
                        <span></span>
                      )
                    }
                  </Form.Item>

                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.activityType !== currentValues.activityType
                    }  >
                    {({ getFieldValue }) =>
                      props.config[key].configurationValueCount == 1 ? (
                        <Form.Item
                          {...restField}
                          name={[name, 'value1']}
                          fieldKey={[fieldKey, 'value1']}
                        // rules={[{ required:  true, message: '请输入判定符' }]}
                        >
                          {props.config[key].valueType == 1 ? (
                            <Input style={{ width: 80 }} size='Small' />
                          ) : (
                            <Select
                            showSearch
                              {...{
                                mode: 'multiple',
                              
                                optionFilterProp:"label",
                                style: { width: '250px' },
                                options: GetSelectVal(props.config[key]),
                                placeholder: 'Select Item...',
                                maxTagCount: 'responsive',
                                mode: 'multiple',
                              }} />
                          )}

                        </Form.Item>
                      ) : (
                        <span></span>
                      )
                    }
                  </Form.Item>


                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.activityType !== currentValues.activityType
                    }  >
                    {({ getFieldValue }) =>
                      props.config[key].configurationValueCount == 2 ? (
                        <Form.Item
                          {...restField}
                          name={[name, 'value1']}
                          fieldKey={[fieldKey, 'value1']}
                        // rules={[{ required:  true, message: '请输入判定符' }]}
                        >
                          <Input style={{ width: 80 }} size='Small' />
                        </Form.Item>
                      ) : (
                        <span></span>
                      )
                    }
                  </Form.Item>

                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.activityType !== currentValues.activityType
                    }  >
                    {({ getFieldValue }) =>
                      props.config[key].configurationValueCount == 2 ? (

                        <Form.Item
                          {...restField}
                          name={[name, 'value2']}
                          fieldKey={[fieldKey, 'value2']}
                        // rules={[{ required:  true, message: '请输入判定符' }]}
                        >
                          <Input style={{ width: 80 }} size='Small' />
                        </Form.Item>
                      ) : (
                        <span></span>
                      )
                    }
                  </Form.Item>
                </Space>
              ))}
            </>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item>
      </Form>
      {/* ----------------------------------------------------------------------------------------- */}
    </Modal>
  );
};

export default CreateConfigForm;
