import React, { PureComponent } from 'react'
import './index.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 { connect } from 'react-redux'

@connect()
class UseCoupon extends PureComponent {

    state = {
        selectedCouponId: 0,
        redeemCode: '',
        couponList: [],
        valid_coupons: [],
        invalid_coupons: [],
        courseId: getParam('id'),
        showUseButton: false,
        courseCouponExchange: false, // 课程券兑换弹窗
        courseCouponData: '' // 兑换课程信息
    }

    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 = () => {
        const {location: {state = {}}} = this.props
        if (this.state.redeemCode !== '') {
            http.post(`${API.home}/m/coupon/exchange`, {
                code: this.state.redeemCode,
                type: state.from.substr(1)
            })
                .then(res => {
                    const data = res.data
                    if (data.code === 200) {
                        // 如果从我的页面进来，点击兑换直接兑换成功课程，弹出弹窗
                        // 如果从订单页面进来，点击兑换兑换成券
                        const coupon = data.data

                        if (state.from === '/my') {
                            if (coupon['ctype'] == 2) {
                                this.setState({
                                    courseCouponData: coupon,
                                    courseCouponExchange: true,
                                    redeemCode: ''
                                })
                            } else {
                                this.setState({
                                    couponList: [...this.state.couponList, coupon],
                                    redeemCode: ''
                                })
                                Toast.info('兑换成功')
                                this.getMyCoupons()
                            }
                        }
                        if (state.from === '/order') {
                            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,
                                    redeemCode: ''
                                })
                            } else {
                                this.setState({
                                    valid_coupons: [...this.state.valid_coupons, coupon],
                                    redeemCode: ''
                                })
                            }
                            Toast.info('兑换成功')
                            this.getAllCoupons()
                        }

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

    getMyCoupons = () => {
        Promise.all([
            http.get(`${API.home}/m/coupon/all`),
            http.get(`${API.home}/m/coupon/expansion`)
        ]).then((coupons) => {
            let myCoupons = []
            const [allCoupons, expansionCoupons] = coupons
            const {data: all} = allCoupons
            const {data: expansion} = expansionCoupons
            if (all.code == 200) {
                Array.isArray(all.data) && (myCoupons = myCoupons.concat(all.data))
            } else {
                Toast.info(all.msg)
            }

            if (expansion.code == 200) {
                Array.isArray(expansion.data)
                && (expansion.data = expansion.data.map(item => (item.ctype = 4, item)))
                && (myCoupons = myCoupons.concat(expansion.data))
            } else {
                Toast.info(expansion.msg)
            }

            this.setState({
                couponList: myCoupons
            })
        })
    }

    getAllCoupons = () => {
        Promise.all([
            http.post(`${API.home}/m/coupon/select`, {course_id: this.state.courseId}),
            http.get(`${API.home}/m/coupon/expansion`)
        ]).then((coupons) => {
            const [selectCoupons, expansionCoupons] = coupons
            const {data: select} = selectCoupons
            const {data: expansion} = expansionCoupons
            if (select.code === 200) {
                const inuse_coupon = select.data['inuse_coupon']
                this.setState({
                    valid_coupons: inuse_coupon
                        ? [...inuse_coupon, ...select.data.valid_coupons]
                        : select.data.valid_coupons,
                    invalid_coupons: select.data.invalid_coupons,
                    selectedCouponId: inuse_coupon.length ? inuse_coupon[0].id : 0
                })

            } else {
                Toast.info(data.msg)
            }
            if (expansion.code == 200) {
                Array.isArray(expansion.data)
                && (expansion.data = expansion.data.map(item => (item.ctype = 4, item)))
                && (this.setState({
                    valid_coupons: this.state.valid_coupons.concat(expansion.data)
                }))
            } else {
                Toast.info(expansion.msg)
            }


        })
    }

    // 立即兑换课程
    toExchangeCourse = (e, code) => {
        e.stopPropagation()
        http.post(`${API['base-api']}/pay/miandan/${code}`, {}).then(res => {
            const data = res.data
            if (data.errno === 200) {
                this.setState({
                    courseCouponExchange: true,
                    courseCouponData: res.data.data
                })
                this.getMyCoupons()
            } else {
                Toast.info(data.msg)
            }
        })
    }

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

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

                if (coupon['limit_course'] === 0) {
                    history.push(`/classify`)
                } else {
                    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()
        }

    }

    // 开始学习
    toStudy = (vCourseId, isHaveVideo) => {
        const {history} = this.props
        if (isHaveVideo == 0) {
            Toast.info('尚未开课，开课后立即上传课程～', 2)
        } else {
            history.push(`/play/video?id=${vCourseId}`)
        }
        this.setState({
            courseCouponExchange: false
        })
    }

    // 关闭弹窗
    closeFreeCourse = () => {
        this.setState({
            courseCouponExchange: false
        })
    }

    endExpansion = id => {
        this.setState({
            couponList: this.state.couponList.map(item => {
                if (item.id === id) {
                    delete item.start_amount
                }
                return item
            })
        })
    }


    render() {
        const {state} = this.props.location
        const {showUseButton, selectedCouponId} = this.state
        return (
            <div className='use-coupon'>
                <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}
                        toExchangeCourse={this.toExchangeCourse}
                        endExpansion={this.endExpansion}
                    />
                    {
                        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>
                {
                    this.state.courseCouponExchange &&
                    <FreeCouponCourse toStudy={this.toStudy} closeFreeCourse={this.closeFreeCourse}
                                      courseCouponData={this.state.courseCouponData}/>
                }
            </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>
    )
}

function FreeCouponCourse(props) {
    const {toStudy, closeFreeCourse, courseCouponData} = props
    return (
        <div className="free-coupon-box">
            <div className="free-coupon-content">
                <div className="coures-content-success"><i className={'iconfont icondanseshixintubiao-5'}/></div>
                <div className="coures-content-title">恭喜你课程兑换成功!赶快去学习吧~</div>
                <img className="coures-content-img" src={courseCouponData.image_name} alt=""/>
                {
                    courseCouponData.course_expire != 0 &&
                    <div className="coures-content-tip"><i
                        className={'iconfont icondanseshixintubiao-8'}/><span>课程有效期：自今日起{courseCouponData.course_expire}天内，请在有效期内学习该课程哦～</span>
                    </div>
                }

                <a className='toStudy'
                   onClick={() => toStudy(courseCouponData.v_course_id, courseCouponData.is_is_start)}>去学习</a>
            </div>
            <div className="free-coupon-close">
                <i className={'iconfont iconiconfront-2'} onClick={() => closeFreeCourse()}/>
            </div>
        </div>
    )
}

export default WithFullSize(UseCoupon)
