import './tab.scss';
import BaseFormControl from '../../baseFormControl';
import { JDTabTpl, JDTabItemTpl } from './tabTpl';
import moment from 'moment';
import { CheckBox, Message, fetch, Modal, Confirm } from '@hot/pc-es-cn-shop-ui';
import JDInput from '../../formType/input';
import JDRadio from '../../formType/radio';
import JDBiConfig from '../../formType/biConfig';
import JDTabComponent from '../../formType/tab';
import JDDateRangeLine from '../../formType/dateRangeLine';
import Utils from '../../utils';
import ImageDom from '../../../imageDom/ImageDom';
import JDList from "./list";
import domain, {INTERFACE} from "../../../../util/domain";
import { ChannelType } from './../../../../util/channelUtil';
import DefaultDatasM from '../../DefaultDatasM';
class JDTab extends BaseFormControl {
    constructor(config) {
        super();
        this.BASE_PATH = domain.backend;
        this.tabModes = [{
            text: '文字类型',
            value: 1,
        }, {
            text: '图片类型',
            value: 2,
        }, {
            text: '时间类型',
            value: 3,
        }];
        this.config = this._getConfig(config);
        this.maxTabNum = 10;
        this.maxTabNumPC = 10;
        this.maxTabNumM_TXT = 4;
        this.maxTabNumM_TIME = 3;
        this.moduleData = this.config.moduleData;
        this.centerModules = this.config.centerModules;
        this.formContent = this.config.formContent;
        this.render();
    }
    
