xihulangzi
/**
 *  update : 2016-04-18 6.16
 *  update : 2016-05-25 6.17  修复进入填写页后返回丢失引流参数问题
 *
 */

define([\'cUtilCommon\', \'cMemberService\', \'DetailSdpHighSpot\', \'DetailOtherTickets\', \'cGuiderService\', \'UITab\', \'cHybridShell\', \'Page\', \'DiyshxModel\', \'DiyshxStore\', \'Slider\', \'cGuider\', \'UIAlert\', \'UICalendarCommon\', \'cPublic\'],
    function (UtilCommon, Member, DetailSdpHighSpot, DetailOtherTickets, cGuiderService, UITab, cHybridShell, Page, DiyshxModel, DiyshxStore, Slider, Guider, UIAlert, UICalendarCommon, cPublic) {
        var collect;
        // var orderConfirmResourceStore = DiyshxStore.OrderConfirmResourceStore.getInstance();
        var isInApp = Lizard.isHybrid || Lizard.isInCtripApp;
        var View = Page.extend({
            pageid: 249130,
            hpageid: 251130,
            //电话直落
            // businessCode: \'Vacation_FlightAndHotel_ SelfDriving\',
            favorited: false,
            isPopShowed: false,
            isCreated: false,
            isShowed: false,
            commonStore: DiyshxStore.DIYSHXCommonStore.getInstance(),
            // priceCheckModel: DiyshxModel.PriceCallendar.getInstance(),
            // priceCheckStore: DiyshxStore.PriceCallendarStore.getInstance(),
            //点击日历后的优惠信息
            promotionInfoModel: DiyshxModel.PromotionInfoModel.getInstance(),
            model: DiyshxModel.SdpDetailNearbySearchModel.getInstance(),
            events: {
                \'click #order-knowledge-a\': \'onOrderKnowledgeClick\',
                \'click .detail-hotel-comment\': \'goToHotelCommentPage\',
                \'click .detail-booking-btn,.js_datelink\': \'goToBookingPage\',
                \'click .detail-collect-icon\': \'onFooterCollectClick\',
                \'click .zby_detailpro_dayschoose a\': \'onSelectedDayClick\',  //延住详情页
                \'click .js_gift_link\': \'showGiftMask\',
                \'click .js_detail_single_modules>.zby_htlplaybox\': \'goToSinglePages\',
                \'click .js_yhq_cell\': \'drawCoupons\',
                \'click .js_showCouponInfo\': \'showCouponInfo\',
                \'click .js_price_link\': \'showPriceInfo\'
            },
            onCreate: function () {
                window.VV = this;
                this.viewTpl = Lizard.T(\'viewportTpl\');
                this.FluxEntrance = this.getQuery(\'FluxEntrance\');
                window.__bfi = window.__bfi || [];
                var pageid;
                if (isInApp) {
                    pageid = this.hpageid;
                    !this.FluxEntrance && (this.FluxEntrance = 20131);
                } else {
                    pageid = this.pageid;
                    !this.FluxEntrance && (this.FluxEntrance = 30131);

                }
                window.__bfi.push([\'_tracklog\', \'Zhoumoyou_City\', \'page_id=\' + pageid + \'&CITY=\' + (this.getQuery(\'cityid\') || 0)]);
            },
            //增加历史记录
            addToHistoryList: function () {
                var data = {
                    "id": this.getQuery(\'sdpid\'),
                    "productname": this.data.SDPInfo.SdpName,
                    "price": this.data.SDPInfo.Price.OriginalPrice.Price,
                    "sightscore": this.data.ScienceInfoList[0].ScineceInfo[0] && this.data.ScienceInfoList[0].ScineceInfo[0].Score,
                    "thumb": this.data.SDPInfo.PictureUrls.length && this.data.SDPInfo.PictureUrls[0].LargeUrl,
                    "hotelid": this.data.JourneysInfo.SHXJourneyInfoV6_5[0].SHXHotelInfos.HotelId,
                    "hotelprice": this.data.singleHotelPrice && this.data.singleHotelPrice.Price,
                    "sightid": this.data.ScienceInfoList[0].ScineceInfo[0] && this.data.ScienceInfoList[0].ScineceInfo[0].ScineceId,
                    "sightprice": this.data.singleSightPrice && this.data.singleSightPrice.Price,
                    "city": this.data.SDPInfo.CityId,
                    "cityname": this.data.SDPInfo.CityName,
                    "page_id": isInApp ? this.hpageid : this.pageid,
                    "starttime": UtilCommon.Date.format(new Date(this.data.SDPInfo.SdpDate.match(/\d+/)[0] - 0), \'Y-m-d\'),
                };
                console.log(data);
                this.setTrackLog(data, \'Zhoumoyou_Trace_Combo\');
            },
            //延住日期选择
            onSelectedDayClick: function (evt) {
                var result = "";
                var $cur = $(evt.currentTarget);
                var $parent = $cur.parent();
                var newSpdid = $cur.data(\'id\');
                if (newSpdid == Lizard.P("sdpid")) { return; }
                //var str = decodeURIComponent(location.href).toLowerCase().split(\'?\');
                //if (str.length > 1) {
                //    result = str[1];
                //    if (/issub=true/i.test(result)) {
                //        result = result.replace(/issub=true/i, \'\');

                //    }
                //}
                //if (/^\w/.test(result) && result) {
                //    result = result;
                //} else if (result) {
                //    result = result.slice(1);
                //}
                // if (this.getQuery(\'nights\')) {
                //     var night = _.find(this.data.SDPInfo.ExtendSdps,function(item){return item.SdpId == newSpdid}).Nights.match(/(\d).*(\d)/)[2];
                //     result = result.replace(/nights=\d+/, \'nights\'+ night);
                // }
                //if ($parent.hasClass(\'js_sdp_days\')) {
                //set store

                this.sdpTypeStore.set({ \'SdpType\': this.data.SDPInfo.SdpType, \'switchTab\': true });
                //var url = location.pathname.replace(/(\/detailnearby\/)(\d+)(.html)/ig, \'$1\' + newSpdid + \'$3\');
                this.forward(\'detailnearby/\' + newSpdid + \'.html\' + location.search);
                this.destroyView(true);
            },
            //浏览历史,只支持Hybrid
            setHistory: function (){
                //不支持H5
                if(Lizard.isHybrid){
                    var bizType = "Weekend",
                        productId = this.getQuery("sdpid") || 0,
                        params = {
                            "bizType" : bizType,
                            "productId" : productId,
                        };
                    CtripBusiness.app_do_business_job(1, "setupHistoryWidget", params, 1111111); 
                    // app.callback = function(obj) {
                    //     if(obj.tagname == "do_business_job"){
                    //         if(obj.param.historyInfo){
                    //             var datas = JSON.parse(obj.param.historyInfo);
                    //             window.location.href = datas.detailURL;
                    //         }
                    //     }
                    // }
                }
            },
            onShow: function () {
                //加入浏览历史
                this.setHistory();
                this.isShow = true;
                if (this.fromView == \'warning404\') {
                    this.isShow = false;
                }
                this.setHeader();
                if (!this.isCreated || !this.$el.html()) {
                    if (this.isCreated && !this.$el.html()) {
                        this.destroyView(true);
                    }
                    //设置参数,用于页面点击后退
                    this.setFromPageParam();
                    this.requestData();
                    this.isCreated = false;
                }
                this.validFromView();
            },
            goToHotelCommentPage: function () {
                var self = this;
                var hotels = [],
                    ticket = [],
                    ttd = [];
                //hotels
                _.each(this.data.JourneysInfo.SHXJourneyInfoV6_5, function (data) {
                    if (!data.SHXHotelInfos.NoVoters) { return; }
                    hotels.push({
                        id: data.SHXHotelInfos.HotelId,
                        score: data.SHXHotelInfos.HotelRatingOverall,
                        count: data.SHXHotelInfos.NoVoters,
                        name: data.SHXHotelInfos.HotelName,
                    });
                });
                //tickets
                if (this.data.ScienceInfoList[0].ScineceInfo.length) {
                    if (this.data.ScienceInfoList[0].ScineceInfo.length < 2) {
                        ticket = [{
                            id: this.data.ScienceInfoList[0].ScineceInfo[0].ScineceId,
                            score: this.data.ScienceInfoList[0].ScineceInfo[0].Score,
                            count: this.data.ScienceInfoList[0].ScineceInfo[0].CommentCount,
                            name: this.data.ScienceInfoList[0].ScineceInfo[0].ScenicSpotName,
                            poiid: this.data.ScienceInfoList[0].ScineceInfo[0].Poi.PoiId//this.getQuery(\'fromtype\') == 2 ? this.data.SDPInfo.PoiId : this.data.ScienceInfoList[0].ScineceInfo[0].Poi.PoiId
                        }];
                    }
                    else {
                        _.each(this.data.ScienceInfoList[0].ScineceInfo, function (item) {
                            if (!item.IsMaster) {
                                ticket.push({
                                    id: item.ScineceId,
                                    score: item.Score,
                                    count: item.CommentCount,
                                    name: item.ScenicSpotName,
                                    poiid: item.Poi.PoiId//this.getQuery(\'fromtype\') == 2 ? this.data.SDPInfo.PoiId : item.Poi.PoiId
                                });
                            }
                        });
                    }
                } else {
                    ticket = [{
                        id: 0,
                        score: 0,
                        count: 0,
                    }];
                }
                //ttd
                if (this.data.TTDInfoList && this.data.TTDInfoList.length) {
                    ttd = this.data.TTDInfoList;
                    _.each(ttd, function (ttd) {
                        ttd.score = ttd.Score;
                        ttd.name = ttd.ProductName;
                        ttd.id = ttd.ProductID;
                        ttd.count = 0;//暂不显示ttd
                    })
                }
                this.commonStore.setDetailCommentInfo({ hotels: hotels, tickets: ticket, ttds: ttd });
                this.forward(\'detailcomment\');
            },
            requestData: function (getCached) {
                this.showLoading();
                this.model.excute(
                    _.bind(this.successForData, this),
                    _.bind(this.errorForData, this)
                );
            },
            successForData: function (data) {
                this.data = data;
                /*
                var self = this;
                setTimeout(function () {
                    self.hideLoading();
                }, 10);
                */
                //下架产品
                //if (this.data.SDPInfo.Invalid) {
                //    this.showInvalidError();
                //    return;
                //}

                this.checkDate = UtilCommon.Date.format(new Date(this.data.SDPInfo.SdpDate.match(/\d+/)[0] - 0), \'Y-m-d\');

                // this.$bookBtn = this.$el.find(\'.btn_next\');
                // this.$bookBtnLabel = this.$el.find(\'.btn_next\');
                //this.$footerFavIcon = this.$el.find(\'.detail-collect-icon\');
                //this.$imageslider = this.$el.find(\'.slider-container-div\');
                /*
                   this.isShow = true;
                this.$el.html(_.template(this.viewTpl, data));
                this.$tab1 = this.$el.find(\'.detail-sdp-highlight-tab\');
                this.$tab3 = this.$el.find(\'.detail-orderknowledge-tab\');
                */
                this.getDetailSingleModel();
                //this.addToHistoryList();
            },
            errorForData: function (data) {
                this.hideLoading();
                this.isShow = false;
                var self = this;
                this.showWarning404(
                   function () {
                       this.$el.hide();
                       self.requestData();
                   }
                );
            },
            afterShow: function () {
                this.isShow = true;
                if (this.sdpTypeStore.getAttr(\'switchTab\') && this.matchSdpType(Lizard.P(\'sdpid\'))) {
                    this.data.SDPInfo.SdpType = this.sdpTypeStore.getAttr(\'SdpType\');
                }
                this.data.JourneysInfo.SHXJourneyInfoV6_5[0].SHXHotelInfos._Star = \'star_\' + this.formatDataStar(this.data.JourneysInfo.SHXJourneyInfoV6_5[0].SHXHotelInfos.HotelRatingOverall);
                this.$el.html(_.template(this.viewTpl, this.data));
                if (!this.$el.find(\'.js_sdp_type > a.cur\').length && this.getMasterSdp()) {
                    this.$el.find(\'.js_sdp_type > a[data-id="\' + this.getMasterSdp().SdpId + \'"]\').addClass(\'cur\');
                }
                // this.$bookBtn = this.$el.find(\'.btn_next\');
                // this.$bookBtnLabel = this.$el.find(\'.btn_next\');
                this.$footerFavIcon = this.$el.find(\'.detail-collect-icon\');
                this.$imageslider = this.$el.find(\'.slider-container-div\');
                this.$tab1 = this.$el.find(\'.detail-sdp-highlight-tab\');
                this.$tab3 = this.$el.find(\'.detail-orderknowledge-tab\');

                this.setHeader();
                ////特惠信息设置2行,超过显示更多按钮
                //this.limitSaleInfoHeight();
                if (this.commonStore.getLoginFlag() && this.data.IsLogin) {
                    this.addToCollection();
                }
                ////设置特卖会信息
                // this.setDealData();

                this.setDetailBookingInfoForOrderconfirm(true);
                this.setDetailInfoForPriceCalender();
                this.setSpotInfoForOrderconfirm();

                this.createImageSlider();
                this.createTabs();
                //this.setFromPageParam();
                //用于h5 登录页面刷新后收藏按钮没选中的bug
                if (this.data.IsLogin) {
                    this.isInCollection();
                }
                this.setSeoInfo();
                this.isCreated = true;
                this.addProductIcons();
                //this.setDetailHistory();
            },
            onHide: function (aa) {
                this.isShow = false;
                this.hideWarning404();
                this.footerPopup && this.footerPopup.hide();
                this.priceCalendar && this.priceCalendar == null;
                this.giftMask && this.giftMask == null;
                //关闭浏览历史插件
                if (Lizard.isHybrid) {
                    var params = {
                        "close" : true,
                    }
                    CtripBusiness.app_do_business_job(1, "setupHistoryWidget", params, 1111111);
                }
                return;
            },
            destroyView: function (type) {
                this._commentInfos = null;
                this.isCreated = false;
                this.footerPriceDetail = null;
                this.detailpricedetailtab = null;
                this.footerPopup && this.footerPopup.hide();
                this.footerPopup = null;
                this.otherTickets = null;
                this.favorited = false;
                this.data = null;
                this.checkDate = null;
                if (this.imageSlider) {
                    this.imageSlider.destroy();
                    this.imageSlider = null;
                }
            },
            //为订单填写页设置预订信息
            setDetailBookingInfoForOrderconfirm: function (type) {
                var varDate;
                var obj = this.commonStore.getBookingInfoForOrderconfirm();
                if (type && obj) {
                    varDate = obj.checkinDate;
                }
                var daysMatch = this.data.SDPInfo.Nights.match(/(\d).*(\d)/);
                var science = this.data.ScienceInfoList[0].ScineceInfo[0];
                var isSegment = this.getQuery(\'ismultiplesegment\');
                this.commonStore.setBookingInfoForOrderconfirm({
                    isOversea: this.getQuery(\'isoversea\') == \'true\' ? true : false,
                    checkinDate: varDate || (this.checkDate ? this.checkDate : ""),
                    nights: daysMatch[2],
                    black: this.data.SDPInfo.Black,
                    sdpId: this.getSdpid() || this.data.SDPID,
                    sdpName: this.data.SDPInfo.SdpName,
                    Districts: _.pluck(this.data.ScienceInfoList, \'DistrictId\'),
                    isHKAndMC: this.data.SDPInfo.IsHkMacIcon,
                    nightsList: this.getSegmentNightsList(varDate || this.checkDate).night || [],
                    isFromHotel: Lizard.P("fromtype") == 1 ? true : false,
                    detailFromHotelHref: Lizard.isHybrid ? "" : Lizard.P("from"),
                    roomId: Lizard.P("roomid") ? Lizard.P("roomid") : "",
                    saleChannel: Lizard.P("fromtype") == 2 ? true : false, //是否团购产品
                    groupid: Lizard.P("groupid") || 0,    //团购id
                    cityId: this.data.SDPInfo.CityId,
                    scenicSpot: {
                        scenicSpotId: science && this.data.ScienceInfoList[0].ScineceInfo[0].ScineceId,
                        scenicSpotName: science && this.data.ScienceInfoList[0].ScineceInfo[0].ScenicSpotName,
                        commentInfo: {
                            CommentScore: science && this.data.ScienceInfoList[0].ScineceInfo[0].Score,
                            CommentVote: science && this.data.ScienceInfoList[0].ScineceInfo[0].CommentCount
                        },
                        scenicSpotPoi: science && this.data.ScienceInfoList[0].ScineceInfo[0].Poi,

                        poiId: science && this.data.ScienceInfoList[0].ScineceInfo[0].Poi.PoiId,
                        poiType: science && this.data.ScienceInfoList[0].ScineceInfo[0].Poi.PoiType
                    }

                });
            },
            //为订单填写页设置主景点名字
            setSpotInfoForOrderconfirm: function () {
                if (this.data.ScienceInfoList[0].ScineceInfo[0]) {
                    this.commonStore.setMainSpotnameForOrderconfirm(this.data.ScienceInfoList[0].ScineceInfo[0].ScenicSpotName);
                }
            },
            setDetailInfoForPriceCalender: function () {
                var daysMatch = this.data.SDPInfo.Nights.match(/(\d).*(\d)/);
                this.commonStore.setDetailInfoForPriceCalender({ ttdList: this.data.TTDInfoList, sdpid: this.getSdpid(), days: daysMatch[1], nights: daysMatch[2], priceIntroduce: this.data.SDPInfo.PriceDetailIntroduceInfo });
            },
            //为图片缩略图页面格式化数据
            getBrowsePic: function () {
                var imgs;

                imgs = this.data.SDPInfo.PictureUrls;
                _.each(imgs, function (room) {
                    room.category = \'\';
                    room.imageDescription = \'\';
                    room.imageThumbnailUrl = room.SmallUrl;
                    room.imageTitle = \'\';//room.ImageTitle;
                    room.imageUrl = room.MiddleUrl || room.LargeUrl;
                    // room.smallsrc = room.SmallUrl;
                    // room[\'data-src\'] = room.MiddleUrl || room.LargeUrl;
                    // room.title = room.ImageTitle;
                });
                this.browseImgs = imgs;
                return this.browseImgs;
            },
            resetTabList: function () {
                if (!this.tablist) { return; }
                if (this.tabIndex == 3) {
                    this.tablist.setVal(1);
                }
            },
            createTabs: function () {
                this.highspottab = false;
                this.commenttab = false;
                this._tab3Showed = false;

                this._hasPicAndText = false;
                this._hasHighspot = false;

                var tabIndex = 0;
                var tabConfig = [];

                if (this.data.SDPInfo.ProductManagerRecInfo.RecContent.length || this.data.SDPInfo.SDPHighLight.ScienceHighLight.length || this.data.SDPInfo.SDPHighLight.HotelHighLight.length || this.data.SDPInfo.SDPHighLight.NoTabHighLight.length) {
                    this._hasHighspot = true;
                    tabConfig.unshift({ id: tabIndex++, name: "套餐亮点" });
                }

                tabConfig.push({ id: tabIndex++, name: "预订须知" })

                if (this.data.beautyPicAndText) {
                    this._hasPicAndText = true;
                    tabConfig.push({ id: tabIndex++, name: "<span class=\'zby_picarrow\'>美图美文</span>" });
                }
                var tag = 0;
                this._tag = tag;
                this.tablist = new UITab({
                    wrapper: this.$el.find(\'.detail-tab-container\'),
                    datamodel: {
                        data: tabConfig,
                        index: 0,
                        curClass: \'cui-tab-current\'
                    },
                    onChange: _.bind(this.onSwitchTab, this)
                });

                this.tablist.$el.find(\'.cui-tab-mod\').addClass(\'package_tab_num\').addClass(\'zby_tab\');
                //美图美文 click
                var fn = this.tablist.clickAction;
                var self = this;
                this._isClickTab = false;
                this.tablist.clickAction = function (t) {
                    var index = $(t.currentTarget).attr("data-index");
                    if (self._hasPicAndText) {
                        if (self._hasHighspot && index == 2 || !self._hasHighspot && index == 1) {
                            self.showPicAndTextPage();
                            return;
                        }
                    }
                    fn.call(self.tablist, t);
                }
                this.tablist.show();
                if (this._hasHighspot) {
                    this.$preTab = this.showDetailHighSpotTab();
                } else {
                    this.$preTab = this.showDetailOrderknowledgeTab();
                }
                return;
            },
            onSwitchTab: function (data) {
                this.$preTab.hide();
                if (this._hasHighspot && data.id == 0) {
                    //TODO:detail-sdp-hightlight-tab
                    this.tabIndex = data.id;
                    this.$preTab = this.showDetailHighSpotTab();
                } else if (data.id == 0) {
                    this.$preTab = this.showDetailOrderknowledgeTab();
                }
                if (this._hasHighspot && data.id == 1) {
                    this.$preTab = this.showDetailOrderknowledgeTab();
                } else if (this.id == 1 || data.id == 2) {
                    this.showPicAndTextPage();
                }
            },
            //美文美图
            showPicAndTextPage: function () {
                var isApp = Lizard.isInCtripApp || Lizard.isHybrid
                if (this.data.beautyPicAndText) {
                    if (!isApp) {
                        location.href = this.data.beautyPicAndText.H5Url + \'?from=\' + location.href;
                    } else {
                        Lizard.jump(this.data.beautyPicAndText.HybirdUrl, { targetModel: 4 })
                    }
                }
                return;
            },
            showDetailHighSpotTab: function () {
                var container;
                if (!this.highspottab) {
                    container = this.$el.find(\'.detail-sdp-highlight-tab\');
                    this.highspottab = new DetailSdpHighSpot({ container: container, root: this, data: this.data.SDPInfo });
                } else {
                    container = this.highspottab.show();
                }
                return container;
            },
            showDetailOrderknowledgeTab: function () {
                this.$tab3.show();
                if (this._tab3Showed) { return this.$tab3; }
                //this.$tab3.show();
                var model = DiyshxModel.BookingPolicyModel1.getInstance();
                model.param.SdpId = this.getSdpid();
                if (this.data.SDPInfo.HasSubSdps && this.subTickets) {
                    model.param.TicketIds = this.subTickets.length > 0 ? this.subTickets[0] : 0;
                } else {
                    model.param.TicketIds = _.pluck(this.data.TicketInfoList, \'TicketId\');
                }

                var loading = this.showBeginLoading(this.$tab3);
                model.excute(function (data) {
                    loading.hide();
                    data.BookingPolicy.isHKAndMC = (this.data.SDPInfo.IsHkMacIcon && this.data.SDPInfo.IsHkMacIcon == 2);
                    data.BookingPolicy.isOversea = this.getQuery(\'isoversea\') == \'true\' ? true: false;
                    data.priceInfo = this.data.SDPInfo.PriceDetailIntroduceInfo;
                    this.$tab3.html(_.template(Lizard.T(\'detail-booking-policy\'), data));
                    this.$tab3.find(\'.hotelname\').html(this.data.JourneysInfo.SHXJourneyInfoV6_5.length == 1 ? this.data.JourneysInfo.SHXJourneyInfoV6_5[0].SHXHotelInfos.HotelName : \'酒店预订说明\');

                }, function () {
                    loading.hide();
                    this.showNetworkError(this.$tab3, _.bind(this.showDetailOrderknowledgeTab, this));

                }, true, this);

                this._tab3Showed = true;
                return this.$tab3;
            },
            //格式化图片数据
            getSliderImages: function () {
                var pics = this.data.SDPInfo.PictureUrls;
                if (!pics) { return false; }
                var result = [], img;
                _.each(pics, function (pic, index) {
                    pic.smallsrc = pic.SmallUrl;
                    pic.tag = index;
                    pic[\'data-src\'] = pic.LargeUrl;
                    pic.title = pic.ImageTitle;
                });
                return pics;
            },
            createImageSlider: function () {
                var that = this, result, el,
                    images = this.getSliderImages();
                //如果没图片
                if (!images || !images.length) { return false; }
                this.imageSlider = new Slider({
                    images: images,
                    root: this.$imageslider,
                    showNav: false,
                    px: 1 / 2,
                    onClick: function (evt) {
                        result = that.getBrowsePic();
                        that.commonStore.setAllPic(result);
                        if (isInApp) {
                            require("cHybridShell").Fn(\'show_photo_broswer\').run(result);
                        } else {
                            setTimeout(function () {
                                that.forward(\'pichoteldetail\');
                            }, 100);
                        }
                    },
                    onShow: function (evt) {
                        var el1 = $(\'<div class="zby_product_id"><span>产品编号:\' + that.data.SDPInfo.SDPID + \'</span></div>\');
                        that.imageSlider._root.append(el1);
                        if (images.length) {
                            el = $(\'<div class="zby_img_num"><span>1/\' + images.length + \'</span></div>\');
                            that.imageSlider._root.append(el);
                        }
                    },
                    onMoved: function (evt) {
                        el.find(\'span\').html(evt.attr(\'tag\') - 0 + 1 + \'/\' + images.length);
                    },
                    onBeforeShow: function (evt) {

                    }
                });
                return;
            },
            //设置fromPge,用于回退时的判断
            setFromPageParam: function () {
                var url;
                if (this.getQuery(\'from\') == \'groupmessage\' || this.getQuery(\'fromshare\')) {
                    //分享出去的
                    this.commonStore.setDetailFromPage1({ type: 4, url: \'index\' });
                    return;
                }
                //设置详情页入住日期
                //this.commonStore.setDetailBookingTime(this.getQuery(\'date\'));
                if (decodeURIComponent(location.href).split(\'?\').length > 2) {
                    //app bug 
                    this.commonStore.setDetailPage(\'detailnearby/\' + Lizard.P.lizParam.sdpid + \'.html?\' + decodeURIComponent(location.href).split(\'?\')[1] + \'&\' + decodeURIComponent(location.href).split(\'?\')[2]);
                } else {
                    this.commonStore.setDetailPage(\'detailnearby/\' + Lizard.P.lizParam.sdpid + \'.html\' + (decodeURIComponent(location.href).split(\'?\').length > 1 ? \'?\' + decodeURIComponent(location.href).split(\'?\')[1] : \'\'));
                }
                //从订单填写页过来
                if (this.fromView == \'orderdetails\') {
                    this.commonStore.setDetailFromPage1({ type: 5, url: this.commonStore.getOrderDetailFromPage() });
                    return;
                }
                if (this.getQuery(\'from_native_page\')) {
                    this.commonStore.setDetailFromPage1({ type: 0 });
                } else if (this.getQuery(\'from\')) {
                    if (/^\/webapp/i.test(this.getQuery(\'from\'))) {
                        url = location.origin + this.getQuery(\'from\');
                    } else {
                        url = this.getQuery(\'from\');
                    }
                    this.commonStore.setDetailFromPage1({ type: 1, url: url });
                }
                this.setPageParam();
            },
            //点击后退按钮
            onReturnBtnClick: function (isFromCalenderTrigger) {
                var self = this;
                if (this.isPopShowed) { return false; }
                //更新sdpTypeStore
                this.sdpTypeStore.set(null);
                setTimeout(function () {
                    if (!isFromCalenderTrigger) {

                        if (self.fromView == \'oversea\' || self.fromView == \'espage\' || self.fromView == \'zhoubian\' || self.fromView == "list" || self.fromView == "index" || self.fromView == \'tourlist\') {
                            self.back();
                            self.destroyView();
                            return false;
                        }
                    }
                    try {
                        fromInfo = self.commonStore.getDetailFromPage1();
                        if (fromInfo.type == 0) {
                            Guider.backToLastPage();
                            return;
                        }
                        if (fromInfo.type == 1) {
                            location.href = fromInfo.url;
                            return;
                        }
                        if (fromInfo.type == 3) {
                            self.back();
                            self.destroyView();
                            return;
                        }
                        if (fromInfo.type == 4) {
                            self.back(\'index\' || \'zhoubian\');
                            return;
                        }
                        if (fromInfo.type == 5) {
                            self.back(fromInfo.url);
                            return;
                        }
                        if (!self.fromView) {
                            self.back(\'index\' || \'zhoubian\');
                            return;
                        }
                    } catch (e) {
                        self.back();
                        self.destroyView();
                        self.back(\'index\' || \'zhoubian\');
                    }
                }, 0);

                return false;
            },
            setHeader: function () {
                var self = this, fromInfo, obj = {};

                obj = {
                    title: \'套餐详情\',
                    view: this,
                    back: true,
                    right: (function () {
                        if (!self.data || !self.data.SDPInfo.SdpName) { return; }
                        var tag = [],
                            tagShare = {
                                // tagname: \'more\',
                                // imagePath: \'/diyshx/pic/h5/scenic_htl/icon_single_comment.png\',
                                tagname: \'home\',
                                iconname: \'home\',
                                callback: function (evt) {
                                    Guider.apply({
                                        hybridCallback: function () {
                                            Guider.home();
                                        },
                                        callback: function () {
                                            window.location = "/html5"
                                        }
                                    });
                                }
                            },
                            tagLove = {
                                tagname: (isInApp) ? \'favorite\' : \'love\',
                                imagePath: \'car/res/logo.png\',
                                callback: function (evt) {
                                    self._loveIcon = evt;
                                    self.onLoveTagClick();
                                }
                            },
                            tagLoved = {
                                tagname: (isInApp) ? \'favorited\' : \'loved\',
                                imagePath: \'car/res/logo.png\',
                                callback: function (evt) {
                                    self._loveIcon = evt;
                                    self.onLovedTagClick();
                                }
                            };

                        tag.push(self.favorited ? tagLoved : tagLove);

                        if (!isInApp) {
                            tag.push(tagShare);
                            obj.home = true;
                        }
                        return tag;
                    })(),
                    events: {
                        returnHandler: function () {
                            self.onReturnBtnClick();
                        }
                    }
                };
                if (isInApp) {
                    obj.moreMenus = [
                        {
                            tagname: \'share\',
                            iconname: \'share\',
                            value: \'转发\',
                            callback: function () {
                                self.shareOut()
                            }
                        },
                       {
                           tagname: \'more_message_center\',
                           iconname: \'comment\',
                           value: \'在线咨询\',
                           callback: function () {
                               self.onChatIconClick();
                           }

                       },
                        {
                            tagname: \'more_home\',
                            iconname: \'home\',
                            value: \'携程首页\',
                            callback: function () {
                                Guider.apply({
                                    hybridCallback: function () {
                                        Guider.home();
                                    },
                                    callback: function () {
                                        window.location = "/html5"
                                    }
                                });
                            }
                        }
                    ]
                };
                this.headerview.set(obj);
            },
            getSdpid: function () {
                var sdpid;
                if (this.selectSdp && this.selectSdp.SdpId) {
                    sdpid = this.selectSdp.SdpId;
                }
                if (!sdpid) {
                    sdpid = this.data.SDPInfo.SDPID;
                }
                return sdpid;
            },
            //重置展开按钮
            resetExpandBtn: function () {
                this.$saleInfo.addClass(\'tips_fold\');
                this.$saleInfo.css(\'height\', \'\');
                this.$moreBtn.html("更多");
                this.$moreBtn.removeClass("a_server").addClass("a_server_on");
                this.isBtnClose = true;
            },
            //收藏图标状态改变后重新更新状态
            refreshHead: function () {
                if (this.$el.css(\'display\') == \'none\') { return; }
                this.setHeader();
            },
            onFooterCollectClick: function () {
                if (!this.favorited) {
                    this.onLoveTagClick();
                } else {
                    this.onLovedTagClick();
                }
            },
            //收藏功能
            addToCollection: function () {
                var self = this;
                collect = this.collect = collect || new cPublic.collect();;
                this.collect.save({
                    "Version": "6700",
                    "Channel": Lizard.isHybrid ? 3 : 2,
                    FavoriteList: [{
                        "BizType": "WEEKEND", //bu模块名
                        "ProductID": this.getMainSdpId(),
                        "ProductType": \'WEEKEND_VIEWHOTEL\',
                        "FromCityID": this.getQuery(\'cityid\') || 0
                    }]
                }, function (err, data) {
                    if (data && data.FavoriteIDs.length) {
                        self._favouriteId = data.FavoriteIDs;
                        self.favorited = true;
                        self.refreshHead();
                        self.updateFooterFavIcon();
                    }
                });
            },
            updateFooterFavIcon: function () {
                if (this.favorited) {
                    this.$footerFavIcon.addClass(\'cur\');
                } else {
                    this.$footerFavIcon.removeClass(\'cur\');
                }
            },
            getMainSdpId: function () {
                var data, self = this;
                if (this.data.SDPInfo.IsExtend) {//延住产品
                    data = this.data.SDPInfo.SDPID;
                } else if (this.data.SDPInfo.HasSubSdps) {//多票种,已废除,挪至SdpType
                    data = _.find(this.data.SDPInfo.SubSdps, function (data) { return data.IsMasterSdp == true }).SdpId;
                } else if (this.data.SDPInfo.SdpType) {//套餐类型
                    data = _.find(this.data.SDPInfo.SdpType, function (data) { return data.SdpId == self.data.SDPInfo.SDPID });
                    if (!data) { return this.data.SDPInfo.SDPID; }
                    else if (data.Relation == 3) {
                        data = _.find(this.data.SDPInfo.SdpType, function (data) {
                            return data.Relation == 1;
                        });
                    }
                    data = data.SdpId;
                } else {
                    data = this.data.SDPInfo.SDPID;
                }
                return data;

            },
            //是否已经收藏
            isInCollection: function (el) {
                var model = DiyshxModel.Fav.isFavModel.getInstance();
                var that = this;
                var obj = {
                    "BizType": "WEEKEND", //bu模块名
                    "ProductID": this.getMainSdpId(),
                    "ProductType": \'WEEKEND_VIEWHOTEL\',
                    "FromCityID": this.getQuery(\'cityid\') || 0
                };

                model.param = {
                    "QueryList": [obj]
                };

                model.excute(function (json) {
                    if (json && json.ResultList && json.ResultList.length) {
                        that.favorited = true;
                        that._favouriteId = json.ResultList[0].FavoriteID;
                        that.refreshHead();
                        that.updateFooterFavIcon();
                    } else {
                        //that.showToast(\'添加收藏失败,稍后再试\');
                        console.log(\'判断是否收藏失败\');
                    }
                });
            },
            //取消收藏
            removeCollection: function (el) {
                var self = this;
                var model = DiyshxModel.Fav.cancleFavModel.getInstance();
                model.param = {
                    "FavoriteIdList": self._favouriteId
                };
                model.excute(function (json) {
                    if (json && json.DeletedList && json.DeletedList.length > 0) {
                        self.favorited = false;
                        self.refreshHead();
                        self.updateFooterFavIcon();
                    } else {
                        self.showToast(\'取消收藏失败,稍后再试\');
                    }
                }, function () {
                    self.showToast(\'取消收藏失败,稍后再试\');
                });
            },
            //收藏按钮点击,取消收藏
            onLovedTagClick: function () {
                var self = this;
                if (!this.collectAlert) {
                    this.collectAlert = new UIAlert({
                        datamodel: {
                            content: \'确定取消收藏?\',
                            btns: [
                            { name: \'取消\', className: \'cui-btns-cancel\' },
                            { name: \'确定\', className: \'cui-btns-ok\' }
                            ]
                        },
                        cancelAction: function () {
                            self.isPopShowed = false;
                            this.hide();
                        },
                        okAction: function () {
                            self.removeCollection();
                            self.isPopShowed = false;
                            this.hide();
                        }
                    });
                }
                this.collectAlert.show();
                self.isPopShowed = true;
            },
            //点击收藏按钮
            onLoveTagClick: function (evt) {
                var self = this;
                if (this.data.IsLogin) {
                    this.addToCollection();
                } else {
                    this.commonStore.setLoginFlag();
                    this.onLogin(window.decodeURIComponent(location.href).match(/\/webapp\/diyshx.*/i)[0], function () {
                        self.addToCollection();
                    });
                }
            },
            //设置seo信息
            setSeoInfo: function () {
                var name;
                if (this.data && this.data.SDPInfo.SdpName) {
                    name = this.data.SDPInfo.SdpName;
                    $(\'title\').html(name + \'-【携程自由行景酒套餐】\');
                    $(\'meta[name="description"]\').attr(\'content\', name + \',最便宜的酒店有哪些?携程自由行套餐频道为您提供最省钱的景点门票与酒店套餐。手机订酒店、景点门票,请访问m.ctrip.com。\');
                    $(\'meta[name="keywords"]\').attr(\'content\', name + \',携程旅行,订酒店,订门票\');
                }
                //seo head添加标记
                var $el = $(\'<a href="//m.ctrip.com/html5/"></a>\');
                $(\'#headerview\').find(\'.icon_home\').append($el);
            },
            onLogin: function (url, callbackFn) {
                var FluxEntrance = this.getFluxEntrance(); //引流渠道号
                var cityid = this.getDiyCid();//售卖站埋参数
                var self = this;
                Member.memberLogin({
                    param: \'from=\' + encodeURIComponent(url) + (FluxEntrance != "0" ? \'?FluxEntrance=\' + FluxEntrance + \'&DiyCid=\' + cityid : ""),
                    callback: function (data) {
                        if (data) {
                            self.data.IsLogin = true;
                            callbackFn.call(self);
                        }
                    }
                });
            },
            //电话直落接口
            callService: function () {
                if (this.hpageid) {
                    cGuiderService.callService();
                }
            },
            //右上角聊天窗口
            onChatIconClick: function () {
                window.location.href = "//m.ctrip.com/webapp/LivechatH5/chat?GroupCode=taocanhotel&AsFrom=0|orderdetail&version=2.0&origin=1&productid=" + this.getSdpid();
            },
            //分享功能
            shareOut: function () {
                if (isInApp) {
                    var url = \'//m.ctrip.com/webapp/diyshx/detailnearby/\' + this.getMainSdpId() + \'.html?fromshare=1\';
                    //var url = "http://w-diy-m.fat19.qa.nt.ctripcorp.com/webapp/diyshx/detail/" + this.data.SDPID + \'.html\';
                    var obj = {
                        imgUrl: this.data.SDPInfo.PictureUrls && this.data.SDPInfo.PictureUrls[0].MiddleUrl,
                        shareUrl: url,
                        title: this.data.SDPInfo.SdpName,
                        text: this.data.SDPInfo.SdpName

                    };
                    var ctripShare = CtripBusiness.app_call_system_share || CtripUtil.app_call_system_share;//必须
                    Guider.downloadData({
                        callback: function (data) {
                            ctripShare(data.savedPath, obj.text, obj.title, obj.shareUrl, false);
                        },
                        url: obj.imgUrl,
                        suffix: \'jpg\'
                    });
                }
            },

            //add by zhuhaizhang
            getPriceCalendarData: function () {
                var self = this;
                var callendarModel = DiyshxModel.PriceCallendar.getInstance();
                callendarModel.param.SdpID = Lizard.P(\'sdpid\');//this.getSdpid()
                callendarModel.param.SaleChannel = 0;
                callendarModel.param.StartDate = this.getSdpDate().checkIn;
                callendarModel.param.DayCount = this.data.SDPInfo.CalenderDaysNum || 60;
                callendarModel.excute(function (data) {
                    _.each(data.list, function (date) {
                        date.date = new Date(date.date);
                    });
                    self.renderPirceCalendarTpl(data, callendarModel.param.DayCount);
                    console.log(data, \'价格日历服务请求成功\');
                }, function (error) {
                    console.log(error, \'价格日历服务请求失败\');
                }, true, this);
            },
            Map_SingleData: {
                1: { \'class\': \'st_blue\', \'text\': \'单订酒店\', \'unit\': \'晚\', \'h5\': \'/webapp/hotel/hoteldetail/{ 酒店id }.html?days=1&atime={入住日期}\', \'hybird\': \'/InlandHotel?checkInDate={入住日期}&checkOutDate={离店日期}&hotelId={ hotelId }&hotelDataType=1\' },
                2: { \'class\': \'st_yellow\', \'text\': \'单订门票\', \'unit\': \'份\', \'h5\': \'/webapp/ticket/dest/t{ 景点id }.html\', \'hybird\': \'ticket/index.html#/dest/t{ 景点id }.html?name={景点名称}\' },
                3: { \'class\': \'st_pink\', \'text\': \'单订玩乐\', \'unit\': \'份\', \'h5\': \'/webapp/activity/dest/t{ 玩乐id }.html\', \'hybird\': \'activity/index.html#dest/t{ 玩乐id }.html\' }
            },
            getDetailSingleModel: function () {
                var self = this, date = new Date();
                var singleModel = DiyshxModel.DetailSingleModel.getInstance();
                singleModel.param.SdpID = Lizard.P(\'sdpid\');//this.getSdpid()
                singleModel.param.SdpDate = this.getSdpDate().checkIn;//date.getFullYear() + \'-\' + (date.getMonth() + 1) + \'-\' + date.getDate();//this.getSdpid()
                singleModel.excute(function (data) {
                    self.data.beautyPicAndText = data.BeautyWords;
                    self.data.singleHotelPrice = self.getSingleModelPrice(data.SingleProductsInfo, 1);
                    self.data.singleSightPrice = self.getSingleModelPrice(data.SingleProductsInfo, 2);
                    self.hideLoading();
                    self.afterShow();
                    data.map_data = self.Map_SingleData;
                    self.renderDetailSingleTpl(data);
                    self.getPromotionInfo();
                    self.getPriceCalendarData();
                    self.addToHistoryList();
                }, function (error) {
                    self.data.beautyPicAndText = null;
                    self.data.singleHotelPrice = \'\';
                    self.data.singleSightPrice = \'\';
                    self.hideLoading();
                    self.afterShow();
                    self.getPromotionInfo();
                    self.getPriceCalendarData();
                    self.addToHistoryList();
                    //self.errorForData();
                }, true, this);
            },
            getSingleModelPrice: function (data, type) {
                return _.find(data, function (item) { return item.ResourceType == type; })
            },
            renderPirceCalendarTpl: function (DATA, CalenderDaysNum) {
                var data = {
                    startDate: new Date(DATA.startDate) || new Date(),
                    displayMonthNum: DATA.months,
                    showRestIcon: false,
                    list: DATA.list,
                    endDate: new Date(DATA.endDate)
                };
                //初始化
                data = getTwoWeeks(data);
                //售卖第一天月份
                data._month = _.dateUtil.format(data.startDate, \'Y年m月\');
                //可售日期的第一天
                data._firstValidDay = _.find(data.list, function (item) { return item.PriceStatus != \'-1\'; });
                //data._firstValidDay = data._firstValidDay && _.dateUtil.format(data._firstValidDay.date, \'Y/m/d\');
                data._firstday = _.dateUtil.format(data.startDate, \'Y-m-d\');
                data._lastDay = _.dateUtil.format(data.endDate, \'Y-m-d\');
                //售罄天数判断
                if (DATA.soldOut < DATA.list.length) {
                    //更新14天的逻辑
                    if (data._firstValidDay && data._firstValidDay.key >= data.diffDay) {
                        data.startDate = new Date(data._firstValidDay.date);
                        data = getTwoWeeks(data);
                        data._month = _.dateUtil.format(data.startDate, \'Y年m月\');
                    }
                }
                //格式化日期
                data._start = _.dateUtil.format(data.startShowTime, \'Y-m-d\');
                data._end = _.dateUtil.format(data.endShowTime, \'Y-m-d\');
                //data._month = _.dateUtil.format(data.startShowTime, \'Y年m月\');//DIY03DDWX-2081
                this.$el.find(\'#js_zby_calendar_month\').html(\'(\' + data._month + \')\');
                //获取14天日期信息
                function getTwoWeeks(data) {
                    //日历第一天星期几
                    data.diffDay = 13 - data.startDate.getDay();
                    //14天第一天
                    data.startShowTime = new Date(data.startDate).setDate(data.startDate.getDate() - data.startDate.getDay());
                    data.startShowTime = new Date(data.startShowTime);
                    data._startMonth = data.startShowTime.getMonth();
                    data.startTime = data.startShowTime;
                    //14天最后一天
                    data.endShowTime = new Date(data.startDate).setDate(data.startDate.getDate() + data.diffDay);
                    data.endShowTime = new Date(data.endShowTime);
                    data._endMonth = data.endShowTime.getMonth();
                    //计算是否需要跨月
                    data.displayMonthNum = data._startMonth != data._endMonth ? data.displayMonthNum + 1 : data.displayMonthNum;
                    data._month = _.dateUtil.format(data.startShowTime, \'Y年m月\');
                    return data;
                }
                //创建价格日历
                this.createCalendar(data);
            },
            priceCalendar: null,
            toBJDate: function (value) {
                if (typeof (value) == "string") {
                    if (value.indexOf("Date") > -1) {
                        //if (value.indexOf(\'Date(-\') > -1) return 0;
                        value = value.match(/(\d+)/)[0];
                    }
                    if (!isNaN(value)) {
                        value = parseInt(value);
                    }
                }
                var date = new Date(value);
                var timezoneOffset = date.getTimezoneOffset();
                date.setTime(date.getTime() + timezoneOffset * 60000 + 28800000);
                return date.getTime();
            },
            createCalendar: function (data) {
                var self = this;
                //if (!this.priceCalendar) {
                this.priceCalendar = new UICalendarCommon({
                    wrapper: self.$el.find(\'.js_zby_dp_calendar\').html(\'\'),
                    template: Lizard.T(\'detail_CalendarTpl\'),
                    datamodel: data,
                    onItemClick: _.bind(function (date, el, target) {
                        var soldout = el.find(\'span.soldout\').length;
                        var iVan = el.find(\'.days\').length;
                        if (soldout) {
                            this.createAlertTips();
                            this.getPriceCalendarData();
                            return;
                        }
                        //this.isCreated = false;
                        if (iVan) {
                            this.orderSearch(_.dateUtil.format(date, \'Y/M/D\'), function () {
                                var url = self.getQueryParam(\'detail\', \'.html\', _.dateUtil.format(date, \'Y-M-D\'));
                                self.forward(url);
                            }, function () {
                                self.createAlertTips();
                                self.getPriceCalendarData();
                            });
                            return;
                        }
                        var url = this.getQueryParam(\'detail\', \'.html\', _.dateUtil.format(date, \'Y-M-D\'));
                        this.forward(url);
                    }, this),
                    dayItemAction: function (dayObj, year, month, day, dateObj, difftime) {
                        dateObj.setHours(0, 0, 0, 0);
                        var _time = dateObj.getTime();
                        var _dayPrice = _.find(data.list, function (item) {
                            var local = self.toBJDate(item[\'Date\']);
                            return local == _time;
                        });
                        var dateStr = dayObj.day1 || dayObj.day;
                        if (_dayPrice) {
                            if (_dayPrice.price == "0") {
                                return \'<span class="soldout">\' + dateStr + \'</span><br /><span class="soldout">售罄</span>\';
                            }
                            else if (_dayPrice.price == "00") {
                                return \'<span class="days">\' + dateStr + \'</span><br /><span style="color:#FF9900;">实时价</span>\';
                            }
                            else {
                                return \'<span class="days">\' + dateStr + \'</span><br /><dfn>¥\' + _dayPrice.price + \'</dfn>\';
                            }
                        }
                        else {
                            return \'<span class="soldout">\' + dateStr + \'</span>\';
                        }
                    },
                    onShow: function () {
                        //起始日期计算
                        //前14天都售罄时,往后移动,即第一个可售有价格开始
                        this.onRemoveNodes(data);
                    },
                    onHide: function () { },
                    onRemoveNodes: function (data) {
                        var start = this.$el.find(\'a[data-cndate="\' + data._start + \'"]\').data(\'curtime\');//14天的第一天
                        var firstDay = this.$el.find(\'a[data-cndate="\' + data._firstday + \'"]\').data(\'curtime\');//价格日历第一天
                        var end = this.$el.find(\'a[data-cndate="\' + data._end + \'"]\').data(\'curtime\');//14天的最后一天
                        //var firstValidDay = this.$el.find(\'a[data-cndate="\' + data._firstValidDay + \'"]\').data(\'curtime\');//价格日历的有价格的第一天
                        //var lastDay = this.$el.find(\'a[data-cndate="\' + data._lastDay + \'"]\').data(\'curtime\');
                        var curtimes = this.$el.find(\'a\');
                        curtimes.each(function (index) {
                            var $this = $(this), curtime = $this.data(\'curtime\');
                            //删除价格日历外的日期
                            if (curtime > start || curtime < end) {
                                $this.remove();
                            }
                            //14天过期日期
                            if (curtime > firstDay) {
                                $this.addClass(\'js_overdue cm-item--disabled\');
                            }
                        });
                    }
                });
                //}
                this.priceCalendar.show();
            },
            renderDetailSingleTpl: function (data) {
                var tpl = Lizard.T(\'detail_singlemodules\');
                var $dom = $($.trim(_.template(tpl, data)));
                this.$el.find(\'.js_detail_single_modules\').html($dom).show();
            },
            //promotionInfoModel 礼包信息
            giftstore: DiyshxStore.GiftStore.getInstance(),
            getPromotionInfo: function () {
                var self = this;
                var promotionModel = DiyshxModel.PromotionInfoModel.getInstance();
                promotionModel.param = {
                    SdpId: this.getQuery(\'sdpid\'),
                    SdpDate: this.getSdpDate().checkIn,
                    Nights: this.getSdpNights()
                };
                promotionModel.excute(function (data) {
                    self.renderPromotionTpl({ PromotionInfo: data.PromotionInfo, HasRoomGift: self.data.JourneysInfo.HasRoomGift, RoomGift: self.data.JourneysInfo.RoomGift || [], CouponInfo: data.CouponInfo });
                    self.giftstore.set({
                        \'Gift\': { PromotionInfo: data.PromotionInfo, HasRoomGift: self.data.JourneysInfo.HasRoomGift, RoomGift: self.data.JourneysInfo.RoomGift || [] }
                    });
                }, function (data) {
                    self.renderPromotionTpl({ PromotionInfo: data.PromotionInfo, HasRoomGift: self.data.JourneysInfo.HasRoomGift, RoomGift: self.data.JourneysInfo.RoomGift || [], CouponInfo: [] });
                    self.giftstore.set({
                        \'Gift\': { PromotionInfo: data.PromotionInfo, HasRoomGift: self.data.JourneysInfo.HasRoomGift, RoomGift: self.data.JourneysInfo.RoomGift || [] }
                    });
                }, true, this);
            },
            renderPromotionTpl: function (data) {
                var tpl = Lizard.T(\'detail_GiftTpl\');
                var giftbox = this.$el.find(\'.js_gift_box\');
                data._Date = this.toBJDate;
                tpl = $($.trim(_.template(tpl, data)));
                tpl.find(\'li.gift_infor\').eq(0).addClass(\'zby_top_giftlink\').append(\'<a href="javascript:" class="gift_link js_gift_link color_blue"><span class="ico_i">礼包详情</span></a>\');
                giftbox.html(tpl);
            },
            drawCoupons: function (e) {
                var self = this;
                var $cur = $(e.currentTarget);
                var $id = $cur.data(\'id\');
                //是否领券
                if ($cur.hasClass(\'clicked\')) { return; }
                if (this.data.IsLogin && !this.drawCouponsClicked) {
                    this.drawCouponsClicked = true;
                    this.getDrawCouponModel({ SdpId: self.getSdpid(), PromotionCode: $id }, $cur);
                } else {
                    this.onLogin(window.decodeURIComponent(location.href).match(/\/webapp\/diyshx.*/i)[0], function () {
                        self.getDrawCouponModel({ SdpId: self.getSdpid(), PromotionCode: $id }, $cur)
                    });
                }
            },
            getDrawCouponModel: function (params, doms) {
                var self = this;
                var drawcouponmodel = DiyshxModel.DrawCouponModel.getInstance();
                drawcouponmodel.param = params;
                drawcouponmodel.excute(function (data) {
                    if (data.Result && data.Result.ResultCode == 1) {
                        self.showToast(\'领券成功\');
                        doms.addClass(\'clicked\');
                        doms.find(\'.q_name\').html(\'已领取优惠券\');
                    } else {
                        self.showToast(\'该优惠券已领取完\');
                    }
                    self.drawCouponsClicked = false;
                }, function (error) {
                    self.showToast(\'领券失败,稍后再试\');
                    self.drawCouponsClicked = false;
                }, true, this);
            },
            giftMask: null,
            showGiftMask: function () {
                // if need
                var self = this;
                //if (!this.giftMask) {
                require([\'ZbyGiftMask\'], function (Mask) {
                    self.giftMask = new Mask({
                        wrapper: $(\'.js_giftlist_box\').html(\'\'),
                        datamodel: self.giftstore.getAttr(\'Gift\'),
                        _toBJDate: self.toBJDate,
                    });
                    self.giftMask.show();
                });

            },
            alertTips: null,
            createAlertTips: function () {
                var self = this;
                if (!this.alertTips) {
                    this.alertTips = new UIAlert({
                        datamodel: {
                            content: "抱歉,当天房型已售罄",
                        }
                    });
                }
                this.alertTips.show();
                this.alertTips = null;
            },
            getQueryParam: function (page, suffix, date) {
                var flux = \'FluxEntrance=\' + this.FluxEntrance;//引流参数
                var sdpid = Lizard.P(\'sdpid\');//sdpid
                var IsMultipleSegment = this.data.JourneysInfo.IsMultipleSegment || false;//多行程段
                var from = window.location.protocol + "//" + window.location.hostname + window.location.pathname + window.location.search;//兼容
                var url = \'\', callendarStore = null;
                page = page || \'pricecalendar\';
                suffix = suffix || \'\';
                url = page + \'/\' + sdpid + suffix + \'?\' + \'iszhoumoyou=1\' + "&nights=" + this.getSdpNights() + \'&IsMultipleSegment=\' + IsMultipleSegment + \'&FluxEntrance=\' + this.FluxEntrance;
                if (page == \'detail\') {
                    url += \'&date=\' + date;
                } else if (this.data.SDPInfo.CalenderDaysNum) {
                    url += \'&days=\' + this.data.SDPInfo.CalenderDaysNum;
                }
                return url;
            },
            goToBookingPage: function () {

                //var obj = {
                //    "from": { "cityname": this.getQuery(\'city\'), "cityid": this.getQuery(\'cityid\') },
                //    "to": { "cityname": this.data.SDPInfo.CityName, "cityid": this.data.SDPInfo.CityId },
                //    "productid": this.getQuery(\'sdpid\'),
                //    "starttime": UtilCommon.Date.format(new Date(this.data.SDPInfo.SdpDate.match(/\d+/)[0] - 0), \'Y-m-d\') || \'\',
                //    "star": this.data.JourneysInfo.SHXJourneyInfoV6_5[0].SHXHotelInfos.Star,
                //    "keywords": "",
                //    "page_id": isInApp ? this.hpageid : this.pageid,
                //};
                //var trackLogKey = isInApp ? \'diyshx_detail_app_basic\' : \'diyshx_detail_h5_basic\';
                //this.setTrackLog(obj, trackLogKey);

                //this.addToHistoryList();
                var url = this.getQueryParam();
                this.forward(url);
            },
            getSdpDate: function () {
                var sdpdate = this.data.SDPInfo.SdpDate;
                sdpdate = this.toBJDate(sdpdate);
                sdpdate = new Date(sdpdate);
                var checkoutdate = new Date(sdpdate).setDate(sdpdate.getDate() + 1);
                checkoutdate = new Date(checkoutdate);
                return {
                    checkIn: _.dateUtil.format(sdpdate, \'Y-M-D\'),
                    checkOut: _.dateUtil.format(checkoutdate, \'Y-M-D\')
                }
            },
            goToSinglePages: function (e) {
                e.preventDefault();
                var $cur = $(e.currentTarget);
                var $siblings = \'\';
                var $url = {
                    h5: $cur.data(\'h5\'),
                    hybird: $cur.data(\'hybird\')
                };
                var from = window.location.protocol + "//" + window.location.hostname + window.location.pathname + window.location.search;//兼容
                if ($cur.data(\'type\') == 1) {//单订酒店的开关
                    $siblings = $cur.siblings(\'.zby_dptitle\');
                    if ($siblings.data(\'hotelcalendar\') == true) {
                        this.forward(this.getQueryParam()); return;
                    }
                    //else { this.forward(this.getQueryParam(\'detail\', \'.html\')); return; }
                    $url.h5 = $url.h5.indexOf(\'?\') > -1 ? $url.h5 + \'&\' : $url.h5 + \'?\';//days=1
                    $url.hybird = $url.hybird.indexOf(\'?\') > -1 ? $url.hybird + \'&\' : $url.hybird + \'?\';

                    if ($siblings.data(\'hoteldetail\') == true) {
                        //客栈,h5url暂无
                    } else {
                        //酒店
                        $url.h5 += \'atime=\' + this.getSdpDate().checkIn.replace(/\-/g, \'\');
                    }
                    $url.hybird += \'checkInDate=\' + this.getSdpDate().checkIn.replace(/\-/g, \'\') + \'&checkOutDate=\' + this.getSdpDate().checkOut.replace(/\-/g, \'\');
                    $url.hybird = \'ctrip://wireless\' + $url.hybird;
                }
                $url.h5 += ($url.h5.indexOf(\'?\') > -1 ? \'&\' : \'?\') + \'from=\' + from;
                !isInApp ? ($url.h5 && Lizard.jump($url.h5)) : ($url.hybird && Lizard.jump($url.hybird, { targetModel: 4 }));
            },
            callendarStore: DiyshxStore.PriceCallendarStore.getInstance(),
            validFromView: function () {
                var refer = {
                    "fromUrl": this.getQuery("from"),
                    "fromView": this.fromView,
                    "fromApp": this.getQuery("from_native_page")
                };
                //this.sdpTypeStore.setAttr(\'switchTab\', false);
                if (!refer.fromUrl && !refer.fromView) return;
                this.callendarStore.setAttr("refer", refer);
            },
            //套餐类型
            sdpTypeStore: DiyshxStore.DetailSdpTypeStore.getInstance(),
            matchSdpType: function (sdpid) {
                //先sdpid是不是mastersdpid
                var mastersdp = this.getMasterSdp();
                if (mastersdp) {
                    sdpid = mastersdp.SdpId;
                    this.sdpTypeStore.setAttr(\'MasterSdp\', mastersdp);
                }
                var SdpType = this.sdpTypeStore.getAttr(\'SdpType\');
                var matchItem = _.find(SdpType, function (item) { return item.SdpId == sdpid });
                return matchItem ? true : false;
            },
            getMasterSdp: function () {
                var sdp = _.find(this.data.SDPInfo.ExtendSdps, function (item) { return item.IsMasterSdp == true; });
                if (!sdp) {
                    sdp = this.sdpTypeStore.getAttr(\'MasterSdp\');
                }
                return sdp;
            },
            //哈哈,产品新加的需求
            orderSearch: function (date, successfn, errorfn) {
                var ordersearch = DiyshxModel.NecessaryOrderSearch.getInstance();
                var opts = {
                    sdpId: this.getQuery(\'sdpid\'),
                    saleChannel: 0,//1团购,0非团购
                    checkinDate: date,//入住日期
                    isMultipleSegment: this.data.JourneysInfo.IsMultipleSegment || false,
                    AutomaticDateType: 0,
                    ServerVersion: 6915
                }
                opts.SelectedTripTimeList = (this.getSegmentNightsList(opts.checkinDate)).dates;
                ordersearch.param = opts;
                ordersearch.excute(function (data) {
                    if (data.SHXHotelInfo && data.SHXHotelInfo.length) {
                        successfn();
                    } else {
                        errorfn();
                    }
                }, function (data) {
                    errorfn();
                }, true, this);
            },
            getSdpNights: function () {
                return this.data.SDPInfo.Nights.match(/天(\d)/)[1] || 1;
            },
            getSegmentNightsList: function (checkindate) {
                var nightslist = this.data.JourneysInfo.SHXJourneyInfoV6_5;
                var list = {}, checkin, checkout;
                list.dates = []; list.night = [];
                _.each(nightslist, function (item) {
                    console.log(checkin, checkout);
                    checkin = item.SegmentNo == 1 ? checkindate : checkout;
                    checkout = new Date(checkin);
                    checkout = new Date(checkout).setDate(checkout.getDate() + item.SegmentNights);
                    checkout = new Date(checkout);
                    checkout = _.dateUtil.format(checkout, \'Y/M/D\');
                    list.dates.push({
                        StartDate: checkin.replace(/\//g, \'-\'),
                        EndDate: checkout.replace(/\//g, \'-\')
                    });
                    list.night.push(item.SegmentNights);
                });
                return list;
            },
            _couponStatus: false,
            showCouponInfo: function (e) {
                //var _status = false;
                var $cur = $(e.currentTarget);
                if (!this._couponStatus) {
                    $cur.removeClass(\'arrow_downward\').addClass(\'arrow_upward\');
                    this.$el.find(\'.js_zby_yhqbox\').show();
                    this._couponStatus = true;
                } else {
                    this._couponStatus = false;
                    $cur.removeClass(\'arrow_upward\').addClass(\'arrow_downward\');
                    this.$el.find(\'.js_zby_yhqbox\').hide();
                }
            },
            getSdpTypeName: function (sdpid) {
                var sdptype = _.find(this.data.SDPInfo.SdpType, function (item) { return item.SdpId == sdpid });
                return sdptype ? sdptype.TypeName : \'\';
            },
            addProductIcons: function () {
                if (!this.imageSlider) { return; }
                var root = this.imageSlider.root;
                root.after(\'<div class="product_label"><dl id="sale_deals_tag"></dl></div>\');
                var iconContainer = this.$el.find(\'#sale_deals_tag\');
                if ((this.data.SDPInfo.Icons & 128) == 128) {
                    this.$imageslider.append(\'<i class="detail_wrzj" style="z-index:200"></i>\');
                }
                if ((this.data.SDPInfo.Icons & 256) == 256) {
                    this.$imageslider.append(\'<i class="detail_crazythr" style="z-index: 200"></i>\');
                }
                if ((this.data.SDPInfo.Icons & 32) == 32) {
                    iconContainer.append(\'<dd class="s_label sale_deals_yellow">11.11</dd>\');
                }
                if ((this.data.SDPInfo.Icons & 64) == 64) {
                    iconContainer.append(\'<dd class="s_label sale_deals_chinared">12.12</dd>\');
                }
                if ((this.data.SDPInfo.Icons & 8) == 8) {
                    iconContainer.append(\'<dd class="s_label sale_deals_chinared">春节特卖</dd>\');
                }
                if ((this.data.SDPInfo.Icons & 4) == 4) {
                    // iconContainer.append(\'<li class="sale_deals_icon_big">爱在杭州</li>\');
                }
                if ((this.data.SDPInfo.Icons & 16) == 16) {
                    iconContainer.append(\'<dd class="s_label sale_deals_lightgreen">送100</dd>\');
                }
                if ((this.data.SDPInfo.Icons & 512) == 512) {
                    iconContainer.append(\'<dd class="s_label sale_deals_lightgreen">超低价</dd>\');
                }
                if (this.data.SDPInfo.IsDealsSinks == 1 && ((this.data.SDPInfo.Icons & 2) == 2)) {
                    iconContainer.append(\'<dd class="s_label sale_deals_deepred">特卖汇</dd>\');
                    this.$el.find(\'.js_countdown_hidden\').hide();
                    this.countDownProducts();
                }
            },
            countDownProducts: function () {
                var _time = this.data.SDPInfo.PromotionTime;
                _time.StartTime = _time.StartTime && this.toBJDate(_time.StartTime);
                _time.EndTime = _time.EndTime && this.toBJDate(_time.EndTime);
                _time.node = this.$el.find(\'.js_zby_Countdown\');
                _time.Invalid = this.data.SDPInfo.Invalid;
                _time.node.data(\'start\', _time.StartTime).data(\'end\', _time.EndTime);
                require([\'CountDown\'], function (CountDown) {
                    var t = new CountDown(_time);
                });
            },
            showPriceInfo: function () {
                var htmls = \'<p style="text-align:left;">1.本起价是在最近24小时内,30天内双人出行共用一间房+包含游玩项目所测算的套餐价格。</p>\'
                    + \'<p style="text-align:left;">2.产品价格会根据您所选择的出发日期、出行人数及套餐内容不同而有所差别,此价格不含附加服务的费用(如单人房差、保险费等)。</p>\';
                this.showMessage({
                    datamodel: {
                        title: \'起价说明\',
                        content: htmls
                    }
                });
            },
            formatDataStar: function (val) {
                var score, star, match;
                score = val.toFixed(2);
                //重新计算分数:4.1-4.4分显示 4星半,4.5-5.0分显示 5星,如小数部分有第二位,则向前进1,如:4.51 取4.6
                var regExp = /(\d+)\.(\d)(\d*)/;
                var match = score.match(regExp);
                if (match[3] > 0) {
                    match[2]++;
                }
                if (match[2] != 0) {
                    score = match[1] + \'.\' + match[2];
                } else {
                    score = match[1];
                }
                if (match[2] > 4) {
                    match[1]++;
                } else if (match[2] > 0) {
                    match[1] += \'.5\';
                }
                return match[1] / 10 * 100;
            },
            //fix bug miss fluxentrance when back from detail
            setPageParam: function () {
                var param = \'\';
                if (!isInApp) {
                    param = window.location.search;
                } else {
                    param = window.location.hash;
                    param = decodeURIComponent(param);
                    if (param.indexOf(\'?\') > -1) {
                        param = \'?\' + param.split(\'?\')[1];
                    } else {
                        param = \'\';
                    }
                }
                this.commonStore.setDetailnearbyPageParam(\'detailnearby/\'+Lizard.P(\'sdpid\')+\'.html\'+param);
            },
            setDetailHistory: function () {
                if (Lizard.isHybrid) {
                    var bizType = "Weekend",
                        productId = Lizard.P(\'sdpid\') || 0,
                        params = {
                            "bizType": bizType,
                            "productId": productId,
                        };
                    CtripBusiness.app_do_business_job(1, "setupHistoryWidget", params, 1111111);
                    // app.callback = function (obj) {
                    //     if (obj.tagname == "do_business_job") {
                    //         if (obj.param.historyInfo) {
                    //             var datas = JSON.parse(obj.param.historyInfo);
                    //             window.location.href = datas.detailURL;
                    //         }
                    //     }
                    // }
                }
            },
        });

        return View;
    });

  

分类:

技术点:

相关文章: