import { get } from 'lodash'
import './style.scss'
import { tpl } from './tpl'
import BaseFormControl from '../../baseFormControl'
import { RadioButton, RadioGroup } from '@hot/pc-es-cn-shop-ui'
import { Message } from '@hot/pc-es-cn-shop-ui'
import JDInput from '../input'
import JDImage from '../image/image'
import JDLink from '../link'
import { IsModuleDecorate } from '../../../../util/channelUtil'
class FloorTitle extends BaseFormControl {
    static TitleType = {
        NO_TITLE: 1,
        TEXT_TITLE: 2,
        IMG_TITLE: 3,
    }
    constructor(config) {
        super(config)
        if (config && config.curTemplate && config.curTemplate.fixed == 1) {
            return;
        }
        let TitleType = FloorTitle.TitleType
        let pcImageWidth = '1210'
        if (page_data.clientType == 'PC') {
            pcImageWidth = this.config.module
                .closest('.J_LayoutArea')
                .attr('data-size')
        }
        this.is21618promotionPage =
            get(this.config, 'domData.extConfig.actName', '') ===
            '21618promotionPage'
        this.DefaultConfig = {
            tips:
                page_data.clientType == 'PC'
                    ? `建议图片宽度为${pcImageWidth}px，高度为60px；大小不超过800k，格式为JPG、PNG。`
                    : '建议图片宽度为1125px，高度为120px；大小不超过300k，格式为JPG、PNG。', 
            format:
                page_data.clientType == 'PC'
                    ? `${pcImageWidth},60`
                    : '1125,120',
            chooseSizeLimit: page_data.clientType == 'PC' ? 800 : 300, 
        }
        if (
            !IsModuleDecorate() &&
            window._Module &&
            window._Module.getActiveModule
        ) {
            const currentModule = window._Module.getActiveModule() 
            this.currentModuleFlag = currentModule.$el.attr('data-module-flag')
        }
        this.isShowSubTextTilteConfigItem =
            this.is21618promotionPage ||
            this.currentModuleFlag == 'mFlashBuyModule'
        this.floorTitleList = [
            { label: '不显示标题', value: TitleType.NO_TITLE },
            { label: '文字标题', value: TitleType.TEXT_TITLE },
            { label: '图片标题', value: TitleType.IMG_TITLE },
        ]
        if (page_data.appType === 5) {
            this.floorTitleList = [
                { label: '图片标题', value: TitleType.IMG_TITLE },
            ]
        }
        if (this.currentModuleFlag == 'mFlashBuyModule') {
            this.floorTitleList = [
                { label: '文字标题', value: TitleType.TEXT_TITLE },
            ]
        }
        this.defaultTextTitle = {
            1: '热卖商品',
            2: '新品推荐',
            3: '商品推荐',
            5: '猜你喜欢',
        }
        this.isTextChanged = false
        this.isSubTextChanged = false
        this.tabs = []
        let type = TitleType.NO_TITLE
        let extConfig = this.config.domData.extConfig
        if (extConfig && extConfig.titleType != null) {
            type = extConfig.titleType
        }
        if (
            (page_data.appType === 3 ||
                this.currentModuleFlag == 'serialNewWareFlag') && 
            extConfig &&
            extConfig.floorTitleListConfig
        ) {
            this.floorTitleList = this.floorTitleList.filter((item) => {
                if (extConfig.floorTitleListConfig.indexOf(item.value) >= 0) {
                    return true
                }
            })
        }
        if (extConfig.floorTitleListConfig) {
            this.floorTitleList = this.floorTitleList.filter((item) => {
                if (extConfig.floorTitleListConfig.indexOf(item.value) >= 0) {
                    return true
                }
            })
        }
        if (this.config.moduleData.type != undefined) {
            type = this.config.moduleData.type
        }
        this.selectType = type 
        this.render()
    }
    
    _getConfig(config) {
        return $.extend(
            true,
            {},
            {
                domData: {},
                moduleData: {},
                disabled: false,
            },
            config,
        )
    }
    
    updateTextTitle(type) {
        if (this.config.updateText && !this.isTextChanged) {
            let defaultText = this.defaultTextTitle[type] || ''
            if (defaultText) {
                if (this.textInput) {
                    this.textInput.setData(defaultText)
                }
            }
        }
    }
    
