//import styleInvite   from 'render/style.js';
import styleInvite from 'render/styleInvite.js'
import { tplInvite } from 'render/tplfn.js'
import Layout from './engine.js'

let selfOpenId = ''
let sharedCanvas = wx.getSharedCanvas()
let sharedContext = sharedCanvas.getContext('2d')

function drawInviteUI(data = [], self) {
    Layout.clearAll()
    let template = tplInvite({
        data,
        self
    })
    Layout.init(template, styleInvite)
    Layout.layout(sharedContext)
}

/**
 * 如果用户之间存在主动分享邀请记录，会通过jsserver写入key为invite的记录
 * 这里把邀请记录拉下来筛选出我的邀请成功记录
 */
function getInviteData(selfOpenId) {
    return new Promise((resolve, reject) => {
        wx.getFriendCloudStorage({
            keyList: ['invite'],
            success: ({ data }) => {
                console.log('getFriendCloudStorage', data)
                data = data.filter(item => item.KVDataList && item.KVDataList.length)
                let result = []

                let self = data.find(item => item.openid === selfOpenId)
                let selfData

                try {
                    selfData = self && self.KVDataList && self.KVDataList[0] && self.KVDataList[0].value && JSON.parse(self.KVDataList[0].value)
                } catch (e) {
                    console.error(e)
                    selfData = null
                }

                if (selfData) {
                    result = data.filter(item => selfData.inviteRecords.find(r => r.openid === item.openid))
                }

                resolve(result)
            }
        })
    })
}

function showPotentialFriend() {
    wx.getPotentialFriendList({
        success: data => {
            let list = data.list || []
            list = list.slice(0, 4)
            console.log('getPotentialFriendList', data)

            let friends = list.map((item, i) => {
                return {
                    nickname: compact(item.nickname),
                    avatarUrl: item.avatarUrl,
                    openid: item.openid
                }
            })
            console.log(friends)
            drawInviteUI(friends)

            Layout.getElementsByClassName('inviteBtn').forEach((item, index) => {
                item.on('click', e => {
                    console.log(`click${index}`)
                    // wx.shareMessageToFriend({
                    //     openId: friends[index].openid,
                    //     title: '点一下，玩一年，装备不花一分钱！',
                    //     imageUrl: 'https://mmocgame.qpic.cn/wechatgame/04rHy004qSjwKC0xBycMOJzAKQC8TP8TmxXbrm80fkW2B0uGAKhv2M1oVVhdPAbk/0',
                    //     imageUrlId: 'VP8NAzQRRAGHQY4RYX945A=='
                    // })
                })
            })
        }
    })
}

function compact(name) {
    if (name.length <= 4) {
        return name
    } else {
        return name.slice(0, 4) + '···'
    }
}

function updateData(data) {
    let value = JSON.stringify({
        wxgame: {
            score: parseInt(data.score),
            update_time: new Date().getTime()
        },
        scene: data.scene
    })
    wx.setUserCloudStorage({
        KVDataList: [{ key: 'rank', value: value }],
        success: res => {
            console.log('setUserCloudStorage', res)
        }
    })
}

function receiveInvite() {
    wx.modifyFriendInteractiveStorage({
        // 这里定义key“2”代表邀请玩家的数量
        key: '2',
        opNum: 1,
        operation: 'add',
        // 静默修改需要用户通过快捷分享消息卡片进入才有效，代表分享反馈操作，无需填写 toUser，直接修改分享者与被分享者交互数据
        quiet: true,
        complete: res => {
            console.log('modifyFriendInteractiveStorage', res)
        }
    })
}

wx.onMessage(data => {
    switch (data.type) {
        case 'updateViewPort':
            Layout.updateViewPort(data.box)
            break
        case 'showInviteUI':
            showPotentialFriend()
            break
        case 'hideInviteUI':
            Layout.clearAll()
            break
        case 'post':
            updateData(data)
            break
        case 'receiveInvite':
            receiveInvite()
            break
    }
})
