import { tbodyTpl, tpl, yiyaoTpl } from './productLinkTpl'
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 Select from '@core/component/select';
import { Messager } from '@core/component/msgDistribute'
import LinkTool from '../../linkTool'
import domain, { INTERFACE } from '@core/util/domain'
import { ShopType } from '@core/util/channelUtil'
import DefaultDatasM from '@core/component/form/DefaultDatasM'
const ProductLink = (($) => {
    const DefaultConfig = {
        tpl: tpl,
        tbodyTpl: tbodyTpl,
    }
    class ProductLink {
        constructor(config) {
            this._config = this._getConfig(config)
            this.el = this._config.node
            this.$el = $(this.el)
            let html = template.render(this._config.tpl, this._config)
            this.$el.html(html)
            let self = this
            let pageTableConfig = {
                node: this.$el.find('.J_table')[0],
                className: 'cd-mytable',
                theadRenderer: ['商品图', '商品名', 'SKU ID', '价格'],
                columnWidth: ['15%', '55%', '15%', '15%'],
                itemRenderer: this._config.tbodyTpl,
                loading: true,
                frontEndPaging: false,
                fixedThead: true,
                pagination: ShortPagination,
                onPageChange: (data) => {
                    let searchType = $('.J_goodsQueryType').val()
                    searchType === '1' ? (searchType = 2) : ''
                    self.queryData(
                        $.extend(this.getSearchInfo(searchType), {
                            pageNo: data.selected,
                        }),
                    )
                },
                onDomReady: () => {},
                onDomUpdate: this._config.onDomUpdate,
            }
            if (this._config.env.shopType === 3) {
                pageTableConfig.theadRenderer = [
                    '商品图',
                    '商品名',
                    '零售价',
                    '批发价',
                ]
                pageTableConfig.columnWidth = ['15%', '55%', '15%', '15%']
            }
            this.eldSelect = new Select('.J_goodsQueryType')
            this.pageTable = new PageTable(pageTableConfig)
            this.search(2)
            this._addEvent()
        }
        
        async queryData(config) {
            let { skuIds, pageNo, keyword, type } = config
            pageNo = pageNo || 1
            let { platformId, shopType } = this._config.env
            switch (shopType) {
                case 3: 
                    shopType = 128
                    break
                case 4: 
                    shopType = 0
            }
            if (type === 1 && keyword !== '' && !/^\d+$/.test(keyword)) {
                Message.error('请输入正确的SKU ID')
                return false
            }
            
            let data
            if (window.page_data.isSDKM) {
                data = DefaultDatasM.linkTool.goodsList
            } else {
                data = await fetch({
                    url: `${domain.backend}/mshop/goods/goodsList.json`,
                    data: {
                        cids: 0,
                        pageNo,
                        pageSize: 4,
                        shopType,
                        platformId,
                        skuIds,
                        keyword,
                        type,
                    },
                    dataType: 'jsonp',
                })
            }
            if (data.result === true) {
                if (shopType === ShopType.JD || shopType === ShopType.JMALL) {
                    data.data.datas.forEach((val) => {
                        val.link = `//conecli.com/${val.skuId}.html`
                    })
                } else if (shopType === ShopType.YHD) {
                    data.data.datas.forEach((val) => {
                        val.link = `//item.yhd.com/${val.skuId}.html`
                    })
                } else if (shopType === 128) {
                    data.data.datas.forEach((val) => {
                        val.link = `${Domain.yao}/item/${val.skuId}.html`
                    })
                }
                if (this._config.env.shopType === 3) {
                    let skuids = data.data.datas
                        .reduce((acc, val) => {
                            acc.push(val.skuId)
                            return acc
                        }, [])
                        .join(',')
                    let priceInfo = await fetch({
                        url: `${Domain.yao}/jshop/priceDetail`,
                        data: {
                            skuids,
                        },
                        dataType: 'jsonp',
                    })
                    let skuObj = {}
                    if (priceInfo.data && priceInfo.data.length) {
                        priceInfo.data.forEach(
                            ({ skuId, retailPrice, wholesalePrice }) => {
                                skuObj[skuId] = {
                                    retailPrice,
                                    wholesalePrice,
                                }
                            },
                        )
                        data.data.datas.forEach((val) => {
                            val.retailPrice =
                                skuObj[val.skuId].retailPrice || '暂无定价'
                            val.wholesalePrice =
                                skuObj[val.skuId].wholesalePrice || '暂无定价'
                        })
                    }
                } else if (this._config.env.shopType === 4) {
                    let skuids = data.data.datas
                        .reduce((acc, val) => {
                            acc.push('J_' + val.skuId)
                            return acc
                        }, [])
                        .join(',')
                    let priceInfo = await fetch({
                        url: INTERFACE.editor.price,
                        data: {
                            skuids,
                            type: 'mgets',
                            source: 'jshop',
                            origin: 2,
                        },
                        dataType: 'jsonp',
                    })
                    let skuObj = {}
                    if (priceInfo.length) {
                        priceInfo.forEach(({ id, sp }) => {
                            skuObj[id.replace('J_', '')] = {
                                sp,
                            }
                        })
                        data.data.datas.forEach((val) => {
                            val.price = ''
                            val.price = skuObj[val.skuId].sp || ''
                        })
                    }
                }
                data.data.datas.forEach((val) => {
                    val.price && (val.price = val.price.replace(/￥/g, ''))
                    val.retailPrice &&
                        (val.retailPrice = val.retailPrice
                            .toString()
                            .replace(/￥/g, ''))
                    val.wholesalePrice &&
                        (val.wholesalePrice = val.wholesalePrice
                            .toString()
                            .replace(/￥/g, ''))
                })
                this.pageTable.update({
                    loading: false,
                    dataProvider: data.data.datas,
                    currentPage: data.data.currentPageNo,
                    totalPage: data.data.totalPage,
                    totalItem: data.data.totalCount,
                })
                this._config.onDomUpdate()
                $('.J_pagination').show()
            } else {
                Message.error(data.msg)
            }
        }
        
        search(searchType) {
            this.queryData(this.getSearchInfo(searchType))
        }
        
        getSearchInfo(searchType) {
            const keyword = this.$el.find('.J_searchInput').val(),
                type =
                    searchType ||
                    parseInt(this.$el.find('.J_goodsQueryType').val() || '1')
            return {
                keyword,
                type,
            }
        }
        
        clearLink() {
            let linkObj = {
                linkType: 1,
                link: '',
                originalData: '',
            }
            Messager.trigger('linkChange', linkObj)
        }
        
        _addEvent() {
            const _this = this
            const searchHolderMap = {
                1: '请输入SKU ID',
                2: '请输入关键字',
                3: '请输入关键字',
            }
            
            this.linkChangeKey = Messager.on('linkChange', (req, res) => {
                this.$el
                    .find('[' + _this._config.linkAttr + ']')
                    .each(function () {
                        let val = $(this).attr(_this._config.linkAttr)
                        if (val === res.link) {
                            this.checked = true
                        } else {
                            this.checked = false
                        }
                    })
            })
            this.$el.on('change', '.J_goodsQueryType', (e) => {
                const key = $(e.currentTarget).val()
                this.$el
                    .find('.J_searchInput')
                    .attr('placeholder', searchHolderMap[key])
            })
            
            this.$el.on(
                'change.productLink',
                '[' + _this._config.linkAttr + ']',
                function () {
                    let $this = $(this)
                    let link = $this.attr(_this._config.linkAttr)
                    let originalData = $this.attr(
                        _this._config.originalDataAttr,
                    )
                    let linkType = LinkTool.Type.ProductLink
                    Messager.trigger('linkChange', {
                        link,
                        originalData,
                        linkType,
                    })
                },
            )
            
            this.$el.on('click.productLink', 'table tbody tr', function () {
                $(this).find('input[type=radio]').trigger('change')
            })
            
            this.$el.on('dblclick.productLink', 'table tbody tr', function () {
                Messager.trigger('confirm')
            })
            
            this.$el.on('click.productLink', '.J_ok', function () {
                Messager.trigger('confirm')
            })
            
            this.$el.on('click.productLink', '.J_cancel', function () {
                Messager.trigger('cancel')
            })
            
            this.$el.on('click.productLink', '.J_searchBtn', () => {
                this.search()
            })
        }
        
        _getConfig(config) {
            let result = $.extend(true, {}, DefaultConfig, config)
            if (config.env.shopType === 3) {
                result.tbodyTpl = yiyaoTpl
            }
            return result
        }
        
        dispose() {
            Messager.off(this.linkChangeKey)
            this.$el.off('change.productLink')
            this.$el.off('click.productLink').off('dblclick.productLink')
        }
    }
    return ProductLink
})($)
export default ProductLink