import BaseFormControl from '../../baseFormControl'
import LinkTool from '../../../linkTool'
import { JDLinkItemTpl, JDLinkTpl } from './tpl'
import { getShopType } from '../../../../util/channelUtil'
import './style.scss'
import ImageDom from '../../../imageDom/ImageDom'
class JDLink extends BaseFormControl {
    constructor(config) {
        super()
        this.linkInfo = null
        this.setConfig(config)
        this.render()
    }
    
    setConfig(config) {
        this.config = $.extend(
            true,
            {},
            {
                placeholder: '请输入信息',
                domData: {},
                moduleData: {},
                attachedPicUpload: false, 
                linkName: true,
                addLink: true,
                operation: true,
                sorting: true,
                tab: [],
                maxNum: 999, 
                addLinkHandler: () => {},
            },
            config,
        )
    }
    render() {
        let $Node = template.render(JDLinkTpl, {
            operation: this.config.operation,
            sorting: this.config.sorting,
            addLink: this.config.addLink,
            linkName: this.config.linkName,
        })
        this.appendFormControl($Node)
        
        if (!this.config.addLink) {
            this.config.operation = this.config.addLink
            this.addLink(this.config.moduleData)
            this.setModuleLinkInfoToNode()
        } else {
            this.initByModuleData()
        }
        this.addEvent()
    }
    
    initByModuleData() {
        
        if ($.isArray(this.config.moduleData)) {
            for (let i = 0, ln = this.config.moduleData.length; i < ln; i++) {
                this.addLink(this.config.moduleData[i])
            }
            this.setModuleLinkInfoToNode()
        }
    }
    
    setModuleLinkInfoToNode() {
        this.element.find('.link-content .J_link_value').each((i, el) => {
            let $Node = $(el)
            if ($.isArray(this.config.moduleData)) {
                $Node.data('linkInfo', this.config.moduleData[i].href)
                $Node.data('defLinkInfo', this.config.moduleData[i].href)
            } else if (this.config.moduleData) {
                if (this.config.linkName) {
                    $Node.data(
                        'linkInfo',
                        this.config.moduleData.href
                            ? this.config.moduleData.href
                            : this.config.moduleData,
                    )
                    $Node.data(
                        'defLinkInfo',
                        this.config.moduleData.href
                            ? this.config.moduleData.href
                            : this.config.moduleData,
                    )
                } else {
                    $Node.data('linkInfo', this.config.moduleData)
                    $Node.data('defLinkInfo', this.config.moduleData)
                }
            }
        })
    }
    addEvent() {
        this.element.find('.J_add_link').on('click', () => {
            this.addLink()
        })
        this.element.find('.J_editScene').on('click', (e) => {
            e.stopPropagation()
        })
        this.element
            .find('.link-content')
            .delegate('.J_link_info', 'click', (evt) => {
                let $Node = $(evt.target).parents('.J_link_info')
                let linkInfo = $Node.find('.J_link_value').data('linkInfo')
                new LinkTool({
                    node: this,
                    linkObj: $.isEmptyObject(linkInfo) ? null : linkInfo,
                    tab: this.config.tab.length != 0 ? this.config.tab : null,
                    tabValueForbidIncrease: !!this.config
                        .tabValueForbidIncrease,
                    env: {
                        platformId: page_data.clientType == 'PC' ? 0 : 1, 
                        shopType: getShopType(), 
                    },
                    onConfirm: (link, linkObj) => {
                        this.setLinkToolSelectUrl(
                            link,
                            $Node.find('.J_link_value'),
                            linkObj,
                        )
                        return false
                    },
                })
            })
        if (this.config.operation) {
            this.addEventForOperation()
        }
        this.getLinkTitleAndOperations()
    }
    
    addEventForOperation() {
        this.element.find('.link-content').delegate('.J_up', 'click', (evt) => {
            let $Node = $(evt.target)
            this.up($Node)
            this.getLinkTitleAndOperations()
            return false
        })
        this.element
            .find('.link-content')
            .delegate('.J_down', 'click', (evt) => {
                let $Node = $(evt.target)
                this.down($Node)
                this.getLinkTitleAndOperations()
                return false
            })
        this.element
            .find('.link-content')
            .delegate('.J_del', 'click', (evt) => {
                let $Node = $(evt.target)
                this.del($Node)
                this.linkNumToMax()
                this.getLinkTitleAndOperations()
                return false
            })
    }
    getLinkTitleAndOperations() {
        let linkNums = this.element.find('.link-item').size()
        this.element.find('.link-item').each((i, el) => {
            let $Node = $(el)
            let index = i + 1
            $Node.find('.J_lint_title').text('导航' + index)
            if (linkNums === 1) {
                $Node.find('.J_up').hide()
                $Node.find('.J_down').hide()
            } else {
                if (index === 1) {
                    $Node.find('.J_up').hide()
                    $Node.find('.J_down').show()
                } else if (index === linkNums) {
                    $Node.find('.J_up').show()
                    $Node.find('.J_down').hide()
                } else {
                    $Node.find('.J_up').show()
                    $Node.find('.J_down').show()
                }
            }
        })
    }
    
