import { tpl, tbodyTpl, subOptionsTpl } from './miniAppTpl';
import { Messager } from '@core/component/msgDistribute';
import ScrollList from '@core/component/scrollList';
import {fetch} from '@core/component/httpClient';
import Message from '@core/component/message';
import LinkTool from '../../linkTool';
import Domain from '@core/util/domain';
const MiniApp = (($) => {
    const DefaultConfig = {
        tpl,
        tbodyTpl,
    };
    class MiniApp {
        constructor(config) {
            const hasSubOptionsChannelKey = ['che93be1ff3e3197f0'];     
            this._config = this._getConfig(config);
            this.el = this._config.node;
            this.$el = $(this.el);
            let html = template.render(this._config.tpl, this._config);
            this.$el.html(html);
            this.ScrollList  = new ScrollList({
                node: this.$el.find('.J_table')[0],
                className: "cd-mytable",
                itemRenderer: this._config.tbodyTpl,
                loading: true,
                needStringify: true,
                pageSize:10,
                queryOptions: {
                    url: Domain.backend + '/mshop/miniApp/queryMiniAppInfos',
                    data:{
                        isLinkTool:true
                    },
                    contentType: 'application/json; charset=UTF-8'
                },
                renderContentBefore:(data)  =>  {
                    data && data.map((item) => {
                        item.hasSubOptions = hasSubOptionsChannelKey.includes(item.channelKey);
                        const url = `${window.location.protocol}//conecli.com/apps/mpshare/index.html?category=jump&des=jdmp&vapptype=1&appId=${item.appId}`;
                        item.qrcode = '//conecli.com/public/qrimg?url=' + encodeURIComponent(url) + '-200-1-4-2.png';
                        return item;
                    });
                },
                onDomUpdate: this._config.onDomUpdate
            })
            this._addEvent();
        }
        
        _addEvent() {
            let _this = this;
            
            function getMiniAppPageData(miniAppId){
                return fetch({
                    url: Domain.backend + '/mshop/miniApp/queryMiniAppPage',
                    method: 'GET',
                    data: {
                        miniAppId
                    }
                });
            }
            
            this.linkChangeKey = Messager.on('linkChange', (req, res) => {
                if(!res.link){
                    return;
                }
                const chooseAppid = res.link.match(/appId=([^&]+)/)[1];
                this.$el.find('.J_rowItem').each(function() {
                    const { appid } = this.dataset;
                    if (appid === chooseAppid) {
                        let isFind = false;
                        $('[' + _this._config.linkAttr + ']', this).each(function() {
                            let val = $(this).attr(_this._config.linkAttr);
                            if (val === res.link) {
                                $(this).closest('.J_rowItem').addClass('active');
                                this.checked = true;
                                isFind = true;
                            } else {
                                this.checked = false;
                            }
                        });
                        if(isFind === false){
                            $(this).trigger('click', chooseAppid);
                        }
                    }
                })
            })
            
            this.$el.on('click.miniApp', '.J_secCate', function() {
                $(this).find('>input[type=radio]').trigger('change');
            })
            
            
            this.$el.on('dblclick.miniApp', '.J_secCate', function(e) {
                Messager.trigger('confirm');
                e.stopPropagation();
            })
            
            this.$el.on('click.miniApp', '.J_arrow', async function(e) {
                e.stopPropagation();
                const $row = $(this).closest('.J_rowItem');
                const hasLoadData = !!$(this).attr('data-loaded');
                if(!hasLoadData){
                    const appId = $(this).attr('data-appId');
                    const {success, data} = await getMiniAppPageData(appId);
                    if(success){
                        const htmlSubOptions = template.render(subOptionsTpl, {data});
                        $row.find('.J_cid').append(htmlSubOptions);
                        $(this).attr('data-loaded', true);
                    }
                    selectRow(this);
                }
                if ($row.is('.active')) {
                    $row.removeClass('active');
                } else {
                    selectRow($row[0])
                }
            })
            
            this.$el.on('click.miniApp', '.J_rowItem', async function(e, chooseAppid) {
                const $arrow = $(this).find('.J_arrow');
                const hasLoadData = !!$arrow.attr('data-loaded');
                if(!hasLoadData){
                    const appId = $arrow.attr('data-appId');
                    const {success, data} = await getMiniAppPageData(appId);
                    if(success){
                        const htmlSubOptions = template.render(subOptionsTpl, {data});
                        const $cid = $(this).find('.J_cid');
                        $cid.append(htmlSubOptions);
                        $arrow.attr('data-loaded', true);
                        if(chooseAppid){
                            $cid.find(`[data-appId=${chooseAppid}]`).trigger('click');
                        }
                    }
                    selectRow(this);
                }else{
                    selectRow(this);
                }
            })
            const EVENT_NAME = 'copy.linkToolMiniApp';
            $('body').off(EVENT_NAME).on(EVENT_NAME, function (e) {
                let cpTxt = $('body').data('linkToolMiniAppAppid') || '',
                    clipboardData = window.clipboardData || e.originalEvent.clipboardData; 
                if(cpTxt){
                    clipboardData.setData('Text', cpTxt);
                    $('body').data('linkToolMiniAppAppid', '');  
                    return false;
                }
            });
            
            this.$el.on('click', '.J_copyId', (e) => {
                e.stopPropagation();
                let dom = e.target;
                let { appid } = dom.dataset;
                $('body').data('linkToolMiniAppAppid', appid);  
                try {
                    if (document.execCommand('copy', false, null)) {
                        Message.success('复制小程序ID成功，请用ctrl＋V后粘贴即可');
                    } else {
                        Message.warn("该浏览器不支持复制，请手动选取复制");;
                    }
                } catch (err) {
                    Message.warn("该浏览器不支持复制，请手动选取复制");;
                }
            });
            
            this.$el.on('change.miniApp', '[' + _this._config.linkAttr + ']', function(e) {
                let $this = $(this);
                let link = $this.attr(_this._config.linkAttr);
                let originalData = $this.attr(_this._config.originalDataAttr);
                let linkType = LinkTool.Type.MiniApp;
                Messager.trigger('linkChange', { link, linkType, originalData });
                $(e.currentTarget).closest('.J_rowItem').find('.cd-qr-code').attr('src','//conecli.com/public/qrimg?url=' + encodeURIComponent(`${window.location.protocol}${link}`) + '-200-1-4-2.png');
            })
            
            this.$el.on('click.miniApp', '.J_ok', function() {
                Messager.trigger('confirm');
            })
            
            this.$el.on('click.miniApp', '.J_cancel', function() {
                Messager.trigger('cancel');
            })
            function selectRow(row) {
                let $row = $(row);
                $row.siblings().removeClass('active');
                $row.addClass('active');
            }
        }
        
        _getConfig(config) {
            return $.extend(true, {}, DefaultConfig, config);
        }
        
        _renderDom() {
            let config = this._config;
            let html = template.render(config.tpl, config);
            this.$el.html(html);
        }
        
        dispose() {
            Messager.off(this.linkChangeKey);
            this.$el.off('click.miniApp').off('linkChange.miniApp').off('change.miniApp')
        }
    }
    return MiniApp;
})($);
export default MiniApp;