<template>
<view id="store-order">
    <view class="border-box">
        <view class="order-item">
            <view class="title mx-1px-bottom">
                收货信息
            </view>
            <view class="address info" @tap="selectAddress">

               <view v-if="form.address && form.address.mobile">
				   <view class="user">
				       <i class="iconfont icon-yonghu1"></i>
				       <view class="name-box">
				           <text class="name">{{form.address.accept_name}}</text>
				           <text class="telephone">{{form.address.mobile}}</text>
				       </view>
				   </view>
				   <view class="address">
				       <i class="iconfont icon-weizhi"></i>
				       <text>{{form.address.address_name}} {{form.address.address}}</text>
				   </view>
			   </view>
				<view class="user"  v-else>
				    <i class="iconfont icon-juxing"></i>
				    <view class="name-box">
				        <text class="add">添加收货地址</text>
				    </view>
				</view>
            </view>
        </view>
        <view class="order-item">
            <view class="title mx-1px-bottom">
                商品清单
            </view>
            <view class="goods info mx-1px-bottom" v-for="(item, index) in block.order.items" :key="index" v-if="block.order.items.length == 1">
                <view class="goods-item">
                    <view class="item-left">
                        <image :src="item.item_meta.image"></image>
                    </view>
                    <view class="item-right">
                        <view class="goods-name item">
                            <view class="name">
                                {{item.item_name}}
                            </view>
                            <view>
                                {{item.quantity}}件
                            </view>
                        </view>
                        <view class="goods-money item">
                            <view>
                                {{item.item_meta.specs_text}}
                            </view>
                            <view>
                                {{item.redeem_point}} 积分
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="info mx-1px-bottom all-goods" v-if="block.order.items.length > 1" @tap="jumpGoods">
                <view class="good-box">
                    <view class="good-img" v-for="(item, index) in block.order.items" :key="index"  v-if="index < 4">
                        <image :src="item.item_meta.image" alt></image>
                    </view>
                </view>
                <div class="num">
                    共{{block.order.count}}件
                </div>
            </view>

            <view class="total">
                {{block.order.count}}件商品，合计 {{block.order.redeem_point}} 积分
            </view>
        </view>

        <view class="order-item">
            <view class="remarks  pointFlex">
                <view>
                    可用积分：
                </view>
                <view>
                    {{extra.point}}
                </view>

            </view>
        </view>
        <view class="order-item">
            <view class="remarks ">
                <view>
                    <input type="text" @input="inputNote" placeholder="买家留言"></input>
                </view>

            </view>
        </view>

    </view>
    <view class="sbumit-order mx-1px-top">
        <view class="back">
            支付积分：<text>{{block.order.redeem_point}}</text>
        </view>
        <button class="sbumit" @tap="submitOrder" :style="'background: ' + config.mainColor" :loading="loading">
            确定兑换
        </button>
    </view>
</view>


</template>
<script>
var app = getApp();
//import { connect, bindActionCreators, store, actions, sandBox, cookieStorage, config } from '../../../lib/myapp.js';
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

// const page = connect.Page(store(), state => {
//   return {
//     detailData: state.goods_detail
//   };
// }, dispatch => {
//   return {
//     getGoodsDetail: bindActionCreators(actions.getGoodsDetail, dispatch, 'GOODS_DETAIL') // queryCommodityStore: bindActionCreators(actions.queryCommodityStore, dispatch ,'COMMODITYSTORE','COMMODITYSPECS')
// 
//   };
// });