    _getConfig(config) {
        let tabType = 1;
        if(config.domData.extConfig){
            switch(config.domData.extConfig.category){
                case 'TAB_TIME':
                tabType = 3;
                break;
                case 'TAB_PICTURE':
                tabType = 2;
                break;
                default:
                tabType = 1;
                break;
            }
        }
        return $.extend(true, {}, {
            domData: {},
            moduleData: {
                tabType: tabType,
                configType: 0,
                tabItemList: [],
            },
            platForm: 'M',
            centerModules: [],
        }, config);
    }
    render() {
        this.setMaxTabNum();
        let typeChangeLabel = null;
        let $TabTplNode = template.render(JDTabTpl, {
            ...this.moduleData,
            platForm: this.config.platForm,
            maxTabNum: this.maxTabNum,
        });
        this.appendFormControl($TabTplNode);
        if (this.config.platForm === 'PC') {
            typeChangeLabel = 'Tab项配置';
            new JDTabComponent({
                domData: {
                    node: this.element.find('.J_tabCate'),
                    name: 'tabCate',
                    formType: {
                        option: this.tabModes,
                    },
                    validate: {
                        must: true,
                    },
                },
                defaultChecked: this.moduleData.tabType,
                change: (mode) => {
                    this.moduleData.tabType = parseInt(mode, 10);
                    this.setMaxTabNum();
                    this.formContent.find('#J_tab_content').attr('class', `cd-type-${this.moduleData.tabType} cd-isbi-${this.moduleData.configType}`);
                    if (this.moduleData.tabType === 3) {
                        this.formContent.find('.J_tabType .cd-body').hide();
                    } else {
                        this.formContent.find('.J_tabType .cd-body').show();
                    }
                    this.formContent.find('.J_max_tab_num').html(this.maxTabNum);
                    const tabItemList = this.formContent.find('#J_tab_content').find('.J_tabItem');
                    const tabItemNum = tabItemList.size();
                    if (tabItemNum > this.maxTabNum) {
                        tabItemList.map((index, tabItem) => {
                            if (index >= this.maxTabNum) {
                                $(tabItem).remove();
                            }
                        });
                    }
                    this.updateTabNum(this.formContent.find('.J_tab_formset'));
                    this.updateTabTextTitleNum();
                },
            });
        }
        let tempOption = [{
            text: '普通Tab',
            value: 0,
        }, {
            text: 'BI Tab',
            value: 1,
        }];
        if (this.config.projectType == ChannelType.YHD) {
            tempOption.pop();
        }
        let moduleType = this.config.moduleInfo.moduleType;
        if(this.config.platForm === 'M' && moduleType==99999 || window.page_data.isSDKM){
            tempOption = [{
                text: '普通Tab',
                value: 0,
            }]
        }
        if($('#J_IsYaoB2B').val() === 'true'){
            tempOption.pop();
        }
        new JDRadio({
            domData: {
                node: this.element.find('.J_tabType'),
                name: 'tabType',
                title: 'Tab项配置',
                dataType: 'JDT_radio',
                formType: {
                    type: 'radio',
                    option: tempOption,
                },
                validate: {
                    must: true,
                },
            },
            defaultChecked: this.moduleData.configType,
            change: (type) => {
                this.moduleData.configType = parseInt(type, 10);
                this.formContent.find('#J_tab_content').attr('class', `cd-type-${this.moduleData.tabType} cd-isbi-${this.moduleData.configType}`);
            },
        });
        this.renderTabContent(this.moduleData);
        this.addEvent();
    }
    setMaxTabNum() {
        if (this.config.platForm === 'PC') {
            this.maxTabNum = this.maxTabNumPC;
        } else {
            if (this.config.moduleData.tabType === 1) {
                this.maxTabNum = this.maxTabNumM_TXT;
            } else if (this.config.moduleData.tabType === 3) {
                this.maxTabNum = this.maxTabNumM_TIME;
            } else {
                this.maxTabNum = this.maxTabNumM_TXT;
            }
        }
    }
    async renderTabContent(moduleData) {
        if (this.config.platForm === 'M') {
            if(!this.centerModules || this.centerModules.length < 1){
                let data;
                if(window.page_data.isSDKM){
                    data = await fetch({
                        
                        url: INTERFACE.sdk.getTabModuleList,
                        data: {
                            templateId: window.page_data.templateId
                        },
                    });
                }
                else{
                    data = await fetch({
                        
                        url: this.BASE_PATH + '/mshop/edit/queryTabModuleList.json',
                        data: {
                            projectId: page_data.projectId,
                            pageId: window.page_data.mobilePageId,
                        },
                    });
                }
                if (data.code === 200) {
                    this.centerModules = data.data;
                }
            }
        }
        let $tabList = this.formContent.find('#J_tab_content');
        let tabElement = template.render(JDTabItemTpl, {
            ...moduleData,
            startIndex: $tabList.find('.J_tabItem').length,
        });
        $tabList.append(tabElement).find('.J_tabItem');
        $.each($tabList.find('.J_tabItem'), (index, item) => {
            this.renderForContentForText($(item));
        });
        this.updateTabNum(this.formContent.find('.J_tab_formset'));
        this.updateTabTextTitleNum();
    }
    updateTabNum(target) {
        let maxTabNum = this.maxTabNum;
        target.find('.J_tab_num').text(target.find('.J_tabItem').size() + 1);
        if (target.find('.J_tabItem').size() > maxTabNum - 1) { 
            this.formContent.find('.J_addTabBtn').hide();
        } else {
            this.formContent.find('.J_addTabBtn').removeAttr('style');
        }
    }
    addEvent() {
        this.addEventOperate(this.formContent.find('.J_tab_formset'));
    }
    addEventOperate(target) {
        target.on('click', '.J_addTabBtn', () => {
            let moduleEmpty = {
                addNewitem: true,
                tabType: this.moduleData.tabType,
                configType: this.moduleData.configType,
                tabItemList: [{}],
            }; 
            this.renderTabContent(moduleEmpty);
            let $lastItem = $(event.target).closest('.J_addTabBtn').parent().find('.J_tabItem').last();
            if($lastItem.find('.J_cat_item').size() === 0){
                $('.J_addCat', $lastItem).trigger('click');
            }
        });
        target.on('click', '.J_tabGoUp', (event) => {
            let currentTabItem = $(event.target).parents('.J_tabItem'),
                beforeCurrentTabItem = currentTabItem.prev('.J_tabItem');
            if (!beforeCurrentTabItem.length) {
                return;
            }
            beforeCurrentTabItem.before(currentTabItem);
            this.updateTabTextTitleNum();
            return false;
        });
        this.formContent.on('click', '.J_tabGoDown', (event) => {
            let currentTabItem = $(event.target).parents('.J_tabItem'),
                afterCurrentTabItem = currentTabItem.next('.J_tabItem');
            if (!afterCurrentTabItem.length) {
                return;
            }
            afterCurrentTabItem.after(currentTabItem);
            this.updateTabTextTitleNum();
            return false;
        });
        target.on('click', '.J_tabRemove', (event) => {
            let currentTabItem = $(event.target).parents('.J_tabItem');
            currentTabItem.remove();
            this.updateTabNum(target);
            return false;
        });
        target.on('click', '.J_tabEdit', (event) => {
            let currentTabItem = $(event.target).parents('.J_tabItem');
            currentTabItem.siblings('.J_tabItem').removeClass('cd-show-detail');
            currentTabItem.addClass('cd-show-detail');
            return false;
        });
        target.on('click', '.J_done', (event) => {
            let currentTabItem = $(event.target).parents('.J_tabItem');
            if (this.validateData(currentTabItem)) {
                currentTabItem.removeClass('cd-show-detail');
                this.updateMainInfo(currentTabItem);
            }
            $('body').trigger('click');
            return false;
        });
        target.on('click', '.J_cancel', (event) => {
            let currentTabItem = $(event.target).parents('.J_tabItem');
            currentTabItem.removeClass('cd-show-detail');
            this.cancelMainInfo(currentTabItem);
        });
    }
    validateData($Node) {
        let prevItem = $Node.prev('.J_tabItem'),
            nextItem = $Node.next('.J_tabItem');
        if (this.moduleData.tabType == 1 && $Node.data('inputInstance').getData() == null) {
            Message.error('请输入tab标题');
            return false;
        }
        if (this.moduleData.tabType == 2) {
            let imgUrl = $Node.find('.J_defaultImg').attr('origindata');
            if (imgUrl && imgUrl == '') {
                Message.error('请上传默认图片');
                return false;
            }
        }
        if (this.moduleData.tabType == 3) {
            if ($Node.data('rangeInstance').getData() == null) {
                return false;
            }
            let curDate = $Node.data('rangeInstance').getData();
            if (prevItem.length > 0 && prevItem.data('rangeInstance').getData()) {
                let prevDate = prevItem.data('rangeInstance').getData();
                if (moment(prevDate.endTime).unix() > moment(curDate.startTime).unix()) {
                    Message.error('当前TAB开始时间必须在上一TAB结束时间之后!');
                    return false;
                }
            }
            if (this.config.platForm === 'M') {
                if (moment(curDate.startTime).year() !== moment(curDate.endTime).year() ||
                    moment(curDate.startTime).dayOfYear() !== moment(curDate.endTime).dayOfYear()) {
                    Message.error('开始时间和结束时间必须是同一天!');
                    return false;
                }
            }
        }
        if ($Node.data('tabModuleListInstance').getData() == null) {
            Message.error('请添加要渲染的模块');
            return false;
        }
        return true;
    }
    renderForContentForText(target) {
        this.renderNavBi(target);
        this.renderTabModuleList(target);
        this.renderJDInputForTitle(target);
        this.renderJDImageForBg(target);
        this.renderJDDateRangeLineForDate(target);
    }
    updateMainInfo(target) {
        let $Node = target;
        let tabTitle = this.moduleData.tabType == 1 ? $Node.data('inputInstance').getData() : {};
        let defaultImg = this.moduleData.tabType == 2 ? $Node.find('.J_defaultImg').attr('originData') : '';
        let currentImg = this.moduleData.tabType == 2 ? $Node.find('.J_currentImg').attr('originData') : '';
        let dateTime = this.moduleData.tabType == 3 ? $Node.data('rangeInstance').getData() : {};
        let biInfo = (this.moduleData.tabType !== 3 && this.moduleData.configType == 1) ? $Node.data('biConfigInstance').getData() : {};
        if (tabTitle) $Node.find('.J_show_name').html(tabTitle.title);
        $Node.find('.J_show_default_img').attr('src', defaultImg).attr('current_img', currentImg);
        $Node.find('.J_show_current_img').attr('src', currentImg);
        if (dateTime && dateTime.endTime) {
            $Node.find('.J_show_end_time').html(dateTime.endTime);
            $Node.find('.J_show_end_time').closest('p').removeClass('cd-hide');
        }
        if (dateTime && dateTime.startTime) {
            $Node.find('.J_show_start_time').html(dateTime.startTime);
            $Node.find('.J_show_start_time').closest('p').removeClass('cd-hide');
        }
        if (biInfo && biInfo.biConfig) {
            let biItem = biInfo.biConfig.biCategoryList;
            let biHtml = '<div>BI分类：<span>' + [biItem[0].firstName, biItem[0].secondName, biItem[0].thirdName].filter(_=>{return !!_}).join('/') + '</span>' + (biItem.length > 1 ? '(' + biItem.length + ')' : '') + '</div>';
            $Node.find('.J_biClass').html(biHtml).attr('back-data', JSON.stringify(biItem));
        }
        if ($Node.data('tabModuleListInstance').getData()) {
            let _names = [], backData = [];
            $Node.data('tabModuleListInstance').getData().forEach(function (item) {
                _names.push(item.moduleName);
                backData.push(item);
            });
            $Node.find('.J_show_moduleName').html(_names.join('、')).attr('back-data', JSON.stringify(backData));
        }
    }
    cancelMainInfo(target) {
        target.find('.J_tab_content_title_val input').val(target.find('.J_show_name').text());
        target.find('.J_defaultImg img').attr('src', target.find('.J_show_default_img').attr('src'));
        target.find('.J_currentImg img').attr('src', target.find('.J_show_default_img').attr('current_img'));
        let startTxt = target.find('.J_show_start_time').text();
        let endTxt = target.find('.J_show_end_time').text();
        if (startTxt.trim(true) != '' && endTxt.trim(true) != '') {
            target.find('.J_dateStart').val(startTxt + ' - ' + endTxt);
        } else {
            target.find('.J_dateStart').val('');
        }
        target.data('rangeInstance').resetData(startTxt + ' - ' + endTxt);
        let oldMode = target.find('.J_show_moduleName').attr('back-data');
        if (oldMode && oldMode != '') {
            let selected = '';
            oldMode = JSON.parse(oldMode);
            target.find('.J_module_selected p').addClass('hide');
            for (let i = 0, ii = oldMode.length; i < ii; i++) {
                let item = oldMode[i];
                selected += '<a href="javascript:;" ' + (item.instanceId ? 'mode-instanceid="' + item.instanceId + '"' : '') + 'module-id="' + item.moduleId + '" template-id="' + item.templateId + '" title="' + item.moduleName + '" draggable="true"><i class="cd-icons cd-icons-tab-module-del cd-tab-module-close"></i><span>' + item.moduleName + '</span></a>';
            }
            target.find('.J_module_selected').html(selected);
        } else {
            target.find('.J_module_selected a').remove();
            target.find('.J_module_selected p').removeClass('hide');
        }
        let oldBIinfo = target.find('.J_biClass').attr('back-data');
        if (oldBIinfo && oldBIinfo != '') {
            target.find('.J_bi_cat_list').html('');
            oldBIinfo = JSON.parse(oldBIinfo);
            target.data('biConfigInstance').addCatItem(oldBIinfo);
            target.data('biConfigInstance').updateCatNames(oldBIinfo);
        } else {
            target.find('.J_bi_cat_list').html('');
        }
    }
    updateTabTextTitleNum() {
        const tabContent = this.formContent.find('#J_tab_content');
        tabContent[0].querySelectorAll('.J_tabItem').forEach((el, index, array) => {
            const $Node = $(el);
            $Node.find('.cd-tab-title').text(`Tab${index + 1}`);
            $Node.find('.J_tabGoUp').show();
            $Node.find('.J_tabGoDown').show();
            if (tabContent.hasClass('cd-type-3')) {
                $Node.find('.J_tabGoUp').hide();
                $Node.find('.J_tabGoDown').hide();
            } else {
                if (el === array[0]) {
                    $Node.find('.J_tabGoUp').hide();
                }
                if (el === array[array.length - 1]) {
                    $Node.find('.J_tabGoDown').hide();
                }
            }
        });
    }
    renderJDImageForBg(target) {
        if (target.data('inputInstance') instanceof JDRadio) {
            return;
        }
        let format;
        if (this.config.platForm === 'M') {
            format = '280-1125,135-135';
            Utils.renderImageDom(target.find('.J_defaultImg'), format, true);
            Utils.renderImageDom(target.find('.J_currentImg'), format, true);
        }else{
            Utils.renderImageDom(target.find('.J_defaultImg'), true);
            Utils.renderImageDom(target.find('.J_currentImg'), true);
        }
        
    }
    renderJDDateRangeLineForDate(target) {
        let tabItemData = $.parseJSON(target.attr('tab-item'));
        if (target.data('rangeInstance') instanceof JDDateRangeLine) {
            return;
        }
        let startTime = tabItemData.startTime ? moment(tabItemData.startTime).format('YYYY-MM-DD HH:mm:ss') : '';
        let endTime = tabItemData.endTime ? moment(tabItemData.endTime).format('YYYY-MM-DD HH:mm:ss') : '';
        target.data('rangeInstance', new JDDateRangeLine({
            startTime: startTime,
            endTime: endTime,
            domData: {
                node: target.find('.J_rangeTime'),
                title: '时间选择',
                validate: {
                    must: true,
                },
                extConfig: {
                    skin: 'cd-rang-newline',
                },
            },
        }));
    }
    renderJDInputForTitle(target) {
        let tabItemData = $.parseJSON(target.attr('tab-item'));
        let index = target.index() + 1;
        if (target.data('inputInstance') instanceof JDInput) {
            return;
        }
        target.data('inputInstance', new JDInput({
            domData: {
                node: target.find('.J_tab_content_title_val'),
                name: 'title',
                title: 'Tab' + index + '标题',
                validate: {
                    must: true,
                },
            },
            defaultValue: tabItemData.title,
        }));
    }
    renderNavBi(target) {
        let tabItemData = $.parseJSON(target.attr('tab-item'));
        if (target.data('biConfigInstance') instanceof JDBiConfig) {
            return;
        }
        let biConfigModuleData = null;
        if (this.moduleData) {
            biConfigModuleData = tabItemData.biConfig;
        }
        target.data('biConfigInstance', new JDBiConfig({
            baseZIndex: 9999,
            domData: {
                name: 'biConfig',
                node: target.find('.J_tabBIconfig'),
            },
            moduleData: biConfigModuleData,
        }));
    }
    renderTabModuleList(target) {
        if (target.data('tabModuleListInstance') instanceof JDList) {
            return;
        }
        let selectedModule = [];
        try {
            let targetData = JSON.parse(target.attr('tab-item'));
            selectedModule = targetData.subModuleInfoList;
        } catch (e) {
        }
        target.data('tabModuleListInstance', new JDList({
            platForm: this.config.platForm,
            maxSelected: 3,
            domData: {
                title: '添加模块',
                node: target.find('.J_tab_module_list'),
                formType: {
                    option: this.centerModules,
                },
                validate: {
                    must: true,
                },
            },
            tabModuleSelected: selectedModule,
        }));
    }
    getData() {
        let hasError = false, prevDate, defaultImg = '', currentImg = '',
            obj = {
                tabData: {
                    tabType: this.moduleData.tabType,
                    configType: this.moduleData.configType,
                    tabItemList: [],
                },
            };
        this.formContent.find('#J_tab_content .J_tabItem').each((index, el) => {
            let subObj = { id: index + 1 };
            let $Node = $(el);
            if (this.moduleData.tabType == 1) {
                let tabName = $Node.data('inputInstance').getData();
                if (tabName && tabName != '') {
                    subObj = $.extend(subObj, tabName);
                } else {
                    Message.error('Tab' + (index + 1) + '未填写标题');
                    hasError = true;
                    return false;
                }
            }
            if (this.moduleData.tabType == 2) {
                defaultImg = $Node.find('.J_defaultImg').attr('originData');
                currentImg = $Node.find('.J_currentImg').attr('originData');
                if (defaultImg == '' || currentImg == '') {
                    Message.error('Tab' + (index + 1) + '未上传默认图片或选中图片');
                    hasError = true;
                    return false;
                }
            }
            subObj = $.extend(subObj, {
                defaultImageUrl: defaultImg,
                selectedImageUrl: currentImg,
            });
            if (this.moduleData.tabType == 3) {
                let dateRange = $Node.data('rangeInstance').getData();
                if (!dateRange) {
                    hasError = true;
                    return false;
                }
                if (index > 0 && prevDate) {
                    if (moment(prevDate.endTime).unix() > moment(dateRange.startTime).unix()) {
                        Message.error('TAB' + (index + 1) + '开始时间必须在TAB' + (index) + '结束时间之后!');
                        hasError = true;
                        return false;
                    }
                }
                prevDate = dateRange;
                subObj = $.extend(subObj, dateRange);
            }
            if (this.moduleData.configType == 1) {
                let biInfo = $Node.data('biConfigInstance').getData();
                if (biInfo && biInfo != '') {
                    subObj = $.extend(subObj, biInfo);
                } else {
                    Message.error('Tab' + (index + 1) + '未填写BI信息');
                    hasError = true;
                    return false;
                }
            }
            let subMode = $Node.data('tabModuleListInstance').getData();
            if (subMode && subMode != '') {
                subObj = $.extend(subObj, { subModuleInfoList: subMode });
            } else {
                Message.error('Tab' + (index + 1) + '未选择子模块');
                hasError = true;
                return false;
            }
            obj.tabData.tabItemList.push(subObj);
        });
        return hasError ? { hasError: true } : obj;
    }
}
export default JDTab;