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

import "./order.scss"

const Item = List.Item;

function OrderList(props) {
  const listData = props.list;
  return (
    <div>
      {
        listData.map((item, index) => {
          console.log(item);
          const { is_coupon, course_id, image_name, price1, price0, simpledescription, course_title, coupon_num, coupon_desc } = item;
          const Info = (
            <div className="order-info">
              <Link to={`/detail?id=${course_id}`}><p className='order-title' style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{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'>¥{item.pdd_group_info.price}</span>)
                }
                <span className='order-price'>¥{price0}</span>
              </p>
            </div>
          )

          return (
            <OrderItem {...item} src={image_name} id={course_id} key={index} info={Info}>
              {
                is_coupon === 1 ? (
                  <div className="order-prefer">
                    <List key={index}>
                      <Item
                        arrow="horizontal"
                        onClick={() => { }}
                      >
                        <Link to={{
                                pathname: `/coupons`,
                                search: `?id=${course_id}`,
                                state: {
                                    from: '/order',
                                    a: 'sldfasldjfsl'
                              }}}>
                          {/* <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>
  );
}

class Order extends Component {
  constructor(props) {
    super(props);
    this.state = {
      perfect: this.props.location.state,
      user_account: 0.00, // 账户余额
      total: 0.00, // 需要支付总金额
      discount: 0.00, // 
      useBalance: false,
      orderList: [],
      info: false,
      offset: 0,
    }
  }
  // 提交订单
  submitOrder = () => {
    if (this.state.orderList.lengtjh === 0) {
      Toast.info('没有要提交的订单！');
      return;
    }
    if (!this.state.perfect) {
      Toast.info('请完善报名信息！');
    }

    http.post(`${api.home}/m/order/submitOrder`, { is_deduction: this.state.useBalance }).then(res => {
      if(res.data.code !== 200) {
        return;
      }
      sessionStorage.removeItem('orderUseCacheObj');
      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
    }));
  };
  componentDidMount() {
    let _this = this;
    if(getParam('id') !== undefined) {
      Promise.all([http.get(`${api.home}/m/del_cart_order/${getParam('id')}`), http.get(`${api.home}/m/order/preorder`), http.get(`${api.home}/m/course/detail/${getParam('id')}`)]).then(res => {

        let preorder = res[1],
          detail = res[2],
          orderList = [];
          console.log(detail);
          if(preorder.data.code !== 200) {
            Toast.info(preorder.data.msg, 2);
            return;
          }
          if(detail.data.code !== 200) {
            Toast.info(preorder.data.msg, 2);
            return;
          }
          const { user_info, user_account, discount } = preorder.data.data;
          const { course_info } = detail.data.data;
          orderList.push(course_info);
          this.cacheObj = {
            perfect: user_info,
            orderList: orderList,
            user_account,
            total: course_info.pdd_group_info.price,
            discount,
          }
          _this.setState({
            perfect: user_info,
            orderList: orderList,
            user_account,
            total: course_info.pdd_group_info.price,
            discount,
          });
      })
    }else{

    http.get(`${api.home}/m/order/preorder`).then((res) => {
      if (res.data.code !== 200) {
        return;
      }
      const { course, total, user_account, user_info, discount } = res.data.data;
      this.cacheObj = {
        perfect: user_info,
        orderList: course,
        user_account,
        total,
        discount,
      }
      this.setState({
        perfect: user_info,
        orderList: course,
        user_account,
        total,
        discount,
      });
      if(this.props.history.action === 'PUSH') {
        sessionStorage.removeItem('orderUseCacheObj');
      } else{
        const cacheObj = sessionStorage.getItem('orderUseCacheObj');
        if(cacheObj !== null) {
          this.setState({
            useBalance: true
          });
          this.computedMoneyByCache();
        }
      }
    })
    }
  };
  render() {
    const {
      perfect,
      orderList,
      user_account,
      total,
      discount,
      useBalance,
      info,
      offset,
    } = this.state;

    return (
      <div className="order-wrapper">
        <Flex>
          <Flex.Item>
            <HeaderBar title='课程报名' arrow={true}></HeaderBar>
            {
              !this.state.perfect &&
              <Link to='/orderinfo' className="order-information">
                <i className="iconfont iconiconfront-6 order-addsize"></i>
                <div className="order-infotext">完善报名信息</div>
                <i className="iconfont iconiconfront-70 order-next"></i>
              </Link>
            }
            {
              this.state.perfect &&
              <div className="order-information2">
                <WingBlank>
                  <Link to={{
                    pathname: '/orderinfo',
                    state: this.state.perfect
                  }
                  } >
                    <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')} />
            </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;