import { tpl, itemTpl } from './liveTpl';
import { Messager } from '@core/component/msgDistribute';
import PageTable from '@core/component/pageTable';
import {fetch} from '@core/component/httpClient';
import ShortPagination from '@core/component/shortPagination';
import Message from '@core/component/message';
import './liveStyle.scss';
import domain from "@core/util/domain";
import LinkTool from "../index";
const Live = (($) => {
    const DefaultConfig = {
    };
    class Live {
        constructor(config) {
            this._config = this._getConfig(config);
            this.el = this._config.node;
            this.$el = $(this.el);
            this._render();
            this._addEvent();
            let linkObj = this._config.linkObj;
            this.liveId = '';
            if(linkObj && linkObj.originalData){
                this.liveId = linkObj.originalData; 
                this.queryLiveData(this.liveId);
            }
        }
        
        _getConfig(config) {
            return $.extend(true, {}, DefaultConfig, config);
        }
        
        _render() {
            let html = template.render(tpl, this._config);
            this.$el.html(html);
            this.pageTable = new PageTable({
                node: this.$el.find('.J_table')[0],
                theadRenderer: ['直播ID', '直播标题', '直播封面图', '直播时间', '直播状态'],
                itemRenderer: itemTpl,
                pageSize: 5,
                columnWidth: ["20%", "20%", "25%", "25%", '10%'],
                fixedThead: true,
                frontEndPaging: true,
                pagination: ShortPagination,
                onDomReady: ($node) => {
                },
                onPageChange: (data) => {
                },
                onDomUpdate: this._config.onDomUpdate
            });
        }
        
        _addEvent() {
            let _config = this._config;
            
            this.linkChangeKey = Messager.on('linkChange', (req, res) => {
                if(res.originalData){
                    this.liveId = res.originalData;
                }
                this.$el.find('[' + _config.linkAttr + ']').each(function() {
                    let val = $(this).attr('data-original-data');
                    if (val === res.originalData) {
                        this.checked = true;
                    } else {
                        this.checked = false;
                    }
                })
            })
            
            this.$el.on('change', '[' + _config.linkAttr + ']', function() {
                let $item = $(this);
                let link = $item.attr(_config.linkAttr);
                let linkType = LinkTool.Type.Live;
                let originalData = $item.attr(_config.originalDataAttr);
                let liveImage = $item.attr('data-img');
                Messager.trigger('linkChange', { link, linkType, originalData, liveImage });
            })
            
            this.$el.on('click', '.J_search', ()=>{
                this.onSearch();
            });
            this.$el.on('click', '.J_restore', () => {
                this.$el.find('.J_liveId').val('');
                if(this.liveId){
                    this.queryLiveData(this.liveId);
                }
                else{
                    this.updateTab([]);
                }
            });
            
            this.$el.on('click.liveLink', '.J_ok', async () => {
                Messager.trigger('confirm');
            })
            
            this.$el.on('click.liveLink', '.J_cancel', function() {
                Messager.trigger('cancel');
            })
        }
        
        async queryLiveData(liveId){
            if(liveId){
                let data = await fetch({
                    url: `${domain.backend}/mshop/project/queryLiveShowInfo`,
                    data: {
                        liveId:liveId
                    },
                    dataType: 'jsonp',
                });
                if(data && data.success && data.data){
                    let _list = [];
                    if(data.data.liveId){
                        _list = [data.data];
                        this.updateTab(_list);
                    }
                    else{
                        Message.error('没有搜索到对应的直播数据');
                    }
                }
            }
        }
        async onSearch(){
            let liveId = this.$el.find('.J_liveId').val().trim();
            if(liveId){
                liveId = parseInt(liveId);
                if(isNaN(liveId)){
                    Message.error('输入的直播ID格式错误，不是纯数字类型');
                }
                else{
                    this.$el.find('.J_liveId').val(liveId);
                    await this.queryLiveData(liveId);
                }
            }
            else{
                Message.error('请输入直播ID');
            }
        }
        
        updateTab(list){
            if(!list){
                list = [];
            }
            if(this.pageTable){
                this.pageTable.update({
                    loading:false,
                    totalItem:list.length,
                    dataProvider:list
                });
            }
        }
        
        dispose() {
            Messager.off(this.linkChangeKey);
            this.$el.off();
        }
    }
    return Live;
})($);
export default Live;