require('./index.less');
require('@lib/toast/dui-toast');
import { compileRender } from './js/template';
import { getUrlParameter } from "@js/tooler";
import { debounce } from './js/utils';
import { get, post } from "@js/request";

const tplElement = {
    main: $('#tpl_main').html(),
}

const API = {
  h5info: '/kjy/mp/content/h5info',
  showCard: '/kjy/mp/seller/showCard',
  contentRead: '/kjy/mp/content/read',
  contentSharedNumIncrease: '/kjy/mp/seller/contentSharedNumIncrease',
  getOaJssdk: '/kjy/mp/seller/getOaJssdk',
  updateDuration: '/kjy/mp/content/updateDuration'
}
const SCID = getUrlParameter('scid');
const FROM = getUrlParameter('from');
const currentView = getUrlParameter('currentView');
function wxInit(){
    let sellerName = contentData.sellerCardVO.sellerName;
    get(API.getOaJssdk, {
        url: window.location.href
    }).then(res => {
        // alert(JSON.stringify(res));
        if(res.success){
            var data = res.data;
            wx.config({
                debug: false,//生产环境需要关闭debug模式
                appId: data.appid,//appId通过微信服务号后台查看
                timestamp: data.timestamp,//生成签名的时间戳
                nonceStr: data.noncestr,//生成签名的随机字符串
                signature: data.sign,//签名
                jsApiList: [//需要调用的JS接口列表
                    'checkJsApi',//判断当前客户端版本是否支持指定JS接口
                    'onMenuShareTimeline',//分享给好友
                    'onMenuShareAppMessage'//分享到朋友圈
                ]
            });
        }
            
    })
    wx.ready(function () {
        var link = window.location.href;
        var title = contentData.title;
        var desc = '来自' + sellerName +　'的分享';
        var img = contentData.mainImgUrl;
        /*
        //分享朋友圈
        wx.updateTimelineShareData({ 
            title: contentData.title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: contentData.mainImgUrl, // 分享图标
            success: function () {
              // 设置成功
            }
        })
        //分享给好友
        wx.updateAppMessageShareData({ 
            title: contentData.title, // 分享标题
            desc: '来源于销售' + sellerName, // 分享描述
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: contentData.mainImgUrl, // 分享图标
            success: function () {
              // 设置成功
            }
        })
        */
        
        
        //分享朋友圈
        wx.onMenuShareTimeline({
            title: title,
            link: link,
            imgUrl: img,// 自定义图标
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                //alert('click shared');
            },
            success: function (res) {
                //alert('shared success');
                //some thing you should do
            },
            cancel: function (res) {
                //alert('shared cancle');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
        //分享给好友
        wx.onMenuShareAppMessage({
            title: title, // 分享标题
            desc: desc, // 分享描述
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: img, // 自定义图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        
        // wx.error(function (res) {
        //     alert(res.errMsg);
        // });
        
    });
}


let isHideCard = false;
let contentData = {};
let isInMiniProgram = true;

(function () {
    const Main = {
        init() {
            this.getArticleContent();
            this.bindEvents();
            this.sendReadMsg();
            this.updateReadeTime();
            // 剪贴板
            var clipboard = new Clipboard('.J_Copy');
            clipboard.on('success', function (e) {
                $.toast({
                    hideTime: 2000,
                    type: 'success',
                    content: '内容已复制'
                })
            });
            clipboard.on('error', function (e) {
                $.toast({
                    hideTime: 2000,
                    type: 'warn',
                    content: '请手动复制'
                })
            });            
        },
        visitId: null,
        times: 1,
        getArticleContent() {
            const self = this;
            get(API.h5info, {
                scid: SCID
            }).then(res => {
                if (res.success) {
                    contentData = res.data;
                    contentData.isInMiniProgram = false;
                    if (currentView) {
                        contentData.isInMiniProgram = true
                    }
                    if (contentData.type == 'article') {
                        document.title = '资讯详情';
                    }
                    $("head").append(contentData.head);
                    compileRender(contentData, tplElement.main, $('#db-content'));
                    if (contentData.showCard) {
                        $('#J_card').show();
                        $('.dui-footer__card').show();
                        $('.switch-anim').prop("checked", true);
                        $('.card-visible__control p').text('显示名片');
                    } else {
                        $('#J_card').hide();
                        $('.dui-footer__card').hide();
                        $('.switch-anim').prop("checked", false);
                        $('.card-visible__control p').text('显示名片');
                    }
                    if (FROM == 'singlemessage' && contentData.myself == 1) {
                        $('.dui-share__methods').show();
                        $('.share-wrap').hide();
                        $('.share-yindao').show();
                        $('.gudide-des').show();
                    }
                    wxInit();
                } else {
                    if (res.code == '100010') {
                      this.getH5Authorize()
                    } else if (res.code == '100020') {
                    //   contentData = {invalid: true};
                      window.location.href = '/error';
                      compileRender(contentData, tplElement.main, $('#db-content'));
                    }
                }
            })
        },
        updateShareTimes () {
            get(API.contentSharedNumIncrease, {contentId: contentData.id}).then(res => {

            });
        },
        updateReadeTime () {
            this.times = this.times +1;
            if (this.visitId) {
                get(API.updateDuration, {visitId: this.visitId});
            }
            setTimeout(() => {
                if (this.times < 360) {
                    this.updateReadeTime();
                }
            }, 5000);
        },
        getH5Authorize () {
            let url = '/kjy/authorize/wxh5base?uri=/kjy/mp/contentview?scid=' + SCID;
            window.location.href = url;
        },
        bindEvents() {
            let self = this;
            $('#db-content').on('change', '.switch-anim', function() {
                if ($('.switch-anim').prop('checked')){
                    console.log("选中");
                    $('.card-visible__control p').text('显示名片');
                    $('#J_card').show();
                    $('.dui-footer__card').show();
                    contentData.showCard = 1;                    
                } else {
                    console.log("没选中");
                    $('.card-visible__control p').text('显示名片');
                    $('#J_card').hide();
                    $('.dui-footer__card').hide();
                    contentData.showCard = 0;                       
                }
                get(API.showCard, {scid: SCID, showCard: contentData.showCard}).then(res => {

                })                
            })
            $('#db-content').on('click', '.dui-footer__btn', function () {
                // let wxQrcode = '';
                // dbAjax('GET', API.h5info, {
                //     scid: SCID
                // }).then(res => {
                //     if (res.success) {
                //         let data = res.data.sellerCardVO;
                //         wxQrcode = data.wechatQrCode;
                //         if (!wxQrcode) {
                //             $('.intercept__modal').show();
                //         } else {
                //             // $('.dui-share__methods').show();
                //             // $('.share-wrap').show();
                //             // self.updateShareTimes();
                //             wx.miniProgram.navigateTo({url: '/pages/share/main?scid=' + SCID});
                            
                //         }
                //     } else {
                //         // $('.dui-share__methods').show();
                //         // $('.share-wrap').show();
                //         // self.updateShareTimes();
                //         wx.miniProgram.navigateTo({url: '/pages/share/main?scid=' + SCID});
                        
                //     }
                // });
                debounce(500, () => {
                    self.updateShareTimes();
                    wx.miniProgram.navigateTo({url: '/pages/share/main?scid=' + SCID});
                });
            });
            $('#db-content').on('click', '.J_pengyouquan', function () {
                wx.miniProgram.navigateTo({url: '/pages/share/main?scid=' + SCID});
            })
            $('#db-content').on('click', '.J_weixin', function () {
                $('.share-yindao').show();
                $('.gudide-des').show();
                $('.share-wrap').hide();
            });
            $('#db-content').on('click', '.share-wrap', function (event) {
                event.stopPropagation(); // 阻止事件向上冒泡;
                return false;
            });             
            $('#db-content').on('click', '.dui-share__methods', function (event) {
                var o = $(event.target).parents(".share-wrap");
                if(o.length){
                    return;
                 }
                $('.dui-share__methods').hide();
                $('.share-yindao').hide();
                $('.gudide-des').hide();
            });             
            $('#db-content').on('click', '.close', () => {
                $('.dui-share__methods').hide();
                $('.share-yindao').hide();
                $('.gudide-des').hide();
            });
            $('#db-content').on('click', '.modal__container .close',() => {
                $('.seller-info__modal').hide();
            });
            $('#db-content').on('click', '.dui-card__wrap',() => {
                $('.seller-info__modal').show();
            });
            $('#db-content').on('click', '.J_complete', () => {
                // 完善名片信息
                let sellerId = contentData.sellerCardVO.id;
                if (sellerId) {
                    wx.miniProgram.navigateTo({url: '/pages/sellercard/card_edit/main?sellerId=' + sellerId});
                    $('.intercept__modal').hide();
                } else {
                    $('.intercept__modal').hide();
                }
            });
            $('#db-content').on('click', '.J_close', () => {
                // 完善名片信息
                $('.intercept__modal').hide();
            });            
        },
        // 查看文章
        sendReadMsg() {
            const self = this;
            get(API.contentRead, {
                scid: SCID
            }).then(res => {
                if (res.success) {
                    self.visitId = res.data.visitId;
                }
            })            
        }
    }
    Main.init();
    // new FastClick(document.body);
})();