    render() {
        this.appendFormControl(tpl)
        this.$titleTab = this.element.find('.J_titleTab')
        this.$titleContent = this.element.find('.J_titleContent')
        this.$textTitle = this.$titleContent.find('.J_textTitleLayer')
        this.$imgTitle = this.$titleContent.find('.J_imgTitleLayer')
        this.renderTab()
        this.renderContent()
    }
    renderTab() {
        let _disabled = this.config.module.crmActivityType === 2 ? true : false
        if (this.floorTitleList) {
            this.floorTitleList.map((item) => {
                let radio = new RadioButton({
                    node: this.$titleTab[0],
                    className: 'cd-radio-item',
                    groupName: 'grouptab',
                    value: item.value,
                    label: item.label,
                    disabled: _disabled,
                })
                this.tabs.push(radio)
            })
        }
        this.radioGroup = new RadioGroup({
            group: this.tabs,
            selectedValue: this.selectType,
            onChange: (value ) => {
                this.clickTab(value)
            },
        })
    }
    
    clickTab(value) {
        this.selectType = value
        let TitleType = FloorTitle.TitleType
        if (this.selectType == TitleType.TEXT_TITLE) {
            this.$textTitle.show()
            this.$imgTitle.hide()
        } else if (this.selectType == TitleType.IMG_TITLE) {
            this.$textTitle.hide()
            this.$imgTitle.show()
        } else {
            this.$textTitle.hide()
            this.$imgTitle.hide()
        }
    }
    renderContent() {
        let _text = ''
        let _subText = ''
        this._imgTitleModulValue = 0
        if (this.config.updateText) {
            _text = this.defaultTextTitle[1]
        }
        if (
            this.config.moduleData.textTitle &&
            this.config.moduleData.textTitle.text
        ) {
            _text = this.config.moduleData.textTitle.text
            _subText = this.config.moduleData.textTitle.subText || ''
            this.isTextChanged = true 
            this.isSubTextChanged = true 
            this._imgTitleModulValue =
                this.config.moduleData.textTitle.picStatus || 0
        }
        if (this.currentModuleFlag == 'mFlashBuyModule') {
            _text = _text ? _text : '为你精选'
            _subText = _subText ? _subText : '特惠好货'
        }
        this.textInput = new JDInput({
            domData: {
                name: 'text',
                node: this.$textTitle[0],
            },
            maxlength: 20,
            char2Modal: true,
            placeholder: `${this.isShowSubTextTilteConfigItem
                ? '主标题最多输入'
                : '请输入最多'
                }20个字符`,
            change: () => {
                this.isTextChanged = true
            },
            defaultValue: _text,
        })
        if (this.isShowSubTextTilteConfigItem) {
            this.subTextInput = new JDInput({
                domData: {
                    name: 'subText',
                    node: this.$textTitle[0],
                },
                maxlength: 20,
                char2Modal: true,
                placeholder: `${this.isShowSubTextTilteConfigItem
                    ? '副标题最多输入'
                    : '请输入最多'
                    }20个字符`,
                change: () => {
                    this.isSubTextChanged = true
                },
                defaultValue: _subText,
            })
        }
        if (this.config.module.crmActivityType === 2) {
            this.textInput.setDisable('disabled')
        }
        let imageTitle = {}
        if (this.config.moduleData.imageTitle) {
            imageTitle = this.config.moduleData.imageTitle
        }
        const defaultImgConfigTipWH = `建议图片宽度为1125px，高度为120px；`
        const imgConfigTipWH = {
            3: this.is21618promotionPage
                ? `建议图片宽度为1125px，高度为152px；`
                : defaultImgConfigTipWH, 
            5: `建议图片宽度为1125px，高度为189px；`,
            14: `建议图片宽度为1125px，高度为152px；`,
            15: `建议图片宽度为1125px，高度为152px；`,
            default: defaultImgConfigTipWH,
        }
        const defaultImgConfigCheckWH = '1125-1125,120-120'
        const imgConfigCheckWH = {
            3: this.is21618promotionPage
                ? '1125-1125,152-152'
                : defaultImgConfigCheckWH, 
            5: '1125-1125,189-189',
            14: '1125-1125,152-152',
            15: '1125-1125,152-152',
            default: defaultImgConfigCheckWH,
        }
        let imgConfig = {
            domData: {
                node: this.$imgTitle.find('.J_imgLayer')[0],
                name: 'imgUrl',
                title: '',
                dateType: 'JDT_IMAGE',
                formType: {
                    type: 'image',
                },
                tips:
                    (imgConfigTipWH[window.page_data.appType] ||
                        imgConfigTipWH.default) +
                    `大小不超过${window.page_config.chooseSizeLimit}KB，格式为JPG、PNG。`,
            },
            format:
                imgConfigCheckWH[window.page_data.appType] ||
                imgConfigCheckWH.default,
            defaultImage: imageTitle.imgUrl || '',
        }
        this.imgTitle = new JDImage(imgConfig)
        let linkInfo = {}
        if (imageTitle.linkInfo) {
            linkInfo = imageTitle.linkInfo
        }
        let JDLinkConfig = {
            domData: {
                name: 'linkInfo',
                title: '',
                node: this.$imgTitle.find('.J_linkLayer')[0],
            },
            linkName: false,
            addLink: false,
            operation: false,
            tab: ['custom', 'product', 'activity', 'shopCategory', 'fansMini'],
            tabValueForbidIncrease: true, 
            moduleData: linkInfo,
        }
        this.link = new JDLink(JDLinkConfig)
    }
    