export default {
  data() {
    return {
      loading: false,
      show: false,
      block: {
        order: {
          items: []
        },
        orderPoint: {
          pointAmount: 0,
          pointCanUse: 0
        },
        otherCoupon: {}
      },
      extra: {
        point: {}
      },
      form: {
        order_no: '',
        address: {},
        coupon: {},
        invoice: {},
        discount: {},
        point: 0,
        note: '',
        formStates: {},
        isDisabled: false //是否禁用优惠折扣按钮

      },
      useList: [[{
        name: '不使用',
        value: 0
      }, {
        name: '使用',
        value: 1
      }]],
      formStates: {
        discountsCheckIndex: -1,
        noDiscountsCheckList: -1,
        pointStatus: false
      },
      temporary: {
        coupons: [],
        //可选择的优惠券
        coupon: {} //当前选择的优惠券

      },
      paymentMoneys: {
        discounts: {},
        total: 0
      },
      check: null,
      is_login: '',
      type: '',
      config: ''
    };
  },

  onShow() {
    this.initData(); // let app =getApp();
    // app.isBirthday().then(()=>{
    //     if(this.$cookieStorage.get("birthday_gift")){
    //         var giftData=this.$cookieStorage.get("birthday_gift").data;
    //         new app.ToastPannel().__page.showText(giftData);
    //     }
    // });
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var gbConfig = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: gbConfig
    });

    if (e.type) {
      this.setData({
        type: e.type
      });
    }

    this.queryUserPoint('default');
  },

  components: {},
  methods: {
   

    addInvoice() {
      wx.navigateTo({
        url: `/pages/store/invoice/invoice?order_no=${this.block.order.order_no}&url=${getCurrentPages()[getCurrentPages().length - 1].route}`
      });
    },

    selectAddress() {
      wx.navigateTo({
        url: `/pages/address/list/list?order_no=${this.block.order.order_no}&url=${getCurrentPages()[getCurrentPages().length - 1].route}`
      });
    },

    jumpGoods() {
      wx.navigateTo({
        url: '/pages/store/orderGoods/orderGoods?no=' + this.block.order.order_no
      });
    },

    inputNote(e) {
      this.setData({
        'form.note': e.detail.value
      });
    },

    change(e) {
      this.setData({
        check: e.detail.value
      });
      var coupons = this.block.coupons;
      var item = coupons[e.detail.value];
      var data = this.$cookieStorage.get('order_form');
      let exclusive = item.discount.exclusive;
      if (!data) return;
      coupons.forEach((v, key) => v.checked = key == e.detail.value);

      if (Array.isArray(item.adjustments)) {
        item.adjustments.sort((a, b) => {
          return Math.abs(a.amount) < Math.abs(b.amount);
        });
      } //                    排他


      if (exclusive) {
        data.formStates.discountsCheckIndex = -1;
        data.isDisabled = true;
      } else {
        data.isDisabled = false;
      }

      data.otherCoupon = item;
      data.coupons = coupons; // Cache.set(cache_keys.order_form, data);

      this.setData({
        block: Object.assign({}, this.block, data)
      });
      this.$cookieStorage.set('order_form', data);
      this.paymentMoney();
    },

    sure() {
      var block = this.block.otherCoupon;
      this.setData({
        [`block.coupon`]: block,
        [`form.coupon`]: block,
        show: false
      });
      console.log(this.form.coupon);
      this.paymentMoney();
    },

    select() {
      if (this.block.coupons.length) {
        this.setData({
          show: true
        });
      } else {
        wx.showModal({
          title: '',
          content: '暂无可使用的优惠券',
          showCancel: false
        });
      }
    },

    cancel() {
      var coupons = this.block.coupons;
      coupons.forEach(v => v.checked = false);
      this.setData({
        [`block.coupons`]: coupons,
        [`form.coupon`]: this.block.otherCoupon,
        [`block.otherCoupon`]: {},
        check: null,
        show: false
      });
    },

    initData() {
      var block = this.$cookieStorage.get('point_order');
      var form = this.$cookieStorage.get('order_form');
      var is_login = this.$cookieStorage.get('user_token');
      this.setData({
        is_login: is_login,
        loading: false
      });

      if (block) {
        if (!form || form.order_no !== block.order.order_no) {
          form = Object.assign({}, this.form);
          form.order_no = block.order.order_no;

          if (block.address) {
            form.address = block.address;
          } // Cache.set(cache_keys.order_form, form);


          this.$cookieStorage.set('order_form', form);
        } else {
          if (form.formStates) {
            this.setData({
              [`formStates.discountsCheckIndex`]: form.formStates.discountsCheckIndex,
              [`formStates.pointStatus`]: form.formStates.pointStatus
            });
          }

          this.setData({
            [`form.isDisabled`]: form.isDisabled,
            [`temporary.coupon`]: form.coupon
          });
        }

        this.setData({
          [`temporary.coupons`]: block.coupons
        });
        this.queryOrderExtra();
        this.setData({
          block: Object.assign({}, this.block, block),
          form: Object.assign({}, this.form, form)
        });
        console.log(this.form);
        this.paymentMoney(); // t.next({block, form});
      } else {// this.addHistory();
          // t.to.router.forward({name: 'user-order-online', params: {status: 1}});
        }
    },

    queryOrderExtra() {
      var oauth = this.is_login;
      this.$http.get({
        api: `api/shopping/order/extraInfo`,
        header: {
          Authorization: oauth
        }
      }).then(res => {
        res = res.data;
        var data = res.data;

        if (res.status) {
          var extra = {
            point: data.userPoint,
            limit: data.pointLimit,
            factor: data.pointToMoney
          };
          this.setData({
            extra: extra
          }); // dispatch(UserOrderExtra, extra);
        }
      });
    },

    changeDiscounts(e) {
      this.setData({
        [`formStates.discountsCheckIndex`]: e.detail.value
      });
      this.paymentMoney();
    },

    submitOrder() {
      if (this.loading) return;
      this.setData({
        loading: true
      });
      var data = {
        order_no: this.form.order_no,
        // 订单编号
        note: this.form.note // 用户留言

      };
		console.log('this.form',this.form)
      if (this.form.address && this.form.address.id) {
        data.address_id = this.form.address.id;
      } else {
        this.setData({
          loading: false
        });
        wx.showModal({
			content:"请填写地址",
			showCancel:false
		})
        return; 
      }

      if (this.form.coupon && this.form.coupon.id) {
        data.coupon_id = this.form.coupon.id;
      }

      if (this.form.invoice && this.form.invoice.id) {
        data.invoice_id = this.form.invoice.id;
      }

      if (this.form.discount && this.form.discount.id) {
        data.discount_id = this.form.discount.id;
      }

      if (this.form.point) {
        data.point = this.form.point;
      }

      this.confirmOrder(data);
    },

    confirmOrder(data) {
      var that = this;
      var oauth = this.is_login;
      this.$http.post({
        api: `api/shopping/order/confirm/point`,
        data: data,
        header: {
          Authorization: oauth
        }
      }).then(res => {
        res = res.data;
        console.log(res);

        if (res.status) {
          this.$cookieStorage.clear('point_order'); // this.$emit('confirm', true, res.data);

          that.confirm(true, res.data);
        } else {
          that.confirm(false, res.message);
        }
      }).catch(rej => {
        wx.showToast({
          title: '提交订单失败，请重试！'
        });
      });
    },

    queryUserPoint(type) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.get({
        api: 'api/users/point',
        header: {
          Authorization: token
        },
        data: {
          type: type
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            this.point = res.data
          }
        }
      });
    },

    confirm(success, data) {
      if (success) {
        this.setData({
          loading: false
        });
        wx.redirectTo({
          url: `/pages/pointStore/success/success?order_no=${data.order.order_no}`
        });
      } else {
        this.setData({
          loading: false
        });
        wx.showModal({
          content: data || '提交订单失败',
          showCancel: false
        });
      }
    },

    paymentMoney() {
      var dis = {
        order: 0,
        point: 0,
        coupon: 0
      };
      var total = this.block.order.total;
      var fixedTotal = this.block.order.total;
      var block = this.$cookieStorage.get('point_order'); // var pointToMoney = block.orderPoint.pointToMoney;
      //                订单折扣

      if (this.block.discounts && Array.isArray(this.block.discounts)) {
        let discounts = this.block.discounts;
        let check = this.formStates.discountsCheckIndex;
        console.warn(check);

        if (check == -1) {
          //                        当选择不使用优惠的情况
          dis.order = 0;
          this.setData({
            [`form.discount`]: {},
            [`form.formStates.discountsCheckIndex`]: check
          });

          if (this.temporary.coupons.length) {
            this.setData({
              [`block.coupons`]: this.temporary.coupons
            });
          } //                            操作积分
          // this.block.orderPoint.pointCanUse = Math.min(total * this.block.orderPoint.pointLimit / this.block.orderPoint.pointToMoney, this.block.orderPoint.userPoint);
          // this.block.orderPoint.pointAmount = Math.max(-(total * this.block.orderPoint.pointLimit), -(this.block.orderPoint.userPoint * this.block.orderPoint.pointToMoney));
          //
          // this.form.coupon = this.temporary.coupon;     // 将选择的优惠券还原


          this.setData({
            [`block.orderPoint.pointCanUse`]: Math.min(total * this.block.orderPoint.pointLimit / this.block.orderPoint.pointToMoney, this.block.orderPoint.userPoint),
            [`block.orderPoint.pointAmount`]: Math.max(-(total * this.block.orderPoint.pointLimit), -(this.block.orderPoint.userPoint * this.block.orderPoint.pointToMoney)),
            [`form.coupon`]: this.temporary.coupon
          });
          this.$cookieStorage.set('order_form', this.form);
        } else {
          //                        当使用了优惠的情况
          let discount = -discounts[check].adjustmentTotal;
          console.log(discount);
          let exclusive = discounts[check].exclusive; //是否排他(优惠券);

          if (discount <= total) {
            if (exclusive) {
              this.setData({
                [`block.coupons`]: [],
                [`form.coupon`]: {}
              });
            } else {
              this.setData({
                [`block.coupons`]: this.temporary.coupons,
                [`form.coupon`]: this.temporary.coupon
              });
            }

            dis.order = discounts[check].adjustmentTotal;
            this.setData({
              [`form.discount`]: discounts[check]
            });
            total -= discount; //                            操作积分

            this.setData({
              [`block.orderPoint.pointCanUse`]: Math.min(total * this.block.orderPoint.pointLimit / this.block.orderPoint.pointToMoney, this.block.orderPoint.userPoint),
              [`block.orderPoint.pointAmount`]: Math.max(-(total * this.block.orderPoint.pointLimit), -(this.block.orderPoint.userPoint * this.block.orderPoint.pointToMoney)),
              [`form.formStates.discountsCheckIndex`]: check
            }); // Cache.set(cache_keys.order_form, this.form);

            this.$cookieStorage.set('order_form', this.form);
          } else {
            // this.$Alert('超过最大优惠折扣', () => {
            //     check = -1;
            // });
            wx.showModal({
              content: '超过最大折扣',
              showCancel: false,
              success: function (res) {
                if (res.confirm) check = -1;
              }
            });
            this.setData({
              [`form.discount`]: {}
            });
            this.$cookieStorage.set('order_form', this.form);
          }
        }
      } //                优惠券折扣


      if (this.block.coupon && this.block.coupon.adjustments && Array.isArray(this.block.coupon.adjustments)) {
        let adjustments = this.block.coupon.adjustments;
        let discount = -adjustments[0].amount;

        if (discount <= total) {
          dis.coupon = adjustments[0].amount;
          total -= discount; //                        操作积分

          this.setData({
            [`block.orderPoint.pointCanUse`]: total * this.block.orderPoint.pointLimit / this.block.orderPoint.pointToMoney,
            [`block.orderPoint.pointAmount`]: -(total * this.block.orderPoint.pointLimit)
          });
        } else {
          wx.showModal({
            content: '超过最大折扣',
            showCancel: false
          });
          this.setData({
            [`form.coupon`]: {},
            [`temporary.coupon`]: {},
            [`form.isDisabled`]: false
          });
          this.$cookieStorage.set('order_form', this.form);
        }
      }

      console.log(this.form, this.block); //              积分折扣

      if (this.form.point) {
        let factor = this.extra.factor;
        let discount = this.form.point * factor;

        if (discount <= total) {
          dis.point = -discount;
          total -= discount;

          if (total < 0) {
            total = 0;

            if (dis.point != 0) {
              dis.total = -(fixedTotal + dis.point);
            }
          } else {
            //                除积分外的优惠
            dis.total = dis.order + dis.coupon;
          }

          this.$cookieStorage.set('order_form', this.form);
        } else {
          this.setData({
            [`form.point`]: 0
          });
          this.$cookieStorage.set('order_form', this.form);
        }
      } // 除积分外的优惠


      dis.total = dis.order + dis.coupon;

      if (this.form.point > this.block.orderPoint.pointCanUse) {
        this.setData({
          [`form.point`]: this.block.orderPoint.pointCanUse
        });
        dis.point = this.block.orderPoint.pointCanUse * 10;
      }

      this.setData({
        [`paymentMoneys.discounts`]: dis,
        [`paymentMoneys.total`]: total
      });
    },

    usePoint() {
      this.setData({
        [`formStates.pointStatus`]: true,
        [`form.point`]: this.block.orderPoint.pointCanUse
      });
      this.paymentMoney();
    },

    modifyPoint(e) {
      var min = 0;
      var max = this.extra.point;
      var val = e.detail.value;
      var use = Math.floor(this.block.order.total * this.extra.limit / this.extra.factor);
      var sun = Math.floor((this.block.order.total + this.paymentMoneys.discounts.total) / this.extra.factor);
      if (!isFinite(use)) use = max;
      if (!isFinite(sun)) sun = max;
      max = Math.min(max, use, sun);
      val = parseInt(val);

      if (isNaN(val)) {
        val = '';
      } else if (val < min) {
        val = min;
      } else if (val > max) {
        val = max;
      }

      e.detail.value = val;
      this.setData({
        [`form.point`]: val
      });
      this.paymentMoney();
    },

    saveForm(e) {
      this.$cookieStorage.set('order_form', this.form);
    },

    back() {
      wx.navigateBack();
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "order";
</style>