var shoppingConfirm = new Vue({
    el: "#shoppingConfirm",
    data: {
        userId: 0,
        userIdentity: '',
        userToken: '',
        type: '',
        productIds: '',
        listData: [],
        kindCount: 0,
        totalCount: 0,
        totalPrice: 0,
        reducedPrice: 0,
        address: {
            id: '',
            townId: '',
            cityId: '',
            provinceId: '',
            name: '',
            mobile: '',
            desc: '',
            town: '',
            city: '',
            province: '',
            default: '',
            selectedId: ''
        },
        addressList: [],
        isShowAddressList: false,
        isShowAddressForm: false,
        addressForm: {
            id: '',
            name: '',
            mobile: '',
            townId: '',
            cityId: '',
            provinceId: '',
            desc: '',
            default: ''
        },
        provinceOptions:[],
        cityOptions:[],
        townOptions:[],
        saveLoading: false,
        rule:{
            name: '^[a-zA-Z\\u4e00-\\u9fa5]{2,}$',
            mobile: '^\\d{6,12}$'
        },
        balance: {
            flag: false,        //使用余额抵扣
            originUserMoney: 0, //初始化后不能改变，用于还原余额抵扣
            userMoney: 0,	    //显示可使用余额
            deductMoney: 0,     //显示已使用的余额
            surplusMoney: 0     //显示勾选后的剩余抵扣
        },
        payInfo: {
            clauseId: 0,         //条款（暂时保留）
            orderShouldPayFee: 0.00,//提交的总价
            balancePayFlag: 0,   //余额抵扣的状态 0不使用，1使用
            freight: 0.00,          //邮费
            freePostFlag:-1      // 0包邮 -1到付 1 有运费
        },
        invoice: {
            id:'',
            type: 0,
            invoiceTitleType: 0, //发票抬头类型 1企业 0个人
            invoiceTitle: '',    //单位名称
            corporationTaxNum:'',//纳税人识别号
            registeredAddress: '',//单位地址
            registeredPhone:'',	 //注册电话
            openBank:'',		//开户银行
            bankAccountNo: ''  //银行账号
        },
        submitLoading: false,
    },
    computed: {

    },
    filters: {
        NumFormat:function(num) {
          var temp = String(num).split('.');
          if (temp.length === 1 || temp[1].length < 2) {
            return Number(num).toFixed(2);
          }else{
            return Number(num);
          }
        }
    },
    methods: {
        blurHandle: function(event) {
            var el = event.currentTarget;
            verifyHandle(el);
        },
        getConfirmList: function (productCount) {
            var _self = this;
            if(this.userId ===0){return;}
            OrderApi.GetOrderConfirmInfo({
                userId: _self.userId,
                count: productCount,
                productIds: this.productIds
            },function(r){
                if (r.code === 0 && r.data) {
                    _self.listData = r.data.list;
                    _self.totalPrice =  r.data.totalPrice;
                    _self.reducedPrice = r.data.reducedPrice;
                    _self.totalCount =  r.data.totalCount;
                    _self.kindCount = r.data.kindCount;
                    _self.balance.userMoney = r.data.userMoney;
                    _self.balance.originUserMoney = r.data.userMoney;
                    _self.payInfo.orderShouldPayFee = r.data.totalPrice;
                    if(r.data.invoice){
                        r.data.invoice.type = 0;
                        _self.invoice =  r.data.invoice;
                    }
                    _self.getAddressList(_self.userId,20);
                }else{
                    CAIMEI.Alert(r.msg, '确定', false);
                }
            });
        },
        // 获取邮费
        getFreight: function(townId){
            var _self = this;
            OrderApi.GetOrderPostage({
                userId: this.userId,
                productIds: this.productIds,
                totalPrice: this.totalPrice,
                townId: townId
            },function (r) {
                if(r.code === 0 && r.data){
                    _self.payInfo.freePostFlag = r.data.freePostFlag;
                    _self.payInfo.freight = (r.data.freePostFlag===1 ? r.data.freight : 0);
                    _self.payInfo.orderShouldPayFee = _self.totalPrice + _self.payInfo.freight;
                }else{
                    CAIMEI.Alert(r.msg, '确定', false);
                }
            })
        },
        // 获取收货地址
        getAddressList: function(userId,pageSize){
            var _self = this;
            OrderApi.GetAddressList({
                userID:userId,
                pageNum:1,
                pageSize:pageSize
            },function (r) {
                if(r.code === 0 && r.data){
                    if(r.data.results){
                        _self.addressList = r.data.results;
                        _self.address.id = r.data.results[0].addressID;
                        _self.address.townId = r.data.results[0].townID;
                        _self.address.cityId = r.data.results[0].cityID;
                        _self.address.provinceId = r.data.results[0].provinceID;
                        _self.address.name = r.data.results[0].shouHuoRen;
                        _self.address.mobile = r.data.results[0].mobile;
                        _self.address.desc = r.data.results[0].address;
                        _self.address.town = r.data.results[0].town;
                        _self.address.city = r.data.results[0].city;
                        _self.address.province = r.data.results[0].province;
                        _self.address.default = true;
                        _self.address.selectedId = r.data.results[0].addressID;
                        _self.getFreight(_self.address.townId);
                    }else{
                        _self.createAddress();
                    }
                    _self.getProvinceOptions();
                }else {
                    CAIMEI.Alert(r.msg, '确定', false);
                    _self.createAddress();
                }
            })
        },
        // 获取全部省份
        getProvinceOptions: function(){
            var _self = this;
            PublicApi.GetProvince({},function(r){
                if(r.code === 0 && r.data){
                    _self.provinceOptions =r.data;
                }else{
                    CAIMEI.Alert(r.msg,'确定',false);
                }
            });
        },
        getCityOptions: function(provinceId,callback){
            var _self = this;
            if(provinceId && provinceId>0){
                _self.cityOptions = [];
                _self.townOptions = [];
                _self.addressForm.cityId = '';
                _self.addressForm.townId = '';
                PublicApi.GetCity({ provinceId: provinceId },function(r){
                    if(r.code === 0 && r.data){
                        _self.cityOptions = r.data;
                        if(callback){callback();}
                    }else{
                        CAIMEI.Alert(r.msg,'确定',false);
                    }
                });
            }
        },
        getTownOptions: function(cityId, callback){
            var _self = this;
            if(cityId && cityId>0){
                _self.townOptions = [];
                _self.addressForm.townId = '';
                PublicApi.GetTown({cityId: cityId},function(r){
                    if(r.code === 0 && r.data){
                        _self.townOptions = r.data;
                        if(callback){callback();}
                    }else{
                        CAIMEI.Alert(r.msg,'确定',false);
                    }
                })
            }
        },
        showAddressBox: function(){
            this.isShowAddressList = true;
            if(!isPC){fixedBody();}
        },
        closeAddressBox: function(){
            this.isShowAddressList = false;
            if(!isPC){looseBody();}
        },
        hideAddressForm: function(){
            this.isShowAddressForm = false;
            if(!isPC){looseBody();}
        },
        createAddress: function(){
            this.isShowAddressForm = true;
            this.addressForm.name= '';
            this.addressForm.mobile= '';
            this.addressForm.townId= '';
            this.addressForm.cityId= '';
            this.addressForm.provinceId= '';
            this.addressForm.desc= '';
            this.addressForm.default= '';
            this.getProvinceOptions();
            if(!isPC){fixedBody();}
        },
        updateAddress: function(){
            this.isShowAddressForm = true;
            this.addressForm.id = this.address.id;
            this.addressForm.name = this.address.name;
            this.addressForm.mobile = this.address.mobile;
            this.addressForm.default = this.address.default;
            this.addressForm.desc = this.address.desc;
            this.addressForm.provinceId = this.address.provinceId;
            var _self = this;
            this.getCityOptions(this.address.provinceId, function(){
                _self.addressForm.cityId = _self.address.cityId;
                _self.getTownOptions(_self.address.cityId,function(){
                    _self.addressForm.townId = _self.address.townId;
                });
            });
            if(!isPC){fixedBody();}
        },
        saveAddressForm: function(){
            var _self = this;
            var pass = verifyForm();
            if (_self.saveLoading) { return false; }
            this.$nextTick(function() {
                if (!pass) {return false;}
                if(!_self.addressForm.townId){
                    CAIMEI.dialog('请选择所在地区');
                    return false;
                };
                _self.saveLoading = true;
                var params = {
                    userID:_self.userId, //用户id ,只在新增收货地址时传
                    shouHuoRen:_self.addressForm.name, //收货人
                    mobile:_self.addressForm.mobile,   //手机
                    townID:_self.addressForm.townId,   //区ID
                    address:_self.addressForm.desc, //地址
                    defaultFlag:_self.addressForm.default?1:0 //是否默认收货地址(0 不是默认,1 默认)
                };
                if(_self.addressForm.id){
                    // 编辑
                    params.addressID = _self.addressForm.id;//编辑保存地址ID
                }
                _self.saveAddress(params);
            });
        },
        saveAddress: function(params){
            var _self = this;
            OrderApi.AddSaveAddress(params,function(r){
                if(r.code === 0){
                    CAIMEI.dialog('保存成功');
                    _self.saveLoading = false;
                    _self.isShowAddressForm = false;
                    // 重新获取地址列表
                    _self.getAddressList(_self.userId,20);
                }else{
                    CAIMEI.Alert(r.msg,'确定',false);
                }
            });
        },
        // 列表直接设为默认地址
        setDefaultAddress: function(addressId){
            var _self = this;
            OrderApi.DefaultAddress({addressId:addressId,userId:_self.userId},function (r) {
                if(r.code === 0 ){
                    // 重新获取地址列表
                    _self.getAddressList(_self.userId,20);
                }else{
                    CAIMEI.Alert(r.msg,'确定',false);
                }
            });
        },
        // 列表删除单个地址
        deleteAddress: function(addressId){
            var _self = this;
            CAIMEI.Modal('确定要删除该地址？','取消','确定',function () {
                OrderApi.DeleteAddress({addressID:addressId,userID:_self.userId},function (r) {
                    if(r.code === 0 ){
                        CAIMEI.dialog('删除成功');
                        // 重新获取地址列表
                        _self.getAddressList(_self.userId,20);
                    }else{
                        CAIMEI.Alert(r.msg,'确定',false);
                    }
                })
            });
        },
        chooseAddress: function(selectedId){
            this.address.selectedId = selectedId;
        },
        confirmAddress: function(){
            var _self = this;
            this.addressList.forEach(function(item){
                if (_self.address.selectedId==item.addressID){
                    _self.address.id = item.addressID;
                    _self.address.townId = item.townID;
                    _self.address.cityId = item.cityID;
                    _self.address.provinceId = item.provinceID;
                    _self.address.name = item.shouHuoRen;
                    _self.address.mobile = item.mobile;
                    _self.address.desc = item.address;
                    _self.address.town = item.town;
                    _self.address.city = item.city;
                    _self.address.province = item.province;
                    _self.address.default = (item.defaultFlag > 0);
                    _self.getFreight(_self.address.townId);
                }
            });
            this.closeAddressBox();
        },
        toggleThisLadder: function(event){
            var el = event.currentTarget;
            if($(el).hasClass("on")){
                $(el).removeClass("on").siblings('.mFixed').hide();
                if(!isPC){looseBody();}
            }else{
                $(el).addClass("on").siblings('.mFixed').show();
                if(!isPC){fixedBody();}
            }
        },
        hideThisLadder: function(event){
            var el = event.currentTarget;
            $(el).parents('.priceTag').find('.tag').removeClass("on").siblings('.mFixed').hide();
            if(!isPC){looseBody();}
        },
        useUserMoney: function(){
            var _self = this;
            if(this.balance.userMoney>0){
                this.$nextTick(function() {
                    var total = _self.totalPrice + _self.payInfo.freight;
                    if(_self.balance.flag){
                        _self.payInfo.balancePayFlag = 1;
                        if(_self.balance.userMoney>=total){
                            // 全部抵扣
                            _self.payInfo.orderShouldPayFee = 0;
                            _self.balance.deductMoney = total;
                            _self.balance.surplusMoney = _self.balance.userMoney-total;
                        }else{
                            // 部分抵扣
                            _self.payInfo.orderShouldPayFee = total - _self.balance.userMoney;
                            _self.balance.deductMoney = _self.balance.userMoney;
                            _self.balance.surplusMoney = 0;
                        }
                    }else{
                        // 取消抵扣
                        _self.payInfo.balancePayFlag = 0;
                        _self.payInfo.orderShouldPayFee = total;
                        _self.balance.userMoney = _self.balance.originUserMoney;
                        _self.balance.deductMoney = 0;
                        _self.balance.surplusMoney = _self.balance.originUserMoney;
                    }
                });
            }
        },
        submitOrder: function(){
            var _self = this;
            if(this.submitLoading){return false;}
            if(!this.address.id){
                CAIMEI.dialog('请先添加收货地址～');
                return false;
            }
            if(this.invoice.type*1 === 1){
                // 普通发票
                if(!this.invoice.invoiceTitle){
                    CAIMEI.dialog('请输入个人抬头');return false;
                }
                if(this.invoice.invoiceTitleType===1 && !this.invoice.corporationTaxNum){
                    CAIMEI.dialog('请输入纳税人识别号');return false;
                }
            }else if(this.invoice.type*1 === 2){
                // 增值税发票
                if(!this.invoice.invoiceTitle){
                    CAIMEI.dialog('请输入个人抬头');return false;
                }
                if(!this.invoice.corporationTaxNum){
                    CAIMEI.dialog('请输入纳税人识别号');return false;
                }
                if(!this.invoice.registeredAddress){
                    CAIMEI.dialog('请输入单位地址');return false;
                }
                if(!this.invoice.registeredPhone){
                    CAIMEI.dialog('请输入注册电话');return false;
                }
                if(!this.invoice.openBank){
                    CAIMEI.dialog('请输入开户银行');return false;
                }
                if(!this.invoice.bankAccountNo){
                    CAIMEI.dialog('请输入银行账号');return false;
                }
            }
            // 发票信息
            if(this.invoice.type*1 === 0){
                this.invoice = Object.assign(this.invoice,'',{type:0});
            }else if(this.invoice.type*1 === 1){
                this.invoice = Object.assign(this.invoice,'',{type:1, invoiceContent: '商品明细'});
            }else if(this.invoice.type*1 === 2){
                this.invoice = Object.assign(this.invoice,'',{type:2});
            }
            //商品信息
            var _orderInfo = this.listData.map(function(supplier){
                    var productInfo = [];
                    supplier.cartList.forEach(function(item){
                        productInfo.push({
                            productId:item.productId,
                            productNum:item.number,
                            presentNum:0,
                            productType:item.productType
                        })
                    });
                    return {
                        shopId: supplier.id,
                        note: supplier.note ? supplier.note : '',
                        productInfo: productInfo
                    }
                });
            var _payInfo = {
                    clauseId: 0,
                    orderShouldPayFee: toFloat(this.payInfo.orderShouldPayFee),
                    balancePayFlag: this.payInfo.balancePayFlag,
                    freight: toFloat(this.payInfo.freight),
                    freePostFlag: this.payInfo.freePostFlag
                };
            var params = {
                    cartType: this.type,
                    orderSource: 1,            // 购买类型:（1购物车提交[对应表cm_cart]，2直接购买提交, 3协销下单）
                    serviceProviderId: '',     // 协销ID（小程序忽略）
                    clubUserId: this.userId,   // 机构用户ID
                    addressId: this.address.id,// 地址ID
                    orderInfo: _orderInfo,             // 商品信息
                    payInfo: _payInfo,               // 订单信息
                    orderInvoice: this.invoice           // 发票信息
            };
            this.submitLoading = true;
            OrderApi.ConfirmOrder({'params':JSON.stringify(params)},function (r) {
                if(r.code === 0){
                    var _data = r.data;
                    if(Number(_data.code) === 1){//余额抵扣全部订单金额
                        var data = { payableAmount: _self.deductMoney };
                        CAIMEI.Storage.removeItem('confirmOrderInfo');
                        CAIMEI.Storage.setItem('confirmOrderInfo',JSON.stringify({data:data}));
                        window.location.href = '/pay/success.html?pageType=www&type=success&payAmount='+_data.payTotalFee;
                    }else{//余额抵扣部分订单金额或者未支付的
                        var data = {
                                orderID:_data.orderID,
                                orderNo:_data.orderNo,
                                orderMark:_data.orderMark,
                                payableAmount:_data.payableAmount
                            };
                        CAIMEI.Storage.removeItem('confirmOrderInfo');
                        CAIMEI.Storage.setItem('confirmOrderInfo',JSON.stringify({data:data}));
                        window.location.href = '/pay/caimei-paycash.html?type=confirm&orderID='+_data.orderID;
                        _self.submitLoading = false;
                    }
                }else{
                    CAIMEI.Alert(r.msg,'确定',true, function(){
                        _self.submitLoading = false;
                    });
                }
            });
        }
    },
    created: function () {
        this.type = getUrlParam("type") ? getUrlParam("type")*1 : "";
        if(globalUserData){
            this.userId = globalUserData.userId;
            this.userIdentity = globalUserData.identity;
            this.userToken = globalUserData.token;
            // type:（1购物车提交[对应表cm_cart]，2直接购买提交, 3协销下单）
            if(this.type === 1) {
                this.productIds = window.localStorage.getItem("shoppingProductIds");
                // 获取列表数据
                this.getConfirmList(null);
            }else if(this.type === 2){
                this.productIds = getUrlParam("id");
                var count = getUrlParam("count");
                if(this.productIds && count) {
                    // 获取列表数据
                    this.getConfirmList(count);
                }else{
                    alertInfo("参数错误，请重新提交订单！");
                }
            }
        }
    },
    mounted: function () {
        var _self = this;
        var minAwayBtm = $("footer").height();
        //处理滚动条控制底部提交fixed
        $(window).scroll(function() {
            var awayBtm = $(document).height() - $(window).scrollTop() - $(window).height();
            if(minAwayBtm <= awayBtm){
                $(".summaryWrap").addClass('fixed');
            }else{
                $(".summaryWrap").removeClass("fixed");
            }
        });
    }
});
