import React, { useState, useEffect } from "react";
import { Form, Button, Input, Image, Select, DatePicker, Upload, message, Checkbox, Row, Col } from 'antd';
import styles from "../../index.less";
import { MinusCircleOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import startAPI from "../../service";
import axios from 'axios';
import moment from "moment";

const activityConfigArray = [
    {
        "configId": null,
        "operator": null,
        "value1": [],
        "value2": null,
        "activity_Id": null,
        "configuration_Id": "8AC2A2BA-BB6E-4566-B147-ACF798146BBD",
        "configurationName": "星期限制",
        "configurationRule": "包含的星期",
        "valueType": 2,
        "configurationValueCount": 1
    },
    {
        "configId": null,
        "operator": null,
        "value1": [],
        "value2": null,
        "activity_Id": null,
        "configuration_Id": "ECBACC1C-6BA8-498E-BDE4-6A012881E0E7",
        "configurationName": "门店限制",
        "configurationRule": "包含的门店",
        "valueType": 2,
        "configurationValueCount": 1
    }
]

/**
 * 特价商品
 * @returns 
 */
const SpecialOffer = (props) => {

    const [form] = Form.useForm();
    const [imgurl, setimgUrl] = useState(null);
    /** 适用门店范围 */
    const [applicableStore, setApplicableStore] = useState([]);

    /**
    * 获取适用店铺
    */
    const GetStores = async () => {
        const response = await startAPI.GetStores();
        if (response.statusCode === 200) {
            setApplicableStore(response.data);
        }
    }

    /** 适用商品范围 */
    const [applyGood, setApplyGood] = useState([]);

    /**
     * 获取商品
     */
    const onFetchGoods = async (goodsType = -1) => {
        const response = await startAPI.GetGoodsById(goodsType);
        if (response.statusCode === 200) {
            const array = [];
            Object.keys(response.data).forEach(item => {
                array.push({
                    id: item,
                    name: response.data[item]
                })
            });
            setApplyGood(array)
        }
    }

    /**
    * 提交
    * @param {*} values 
    */
    const onSubmitActivity = async (values) => {
        values.activityType = 3;
        values.activityRewards.forEach(item => {
            item.id = "";
            item.activityInfo_Id = "";
        })
        values.activityStartTime = moment(values.activityStartAndEndTime[0]).format('YYYY-MM-DD');
        values.activityEndTime = moment(values.activityStartAndEndTime[1]).format('YYYY-MM-DD');
        values.status = 0;
        values.isShow = 1;
        values.isDeleted = 0;
        values.consumptionType = 0;
        values.isGiftGoodsParticipate = 0;
        values.activityConfiguration = [];
        values.activityConfig.forEach(config => {
            const findConfig = activityConfigArray.find(item => item.configuration_Id === config);
            if (findConfig) {
                findConfig.configId = [findConfig.configuration_Id];
                if (findConfig.configurationName === '星期限制') {
                    findConfig.operator = values.weekOperator;
                    findConfig.value1 = values.weekValue;
                } else if (findConfig.configurationName === '门店限制') {
                    findConfig.operator = values.storeOperator;
                    findConfig.value1 = values.storeValue;
                }
                values.activityConfiguration.push(findConfig);
            }
        });

        delete values.storeOperator;
        delete values.storeValue;

        delete values.weekOperator;
        delete values.weekValue;
        const response = await startAPI.FastAddActivity(values);
        if (response.statusCode === 200) {
            message.success('新建活动成功！');
            form.resetFields();
            props.onSuccessCreate && props.onSuccessCreate();
        } else {
            message.error(response.errors || '创建失败 请重试！');
        }
    }

    useEffect(() => {
        GetStores();
        onFetchGoods();
    }, []);

    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;
            startAPI.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 => {
                        form.setFieldsValue({ activityImg: r.seeUrl });
                        if (response.status == 200 || response.statusText == 'OK') {
                            setimgUrl(r.seeUrl)
                        }
                    })
                        .catch(onError);
                };
            });
        },
    };

    return <div className={styles.activity_form_container} >
        <Form
            form={form}
            name="basic"
            labelCol={{
                span: 3,
            }}
            initialValues={{
                remember: true,
            }}
            onFinish={(values) => {
                onSubmitActivity(values);
            }}
            layout="vertical"
            autoComplete="off"
        >
            <Form.Item
                label="活动名称"
                name="activityName"
                rules={[
                    {
                        required: true,
                        message: '请输入活动名称！',
                    },
                ]}
            >
                <Input style={{ width: '100%' }} placeholder="请输入活动名称" />
            </Form.Item>


            <Form.Item label="商品信息">
                <Form.List name="activityRewards">
                    {(fields, { add, remove }, { errors }) => (
                        <>
                            {fields.map(({ key, name, fieldKey, ...restField }) => (
                                <div className={styles.common_form_row}>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'rewardValue']}
                                        fieldKey={[fieldKey, 'rewardValue']}
                                        rules={[{ required: true, message: '请选择商品' }]}
                                    >
                                        <Select style={{ width: '200px' }}>
                                            {
                                                applyGood.map(item => {
                                                    return <Select.Option value={item.id} key={item.id}>
                                                        {item.name}
                                                    </Select.Option>
                                                })
                                            }
                                        </Select>
                                    </Form.Item>
                                    <div style={{ margin: '0 10px 24px 10px' }}>促销价：</div>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'value']}
                                        fieldKey={[fieldKey, 'value']}
                                        rules={[{ required: true, message: '请输入促销价' }]}>
                                        <Input style={{ width: '100%' }} placeholder="请输入促销价" />
                                    </Form.Item>

                                    <MinusCircleOutlined style={{ fontSize: '25px', marginLeft: '20px', marginBottom: '24px' }} onClick={() => remove(name)} />
                                </div>
                            ))}
                            <Form.Item>
                                <Button
                                    type="dashed"
                                    onClick={() => add()}
                                    style={{
                                        width: '100%',
                                    }}
                                    icon={<PlusOutlined />}
                                >
                                    添加
                                </Button>
                                <Form.ErrorList errors={errors} />
                            </Form.Item>
                        </>
                    )}
                </Form.List>
            </Form.Item>

            <Form.Item
                name="activityStartAndEndTime"
                label="起止时间"
                rules={[{ required: true }]}
            >
                <DatePicker.RangePicker style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item name="remark" label="备注" rules={[{ required: true, max: 200 }]}>
                <Input.TextArea rows={4} placeholder="请输入备注" />
            </Form.Item>

            <Form.Item name="activityRule" label="规则说明" rules={[{ required: true, max: 500 }]}>
                <Input.TextArea rows={4} placeholder="请输入规则说明" />
            </Form.Item>

            <Form.Item name="activityImg" label="活动图片" rules={[{ required: true }]}
            >
                <Upload
                    {...uploadProp}
                >
                    {imgurl ? <Image
                        width={200}
                        height={200}
                        src={imgurl}
                        fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0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AkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
                    /> : <Button icon={<UploadOutlined />}>上传</Button>}
                </Upload>
            </Form.Item>

            <Form.Item name="isAutoSend" label="参与方式" rules={[{ required: true }]}>
                <Select placeholder="请选择参与方式">
                    <Select.Option value={0}>点击参与（需要用户主动点击）</Select.Option>
                    <Select.Option value={1}>自动参与（满足特定条件自动参与）</Select.Option>
                </Select>
            </Form.Item>

            <Form.Item name="activityConfig" label="活动配置" rules={[{ required: true, message: '请至少选择一个活动配置！' }]}>
                <Checkbox.Group style={{
                    width: '100%',
                }}>
                    <Row>
                        {
                            activityConfigArray.map((config, index) => {
                                return <Col key={index} span={24} style={{ marginBottom: '10px', display: 'flex', alignItems: 'center' }}>
                                    <Checkbox style={{ minWidth: '230px' }} value={config.configuration_Id}>{config.configurationName}：{config.configurationRule}</Checkbox>
                                    {index === 0 && (
                                        <>
                                            <Form.Item
                                                name="weekOperator"
                                                noStyle
                                            >
                                                <Select style={{ width: 80, margin: '0 20px' }} size='Small' placeholder="条件">
                                                    <Select.Option value=">">大于</Select.Option>
                                                    <Select.Option value="<">小于</Select.Option>
                                                    <Select.Option value="==">等于</Select.Option>
                                                    <Select.Option value=">=and<=">包含</Select.Option>
                                                </Select>
                                            </Form.Item>
                                            <Form.Item
                                                name="weekValue"
                                                noStyle
                                            >
                                                <Select style={{ width: 280 }} size='Small' mode="multiple" placeholder="星期">
                                                    <Select.Option value="1">星期一</Select.Option>
                                                    <Select.Option value="2">星期二</Select.Option>
                                                    <Select.Option value="3">星期三</Select.Option>
                                                    <Select.Option value="4">星期四</Select.Option>
                                                    <Select.Option value="5">星期五</Select.Option>
                                                    <Select.Option value="6">星期六</Select.Option>
                                                    <Select.Option value="0">星期日</Select.Option>
                                                </Select>
                                            </Form.Item>
                                        </>
                                    )}
                                    {index === 1 && (
                                        <>
                                            <Form.Item
                                                name="storeOperator"
                                                noStyle
                                            >
                                                <Select style={{ width: 80, margin: '0 20px' }} size='Small' placeholder="条件">
                                                    <Select.Option value=">">大于</Select.Option>
                                                    <Select.Option value="<">小于</Select.Option>
                                                    <Select.Option value="==">等于</Select.Option>
                                                    <Select.Option value=">=and<=">包含</Select.Option>
                                                </Select>
                                            </Form.Item>
                                            <Form.Item
                                                name="storeValue"
                                                noStyle
                                            >
                                                <Select style={{ width: 280 }} size='Small' mode="multiple" placeholder="门店">
                                                    {
                                                        applicableStore.map(item => {
                                                            return <Select.Option value={item.id} key={item.id}>
                                                                {item.name}
                                                            </Select.Option>
                                                        })
                                                    }
                                                </Select>
                                            </Form.Item>
                                        </>
                                    )}
                                </Col>
                            })
                        }
                    </Row>
                </Checkbox.Group>
            </Form.Item>

            <Form.Item>
                <Button type="primary" htmlType="submit">
                    提交
                </Button>
                <Button style={{ marginLeft: '20px' }} onClick={() => {
                    form.resetFields();
                    setimgUrl(null);
                }}>
                    重置
                </Button>
            </Form.Item>

        </Form>
    </div>
}

export default SpecialOffer;