    setData() {
    }
    
    getData(arg) {
        if (this.config && this.config.curTemplate && this.config.curTemplate.fixed == 1) {
            return {
                floorTitle: {
                    type: "2",
                    textTitle: {
                        text: "限时秒杀"
                    }
                }
            };
        }
        let isAutoPullDataMode
        if (arg) {
            isAutoPullDataMode = arg.isAutoPullDataMode
        }
        let TitleType = FloorTitle.TitleType
        let data = {
            type: this.selectType,
        }
        const extConfig = this.config.domData.extConfig
        let defaultTextTitleData = extConfig.defaultTextTitleData 
        if (defaultTextTitleData) {
            try {
                defaultTextTitleData = JSON.parse(defaultTextTitleData)
            } catch (err) {
                defaultTextTitleData = null
            }
        }
        if (isAutoPullDataMode) {
            const autoPullModeTextTitleData = get(
                this.config,
                'domData.extConfig.autoPullModeTextTitleData',
                '',
            )
            try {
                const jsonData = JSON.parse(
                    autoPullModeTextTitleData.replace(/'/g, '"'),
                )
                data['textTitle'] = {}
                Object.assign(data['textTitle'], jsonData)
            } catch (e) {
                const tip = `中台模板配置xml内容中的extConfig项的autoPullModeTextTitleData值【${autoPullModeTextTitleData}】格式错误，该值必须是一个可JSON.parse的字符串！`
                console.error(tip)
            }
        } else {
            if (this.selectType == TitleType.TEXT_TITLE) {
                if (this.currentModuleFlag == 'mFlashBuyModule') {
                    data['textTitle'] = this.textInput.getData()
                        ? this.textInput.getData()
                        : { text: '为你精选' }
                } else if (defaultTextTitleData) {
                    data['textTitle'] = this.textInput.getData()
                        ? this.textInput.getData()
                        : defaultTextTitleData
                } else {
                    data['textTitle'] = this.textInput.getData() || {}
                }
                if (this.isShowSubTextTilteConfigItem) {
                    if (this.currentModuleFlag == 'mFlashBuyModule') {
                        Object.assign(
                            data['textTitle'],
                            this.subTextInput.getData()
                                ? this.subTextInput.getData()
                                : { subText: '特惠好货' },
                        )
                    } else {
                        Object.assign(
                            data['textTitle'],
                            this.subTextInput.getData(),
                        )
                    }
                }
            } else if (this.selectType == TitleType.IMG_TITLE) {
                data['imageTitle'] = this.imgTitle.getData()
                data['imageTitle'] = $.extend(
                    data['imageTitle'],
                    this.link.getData(),
                )
            }
        }
        let result = {}
        result[this.config.domData.name] = data
        return result
    }
    
    validateData() {
        let value
        let TitleType = FloorTitle.TitleType
        if (this.selectType == TitleType.TEXT_TITLE) {
            value = this.textInput.getValue()
            if (!value) {
                Message.error('请配置文字标题')
                return false
            }
        } else if (this.selectType == TitleType.IMG_TITLE) {
            value = this.imgTitle.getValue()
            if (!value) {
                Message.error('请配置图片标题')
                return false
            }
        }
        return true
    }
    
    dispose() { }
}
export default FloorTitle