import Vue from 'vue'
import axios from 'axios'
import axiosJsonp from 'axios-jsonp';
import lib from 'lib'
import _ from 'underscore'
import WjySdk from 'extSdk';

var type = lib.getParam("type"),
    urlboxAId = lib.getParam("boxAId"),
    weekName = ["日","一","二","三","四","五","六"],
    areaName = {
        "1" : "中国",
        "2" : "美国",
        "3" : "美国",
        "4" : "美国",
        "5" : "全球"
    },
    cacheArticle = {}, //缓存榜单列表
    cacheArticleDetailList = {}, //缓存电影列表
    timeStamp = (new Date()).getTime(), 
    lastDay = lib.handleTime(timeStamp-24*60*60*1000,2).substring(0,10),
    curDay = lib.handleTime(timeStamp,2).substring(0,10),
    curMonth = lib.handleTime(timeStamp).substring(0,8),
    curFilmReleaseDate = 0; //当前上映时间

export default {
    activated() {
    },
    methods: {
        onScroll(){
            if(this.detailIsloading || this.detailNextFlag==0) return

            let boxScroller = this.$refs["filmDetailBoxScroller"],
                boxScrollerList = this.$refs["filmDetailBoxList"],
                scrollTop = boxScroller.scrollTop,
                boxScrollerHeight = boxScroller.clientHeight,
                boxScrollerListHeight = boxScrollerList.clientHeight;

            if(boxScrollerListHeight <= scrollTop+boxScrollerHeight+40) {
                this.getBoxOfficeDetails()
            }
        },
        showBoxofficeDetail(id){
            WjySdk.openUrl(`${location.origin}/?page=zt-boxofficeDetail&id=${id}`)
        },
        toVideoPreview(articleId){
            WjySdk.toVideoPreview(articleId)
        },
        toCommentaryDetail(commentaryId){
            WjySdk.toCommentaryDetail(commentaryId)
        },
        toVideoDetail(articleId){
            if (articleId==0){
                lib.showTip("暂无解说视频")
            } else {
                WjySdk.toVideoDetail(articleId)
            }
        },
        changeNav(type){ //type:true/false=>地区切换/时间切换

            if(this.isloading) return
            if(type==this.type) return

            this.type = type
            this.nextFlag = 1
            this.timeline = 0
            this.articles = []

            this.getBoxOfficeList()
            this.handleUpdataTip()

            lib.setParam("type",this.type)
            lib.setTitle(`${areaName[this.type]}票房榜`)
            $("html,body").scrollTop(0)
        },
        handleUpdataTip(){
            switch(this.type){
                case 2 : 
                    //北美当日数据比中国晚一天
                    this.updataTip = `${lastDay} 当日票房（每日更新）`
                    break;
                case 3 : 
                    this.updataTip = `${curMonth} 票房（每日更新）` 
                    break;
                case 4 : 
                    this.updataTip = `美国影史总票房（每日更新）` 
                    break;
                default :
                    this.updataTip = `全球影史总票房（每日更新）` 
                    break;
            }
        },
        getBoxOfficeList(){
            let self = this
            let url = `${lib.apiUrl}/functionalTopic/boxOfficeProList.do`
           
            let param = {
                type : self.type,
                count : 20,
                timeline : self.timeline,
                channel : "LuciferChannel",
                ver : 1,
                os : 1,
                uid : 1,
                token : "lucifer_test_token"
            }

            //取缓存数据
            if(cacheArticle[`${self.type}`]) {
                self.nextFlag = 0
                self.articles = cacheArticle[`${self.type}`]
                return
            }

            self.isloading = true
            axios({
                url: url,
                params : param,
                adapter: axiosJsonp,
                callbackParamName: 'c' // optional, 'callback' by default
            }).then((res) => {
                self.isloading = false

                let ret = lib.formatHttpProtocol(res.data);
                if(ret.code == 0 && ret.data.boxOffices) {
                    let data = ret.data
                    
                    self.nextFlag = data.next
                    self.timeline = data.timeline
                    self.articles = self.articles.concat(data.boxOffices)

                    if(self.type==1 && data.totalBoxOffice) {
                        self.totalBoxOffice = data.totalBoxOffice
                        self.upDate = data.upDate

                        _.each(self.articles,(item,index)=>{
                            item.releaseDateStr = self.parseUpdateInfo(item)
                        })
                    }

                    //缓存实时和月榜数据
                    if(self.type==2||self.type==3) cacheArticle[`${self.type}`]=self.articles
                } else {
                    self.nextFlag = 0
                    self.timeline = 0
                }
            })
        },
        //中国榜单上映时间累计票房
        parseUpdateInfo(film){
            let now = new Date(),
                nowTime = now.getTime() ,
                restTime = (nowTime - film.releaseDate) /1000,
                restYear = Math.ceil(restTime / (365 * 60 * 60 * 24)),
                restDay = Math.ceil(restTime / (60 * 60 * 24)),
                releaseDateStr = "",
                sumBoxOfficeStr = "";

            if(!film.sumBoxOffice) sumBoxOfficeStr = ""
            if(film.sumBoxOffice > 1e8) {
                let num = (film.sumBoxOffice/1e8).toFixed(2)
                sumBoxOfficeStr = `累计<span>${num.substring(0,num.lastIndexOf('.')+2)}</span>亿`
            }else if(film.sumBoxOffice > 1e4){
                let num = Math.floor(film.sumBoxOffice/1e4)
                sumBoxOfficeStr = `累计<span>${num}</span>万`
            } else {
                let num = (film.sumBoxOffice/1e4).toFixed(3)
                sumBoxOfficeStr = `累计<span>${num.substring(0,num.lastIndexOf('.')+2)}</span>万`
            }

            if(restDay>365){
                releaseDateStr = `已上映<span>${restYear}</span>年`
            }else if(restDay>1){
                releaseDateStr = `已上映<span>${restDay}</span>天`
            }else if(restDay==1){
                releaseDateStr = `<span>今日上映</span>`
            } else {
                releaseDateStr = `<span>点映</span>`
            }

            return `${releaseDateStr} ${sumBoxOfficeStr}`
        }
    },
    data() {
        return {
            articles : [],              //列表
            urlboxAId : urlboxAId?urlboxAId:-1,
            curDay : curDay.replace(/-/g,"."),
            type : type?type:1,         //1:中国实时票房(人民币) 2：北美日票房（美元） 3：北美单月票房 4 ：北美总票房 5 ：北美全球总票房
            timeline : 0,               //翻页标志
            isloading : false,          //是否loading
            nextFlag : 1,               //下一页标志
            updataTip : ``,             //更新提示
            totalBoxOffice : 0,         //中国-今日大盘
            upDate : 0,                 //中国-更新时间
        }
    },
    mounted() {
        lib.setTitle(`${areaName[this.type]}票房榜`)
        this.handleUpdataTip()
        this.getBoxOfficeList()
    },
    filters : {
        parseBoxOffice : function(value){
            let result = 0;
            
            if(!value) return "--"
            if(value > 1e8) {
                let num = (value/1e8).toFixed(2)
                result = `${num.substring(0,num.lastIndexOf('.')+2)}亿`
            }else if(value > 1e4){
                let num = Math.floor(value/1e4)
                result = `${num}万`
            } else {
                let num = (value/1e4).toFixed(3)
                result = `${num.substring(0,num.lastIndexOf('.')+2)}万`
            }

            return result;
        },
        parseReleaseDate : function(value){
            let now = new Date()
            let nowTime = now.getTime() 
            let restTime = (nowTime - value) /1000
            let restYear = Math.ceil(restTime / (365 * 60 * 60 * 24))
            let restDay = Math.ceil(restTime / (60 * 60 * 24))

            if(restDay>365){
                return `${restYear}年`
            }else if(restDay>=0){
                return `${restDay}天`
            }
        },
        parseDate : function(value){
            return lib.handleTime(value,2).substring(0,10)
        },
        parseUpdateTime : function(value){
            return lib.handleTime(value).substring(11,17);
        },
        parseReleaseDateStr : function(value){
            let curDate = new Date(value),
                restTime = (value -curFilmReleaseDate) /1000,
                restYear = Math.ceil(restTime / (365 * 60 * 60 * 24)),
                restDay = Math.ceil(restTime / (60 * 60 * 24))+1,
                restTimeStr = "";

            if(restDay>365){
                restTimeStr = `上映第${restYear}年`
            }else if(restDay>0){
                restTimeStr = `上映第${restDay}天`
            }else{
                restTimeStr = `预售`;
            }

            return `周${weekName[curDate.getDay()]} ${restTimeStr}`
        }
    }
}