import React, { Component } from 'react';
import { Flex, List, WingBlank, Toast } from 'antd-mobile';
import { OrderItem } from '@/common/index';
import { Link } from 'react-router-dom';
import { http, getParam } from "@/utils";
import { throttle } from 'lodash';
import {HeaderBar} from '../../common';
import {connect} from 'react-redux';
import {getCourses} from './../detail/actions';

import "./order.scss"

const Item = List.Item;

function OrderList(props) {
  const listData = props.list;
  return (
    <div>
      {
        listData.map((item, index) => {
          const { is_coupon, course_id, image_name, price1, price0, simpledescription, course_title, coupon_num, coupon_desc} = item;
          let NewPrice = (<span className='order-newprice'>¥{price1}</span>);
          if(props.locationState && props.locationState.group) {
            NewPrice = (<span className='order-newprice'>¥{props.groupPrice}</span>);
          }
          const Info = (
            <div className="order-info">
              {/* <Link to={`/detail?id=${course_id}`}> */}
                <p
                  className='order-title'
                  style={{
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                  onClick={() => props.toDetail(course_id)}
                >
                  {course_title}
                </p>
                {/* </Link> */}
              <p className='order-content' style={{ WebkitBoxOrient: 'vertical', WebkitLineClamp: '2', wordBreak: 'break-all', overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box' }}>{simpledescription}</p>
              <p className='order-des'>
                {/*// 这里根据类型判断 来显示什么价格 拼团还是砍价 还是特训营*/ }
                {/*{*/}
                {/*  props.courseId === undefined ? (<span className='order-newprice'>¥{price1}</span>) : (<span className='order-newprice'>¥{price0}</span>)*/}
                {/*}*/}
                {NewPrice}
                <span className='order-price'>¥{price0}</span>
              </p>
            </div>
          );

          return (
            <OrderItem
              {...item}
              src={image_name}
              id={course_id}
              key={index}
              info={Info}
              isaist={props.isaist}
              toDetail={props.toDetail}
            >
              {
                (props.locationState && (props.locationState.type || props.locationState.simple)) ? (
                  <div className="order-prefer">
                    <List key={index}>
                      <Item
                        arrow="horizontal"
                        onClick={() => { }}
                      >
                        <Link to={{
                                pathname: `/coupons`,
                                search: `?id=${course_id}`,
                                state: {
                                    from: '/order'
                              }}}>
                          {/* <Link to='coupons' query={{id: course_id}} state={{from: '/order'}}> */}
                          <Flex justify='between'>
                            <span 
                              style={{ 
                                color: '#333', 
                                fontSize: '15px' 
                              }}
                            >优惠券</span>
                            <span 
                              style={{ 
                                fontSize: '14px', 
                                color: '#999999' 
                              }}
                            >
                              {!coupon_desc ? (coupon_num === 0 ? '无' : `${coupon_num}张可用`) : (coupon_desc)}
                            </span>
                          </Flex>
                        </Link>
                      </Item>
                    </List>
                  </div>
                ) : null
              }

            </OrderItem>
          )
        })
      }
    </div>
  );
}

@connect()
class Order extends Component {
  constructor(props) {
    super(props);
    this.state = {
      groupPrice: '',
      perfect: this.props.location.state,
      user_account: 0.00, // 账户余额
      total: 0.00, // 需要支付总金额
      discount: 0.00, //
      useBalance: false,
      orderList: [],
      info: false,
      offset: 0,
    };
  }
  // 提交订单
  submitOrder = () => {
    const {total} = this.state;
    if (this.state.orderList.length === 0) {
      Toast.info('没有要提交的订单！');
      return;
    }
    if (!this.state.perfect) {
      Toast.info('请完善报名信息！');
    }
    const { location: { state ={} } } = this.props;
    if(state.group === 1) {
      let params = state.pdd_order_id? {
        course_id: getParam("id"),
        ischeck: this.state.useBalance,
        pdd_order_id: state.pdd_order_id
      } : {
        course_id: getParam("id"),
        ischeck: this.state.useBalance,
      }
      http.post(`${API['base-api']}/pdd/m`, params).then(res => {
        console.log(res);
        if(res.data.errno === 200) {
          sessionStorage.removeItem('orderUseCacheObj');
          if (res.data.data.pay_jump === 1) {
            this.props.history.push(`/togroup?id=${res.data.data.oid}`);
            return;
          }
          this.props.history.push(`/payorder?oid=${res.data.data.oid}`, {group: 1});

        }else {
          Toast.info(res.data.msg, 2);
          return;
        }
      });
    }else{
      let url = `${API['base-api']}/m/v34/cart/order?ischeck=${this.state.useBalance}`;
      if(this.props.location.state && this.props.location.state.type === 1) {
        url += '&type=1'
      }
      http.get(url).then(res => {
        if(res.data.errno !== 0) {
          Toast.info(res.data.msg, 2);
          return;
        }
        sessionStorage.removeItem('orderUseCacheObj');
        if (res.data.data.is_free === 1) {
          this.props.history.replace(`/purchased`);
          return;
        }
        this.props.history.replace(`/payorder?oid=${res.data.data.order_id}`);
      });
    }

  }
  // 勾选取消勾选 是否使用余额
  useBalance = () => {
    let useBalanceFlag = this.state.useBalance;
    this.setState({
      useBalance: !useBalanceFlag
    });
    if (!useBalanceFlag) {
      this.cacheObj = {
        ...this.state
      };
      sessionStorage.setItem('orderUseCacheObj', JSON.stringify(this.state));
    }else{
      sessionStorage.removeItem('orderUseCacheObj');
    }
    this.computedMoney(useBalanceFlag);
  }
  // 勾选取消勾选时：计算金额、优惠金额、优惠券等
  computedMoney = (useBalanceFlag) => {
    let totalSale = parseFloat(this.cacheObj.total),
      userAccount = parseFloat(this.cacheObj.user_account);
    const { discount } = this.state;
    if (!useBalanceFlag) {
      if (totalSale > userAccount) {
        this.setState({
          offset: userAccount.toFixed(2),
          total: (totalSale - userAccount).toFixed(2),
          discount: (userAccount + parseFloat(discount)).toFixed(2),
        });
      } else {
        this.setState({
          offset: totalSale.toFixed(2),
          total: 0,
          discount: (totalSale + parseFloat(discount)).toFixed(2),
        });
      }
    } else {
      this.setState({
        offset: this.cacheObj.offset,
        total: this.cacheObj.total,
        discount: this.cacheObj.discount,
      });
    }
  };
  // 选择优惠券返回时根据是否勾选计算
  computedMoneyByCache = () => {
    let totalSale = parseFloat(this.cacheObj.total),
      userAccount = parseFloat(this.cacheObj.user_account),
      discount = parseFloat(this.cacheObj.discount);
      if(totalSale > userAccount) {
        this.setState({
          offset: userAccount.toFixed(2),
          total: (totalSale - userAccount).toFixed(2),
          discount: (discount + userAccount).toFixed(2),
        });
      }else{
        this.setState({
          offset: totalSale.toFixed(2),
          total: 0,
          discount: totalSale.toFixed(2),
        });
      }
  };
  // 展示余额抵扣规则
  showInfo = () => {
    this.setState((prevState) => ({
      info: !prevState.info
    }));
  };

  // 公共方法 存储数据
  publicGetData = (res) => {
    let { course, total, user_account, user_info, discount } = res;
    if(this.props.location.state && this.props.location.state.group === 1) {
      total = this.state.groupPrice;
    }
    this.cacheObj = {
      perfect: user_info,
      orderList: course,
      user_account,
      total,
      discount,
    };
    this.setState({
      perfect: user_info,
      orderList: course,
      user_account,
      total,
      discount,
    });
  };
  // 公共方法 本地存储
  publicLocalStorage = () => {
    if(this.props.history.action === 'PUSH') {
      sessionStorage.removeItem('orderUseCacheObj');
      this.setState({
        discount: 0.00,
      });
    } else{
      const cacheObj = sessionStorage.getItem('orderUseCacheObj');
      if(cacheObj !== null) {
        this.setState({
          useBalance: true
        });
        this.computedMoneyByCache();
      }
    }
  };
  componentDidMount() {
    let _this = this;
    // type: 1,返现课程，simple: 1,正常购买
    if(this.props.location.state && this.props.location.state.type === 1) {
      http.get(`${API['base-api']}/m/order/preorder?type=1`).then((res) => {
        if(res.data.errno === 200) {
          this.publicGetData(res.data.data);
          this.publicLocalStorage();
        }else{
          Toast.info(res.data.msg, 2);
        }
      })
    } else if (this.props.location.state && (this.props.location.state.simple === 1 || this.props.location.state.bargain === 1)) {
      // 普通课程立即报名 不带 type = 1
      http.get(`${API['base-api']}/m/order/preorder`).then(res => {
        if(res.data.errno === 200) {
          this.publicGetData(res.data.data);
          this.publicLocalStorage();
        }else{
          Toast.info(res.data.msg, 2);
        }
      });
    } else if (this.props.location.state && this.props.location.state.group === 1){
      // 获取一键开团的课程
      Promise.all([http.get(`${API.home}/m/course/detail/${getParam('id')}`),http.get(`${API['base-api']}/m/order/preorder`)]).then(resList => {
        let courseInfo = resList[0],
            orderInfo = resList[1];
        let newData = {};
        if(orderInfo.data.errno === 200) {
          newData = Object.assign({}, orderInfo.data.data, {course: []});
        }else{
          Toast.info(orderInfo.data.msg, 2);
          return;
        }
        if(courseInfo.data.code === 200) {
          newData.course.push(courseInfo.data.data.course_info);
          this.setState({
            groupPrice: courseInfo.data.data.course_info.pdd_group_info.price
          })
        }else{
          Toast.info(courseInfo.data.msg, 2);
          return;
        }
        // this.groupPrice = orderInfo.data.data.course_info.pdd_group_info.price;
        // if(courseInfo.data.data.course.length === 0) {
        //   courseInfo.data.data.course.push(orderInfo.data.data.course_info)
        // }
        this.publicGetData(newData);
        this.publicLocalStorage();
      });
    } else {
      // if(getParam('id')) {
      //   Promise.all([http.get(`${API.home}/m/del_cart_order/${getParam('id')}`), http.get(`${API['base-api']}/m/order/preorder`)]).then(res => {
      //     console.log(res);
      //     let preorder = res[1],
      //         orderList = preorder.data.data.course;
      //     if(preorder.data.errno !== 200) {
      //       Toast.info(preorder.data.msg, 2);
      //       return;
      //     }

      //     this.publicGetData(preorder);
      //     this.publicLocalStorage();
      //   })
      // }else{
        http.get(`${API['base-api']}/m/order/preorder`).then((res) => {
          console.log('为了验证什么条件下会走这段代码');
          if (res.data.errno !== 200) {
            Toast.info(res.data.msg, 2);
            return;
          }

          this.publicGetData(res.data.data);
          this.publicLocalStorage();
        })
      // }
    }
    // else {
    //   if(getParam('id')) {
    //     Promise.all([http.get(`${API.home}/m/del_cart_order/${getParam('id')}`), http.get(`${API.home}/m/order/preorder`)]).then(res => {
    //       console.log(res);
    //       let preorder = res[1],
    //           orderList = preorder.data.data.course;
    //       if(preorder.data.errno !== 200) {
    //         Toast.info(preorder.data.msg, 2);
    //         return;
    //       }
    //
    //       this.publicGetData(preorder);
    //       this.publicLocalStorage();
    //     })
    //   }else{
    //     http.get(`${API.home}/m/order/preorder`).then((res) => {
    //       console.log('为了验证什么条件下会走这段代码');
    //       if (res.data.errno !== 200) {
    //         Toast.info(res.data.msg, 2);
    //         return;
    //       }
    //
    //       this.publicGetData(res);
    //       this.publicLocalStorage();
    //     })
    //   }
    // }
  };

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

  render() {
    const {
      perfect,
      orderList,
      user_account,
      total,
      discount,
      useBalance,
      info,
      offset,
      groupPrice
    } = this.state;

    return (
      <div className="order-wrapper">
        <Flex>
          <Flex.Item>
            <HeaderBar title='课程报名' arrow={true} />
            {
              !this.state.perfect &&
              <Link to={{
                pathname: '/orderinfo',
                state: {type: this.props.location.state ? this.props.location.state.type : null, id: getParam('id')}
              }}
              className="order-information">
                <i className="iconfont iconiconfront-6 order-addsize" />
                <div className="order-infotext">完善报名信息</div>
                <i className="iconfont iconiconfront-70 order-next" />
              </Link>
            }
            {
              this.state.perfect &&
              <div className="order-information2">
                <WingBlank>
                  <Link to={{
                    pathname: '/orderinfo',
                    state: {
                      ...this.state.perfect,
                      ...this.props.location.state,
                      id: getParam('id')
                    }
                  }
                  } >
                    <Flex align='center' justify='between' style={{ height: '80px' }}>
                      <i className="iconfont iconiconfront-20 user-icon"></i>

                      <Flex direction='column' justify='between' align='start' className="order-cell">
                        <div className="name">{`姓名：${perfect.real_name}`}</div>
                        <div>{`电话：${perfect.cellphone}`}</div>
                      </Flex>

                      <Flex align='start' className="order-cell">
                        <div>{`QQ：${perfect.qq}`}</div>
                      </Flex>

                    </Flex>
                  </Link>
                </WingBlank>
              </div>
            }
            <div className="order-list">
              <OrderList
                list={orderList}
                compute={this.computedMoney}
                courseId={getParam('id')}
                locationState={this.props.location.state}
                groupPrice={groupPrice}
                toDetail={this.toCourseDetail}
              />
            </div>
            <div className="order-balance">
              <List>
                <Item
                  className="order-prefer-text"
                >
                  <Flex justify='between'>
                    <Flex align='center'>
                      <span>余额抵扣</span>
                      <span className="order-balanceprice"> (余额: <i className="order-money">{`${user_account}元`}</i>)</span>
                      <i className="iconfont iconiconfront-22 question-mark" onClick={this.showInfo}></i>
                    </Flex>

                    <Flex>
                      {
                        useBalance ? (
                          <>
                            <span style={{ color: '#FF2121', fontSize: '15px', marginRight: "6px" }}>{`-¥${offset}`}</span>
                            <i className={`iconfont icondanseshixintubiao-5 balance-used`} onClick={throttle(this.useBalance, 600)}></i>
                          </>
                        ) : (
                          <i className='circle-icon' onClick={throttle(this.useBalance, 600)}></i>
                        )
                      }
                    </Flex>
                  </Flex>
                </Item>
              </List>
            </div>
            <div className="order-bar">
              <div className="order-course">
                <span className="order-course-text">{`${orderList.length}门课程`}</span>
              </div>
              <div className="order-bar-text">
                <div className="order-amount">
                  <span className="order-amount-title">合计:</span>
                  <span className="order-amount-price">{`￥${total}`}</span>
                </div>
                <div className="order-preprice">
                  <span className="order-preprice-title">已优惠:</span>
                  <span className="order-preprice-price">{`¥${discount}`}</span>
                </div>
              </div>
              {
                perfect ? (

                  <button type="button" className="order-button has-info">
                    <span className="order-button-text" onClick={this.submitOrder}>提交订单</span>
                  </button>
                ) : (

                    <button type="button" className="order-button">
                      <span className="order-button-text" onClick={this.submitOrder}>提交订单</span>
                    </button>
                  )
              }
            </div>
          </Flex.Item>
        </Flex>
        {
          info ? (
            <div style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0, 0, 0, 0.8)', zIndex: '99' }}>
              <div style={{ padding: '20px', backgroundColor: '#FFF', width: '300px', height: '170px', margin: '0 auto', position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }}>
                <Flex direction='column' justify='between' align='center' style={{ height: '100%' }}>
                  <p style={{ fontSize: '16px', color: '#333333' }}>余额抵扣说明</p>
                  <p style={{ lineHeight: '20px', fontSize: '13px', color: '#666666' }}>分销课程或者参与七月在线的相关活动，可获得资金奖励。账户资金可直接提现，也可抵扣课程费用。</p>
                  <div onClick={this.showInfo} style={{ width: '260px', height: '30px', lineHeight: '30px', textAlign: 'center', borderRadius: '3px', border: '1px solid #0099FF', color: '#0099FF', fontSize: '15px' }}>知道了</div>
                </Flex>
              </div>
            </div>
          ) : null
        }
      </div>

    )
  }

}

export default Order;