import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Checkbox, Modal, Toast} from 'antd-mobile'
import {HeaderBar} from '../../common'
import Loading from '@/common/Loading'
import ShopCart from './cartList.js'
import './card.scss'
import classnames from 'classnames'
import {http} from "@/utils";
import {getCourses} from './../detail/actions';

const alert = Modal.alert;

class Cart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            checkedNum: 0,
            allPrice: 0,
            cartNmu: 0,
            courseIdarr: [], // 选中的课程id
            isLoading: true
        }

    }


    componentDidMount() {
        this.getList()
    }

    // 获取课程列表
    getList = () => {
        http.get(`${API.home}/m/cart/list`).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    data: res.data.data.courses,
                    isLoading: false
                })
            } else {
                Toast.info(res.data.msg, 2);
            }
        })
    }

    //全选
    allChange(e) {
        let checked = e.target.checked
        let newData = this.state.data.map((item, i) => {
            return {
                ...item,
                check: checked
            }
        })
        this.setState({
            data: newData
        })
        this.calc(newData)

        if (checked) {
            let arr = []
            newData.map((item, i) => {
                arr.push(item.course_id)
            })
            this.setState({
                courseIdarr: arr
            })

        } else {
            this.setState({
                courseIdarr: []
            })
        }

    }

    //点击
    checkChange(id, check) {
        let newData = this.state.data.map((item, i) => {
            if (item.course_id === id) {
                return {
                    ...item,
                    check: check
                }
            } else {
                return item;
            }
        })
        this.setState({
            data: newData
        })
        this.calc(newData)
        let arr = []
        newData.forEach((item, i) => {
            if (item.check) {
                arr.push(item.course_id)
                this.setState({
                    courseIdarr: arr
                })
            } else {
                this.setState({
                    courseIdarr: arr
                })
            }
        })
    }

    //计算总价
    calc(newData) {
        let allPrice = 0;
        let checkedNum = 0;
        let cartNmu = 0;
        let arr = []
        newData.forEach((item, i) => {
            if (item.check) {
                arr.push(item)
                cartNmu += 1;
                checkedNum = arr.length;
                allPrice += parseFloat(item.price1);
            }
        })
        this.setState({
            checkedNum,
            allPrice,
            cartNmu
        })
    }

    // 去结算
    tobuy = () => {
        // console.log(this.state.courseIdarr);
        http.get(`${API['base-api']}/m/cart/addtopreorder/[${this.state.courseIdarr}]`).then((res) => {
            if (res.data.errno == 0) {
                this.props.history.push(`/order?id=[${this.state.courseIdarr}]`,{simple: 1})
            } else {
                Toast.info(res.data.msg, 2);
            }
        })
    }


    // 删除
    todelete = () => {
        if (this.state.courseIdarr.length > 0) {
            alert('', '确定从购物车中删除?', [
                {text: '取消', onPress: () => console.log('cancel')},
                {
                    text: '确认',
                    onPress: () => {
                        let data = {
                            course_ids: this.state.courseIdarr
                        }
                        http.post(`${API.home}/m/cart/remove`, data).then((res) => {
                            if (res.data.code === 200) {
                                this.getList()
                                this.setState({
                                    checkedNum: 0,
                                    allPrice:0
                                })
                            } else {
                                Toast.info(res.data.msg, 2);
                            }
                        })
                    }
                }
            ])
        }

    }

    toCourseDetail = (id) => {
        // console.log(id);
        const { dispatch, history } = this.props;
        // dispatch(getCourses(id, () => {
            history.push(`/detail?id=${id}`)
        // }));
    }


    render() {
        return (
            <div className="cart-page" style={{overflow: 'hidden'}}>
                <HeaderBar title='购物车' arrow={true} cart={false} delete={true} toDelete={this.todelete}></HeaderBar>

                <Loading isLoading={this.state.isLoading}>
                    <div className="cart-body">
                        <ShopCart
                            checkChange={this.checkChange.bind(this)}
                            data={this.state.data}
                            toDetail={this.toCourseDetail}
                        />

                        <div className="cart-footer">
                            <div className="cart-label">
                                <Checkbox onChange={(e) => {
                                    this.allChange(e)
                                }}/>
                                <div>全选</div>
                            </div>
                            <div className="all-pirce">
                                <p>
                                    <span>合计:</span>
                                    <span>¥{this.state.allPrice}</span>
                                </p>
                            </div>
                            <div className={classnames({
                                'active': this.state.checkedNum > 0
                            })} onClick={() => {
                                if (this.state.checkedNum > 0) {
                                    this.tobuy()
                                }
                            }}>
                                结算<span> ( {this.state.checkedNum} ) </span>
                            </div>
                        </div>

                    </div>
                </Loading>


            </div>
        )
    }
}

export default connect()(Cart)