import { linkToolLayoutTpl } from './linkToolTpl'
import Modal from '@core/component/modal';
import Message from '@core/component/message';
import FrequentLink from './frequentLink' 
import ProductLink from './productLink' 
import Coupon from './coupon' 
import ActivityPage from './activityPage' 
import Anchor from './anchor' 
import ShopCategory from './shopCategory' 
import CutsomLink from './customLink' 
import UserDefineLink from './userDefineLink' 
import Live from './live' 
import AuctionProduct from './auctionProduct' 
import MiniApps from './miniApps'
import WidgetPlug from './widgetPlug'
import { Messager, DataPersistence } from '@core/component/msgDistribute'
import { ShopType, IsJDShop } from '@core/util/channelUtil'
import YaoProduct from './yaoProduct'
import SceneGuide from './sceneGuide'
import DoctorList from './doctorList'
import MiniApp from './miniApp'
import FansMini from './fansMini'
import FinanceCouponLink from './financeCouponLink'
let actions = {
    linkChange(data) {
        return data
    },
    confirm() {
        return
    },
    cancel() {
        return
    },
}
DataPersistence.addAction(actions)
const LinkTool = (($) => {
    const DefaultConfig = {
        linkAttr: 'data-link',
        originalDataAttr: 'data-original-data',
        linkObj: {
            link: '', 
            linkType: 1, 
            originalData: '', 
        },
        onConfirm: function (link, linkObj) {
            console.log('获得了链接：', link, '链接Obj:', linkObj)
        },
        tabValueForbidIncrease: false, 
        tab: [], 
        mTab: [
            'custom',
            'frequent',
            'product',
            'activity',
            'shopCategory',
            'coupon',
            'anchor',
            'index',
            'member',
            'live',
            'miniApps',
            'widgetPlug',
            'search',
            'sceneGuide',
            'doctorList',
            'miniApp',
            'fansMini',
            'financeCouponLink',
        ], 
        pcTab: [
            'custom',
            'frequent',
            'product',
            'activity',
            'userdefine',
            'shopCategory',
            'coupon',
            'anchor',
            'index',
            'productList',
            'summary',
            'member',
            'search',
        ], 
        env: {
            platformId: 1, 
            shopType: 0, 
            shopId: window.page_data ? window.page_data.shopId || '' : '',
            venderId: window.page_data ? window.page_data.venderId || '' : '',
            venderType: window.page_data ? window.page_data.venderType : '',
        },
        selected: {
        },
    }
    const DefaultDialogConfig = {
        title: '链接小工具',
        type: 'normal',
        width: 1100,
        height: 700,
        className: 'cd-link-tool',
        content: linkToolLayoutTpl,
        helper: {
            url: window.page_data.isSDKM
                ? '//conecli.com'
                : 'https://conecli.com/article/680.html',
            target: '_blank',
        },
    }
    class LinkTool {
        static Type = {
            CustomLink: 1, 
            ProductLink: 2, 
            Coupon: 3, 
            Index: 4, 
            SearchResult: 5, 
            Summary: 6, 
            List: 7, 
            MemberCenter: 8, 
            ActivityPage: 9, 
            ShopCategory: 10, 
            Anchor: 11, 
            Detail: 12, 
            Custom: 13, 
            Live: 14, 
            AuctionProduct: 15, 
            MiniApps: 18, 
            WidgetPlug: 17, 
            yaoProduct: 16, 
            SceneGuide: 19, 
            DoctorList: 20, 
            MiniApp: 21, 
            FansMini: 24, 
            FinanceCouponLink: 25, 
        }
        static TabType = {
            frequent: 0, 
            product: 1, 
            userdefine: 7, 
            activity: 3, 
            shopCategory: 5, 
            coupon: 2, 
            anchor: 4, 
            custom: 6, 
            index: -1, 
            productList: -2, 
            summary: -3, 
            member: -4, 
            search: -5, 
            live: 8, 
            auction: 9, 
            miniApps: 11, 
            widgetPlug: 12, 
            yao: 10, 
            sceneGuide: 13, 
            doctorList: 14, 
            miniApp: 15, 
            fansMini: 16, 
            financeCouponLink: 17, 
        }
        static SwitchMap = {
            [LinkTool.Type.CustomLink]: LinkTool.TabType.custom,
            [LinkTool.Type.ProductLink]: LinkTool.TabType.product,
            [LinkTool.Type.Coupon]: LinkTool.TabType.coupon,
            [LinkTool.Type.Index]: LinkTool.TabType.frequent,
            [LinkTool.Type.SearchResult]: LinkTool.TabType.frequent,
            [LinkTool.Type.Summary]: LinkTool.TabType.frequent,
            [LinkTool.Type.List]: LinkTool.TabType.frequent,
            [LinkTool.Type.MemberCenter]: LinkTool.TabType.frequent,
            [LinkTool.Type.ActivityPage]: LinkTool.TabType.activity,
            [LinkTool.Type.ShopCategory]: LinkTool.TabType.shopCategory,
            [LinkTool.Type.Anchor]: LinkTool.TabType.anchor,
            [LinkTool.Type.Custom]: LinkTool.TabType.userdefine,
            [LinkTool.Type.Live]: LinkTool.TabType.live,
            [LinkTool.Type.AuctionProduct]: LinkTool.TabType.auction,
            [LinkTool.Type.yaoProduct]: LinkTool.TabType.yao,
            [LinkTool.Type.MiniApps]: LinkTool.TabType.miniApps,
            [LinkTool.Type.WidgetPlug]: LinkTool.TabType.widgetPlug,
            [LinkTool.Type.SceneGuide]: LinkTool.TabType.sceneGuide,
            [LinkTool.Type.DoctorList]: LinkTool.TabType.doctorList,
            [LinkTool.Type.MiniApp]: LinkTool.TabType.miniApp,
            [LinkTool.Type.FansMini]: LinkTool.TabType.fansMini,
            [LinkTool.Type.FinanceCouponLink]:
                LinkTool.TabType.financeCouponLink,
        }
        static TypeName = {
            1: '自定义链接',
            2: '商品链接',
            3: '优惠券',
            4: '店铺首页',
            5: '店铺搜索结果页',
            6: '店铺简介页',
            7: '店铺列表页',
            8: '会员中心',
            9: '店铺二级页',
            10: '店铺分类',
            11: '锚点',
            12: '详情页',
            13: '店铺自定义页',
            14: '直播',
            15: '拍品',
            16: '药品',
            18: '小程序链接',
            21: '购物小程序',
        }
        constructor(config) {
            this._config = this._getConfig(config)
            
            if (window.page_data && window.page_data.isAuction) {
                if (this._config.tab && this._config.tab.length > 0) {
                    let index = this._config.tab.indexOf('product')
                    if (index !== -1) {
                        this._config.tab[index] = 'auction'
                        this._config.tab = [...new Set(this._config.tab)]
                    }
                }
                if (this._config.mTab && this._config.mTab.length > 0) {
                    let index = this._config.mTab.indexOf('product')
                    if (index !== -1) {
                        this._config.mTab[index] = 'auction'
                        this._config.mTab = [...new Set(this._config.mTab)]
                    }
                }
                if (this._config.pcTab && this._config.pcTab.length > 0) {
                    let pIndex = this._config.pcTab.indexOf('product')
                    if (pIndex !== -1) {
                        this._config.pcTab[pIndex] = 'auction'
                        this._config.pcTab = [...new Set(this._config.pcTab)]
                    }
                }
            }
            if (window.page_data && window.page_data.yaoB2B == true) {
                if (this._config.tab && this._config.tab.length > 0) {
                    let index = this._config.tab.indexOf('product')
                    if (index !== -1) {
                        this._config.tab[index] = 'yao'
                        this._config.tab = [...new Set(this._config.tab)]
                    }
                }
                if (this._config.mTab && this._config.mTab.length > 0) {
                    let index = this._config.mTab.indexOf('product')
                    if (index !== -1) {
                        this._config.mTab[index] = 'yao'
                        this._config.mTab = [...new Set(this._config.mTab)]
                    }
                }
                if (this._config.pcTab && this._config.pcTab.length > 0) {
                    let pIndex = this._config.pcTab.indexOf('product')
                    if (pIndex !== -1) {
                        this._config.pcTab[pIndex] = 'yao'
                        this._config.pcTab = [...new Set(this._config.pcTab)]
                    }
                }
            }
            let thisDialogConfig = $.extend(true, {}, DefaultDialogConfig, {
                onDomReady: ($dom) => {
                    this.$dialog = $dom
                    this.linkChange(this._config.linkObj)
                },
                onClose: () => {
                    this.cancel()
                },
            })
            thisDialogConfig.content = template.render(
                DefaultDialogConfig.content,
                this._config,
            )
            this.modal = new Modal(thisDialogConfig)
            this.$dialog = this.modal._$dialog
            this._addEvnet()
            let type
            let linkType = this._config.linkObj.linkType
            let first = this.$dialog.find('input[type="radio"]').eq(0)
            if (config.linkObj !== null && linkType >= 0) {
                type = LinkTool.SwitchMap[linkType]
                let radio = this.$dialog
                    .find('.J_tab input[type="radio"]')
                    .filter(function () {
                        return LinkTool.TabType[$(this).attr('id')] === type
                    })
                if (radio.length) {
                    radio[0].checked = true
                } else {
                    type =
                        LinkTool.TabType[
                            this.$dialog
                                .find('input[type="radio"]')
                                .eq(0)
                                .attr('id')
                        ]
                    if (first.length) {
                        first[0].checked = true
                    }
                }
            } else {
                if (first.length) {
                    type = LinkTool.TabType[first.attr('id')]
                    first[0].checked = true
                }
            }
            this.switchTab(type)
            const $input = $('.J_tab input', this.$dialog)
            if ($input.length === 1) {
                const $Tab = $input.closest('.J_tab')
                $Tab.css('pointer-events', 'none')
                $input[0].checked = false
            }
            Messager.trigger('linkChange', this._config.linkObj)
        }
        
        _getConfig(config) {
            if (config.tabValueForbidIncrease === undefined) {
                config.tabValueForbidIncrease =
                    DefaultConfig.tabValueForbidIncrease
            }
            let tab = []
            if (config.env.platformId === 0) {
                if (!config.tab || config.tab.length == 0) {
                    tab = DefaultConfig.pcTab
                } else {
                    tab = config.tab.filter((val) => {
                        return DefaultConfig.pcTab.includes(val)
                    })
                }
            } else if (config.env.platformId === 1) {
                if (!config.tab || config.tab.length == 0) {
                    tab = DefaultConfig.mTab
                } else {
                    tab = config.tab.filter((val) => {
                        return DefaultConfig.mTab.includes(val)
                    })
                }
            } else {
                console.warn('初始化没有传入platformId')
            }
            let shopType = config.env.shopType
            if (shopType === ShopType.MEDICAL) {
                tab = tab.filter((val) => {
                    if (val === 'coupon' || val === 'activity') {
                        return false
                    }
                    return true
                })
            } else if (
                shopType === ShopType.SAM &&
                config.env.platformId === 0
            ) {
                tab = tab.filter((val) => {
                    if (val === 'activity') {
                        return false
                    }
                    return true
                })
            } else if (shopType === ShopType.JMALL) {
                tab = tab.filter((val) => {
                    if (val === 'frequent') {
                        return false
                    }
                    return true
                })
            } else if (shopType === ShopType.YAO) {
                tab = tab.filter((val) => {
                    if (
                        val === 'userdefine' ||
                        val === 'activity' ||
                        val === 'shopCategory'
                    ) {
                        return false
                    }
                    return true
                })
            } else if (shopType !== ShopType.JMALL) {
                tab = tab.filter((val) => {
                    if (val === 'miniApps' || val === 'widgetPlug') {
                        return false
                    }
                    return true
                })
            }
            if (window.page_data.isSDKM) {
                tab = tab.filter((val) => {
                    if (val === 'custom') {
                        return false
                    }
                    return true
                })
            }
            if (
                !config.tabValueForbidIncrease &&
                !(
                    tab.length == 1 &&
                    (tab[0] == 'sceneGuide' ||
                        tab[0] == 'coupon' ||
                        tab[0] == 'live' ||
                        tab[0] == 'anchor')
                ) &&
                !page_data.pingouShop &&
                shopType !== ShopType.JMALL &&
                page_data.appType !== 9 && 
                !page_data.isSDKM && 
                page_data.clientType !== 'PC' &&
                !page_data.isLuxuryGoodsVender 
            ) {
                tab = tab.concat(['miniApp', 'fansMini'])
            }
            let result = $.extend(true, {}, DefaultConfig, config)
            result.tab = tab
            result.linkObj = result.linkObj || DefaultConfig.linkObj
            return result
        }
        _addEvnet() {
            this.$dialog.on('click', '.J_tab label', (e) => {
                e.stopPropagation()
            })
            this.$dialog.on('click', '.J_tab', () => {
                let checked = this.$dialog.find(
                    '.J_tab input[type="radio"]:checked',
                )
                let type = LinkTool.TabType[checked.attr('id')]
                this.switchTab(type)
            })
            this.$dialog.on('keyup', '.J_linkInput', this.linkChange.bind(this))
            this.linkChangeKey = Messager.on('linkChange', (req, res) => {
                let input = this.$dialog.find('.J_linkInput')
                const resCopy = JSON.parse(JSON.stringify(res))
                delete resCopy.isFromClick
                input
                    .val(res.link)
                    .attr('data-linkobj', JSON.stringify(resCopy))
            })
            
            this.confirmKey = Messager.on('confirm', () => {
                let linkObj = this.$dialog
                    .find('.J_linkInput')
                    .attr('data-linkobj')
                linkObj = JSON.parse(linkObj)
                if (linkObj.linkType === 1 && !linkObj.originalData) {
                    Message.error('没有选择链接或输入链接为空')
                    return false
                }
                if (linkObj.linkType === 1) {
                    const url = this.$dialog.find('.J_linkInput').val()
                    if (
                        /^\/\/coupon.m.conecli.com\/coupons\/show.action/.test(url)
                    ) {
                        linkObj.originalData = linkObj.link = url
                    }
                }
                typeof linkObj.link === 'string' &&
                    (linkObj.link = linkObj.link.trim())
                typeof linkObj.originalData === 'string' &&
                    (linkObj.originalData = linkObj.originalData.trim())
                this.send(linkObj)
                this.dispose()
            })
            
            this.cancelKey = Messager.on('cancel', () => {
                this.cancel()
            })
        }
        switchTab(type) {
            let _this = this
            let $contentNode = this.$dialog.find('.J_mainContent')
            if (this.contentCom) {
                this.contentCom.dispose()
            }
            let node = $contentNode
            let { linkAttr, originalDataAttr, env, linkObj, tab, selected } =
                this._config
            switch (type) {
                case LinkTool.TabType.frequent:
                    this.contentCom = new FrequentLink({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        tab,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.product:
                    this.contentCom = new ProductLink({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.coupon:
                    this.contentCom = new Coupon({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        selected,
                        getParentLinkObj: () => {
                            return _this.getLinkObj()
                        },
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.activity:
                    this.contentCom = new ActivityPage({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.anchor:
                    this.contentCom = new Anchor({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.shopCategory:
                    this.contentCom = new ShopCategory({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.custom:
                    this.contentCom = new CutsomLink({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.userdefine:
                    this.contentCom = new UserDefineLink({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.live:
                    this.contentCom = new Live({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.auction:
                    this.contentCom = new AuctionProduct({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.yao:
                    this.contentCom = new YaoProduct({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.miniApps:
                    this.contentCom = new MiniApps({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.widgetPlug:
                    this.contentCom = new WidgetPlug({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.sceneGuide:
                    this.contentCom = new SceneGuide({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.doctorList:
                    this.contentCom = new DoctorList({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.miniApp:
                    this.contentCom = new MiniApp({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.fansMini:
                    this.contentCom = new FansMini({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                case LinkTool.TabType.financeCouponLink:
                    this.contentCom = new FinanceCouponLink({
                        node,
                        linkAttr,
                        originalDataAttr,
                        env,
                        linkObj,
                        onDomUpdate: function () {
                            let linkObj = JSON.parse(
                                _this.$dialog
                                    .find('.J_linkInput')
                                    .attr('data-linkobj'),
                            )
                            Messager.trigger('linkChange', linkObj)
                        },
                    })
                    break
                default:
            }
            this.clearLink()
        }
        
        getLinkObj() {
            if (this.$dialog) {
                let linkObj = JSON.parse(
                    this.$dialog.find('.J_linkInput').attr('data-linkobj'),
                )
                return linkObj
            }
            return null
        }
        
        clearLink() {
            let linkObj = DefaultConfig.linkObj
            Messager.trigger('linkChange', linkObj)
        }
        send(obj) {
            if (obj.linkType === undefined) {
                obj.linkType = 1
                obj.originalData = obj.link
            }
            let extraData
            if (Object.prototype.hasOwnProperty.call(obj, 'extraData')) {
                extraData = obj.extraData
                delete obj.extraData
            }
            this._config.onConfirm(obj.link, obj, extraData)
            this.dispose()
        }
        cancel() {
            this.dispose()
        }
        linkChange(linkObj) {
            let input = this.$dialog.find('.J_linkInput')
            input
                .val(linkObj.link)
                .attr('data-linkobj', JSON.stringify(linkObj))
        }
        
        dispose() {
            this.contentCom.dispose()
            this.modal.close()
            
            Messager.off(this.cancelKey)
            Messager.off(this.confirmKey)
            Messager.off(this.linkChangeKey)
        }
    }
    return LinkTool
})($)
export default LinkTool