/** @format */
import * as React from 'react';
import {Popconfirm, Row, Col, Divider, Radio, InputNumber, List, notification, Empty} from 'antd';
import ModalForm from '../../../../../components/modalForm';
import {RowProps} from 'antd/es/row';
import Input from '../../../../../components/input';
import Button from '../../../../../components/button';
import message from '../../../../../components/message';
import {decodeBase64} from '../../../../../utils/base64';
import {
    useDeleteCombo,
    useInsertCombo,
    useDataApiQueryTypeDetail,
    DataApiQueryTypeDetailProps,
    useUpdateQueryType,
} from '../../../../../service/configQueryType';
const Rows = (props: RowProps) => <Row {...props} style={{marginBottom: 15, marginTop: 15}} />;

interface ModalFormProps {
    type: 1 | 2;
    defaultDataSource: any[];
    onOk?: () => void;
    title: string;
}

const ModalAddCount: React.FC<ModalFormProps> = props => {
    const id = new URLSearchParams(decodeBase64(location.search.slice(1))).get('id');
    const {children, type, defaultDataSource, onOk, title} = props;
    const [insertState, requestInsert] = useInsertCombo();
    const [state, setState] = React.useState({visible: false, dataSource: defaultDataSource});
    const handleUpdateVisible = () => {
        setState(preState => ({...preState, visible: !preState.visible}));
    };
    const handleAdd = () => {
        setState(preState => ({
            ...preState,
            dataSource: preState.dataSource.concat({count: 20, price: 100, total_day: 10, id: Date.now()}),
        }));
    };
    const handleRemove = (id: number) => {
        const newData = state.dataSource.map((element)=>{
            if(element.id === id){
                element.is_delete = true
            }
            return element
        })
        setState(preState => ({...preState, dataSource: newData }));
    };
    React.useEffect(() => {
        if (state.visible) {
            setState(preState => ({...preState, dataSource: defaultDataSource}));
        }
    }, [state.visible]);
    const handleSubmit = () => {
        requestInsert(
            state.dataSource.map(element => {
                return {
                    ...element,
                    query_type_id: Number(id),
                    type: type,
                };
            }),
        ).then(error => {
            if (error) {
                return notification.error({
                    message: '更新配额失败!',
                    description: error,
                });
            }
            handleUpdateVisible();
            onOk && onOk();
        });
    };
    const modalType = type === 1 ? 'total' : 'time';
    return (
        <>
            {React.isValidElement(children) &&
                React.cloneElement(children, {
                    onClick: handleUpdateVisible,
                })}
            <ModalForm
                visible={state.visible}
                loading={insertState.loading}
                onOk={handleSubmit}
                width={type === 1 ? 650 : 800}
                onCancel={handleUpdateVisible}
                title={title}
            >
                {state.dataSource.length === 0 ? (
                    <Empty />
                ) : (
                    state.dataSource.map((element, index) => {
                        return (
                            !element?.is_delete && <Row gutter={24} key={element.id} type='flex' align='middle' style={{marginBottom: 15}}>
                                <Col xxl={4} lg={modalType === 'time' ? 3 : 3}>
                                    序号:{index + 1}
                                </Col>
                                {modalType === 'time' ? (
                                    <Col xxl={4} lg={5}>
                                        <InputNumber
                                            formatter={value => `${value}天`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                            value={element.total_day}
                                            min={1}
                                            onChange={value => {
                                                setState(preState => ({
                                                    ...preState,
                                                    dataSource: preState.dataSource.map(item => {
                                                        if (item.id === element.id) {
                                                            return {
                                                                ...item,
                                                                total_day: value || 1,
                                                            };
                                                        }
                                                        return item;
                                                    }),
                                                }));
                                            }}
                                        />
                                    </Col>
                                ) : null}
                                <Col xxl={modalType === 'time' ? 4 : 5} lg={5}>
                                    <InputNumber
                                        formatter={value =>
                                            `${value} ${modalType === 'time' ? '次/天' : '次'}`.replace(
                                                /\B(?=(\d{3})+(?!\d))/g,
                                                ',',
                                            )
                                        }
                                        min={1}
                                        value={element.count}
                                        onChange={value => {
                                            setState(preState => ({
                                                ...preState,
                                                dataSource: preState.dataSource.map(item => {
                                                    if (item.id === element.id) {
                                                        return {
                                                            ...item,
                                                            count: value || 1,
                                                        };
                                                    }
                                                    return item;
                                                }),
                                            }));
                                        }}
                                    />
                                </Col>
                                <Col xxl={modalType === 'time' ? 4 : 6} lg={5}>
                                    <InputNumber
                                        value={element.price}
                                        min={0}
                                        formatter={value => `${value}￥`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                        onChange={value => {
                                            setState(preState => ({
                                                ...preState,
                                                dataSource: preState.dataSource.map(item => {
                                                    if (item.id === element.id) {
                                                        return {
                                                            ...item,
                                                            price: value,
                                                        };
                                                    }
                                                    return item;
                                                }),
                                            }));
                                        }}
                                    />
                                </Col>
                                <Col xxl={modalType === 'time' ? 4 : 6}>
                                    折合
                                    {modalType === 'time'
                                        ? `${(element.price / element.total_day).toFixed(2)}￥/天`
                                        : `${(element.price / element.count).toFixed(2)}￥/次`}
                                </Col>
                                {state.dataSource.length > 1 && (
                                    <Col xxl={3}>
                                        <Popconfirm title='是否删除该条配额' onConfirm={() => handleRemove(element.id)}>
                                            <Button shape='circle' icon='delete' type='danger' />
                                        </Popconfirm>
                                    </Col>
                                )}
                            </Row>
                        );
                    })
                )}

                <Button onClick={handleAdd} type='primary'>
                    添加
                </Button>
            </ModalForm>
        </>
    );
};

/**
 * 查询方式得套餐设置页面
 */
const PackageConfig: React.FC = () => {
    const id = new URLSearchParams(decodeBase64(location.search.slice(1))).get('id');
    const [detailState, requestDetail] = useDataApiQueryTypeDetail(Number(id));
    const [deleState, requestDelete] = useDeleteCombo();
    const [updateState, requestUpdate] = useUpdateQueryType();
    const [state, setState] = React.useState<{data: DataApiQueryTypeDetailProps}>({
        data: {
            is_free: false,
            total_data_combos: [],
            day_data_combos: [],
            free_data_combos: [],
            free_total: 0,
            unit_price:0,
        },
    });
    const handleSubmit = () => {
        requestUpdate({
            is_free: state.data.is_free,
            query_type_id: Number(id),
            count: state.data.free_total,
            unit_price:state.data.unit_price,
        }).then(error => {
            if (error) {
                return notification.error({
                    message: '更新查询方式失败!',
                    description: error,
                });
            }
            message.success('套餐配置成功!');
        });
    };
    React.useEffect(() => {
        setState(preState => ({
            ...preState,
            data: {
                ...detailState.dataSource,
                free_total:
                    detailState.dataSource.free_data_combos.length > 0
                        ? detailState.dataSource.free_data_combos[0].count
                        : 0,
            },
        }));
    }, [detailState]);
    return (
        <React.Fragment>
            <h3>业务信息</h3>
            <Rows>
                <Col span={2}>计费类型:</Col>
                <Col span={6}>
                    <Radio.Group
                        value={state.data.is_free}
                        onChange={e =>
                            setState(preState => ({...preState, data: {...preState.data, is_free: e.target.value}}))
                        }
                    >
                        <Radio value={false}>收费</Radio>
                        <Radio value={true}>免费</Radio>
                    </Radio.Group>
                </Col>
            </Rows>
            <Rows>
                {!state.data.is_free ? (
                    <>
                        <Col span={2}>试用次数:</Col>
                        <Col span={6}>
                            <InputNumber
                                value={state.data.free_total}
                                onChange={value =>
                                    setState(preState => ({...preState, data: {...preState.data, free_total: value}}))
                                }
                                min={0}
                            />
                        </Col>
                    </>
                ) : null}
            </Rows>
            <Rows>
                {!state.data.is_free ? (
                    <>
                        <Col span={2}>单价:</Col>
                        <Col span={6}>
                            <InputNumber
                                value={state.data?.unit_price}
                                onChange={value =>
                                    setState(preState => ({...preState, data: {...preState.data, unit_price: value}}))
                                }
                                min={0}
                            />
                        </Col>
                    </>
                ) : null}
            </Rows>

            <Button type='primary' loading={updateState.loading} onClick={handleSubmit}>
                保存
            </Button>

            {!state.data.is_free && (
                <div>
                    <Divider />
                    <List
                        split={false}
                        header={<div>按次数配额</div>}
                        footer={
                            <ModalAddCount
                                onOk={() => {
                                    requestDetail(Number(id));
                                }}
                                type={1}
                                title='添加(按次)'
                                defaultDataSource={state.data.total_data_combos}
                            >
                                <Button type='primary'>修改</Button>
                            </ModalAddCount>
                        }
                        dataSource={state.data.total_data_combos}
                        renderItem={(item: any, index) => (
                            <List.Item>
                                <Col xxl={2} lg={3}>
                                    <span>序号:{index + 1}</span>
                                </Col>
                                <Col span={3}>
                                    <span>{item.count}次</span>
                                </Col>
                                <Col span={3}>
                                    <span>{item.price}￥</span>
                                </Col>
                                <Col span={3}>
                                    <span>{(item.price / item.count).toFixed(2)}￥/次</span>
                                </Col>
                            </List.Item>
                        )}
                    />
                    <List
                        header={<div>按时间配额:</div>}
                        footer={
                            <ModalAddCount
                                title='添加(按时)'
                                onOk={() => {
                                    requestDetail(Number(id));
                                }}
                                type={2}
                                defaultDataSource={state.data.day_data_combos}
                            >
                                <Button type='primary'>修改</Button>
                            </ModalAddCount>
                        }
                        dataSource={state.data.day_data_combos}
                        renderItem={(item: any, index) => (
                            <List.Item>
                                <Col xxl={2} lg={3}>
                                    <span>序号:{index + 1}</span>
                                </Col>
                                <Col span={3}>
                                    <span>{item.total_day}天</span>
                                </Col>
                                <Col span={3}>
                                    <span>{item.count}次/天</span>
                                </Col>
                                <Col span={3}>
                                    <span>{item.price}￥</span>
                                </Col>
                                <Col span={3}>
                                    <span>折合{(item.price / item.total_day).toFixed(2)}￥/天</span>
                                </Col>
                            </List.Item>
                        )}
                    />
                </div>
            )}
        </React.Fragment>
    );
};
export default PackageConfig;
