"use strict";

import httpRequestApi from '../../utils/APIClient';

Component({
    options: {
        addGlobalClass: true,
        pureDataPattern: /^_/
    },
    properties: {
        showMyBtn: {
            type: Boolean,
            value: false
        },
        ifHeadTap: {
            type: Boolean,
            value: true
        },
        isSwiper: {
            type: Boolean,
            value: true
        },
        noMoreWork: {
            type: Boolean,
            value: false
        },
        duration: {
            type: Number,
            value: 500
        },
        easingFunction: {
            type: String,
            value: 'easeInOutCubic' // easeInCubic 缓入 easeOutCubic 缓出  easeInOutCubic 缓入缓出 default linear
        },
        loop: {
            type: Boolean,
            value: true
        },
        videoList: {
            type: Array,
            value: [],
            observer: function observer() {
                console.log('数据更新111111', arguments)
                let newValue = arguments[0];
                let oldValue = arguments[1];
                if (newValue && oldValue && (this.data.activeIndex || this.data.activeIndex === 0)) {
                    let newVideoShow = newValue[this.data.activeIndex].videoShow;
                    let oldVideoShow = oldValue[this.data.activeIndex].videoShow;
                    if (newVideoShow !== oldVideoShow && oldVideoShow) {
                        console.log('把值设置为true')
                        newValue[this.data.activeIndex].videoShow = true;
                        this.setData({
                        })
                    }
                }
                let newVal = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
                this.updateSonList(newVal);
            }
        },
        nextMargin: {
            type: String,
            value: '400rpx'

        }
    },
    data: {
        sonVideoList: [], // 子组件里的视频组件
        activeType: '',
        nextQueue: [],
        prevQueue: [],
        curQueue: [],
        circular: false,
        // nextMargin: '400rpx',
        _last: 0,
        // _last: 1,
        _change: -1,
        _invalidUp: 0,
        _invalidDown: 0,
        _videoContexts: [],
        inputValue: '',
        showControl: 0,
        flowerNum: 0
    },
    lifetimes: {
        attached: function attached() {
            this.data._videoContexts = [wx.createVideoContext('video_0', this), wx.createVideoContext('video_1', this), wx.createVideoContext('video_2', this)];
        }
    },
    /*     observers: {
            '**': function() {
              // 每次 setData 都触发
              console.log('数据更新333333',this.data)

            },
          }, */
    methods: {
        _videoListChanged: function _videoListChanged(newVal) {
            var _this = this;

            var data = this.data;
            console.log('newVal', newVal)
            newVal.forEach(function (item) {
                data.nextQueue.push(item);
            });
            if (data.curQueue.length === 0) {
                this.setData({
                    curQueue: data.nextQueue.splice(0, 3)
                }, function () {
                    _this.playCurrent(1);
                    // _this.playCurrent(0);
                });
            }
        },
        updateSonList: function updateSonList(newVal) {
            this.setData({
                sonVideoList: newVal,
                activeIndex: ''
            })
        },
        animationfinish: function animationfinish(e) {
            var _data = this.data,
                _last = _data._last,
                _change = _data._change,
                curQueue = _data.curQueue,
                prevQueue = _data.prevQueue,
                nextQueue = _data.nextQueue;

            var current = e.detail.current;
            var diff = current - _last;
            if (diff === 0) return;
            this.data._last = current;
            this.playCurrent(current);
            this.triggerEvent('change', {
                activeId: curQueue[current].id,
                // index: current,
                // _last,
                // nextQueue,
            });
            var direction = diff === 1 || diff === -2 ? 'up' : 'down';
            if (direction === 'up') {
                if (this.data._invalidDown === 0) {
                    var change = (_change + 1) % 3;
                    var add = nextQueue.shift();
                    var remove = curQueue[change];
                    if (add) {
                        prevQueue.push(remove);
                        curQueue[change] = add;
                        this.data._change = change;
                    } else {
                        this.data._invalidUp += 1;
                    }
                } else {
                    this.data._invalidDown -= 1;
                }
            }
            if (direction === 'down') {
                if (this.data._invalidUp === 0) {
                    var _change2 = _change;
                    var _remove = curQueue[_change2];
                    var _add = prevQueue.pop();
                    if (_add) {
                        curQueue[_change2] = _add;
                        nextQueue.unshift(_remove);
                        this.data._change = (_change2 - 1 + 3) % 3;
                    } else {
                        this.data._invalidDown += 1;
                    }
                } else {
                    this.data._invalidUp -= 1;
                }
            }
            var circular = true;
            if (nextQueue.length === 0 && current !== 0) {
                circular = false;
            }
            if (prevQueue.length === 0 && current !== 2) {
                circular = false;
            }
            this.setData({
                curQueue: curQueue,
                circular: circular
            });
        },
        playCurrent: function playCurrent(current) {
            console.log('playCurrent', current)
            // return; // 注掉自动播放
            this.data._videoContexts.forEach(function (ctx, index) {
                index !== current ? ctx.pause() : ctx.play();
            });
        },
        onPlay: function onPlay(e) {
            console.log('播放记录', e)
            httpRequestApi.playLogReport({
                userReadId: e.currentTarget.dataset.id,
                playStopTime: 1000
            }).success(res => {
                console.log('播放记录', res)
            })
            // this.trigger(e, 'play');
        },
        onPlayList: function onPlayList(e) {
            console.log('lastVideoId', this.data.lastVideoId);
            console.log('lastVideoId', e);
            httpRequestApi.playLogReport({
                userReadId: e.target.dataset.id,
                playStopTime: 1000
            }).success(res => {
                console.log('播放记录', res)
            })
            if (this.data.lastVideoId && e.target.id !== this.data.lastVideoId) {
                const lastVideo = wx.createVideoContext(this.data.lastVideoId, this)
                lastVideo.stop();
                this.setData({
                    lastVideoId: e.target.id
                })
            }
            if (!this.data.lastVideoId) {
                this.setData({
                    lastVideoId: e.target.id
                })
            }
            this.triggerEvent('onPlay')
        },
        onPause: function onPause(e) {
            this.trigger(e, 'pause');
        },
        onEnded: function onEnded(e) {
            console.log('播放结束', e)
            // this.trigger(e, 'ended');
        },
        onError: function onError(e) {
            console.log('视频出错', e)
            // this.trigger(e, 'error');
        },
        onTimeUpdate: function onTimeUpdate(e) {
            this.trigger(e, 'timeupdate');
        },
        onWaiting: function onWaiting(e) {
            this.trigger(e, 'wait');
        },
        onProgress: function onProgress(e) {
            this.trigger(e, 'progress');
        },
        onLoadedMetaData: function onLoadedMetaData(e) {
            this.trigger(e, 'loadedmetadata');
        },
        onTimeUpdate: function onTimeUpdate(e) {

        },
        openComment: function openComment(e) {
            console.log(e)
            let index = e.currentTarget.dataset.index;
            this.setData({
                activeIndex:index
            })
            this.trigger(e, 'openComment')
        },
        // 展示视频
        showVideo: function showVideo(e) {
            let index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
            console.log('showVideo')
            const str = `sonVideoList[${index}].videoShow`;
            if (this.data.lastIndex || this.data.lastIndex === 0) {
                const lastStr = `sonVideoList[${this.data.lastIndex}].videoShow`;
                this.setData({
                    lastIndex: index,
                    [lastStr]: false,
                    [str]: true
                })
            } else {
                this.setData({
                    lastIndex: index,
                    [str]: true
                })
            }

        },
        // 点击头部
        headTap: function headTap(e) {
            if (!wx.getStorageSync('user').wechatName) {
                wx.navigateTo({
                    url: `../../pages/login/login`
                });
                return;
            }
            let uid = e.target.dataset.uid ? e.target.dataset.uid : e.currentTarget.dataset.uid;
            // this.trigger(e, 'headTap')
            console.log('点击头像', e)
            wx.navigateTo({
                url: `../../pages/myworks/myworks?uid=${uid}`,
                fail: (err) => {
                    console.log('跳转错误', err)
                    wx.navigateTo({
                        url: `../../../pages/myworks/myworks?uid=${uid}`
                    });
                }
            });

        },
        // 去朗读
        goToReading: function goToReading(e) {
            this.trigger(e, 'goToReading')
        },
        // 收藏课程
        collectTap: function collectClass(e) {
            if (!wx.getStorageSync('user').wechatName) {
                wx.navigateTo({
                    url: `../../pages/login/login`
                });
                return;
            }
            console.log('收藏按钮', e);
            const data = {
                targetCode: e.target.dataset.id ? e.target.dataset.id : e.currentTarget.dataset.id,
                favoritesType: e.target.dataset.type ? e.target.dataset.type : e.currentTarget.dataset.type
            }
            const index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
            this.setData({
                activeIndex:index
            })
            console.log('视频index', index);
            if (this.data.curQueue.length <= 0) {
                let str = `videoList[${index}].isFavorite`
                httpRequestApi.collectClass(data).success((res) => {
                    let isCollect = res.data.data.status === 'NORMAL' ? true : false;
                    // this.setData({
                    //     [str]: isCollect
                    // })
                    if (res.data.count > 0) {
                        this.setData({
                            flowerNum: res.data.count
                        })
                        this.flowerAnimationHandler();
                    }
                    this.triggerEvent('collectTap', {
                        index,
                        isCollect
                    })
                });

            } else {
                let str = `curQueue[${index}].isFavorite`;
                let str2 = `curQueue[${index}].favoritesAmount`
                httpRequestApi.collectClass(data).success((res) => {
                    console.log('收藏数', this.data.curQueue[index].favoritesAmount)
                    this.setData({
                        [str]: !this.data.curQueue[index].isFavorite,
                        [str2]: res.data.data.status === 'NORMAL' ? this.data.curQueue[index].favoritesAmount + 1 : this.data.curQueue[index].favoritesAmount - 1
                    })
                });
            }

        },
        // 点赞
        likeTap: function likeTap(e) {

            if (!wx.getStorageSync('user').wechatName) {
                wx.navigateTo({
                    url: `../../pages/login/login`
                });
                return;
            }
            const isLike = e.target.dataset.islike ? e.target.dataset.islike : e.currentTarget.dataset.islike;
            console.log('isLike', isLike)
            if (isLike) {
                return;
            }
            const id = e.target.dataset.id ? e.target.dataset.id : e.currentTarget.dataset.id;
            const index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
            this.setData({
                addComeOut: index,
                activeIndex: index,
                activeType: 'like'
            })
            setTimeout(() => {
                if (this.data.addComeOut) {
                    this.setData({
                        addComeOut: ''
                    })
                }
            }, 1100)
            console.log('视频index', index);
            if (this.data.isSwiper) {
                let likeStr = `curQueue[${index}].isLike`;
                let likeNumStr = `curQueue[${index}].likes`;
                httpRequestApi.likeWorks(id).success((res) => {
                    this.setData({
                        [likeStr]: true,
                        [likeNumStr]: this.data.curQueue[index].likes + 1
                    })
                });
            } else {
                let likeStr = `videoList[${index}].isLike`;
                let likeNumStr = `videoList[${index}].likes`;
                httpRequestApi.likeWorks(id).success((res) => {
                    console.log('小红花个数', res.data.count)
                    if (res.data.count > 0) {
                        this.setData({
                            flowerNum: res.data.count
                        })
                        this.flowerAnimationHandler();
                    }
                    this.triggerEvent('likeTap', {
                        index,
                    })
                });
            }
        },
        addShareAmount: function (e) {
            console.log('+++++1', e.detail.index);

            this.triggerEvent('addShareAmount', {
                index: e.detail.index
            })
        },
        // 下载视频
        download: function (e) {
            // console.log(e.currentTarget.dataset)
            wx.showLoading({
                title: '保存到本地',
                mask: true
            })
            const {
                url
            } = e.currentTarget.dataset;
            wx.downloadFile({
                url,
                success(res) {
                    // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                    if (res.statusCode === 200) {
                        console.log(res.tempFilePath)
                        wx.saveVideoToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success(res) {
                                wx.hideLoading()
                                wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 2000,
                                    mask: true
                                })
                            },
                            fail(error) {
                                console.log(error)
                            }
                        })
                    }
                },
                fail() {
                    wx.hideLoading()
                    wx.showToast({
                        title: '网络不给力',
                        icon: 'error',
                        duration: 2000,
                        mask: true
                    })
                }
            })
        },
        delete: function (e) {
            console.log('删除', e)
            wx.showModal({
                title: '确认删除吗？',
                content: '作品将被永久删除，无法找回。',
                confirmText: '确认',
                cancelText: '取消',
                success: (res) => {
                    if (res.confirm) {
                        /* let data = {
                            id: e.currentTarget.dataset.id,
                            status: status === 'NORMAL' ? 'DISABLE' : 'NORMAL'
                        }
                        httpRequestApi.putWork(data).success(res => {
                            console.log('已隐藏', res)
                            this.triggerEvent('delHideMyWork');
                        }) */
                        let data = {
                            id: e.currentTarget.dataset.id,
                            status: 'DEL'
                        }
                        httpRequestApi.putWork(data).success(res => {
                            console.log('已删除', res)
                            this.triggerEvent('delHideMyWork');
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        },
        hide: function (e) {
            console.log('隐藏', e)
            const status = e.currentTarget.dataset.status ? e.currentTarget.dataset.status : e.target.dataset.status
            console.log('当前状态', status)
            let data = {
                id: e.currentTarget.dataset.id,
                status: status === 'NORMAL' ? 'DISABLE' : 'NORMAL'
            }
            httpRequestApi.putWork(data).success(res => {
                console.log('已隐藏', res)
                if (res.data.data.status === 'DISABLE') {
                    wx.showToast({
                        title: '该作品仅自己可见',
                        icon: 'none',
                        duration: 2000
                    })
                }

                this.triggerEvent('delHideMyWork');
            })
        },
        openShare: function (e) {
            this.triggerEvent('openShare', e)
            const obj = e.currentTarget.dataset
            const scene = obj.activity ? `${obj.id}&activity=true` : obj.id
            this.shareDialog = this.selectComponent("#share-dialog");
            const data = {
                avatar: obj.avatar,
                author: obj.author,
                iconImg: obj.iconImg,
                title: obj.title,
                path: `pages/index/index`,
                scene,
                type: obj.type,
                grade: obj.grade,
                productId: 1,
                shareImg: obj.shareImg,
                index: obj.index,
                activity: obj.activity || ''
            }
            this.setData({
                noScroll: 'noScroll'
            })
            this.shareDialog.share(data);
            // this.shareDialog.shareFriend();
        },
        flowerAnimationHandler: function () {
            this.flowerBox = this.selectComponent("#flower-toast");
            console.log('this.flower', this.flowerBox)
            this.flowerBox.comeOut();
        },
        trigger: function trigger(e, type) {
            if (!wx.getStorageSync('user').wechatName) {
                wx.navigateTo({
                    url: `../../pages/login/login`
                });
                return;
            }
            var ext = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

            // var detail = e.detail;
            var activeId = e.target.dataset.id ? e.target.dataset.id : e.currentTarget.dataset.id;
            var activeIndex = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
            this.triggerEvent(type, {
                activeId: activeId,
                activeIndex: activeIndex
            }, {
                bubbles: false
            });
            /*   this.triggerEvent(type, Object.assign(Object.assign(Object.assign({}, detail), {
                  activeId: activeId
              }), ext)); */
        }
    }
});
