// packagecard/marketing/marketingposter.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        posterTempleteList: [],
        posterHistoryList: [],
        currentIndex: 0,
        currentPage: 1,
        totalPage: 0,
        isShowSel: false,
        tabList: [{
            name: '营销模板',
        }, {
            name: '我的海报'
        }],
        isRefreshing: false, //是否刷新中
        isLoadMore: false, //是否在加载中
        hasMore: true,
        imgUrl: app.urls.baseImgUrl,
        isRefresh: false,
        currentTypeIndex: 0, //当前选择的类型索引
        optionsList: [], //类型
        curTypeId: '',
        isShowOptions: false, //是否显示选项
        curItemIndex: -1, //点击分享按钮弹出的
        curTypeName: '全部',
        contentHeight: 550, //内容区域的高度
        shareTitle: '活动'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var _self = this
        //获取类型
        _self.getOptionsList()
        this.setData({
            contentHeight: app.globalData.windowHeight
        })
        try {
            var title = wx.getStorageSync('postertitle')
            if (title) {
                _self.setData({
                    shareTitle: title
                })
            }
        } catch (error) {

        }
    },
    //获取类型
    getOptionsList() {
        var _self = this
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get(app.urls.getDictionaryList.format({
                dataParentId: '4bf68c60-eac5-480d-b5e1-15203d0282f9'
            }), {
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                if (res.data.length > 0) {
                    _self.setData({
                        optionsList: res.data,
                    })
                    //根据第一条获取数据
                    _self.getTempleteList()
                }
                var allItem = {
                    dataName: '全部',
                    dataId: '2'
                }
                var tempItem = {
                    dataName: '我的收藏',
                    dataId: '1'
                }
                _self.data.optionsList.unshift(allItem)
                _self.data.optionsList.push(tempItem)
                _self.setData({
                    curTypeId: res.data[0].dataId,
                    optionsList: _self.data.optionsList
                })
            })
            .catch(err => {
                console.log(err)
            })
    },
    //显示类型选项
    showType() {
        this.setData({
            isShowOptions: !this.data.isShowOptions
        })
    },

    //选择类型
    chooseType(e) {
        var _self = this
        var id = e.currentTarget.dataset.id
        var idx = e.currentTarget.dataset.idx
        var name = e.currentTarget.dataset.name
        _self.setData({
            currentTypeIndex: idx,
            curTypeId: id,
            curTypeName: name,
            posterHistoryList: [],
            posterTempleteList: [],
            isShowOptions: false
        })
        if (_self.data.currentIndex == 0) {
            if (_self.data.curTypeId == '1') {
                _self.getFavorList()
            } else {
                _self.getTempleteList()
            }
        } else {
            _self.getHistoryList()
        }
    },
    //收藏
    doFavor(e) {
        var _self = this
        var idx = e.currentTarget.dataset.idx
        var id = e.currentTarget.dataset.id
        var favor = e.currentTarget.dataset.favor
        var msg = ''
        if (favor) {
            msg = '取消收藏...'
        } else {
            msg = '收藏中...'
        }
        wx.showLoading({
            title: msg,
        })
        app.http.post(app.urls.doSaveCollect, {
                header: {
                    token: app.globalData.token
                },
                data: {
                    businessId: id,
                    projectId: 'poster'
                }
            })
            .then(res => {
                wx.hideLoading({})
                _self.data.posterTempleteList[idx].cardCollect = !favor
                _self.setData({
                    posterTempleteList: _self.data.posterTempleteList
                })
            })
            .catch(err => {})
    },
    //是否需要刷新
    onShow() {
        var _self = this
        if (_self.data.isRefresh) {
            _self.dorefreshList()
        }
    },
    doShare(e) {
        var _self = this
        var idx = e.currentTarget.dataset.idx
        _self.setData({
            curItemIndex: idx,
            isShowSel: true
        })
    },
    //分享
    onShareAppMessage(res) {
        var _self = this
        _self.setData({
            isShowSel: false
        })
        wx.showShareMenu({
            withShareTicket: true,
            success: function (res) {
                console.log(res)
            }
        })
        var type = res.target.dataset.sharetype
        var img = _self.data.imgUrl + _self.data.posterHistoryList[_self.data.curItemIndex].cardTemplateUsePhotoUrl
        var id = _self.data.posterHistoryList[_self.data.curItemIndex].cardTemplateUseId
        var userId = _self.data.posterHistoryList[_self.data.curItemIndex].creator
        if (type && type == '2') {
            //转发个人动态

        } else {
            var param = '/pages/index/index?cardTemplateUseId=' + id + '&userId=' + userId;
            return {
                title: _self.data.shareTitle,
                path: param,
                imageUrl: img
            }
        }
    },
    //预览图片
    toImg() {
        var _self = this
        _self.setData({
            isShowSel: false
        })
        var img = _self.data.imgUrl + _self.data.posterHistoryList[_self.data.curItemIndex].cardTemplateUsePhotoUrl
        wx.previewImage({
            urls: [img],
        })
    },
    //保存图片到相册
    toAlbum() {
        var _self = this
        _self.setData({
            isShowSel: false
        })
        var img = _self.data.imgUrl + _self.data.posterHistoryList[_self.data.curItemIndex].cardTemplateUsePhotoUrl
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.writePhotosAlbum']) {
                    //已经授权相册权限
                    _self.saveToAlbum(img)
                } else if (res.authSetting['scope.writePhotosAlbum'] == undefined) {
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success(res) {
                            _self.saveToAlbum(img)
                        },
                        fail() {
                            wx.showToast({
                                title: '您没有授权,无法保存',
                                icon: 'none'
                            })
                        }
                    })
                } else {
                    wx.openSetting({
                        success(res) {
                            if (res.authSetting['scope.writePhotosAlbum']) {
                                _self.saveToAlbum(img)
                            } else {
                                wx.showToast({
                                    title: '您没有授权,无法保存',
                                    icon: 'none'
                                })
                            }
                        }
                    })
                }
            }
        })
    },
    //保存图片到相册
    saveToAlbum(url) {
        wx.showLoading({
            title: '保存中...',
        })
        wx.downloadFile({
            url: url,
            success(res) {
                if (res.statusCode == 200) {
                    var path = res.tempFilePath
                    wx.saveImageToPhotosAlbum({
                        filePath: path,
                        success(res) {
                            wx.hideLoading({})
                            if (res.errMsg == 'saveImageToPhotosAlbum:ok') {
                                wx.showToast({
                                    title: '保存成功',
                                    icon: 'success'
                                })
                            }
                        },
                        fail(err) {
                            wx.hideLoading({})
                            wx.showToast({
                                title: '保存失败,稍后重试',
                                icon: 'error'
                            })
                        }
                    })
                }
            },
            fail(err) {
                wx.hideLoading({})
                wx.showToast({
                    title: '保存失败,稍后重试',
                    icon: 'error'
                })
            }
        })
    },
    loadMore() {
        var _self = this
        if (_self.data.hasMore) {
            if (_self.data.isLoadMore) {
                return
            }
            this.setData({
                isLoadMore: true
            })
        }
    },
    dorefreshList() {
        var _self = this
        _self.setData({
            posterHistoryList: [],
            posterTempleteList: [],
            isRefreshing: true,
            isLoadMore: false,
            hasMore: true,
            isRefresh: false
        })
        if (_self.data.currentIndex == 0) {
            //获取模板
            if (_self.data.curTypeId == '1') {
                _self.getFavorList()
            } else {
                _self.getTempleteList()
            }
        } else {
            _self.getHistoryList()
        }
    },
    //获取模板列表
    getTempleteList() {
        var _self = this
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get(app.urls.getPosterTempleteList, {
                header: {
                    token: app.globalData.token
                },
                data: {
                    templateType: _self.data.curTypeId == '2' ? '' : _self.data.curTypeId
                }
            })
            .then(res => {
                wx.hideLoading({})
                res.data.forEach(it => {
                    if (it.picturesTemplateNumber < 100) {
                        //小于100次显示数值
                    } else {
                        //大于100次
                        if (it.picturesTemplateNumber > 100 && it.picturesTemplateNumber < 999) {
                            it.number = '一百+'
                        }
                    }
                })
                _self.setData({
                    isRefreshing: false,
                    isLoadMore: false,
                    posterTempleteList: res.data
                })
            })
            .catch(err => {
                console.log(err)
                _self.setData({
                    isRefreshing: false,
                    isLoadMore: false
                })
            })
    },
    //获取收藏的列表
    getFavorList() {
        var _self = this
        _self.setData({
            posterTempleteList: []
        })
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get(app.urls.getPosterFavorList, {
                header: {
                    token: app.globalData.token
                }
            })
            .then(res => {
                wx.hideLoading({})
                _self.setData({
                    isRefreshing: false,
                    isLoadMore: false,
                    posterTempleteList: res.data
                })
            })
            .catch(err => {
                _self.setData({
                    isRefreshing: false,
                    isLoadMore: false
                })
            })
    },

    //获取历史发布列表
    getHistoryList() {
        var _self = this
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get(app.urls.getPosterHistory, {
                header: {
                    token: app.globalData.token
                },
                data: {
                    mode: '2',
                    templateType: _self.data.curTypeId == '2' ? '' : _self.data.curTypeId
                }
            })
            .then(res => {
                wx.hideLoading({})
                _self.setData({
                    posterHistoryList: res.data,
                    isRefreshing: false,
                    isLoadMore: false
                })
            })
            .catch(err => {
                _self.setData({
                    isLoadMore: false,
                    isRefreshing: false
                })
                console.log(err)
            })
    },
    onReachBottom() {
        // this.loadMore()
    },
    onChange(e) {
        var _self = this
        if (_self.data.currentIndex != 0) {
            var tempItem = {
                dataName: '我的收藏',
                dataId: '1'
            }
            _self.data.optionsList.push(tempItem)
        } else {
            _self.data.optionsList.splice(_self.data.optionsList.length - 1, 1)
        }
        _self.setData({
            optionsList: _self.data.optionsList
        })
        _self.setData({
            currentIndex: e.detail.index
        })
        //重置所有数据重新加载
        _self.dorefreshList()
    },
    //去创建海报
    toCreate(e) {
        var id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/packagecard/marketing/marketingpublish?posterId=' + id
        })
    },
    //编辑海报
    toEdit(e) {
        var id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/packagecard/marketing/posteredit?id=' + id,
        })
    },
    // 生成随机id
    buildId: function () {
        var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

        var nums = "";

        for (var i = 0; i < 36; i++) {
            var id = parseInt(Math.random() * 61);

            nums += chars[id];
        }
        return nums
    },
    //隐藏弹框
    onClose(e) {
        this.setData({
            isShowSel: false
        })
    }
})