var shoppingConfirm = new Vue({
    el: "#shoppingConfirm",
    data: {
        userId: 0,
        userIdentity: '',
        userToken: '',
        optionData:'',
        subType:'',//跳转类型
        cartType:'',//提交订单类型
        goodsList:[],//商品列表
        isEmpty:false,//是否显示列表
        allPrice:'',//订单总价格
        allCount:'',//订单总数量
        productKind:'',//商品种类
        payAllPrice:'',//支付价格
        surplusMoney:0.00,//显示勾选后的剩余抵扣
        userMoney:0.00,	//显示可使用余额
        deductMoney:0.00,//显示已使用的余额
        productIds:'',//商品ID
        productCount:'',//提交订单的商品数量
        addressList:[],//收货地址
        addressData:{},//初始化地址信息
        hanldAddressData:{},//选择确定的地址信息
        isAddType:'',
        addAddressData:{
            addressID:'',
            allAddress:'所在地区',
            userID: '',			//用户id ,只在新增收货地址时传
            shouHuoRen: '',		//收货人
            mobile:'',			//收货人手机
            townID:'',			//区ID
            address: '',	//地址
            defaultFlag:0,		//是否默认收货地址(0 不是默认,1 默认)
        },//初始化地址信息
        addressID:'',//地址ID
        townID:'',//区ID
        freightText:'',
        freightMoney:'',
        selectedFreight:'',//默认邮费
        hanldFreePostFlag:'',//
        hanldFreight:'',//
        isRequest:false,
        isFiexdClass:'float',
        isDefaultFlag:false,
        isShowAddress:false,
        isShowInvoice:false,
        isShowBalance:false,
        isShwoAddModel:false,
        isShowCascader:false,
        isConDisabled:false,
        isSubDisabled:false,
        isCheckedBalabce:false,
        isDefaultChecked:false,
        balanceDeductionFlag:2,
        isAddressListLength:false,
        invoiceType:'1',
        invoiceTitle:0,
        goodRemark:[],
        optionList:['到付'],
        ProvinceList:[],
        cityArray:[],
        townArray:[],
        currentTab:0,
        choseAddressText:'',//选取的地址信息
        freightData:'',//运费信息
        orderInfo:[],//提交的商品信息
        payInfo:{},	//订单信息
        addTabList:[
            {name:'省'},
            {name:'区'},
            {name:'市'}
        ],
        addressFrom: {
            name:'',
            province: '',
            city: '',
            town: ''
        },
        invoiceData:{//初始化发票信息
            id:'',
            invoiceTitle:'',	 //单位名称
            corporationTaxNum:'',//纳税人识别号
            registeredAddress: '',//单位地址
            registeredPhone:'',	 //注册电话
            openBank:'',		//开户银行
            bankAccountNo: ''  ,//银行账号
            type:0
        },
        invoiceTypeList:[
            {value:'1',name:'不开发票'},
            {value:'2',name:'普通发票'},
            {value:'3',name:'增值税发票'}
        ],
        invoiceTitleList:[
            {value:'0',name:'个人'},
            {value:'1',name:'公司'},
        ],
        peopleInvoiceData:{
            invoiceTitle:'',   //单位名称
            invoiceContent:'明细', //商品明细
            corporationTaxNum:'',//纳税人识别号
            invoiceTitleType:'0'//发票抬头类型 1企业 0个人
        },
        checkedAddressItemIndex:0,
    },
    filters: {
        NumFormat:function(text) {
            return Number(text).toFixed(2);
        }
    },
    computed: {

    },
    methods: {
        getAddressList:function(userId,pageSize){//获取收货地址
            var _self = this;
            OrderApi.GetAddressList({userID:userId,pageNum:1,pageSize:pageSize},function (response) {
                if(response.code == 0){
                    var data = response.data;
                    if(data.results != ''){
                        _self.addressList = [];
                        _self.addressList = data.results;
                        _self.addressData =  data.results[0];
                        _self.addressID = data.results[0].addressID;
                        _self.townID = data.results[0].townID;
                        _self.getFreightData();
                        _self.isAddressListLength = false;
                    }else{
                        _self.isAddressListLength = true;
                        _self.addressData = _self.addressData;
                        _self.GetProvinceFn()
                    }
                }else {
                    CAIMEI.Alert(response.msg, '确定', false);
                }
            })
        },
        getConfirmInfo: function (productIds, productCount) {//订单初始化
            var _self = this;
            if(_self.userId ===0){return;}
            OrderApi.GetOrderConfirmInfo({userId: _self.userId,count: productCount,productIds: productIds},function(response){
                if (response.code === 0 && response.data) {
                    var data = response.data;
                    _self.isRequest = true;
                    _self.goodsList = data.list;
                    _self.allPrice =  data.totalPrice;
                    _self.allCount =  data.totalCount;
                    _self.payAllPrice = data.totalPrice;
                    _self.productKind = data.productKind;
                    _self.userMoney = data.userMoney;
                    _self.getAddressList(_self.userId,20);
                }else{
                    CAIMEI.Alert(response.msg, '确定', false);
                }
            });
        },
        getFreightData :function(){//获取邮费信息
            var _self = this;
            var params ={userId:_self.userId,productIds:_self.productIds,totalPrice:_self.allPrice,townId:_self.addressData.townID};
            OrderApi.GetOrderPostage(params,function (response) {
                if(response.code == 0){
                    _self.freightData = response.data;
                    _self.hanldFreePostFlag = response.data.freePostFlag;
                    _self.hanldFreight = response.data.freight;
                    switch(_self.freightData.freePostFlag){
                        case 0:
                            _self.freightText = '包邮';
                            _self.freightData.freight  = 0;
                            break;
                        case 1:
                            _self.freightText = '';
                            _self.freightMoney =  _self.freightData.freight;
                            var key = '到付';
                            _self.optionList = [key];
                            _self.optionList.unshift(_self.orderPriceToFixed(_self.freightMoney));
                            _self.selectedFreight = _self.optionList[0];
                            break;
                        case -1:
                            _self.freightText = '到付';
                            _self.freightData.freight  = 0;
                            break;
                    };
                    if(_self.hanldFreePostFlag == 1){
                        _self.payAllPrice = _self.allPrice + response.data.freight;
                        _self.attributePallPrice();
                    }else{
                        _self.payAllPrice = _self.allPrice;
                        _self.attributePallPrice();
                    }
                }else{
                    CAIMEI.Alert(response.msg, '确定', false);
                }
            })
        },
        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();}
        },
        submitOrder: function(){

        },
        GetProvinceFn: function(){//获取全部省份
            var _self = this;
            PublicApi.GetProvince({},function(response){
                if(response.code == 0){
                    _self.ProvinceList =response.data;
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        ChangeProvince:function () {//选择省份
            var _self = this;
            _self.addressFrom.province = event.target.value;
            if(_self.addressFrom.province==''){//省为请选择时市区初始化
                _self.cityArray=[];
                _self.townArray=[];
                _self.addAddressData.townID=''
            }else {
                _self.ChangeGetcity();
            }
        },
        ChangeGetcity:function(event){//加载市
            var _self = this;
            PublicApi.GetCity({ provinceId: _self.addressFrom.province },function(response){
                if(response.code == 0 ){
                    _self.cityArray = response.data;
                    _self.addressFrom.city = event.target.value;
                    if(_self.addressFrom.city==''){
                        _self.townArray=[];
                    }else {
                        _self.ChangeGetcTown();
                    }
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        ChangeGetcTown:function(event){//选择地区
            var _self = this;
            PublicApi.GetTown({ cityId: _self.addressFrom.city },function(response){
                if(response.code == 0 ){
                    _self.townArray = response.data;
                    _self.addAddressData.townID = event.target.value;
                    console.log(_self.addAddressData.townID)
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        settingDefaultFlag :function(){//添加&&编辑 保存 设置默认地址按钮
            var _self = this;
            _self.isDefaultFlag=! _self.isDefaultFlag;
            if(_self.isDefaultFlag){
                _self.addAddressData.defaultFlag = '1';
            }else{
                _self.addAddressData.defaultFlag = '0';
            }
        },
        addAddressFn :function(){//添加新的地址
            var _self = this;
            _self.addAddressData={
                addressID:'',
                allAddress:'',
                userID: '',		//用户id ,只在新增收货地址时传
                shouHuoRen: '',	//收货人
                mobile:'',		//收货人手机
                townID:'',		//区ID
                address: '',	//地址
                defaultFlag:0,	//是否默认收货地址(0 不是默认,1 默认)
            };
            _self.isAddType = 'add';
            _self.isShwoAddModel = true;
        },
        editAddress :function(item){//编辑地址
            var _self = this;
            if(_self.defaultFlag =='1'){
                _self.isDefaultChecked = true;
            }else{
                _self.isDefaultChecked = false;
            }
            _self.isAddType = 'edit';
            _self.isShwoAddModel = true;
            _self.addAddressData = item;
            _self.addAddressData.allAddress=item.province+''+item.city+''+item.town;
        },
        defaultAddressFn :function(addressID){//列表直接设为默认地址
            var _self = this;
            OrderApi.DefaultAddress({addressId:addressID,userId:_self.userId},function (response) {
                if(response.code == 0 ){ //成功
                    _self.addressList = [];
                    _self.getAddressList(_self.userId,20);
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            });
        },
        deleteAddress :function(addressID){//列表删除单个地址
            var _self = this;
            CAIMEI.Modal('确定要删除该地址？','取消','确定',function () {
                OrderApi.DeleteAddress({addressID:addressID,userID:_self.userId},function (response) {
                    if(response.code == 0 ){ //删除成功
                        CAIMEI.dialog('删除成功');
                        _self.addressList = [];
                        _self.getAddressList(_self.userId,20);
                    }else{
                        CAIMEI.Alert(response.msg,'确定',false);
                    }
                })
            });
        },
        changeHandle :function(index) {//商品备注的值被改变后
            this.goodsList[index].note = this.goodRemark[index];
            // console.log(this.goodsList)
        },
        ConfirmAddressFn :function(){//保存地址
            var _self = this;
            if(_self.addAddressData.townID == ""){
                CAIMEI.dialog('请选择所在地区');
                return;
            };
            if(_self.addAddressData.address == ""){
                CAIMEI.dialog('请填写详细地址');
                return;
            };
            if(_self.addAddressData.shouHuoRen == ""){
                CAIMEI.dialog('请输入收货人姓名');
                return;
            };
            if(_self.addAddressData.mobile == ""){
                CAIMEI.dialog('请输入收货人手机号');
                return;
            };
            if( _self.isAddType == 'add'){
                var params = {
                        userID:_self.userId  ,		//用户id ,只在新增收货地址时传
                        shouHuoRen:_self.addAddressData.shouHuoRen ,//收货人
                        townID:_self.addAddressData.townID,			//区ID
                        address:_self.addAddressData.address,//地址
                        mobile:_self.addAddressData.mobile,			//手机
                        defaultFlag:_self.addAddressData.defaultFlag//是否默认收货地址(0 不是默认,1 默认)
                };
            }else{
                var params = {
                        addressID:_self.addAddressData.addressID,//编辑保存地址ID
                        userID:_self.userId  ,		//用户id ,只在新增收货地址时传
                        shouHuoRen:_self.addAddressData.shouHuoRen ,//收货人
                        townID:_self.addAddressData.townID,			//区ID
                        address:_self.addAddressData.address,//地址
                        mobile:_self.addAddressData.mobile,			//手机
                        defaultFlag:_self.addAddressData.defaultFlag//是否默认收货地址(0 不是默认,1 默认)
                };
            }
            _self.isConDisabled = true;
            OrderApi.AddSaveAddress(params,function(response){
                if(response.code == 0){
                    CAIMEI.dialog('保存成功');
                    _self.getAddressList(_self.userId,20);
                    _self.isShwoAddModel = false;
                    _self.isConDisabled = false;
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            });
        },
        ConfirmOrderFn :function(){//提交订单
            var _self = this;
            if (_self.isSubDisabled) { return false; }
            if(_self.addressID == ''){
                CAIMEI.dialog('请先添加收货地址～');
                return;
            }
            //选择开发票处理
            if(_self.invoiceType == '1'){
                CAIMEI.returnedTarget();
                _self.invoiceData = Object.assign(_self.invoiceData,'',{type:0});
            }else if(_self.invoiceType == '2'){
                switch(_self.peopleInvoiceData.invoiceTitleType){
                    case '0':
                        if(_self.peopleInvoiceData.invoiceTitle == ""){
                            CAIMEI.dialog('请输入个人抬头');
                            return;
                        }
                        break;
                    case '1':
                        if(_self.peopleInvoiceData.invoiceTitle == ""){
                            CAIMEI.dialog('请输入公司抬头');
                            return
                        }
                        if(_self.peopleInvoiceData.corporationTaxNum == ""){
                            CAIMEI.dialog('请输入纳税人识别号');
                            return
                        }
                        break;
                }
            }else if(_self.invoiceType == '3'){
                if(_self.invoiceData.invoiceTitle == ""){
                    CAIMEI.dialog('请输入单位名称');
                    return;
                }
                if(_self.invoiceData.corporationTaxNum == ""){
                    CAIMEI.dialog('请输入纳税人识别号');
                    return;
                }
                if(_self.invoiceData.registeredAddress == ""){
                    CAIMEI.dialog('请输入单位地址');
                    return;
                }
                if(_self.invoiceData.registeredPhone == ""){
                    CAIMEI.dialog('请输入注册电话');
                    return;
                }
                if(_self.invoiceData.openBank == ""){
                    CAIMEI.dialog('请输入开户银行');
                    return;
                }
                if(_self.invoiceData.bankAccountNo == ""){
                    CAIMEI.dialog('请输入银行账号');
                    return;
                }
                CAIMEI.returnedTarget();
                _self.invoiceData = Object.assign(_self.invoiceData,'',{type:2});
            }
            //商品信息
            _self.orderInfo = _self.goodsList.map(function(el){
                var productInfo = [];
                el.cartList.forEach(function(item){
                    productInfo.push({
                        productId:item.productId,
                        productNum:item.number,
                        presentNum:0
                    })
                });
                return {shopId:el.id,note:el.note?el.note:'',productInfo:productInfo}
            });
            //订单信息
            _self.payInfo = {
                clauseId:0,//条款（暂时保留）
                orderShouldPayFee:_self.payAllPrice.toFixed(2),//提交的总价
                balancePayFlag:_self.balanceDeductionFlag,//余额抵扣的状态
                freight:parseInt(_self.hanldFreight).toFixed(2),//邮费
                freePostFlag:parseInt(_self.hanldFreePostFlag)//运费形式
            };
            var  params = {
                    orderSource:1,
                    clubUserId:_self.userId,
                    cartType:_self.cartType,
                    addressId:_self.addressID,
                    orderInfo:_self.orderInfo,
                    payInfo:_self.payInfo,	//订单信息
                    orderInvoice:_self.invoiceData
            };
            // console.log('最后参数',params);
            //提交
            _self.isSubDisabled = true;
            OrderApi.ConfirmOrder({'params':JSON.stringify(params)},function (response) {
                // console.log(response);
                if(response.code === 1){
                    var data = { payableAmount: _self.deductMoney };
                    CAIMEI.Storage.removeItem('confirmOrderInfo');
                    CAIMEI.Storage.setItem('confirmOrderInfo',JSON.stringify({data:data}));
                    window.location.href = '/order/paySuccess.jsp';
                }else if(response.code === 2){
                    var data = {
                        orderID:response.data.orderID,
                        orderNo:response.data.orderNo,
                        orderMark:response.data.orderMark,
                        payableAmount:response.data.payableAmount
                    };
                    CAIMEI.Storage.removeItem('confirmOrderInfo');
                    CAIMEI.Storage.setItem('confirmOrderInfo',JSON.stringify({data:data}));
                    window.location.href = '/web/order/view/pay/caimei-paycash.jsp?type=confirm&orderID='+response.data.orderID;
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                    _self.isSubDisabled = false;
                }
            })
        },
        checkedAddressItemFn:function(index,item){//选择地址处理
            var _self = this;
            _self.checkedAddressItemIndex = index;
            _self.hanldAddressData = item;
        },
        ConfirmCheckedAddressFn:function(){//确定使用选择的地址
            var _self = this;
            _self.addressData =  _self.hanldAddressData;
            _self.isShowAddress = false;
        },
        HideCheckedAddressFn :function(){//隐藏选择地址列表
            var _self = this;
            _self.isShowAddress = false;
        },
        CancelAddressFn:function(){
            var _self = this;
            _self.isShwoAddModel = false;
        },
        ShowCheckedAddressFn :function(){//显示地址列表选择地址
            var _self = this;
            _self.isShowAddress = true;
        },
        ShowAddAddressFn :function(){//显示新增地址
            var _self = this;
            _self.isAddType = 'add';
            _self.isShwoAddModel = true;
            _self.addressData = this.addressData;
            _self.GetProvinceFn();
        },
        radioChange :function(value){//发票信息选择
            var _self=this;
            _self.invoiceType = event.target.value;
            for (var i = 0; i < _self.invoiceTypeList.length; i++) {
                if (_self.invoiceTypeList[i].value === _self.invoiceType) {
                    _self.current = i;
                    break;
                }
            }
            switch(_self.invoiceType){
                case '1':
                    CAIMEI.returnedTarget();
                    _self.invoiceData = Object.assign(_self.invoiceData,'',{type:0});
                    break;
                case '2':
                    _self.invoiceTitle = "0";
                    _self.peopleInvoiceData.invoiceTitleType = "0";
                    CAIMEI.returnedTarget();
                    _self.invoiceData = Object.assign(_self.peopleInvoiceData,'',{type:1});
                    break;
                case '3':
                    _self.getUseFindInvoice();
                    break;
            }
        },
        radioChangeTitle :function(event) {//发票抬头选择
            this.peopleInvoiceData.invoiceTitleType = event.target.value;
            for (var i = 0; i < this.invoiceTitleList.length; i++) {
                if (this.invoiceTitleList[i].value === this.peopleInvoiceData.invoiceTitleType) {
                    break;
                }
            }
            switch(this.peopleInvoiceData.invoiceTitleType){
                case '1':
                    this.peopleInvoiceData.invoiceTitle = "";
                    this.peopleInvoiceData.invoiceContent = "明细";
                    break;
            }
        },
        getUseFindInvoice :function(){//获取发票信息
            var _self = this;
            OrderApi.GetFindInvoice({userId:_self.userId},function(response){
                if(response.code == 0){
                    if(response.data == null){
                        CAIMEI.returnedTarget();
                        _self.invoiceData = Object.assign(_self.invoiceData,'',{type:0,userId:_self.userId})
                    }else{
                        _self.invoiceData = response.data
                    }
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        checkedBalabce :function(){//勾选使用余额
            if(this.userMoney > 0){
                this.isCheckedBalabce = !this.isCheckedBalabce;
                if(this.isCheckedBalabce){
                    this.balanceDeductionFlag =1;
                    this.attributePallPrice()
                }else{
                    if(this.hanldFreePostFlag == 1 || this.hanldFreePostFlag == '1'){
                        this.payAllPrice = this.allPrice+ parseInt(this.freightData.freight);
                    }else{
                        this.payAllPrice = this.allPrice;
                    }
                    this.deductMoney = 0.00;
                    this.balanceDeductionFlag = 2;
                }
            }else{
                return
            }
        },
        gernerateId :function(index){
            return "male_" +index
        },
        gernerateTitleId :function(index){
            return "title_" +index
        },
    },
    created: function () {
        var _self = this;
        _self.subType = getUrlParam("type") ? getUrlParam("type")*1 : "";
        if(globalUserData){
            _self.userId = globalUserData.userId;
            _self.userIdentity = globalUserData.identity;
            _self.userToken = globalUserData.token;
            // subType:（1购物车提交[对应表cm_cart]，2直接购买提交）
            if(_self.subType === 1) {
                _self.cartType= 1;
                _self.productIds = window.localStorage.getItem("shoppingProductIds");
                // 获取列表数据
                _self.getConfirmInfo( _self.productIds, null);
            }else if(_self.subType === 2){
                _self.cartType= 2;
                _self.productIds = getUrlParam("id");
                _self.productKind = getUrlParam("count");
                if(_self.productIds && _self.productKind) {
                    // 获取列表数据
                    _self.getConfirmInfo(_self.productIds,_self.productKind);
                }else{
                    CAIMEI.Alert('参数错误，请重新提交订单！', '确定', false);
                }
            }
        }
    },
    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");
            }
        });
    }
});
