import React, { PureComponent } from 'react';
import './coupons.scss'

import RedeemBar from "./RedeemBar";
import Coupon from './Coupon'
import { http, getParam } from '@/utils'
import { WithFullSize } from '@/HOCs'
import { Toast } from 'antd-mobile'
import { isEmpty } from 'lodash'
import { HeaderBar } from "@/common";
import {connect} from 'react-redux';
import {getCourses} from './../detail/actions';

@connect()
class UseCoupon extends PureComponent {

    state = {
        selectedCouponId: 0,
        redeemCode: '',
        couponList: [],
        valid_coupons: [],
        invalid_coupons: [],
        courseId: getParam('id'),
        showUseButton: false
    }

    componentDidMount() {

        const {history, location} = this.props

        const {state} = this.props.location


        if (state && state.from) {
            if (state.from === '/my') {
                this.getMyCoupons();
                this.setState({
                    showUseButton: true
                })
            } else {
                if (!this.state.courseId) {
                    location.state && location.state.from ? history.replace(location.state.from) : history.goBack()
                }
                this.getAllCoupons();
            }
        }
    }

    handleChange = e => {
        let value = e ? e.target.value : ''
        this.setState({redeemCode: value})
    }

    exchange = () => {
        if (this.state.redeemCode !== '') {
            http.post(`${API.home}/m/coupon/exchange`, {
                code: this.state.redeemCode
            })
                .then(res => {
                    const data = res.data
                    if (data.code === 200) {

                        const coupon = data.data

                        if (this.state.showUseButton) {
                            this.setState({
                                couponList: [...this.state.couponList, coupon],
                                redeemCode: ''
                            })
                        } else {

                            const coupon = data.data

                            if (coupon['ctype'] == 2
                                && coupon['limit_course'] != this.state.courseId) {
                                this.setState({
                                    invalid_coupons: [...this.state.invalid_coupons, coupon],
                                    showUseButton: null
                                });
                            } else {
                                this.setState({
                                    valid_coupons: [...this.state.valid_coupons, coupon],
                                    redeemCode: ''
                                })
                            }

                        }
                        Toast.info('兑换成功')
                        this.getMyCoupons()
                    } else {
                        Toast.info(data.msg)
                    }
                })
        } else {
            Toast.info('请输入兑换码')
        }
    }

    getMyCoupons = () => {
        http.get(`${API.home}/m/coupon/all`)
            .then(res => {
                const data = res.data
                if (data.code === 200) {
                    this.setState({
                        couponList: isEmpty(data.data) ? [] : data.data
                    })
                } else {
                    Toast.info(data.msg)
                }
            })
    }

    getAllCoupons = () => {
        http.post(`${API.home}/m/coupon/select`, {course_id: this.state.courseId})
            .then(res => {
                const data = res.data
                if (data.code === 200) {

                    const inuse_coupon = data.data['inuse_coupon'];


                    this.setState({
                        valid_coupons: inuse_coupon
                            ? [...inuse_coupon, ...data.data.valid_coupons]
                            : data.data.valid_coupons,
                        invalid_coupons: data.data.invalid_coupons,
                        selectedCouponId: inuse_coupon.length ? inuse_coupon[0].id : 0
                    })

                } else {
                    Toast.info(data.msg)
                }
            })
    }

    useCoupon = val => {
        const {history, dispatch} = this.props
        const coupon = this.state.couponList.find(item => item.id === val)

        if (val) {
            if (this.state.showUseButton) {

                if (coupon['ctype'] === 1) {
                    history.push(`/classify`)
                } else {
                    dispatch(getCourses(coupon['limit_course'], () => {
                        history.push(`/detail?id=${coupon['limit_course']}`);
                        return false;
                    }));
                }

            } else {

                const {courseId, selectedCouponId} = this.state

                if (selectedCouponId === val) {


                    http.post(`${API.home}/m/coupon/cancel`, {
                        course_id: courseId
                    }).then(res => {
                        const data = res.data
                        if (data.code === 200) {


                            this.setState({
                                selectedCouponId: 0
                            })


                        } else {
                            Toast.info(data.msg)
                        }
                    })


                } else {
                    http.post(`${API.home}/m/coupon/use`, {
                        course_id: this.state.courseId,
                        coupon_id: val
                    })
                        .then(res => {
                            const data = res && res.data
                            if (data.code === 200) {

                                this.setState({selectedCouponId: val})
                                this.props.history.goBack()


                            } else {
                                Toast.info(data.msg)
                            }
                        })

                }


            }

        } else {
            Toast.info('未知错误')
            location.reload()
        }

    }

    render() {
        const {state} = this.props.location
        const {showUseButton, selectedCouponId} = this.state
        return (
            <div className='use-coupon'>
                <HeaderBar title='优惠券' arrow={true}/>
                <RedeemBar onChange={this.handleChange}
                           exchange={this.exchange}
                           redeemCode={this.state.redeemCode}/>
                <div className="coupons-area">
                    <Content
                        coupons={
                            state
                            && state.from
                            && state.from === '/my'
                                ? this.state.couponList
                                : this.state.valid_coupons
                        }
                        showUseButton={showUseButton}
                        selectedCouponId={selectedCouponId}
                        select={this.select}
                        useCoupon={this.useCoupon}
                    />
                    {
                        this.state.invalid_coupons.length > 0 &&
                        (
                            <>
                                <div className='invalid-title'>- 不可使用的优惠券 -</div>
                                <Content
                                    coupons={this.state.invalid_coupons}
                                    selectedCouponId={selectedCouponId}
                                    select={this.select}
                                    purpose={'use'}
                                    invalid={'invalid'}
                                />
                            </>
                        )
                    }
                </div>
            </div>
        );
    }
}

function Content({coupons, ...rest}) {
    if (coupons.length === 0) {
        return (
            <div className='empty'>
                <p>暂无可使用的优惠券</p>
            </div>
        )
    }
    return (
        <ul>
            {
                coupons.map(item => {
                    return (
                        <Coupon
                            key={item.id}
                            {...item}
                            id={item.id}
                            {...rest}
                        />
                    )
                })
            }
        </ul>
    )
}

export default WithFullSize(UseCoupon);