    resetDefInfoToInfo() {
        this.element.find('.link-content').each((i, el) => {
            let $Node = $(el)
            let $NameNode = $Node.find('.J_link_name')
            let $LinkNode = $Node.find('.J_link_value')
            if ($LinkNode.data('defLinkInfo')) {
                $LinkNode.data('linkInfo', $LinkNode.data('defLinkInfo'))
            }
            let linkInfo = $LinkNode.data('linkInfo')
            this.setLinkToolSelectUrl(linkInfo.link, $LinkNode, linkInfo)
            $NameNode.val($NameNode.attr('defValue'))
        })
    }
    
    saveInfoToDefInfo() {
        this.element.find('.link-content').each((i, el) => {
            let $Node = $(el)
            let $NameNode = $Node.find('.J_link_name')
            let $LinkNode = $Node.find('.J_link_value')
            $NameNode.attr('defValue', $NameNode.val())
            $LinkNode.data('defLinkInfo', $LinkNode.data('linkInfo'))
        })
    }
    
    up(node) {
        if (node) {
            let currentNode = node.parents('.link-item')
            let preNode = currentNode.prev()
            preNode.before(currentNode)
        }
    }
    
    down(node) {
        if (node) {
            let currentNode = node.parents('.link-item')
            let nextNode = currentNode.next()
            nextNode.after(currentNode)
        }
    }
    
    del(node) {
        node && node.parents('.link-item').remove()
    }
    addLink(linkInfo) {
        
        if (this.config.linkName) {
            this.element.find('.link-content').append(
                template.render(JDLinkItemTpl, {
                    operation: this.config.operation,
                    linkName: this.config.linkName,
                    title: (linkInfo && linkInfo.title) || '',
                    linkInfo: (linkInfo && linkInfo.href) || {},
                    hasPicUpload: this.config.attachedPicUpload,
                    index:
                        this.element.find('.link-content .link-item').size() +
                        1,
                }),
            )
        } else {
            this.element.find('.link-content').append(
                template.render(JDLinkItemTpl, {
                    operation: this.config.operation,
                    linkName: this.config.linkName,
                    linkInfo: linkInfo ? linkInfo : {},
                    hasPicUpload: this.config.attachedPicUpload,
                    index:
                        this.element.find('.link-content .link-item').size() +
                        1,
                }),
            )
        }
        this.getLinkTitleAndOperations()
        this.config.addLinkHandler(
            this.element
                .find('.link-content .link-item .J_link_extends_node')
                .eq(this.element.find('.link-content .link-item').size() - 1),
        )
        this.linkNumToMax()
        if (this.config.attachedPicUpload) {
            let $wrap = this.element.find('.J_picUpload').last(), 
                itemIndex =
                    this.element.find('.link-content .link-item').length - 1
            if (this.config.moduleData && this.config.moduleData[itemIndex]) {
                $wrap.attr(
                    'originData',
                    this.config.moduleData[itemIndex].image.value,
                )
            }
            new ImageDom({
                node: $wrap,
                format: this.config.format,
                typeLimit: this.config.typeLimit,
                fileUploadSuccess: () => {},
                chooseSuccess: () => {},
            })
        }
    }
    
    linkNumToMax() {
        if (this.element.find('.link-item').size() >= this.config.maxNum) {
            this.element.find('.J_add_link').hide()
            return true
        } else {
            this.element.find('.J_add_link').removeAttr('style')
            return false
        }
    }
    
    setLinkToolSelectUrl(link, node, linkObj) {
        if (!$.isEmptyObject(linkObj)) {
            node.data('linkInfo', linkObj)
        }
        node.val(link)
    }
    
    getData() {
        let dataArray = []
        this.element.find('.link-item').each((i, el) => {
            let $Node = $(el)
            let linKInfo = $Node.find('.J_link_value').data('linkInfo')
            let obj = {}
            if (this.config.linkName && $Node.find('.J_link_name').val()) {
                obj['title'] = $Node.find('.J_link_name').val()
            }
            obj['type'] = i
            
            if (!$.isEmptyObject(linKInfo)) {
                
                if (this.config.addLink) {
                    obj['href'] = linKInfo 
                    dataArray.push(obj)
                } else {
                    
                    if (this.config.linkName) {
                        obj['href'] = linKInfo.href || linKInfo
                        dataArray = obj
                    } else {
                        dataArray = linKInfo
                    }
                }
                if (this.config.attachedPicUpload) {
                    let value = $Node.find('.cd-image-panel').attr('data-url'),
                        picWidth = Number(
                            $Node.find('.J_imgSize').attr('picWidth'),
                        ),
                        picHeight = Number(
                            $Node.find('.J_imgSize').attr('picHeight'),
                        )
                    obj.image = {
                        value,
                        picWidth,
                        picHeight,
                    }
                }
            } else {
                if (!$.isEmptyObject(obj)) {
                    
                    if (this.config.addLink) {
                        dataArray.push(obj)
                    } else {
                        dataArray = obj
                    }
                }
            }
        })
        let result = {}
        
        if (dataArray.length === 0 || $.isEmptyObject(dataArray)) {
            return null
        } else {
            result[this.config.domData.name] = dataArray
        }
        return result
    }
}
export default JDLink