import Modal from '@core/component/modal';
import Message from '@core/component/message';
import LongPagination from '@core/component/longPagination';
import { send } from '@core/lib/util'
import { status1, status4 } from '@core/lib/const'
import Domain from '@core/util/domain'
import MAIN_RENDER from './template/main.tpl'
import LIST_RENDER_1 from './template/list1.tpl'
import LIST_RENDER_2 from './template/list2.tpl'
import LIST_RENDER_3 from './template/list3.tpl'
import LIST_RENDER_4 from './template/list4.tpl'
import LIST_RENDER_5 from './template/list5.tpl'
import SKUS_RENDER from './template/skus.tpl'
import diffDOM from 'diff-dom'
import differenceWith from 'lodash/differenceWith'
import unionWith from 'lodash/unionWith'
import { getChannelId, IsYaoB2B } from '@core/util/channelUtil'
let RENDER = [
    LIST_RENDER_1,
    LIST_RENDER_2,
    LIST_RENDER_3,
    LIST_RENDER_4,
    LIST_RENDER_1,
    LIST_RENDER_1,
    LIST_RENDER_1, 
    LIST_RENDER_5, 
]
let dd = new diffDOM({
    valueDiffing: false,
})
let dom = $('<div class="table-con"></div>')[0]
let category1 = []
let category2 = []
let pageObj
const API = {
    category:
        (window.page_data.isSDKM
            ? `${Domain.zxDesigner}/sdk`
            : Domain.opJshop) + '/operations/skuGoods/getGoodCatesByFatherId',
    sku:
        (window.page_data.isSDKM
            ? `${Domain.zxDesigner}/sdk`
            : Domain.opJshop) + '/operations/skuGoods/getGoodListByCatesIds',
    skus:
        (window.page_data.isSDKM
            ? `${Domain.zxDesigner}/sdk`
            : Domain.opJshop) + '/operations/skuGoods/getGoodInfoBySkuId',
    getSuperSkus:
        (window.page_data.isSDKM
            ? `${Domain.zxDesigner}/sdk`
            : Domain.opJshop) + '/operations/skuGoods/getSuperNewProductByPage',
}
let query = {
    pageNo: 1,
    pageSize: 10,
}
const skuReg = /[^0-9|,]/
const HELP_LINK = [
    null,
    {
        link: '//conecli.com/article/756.html',
        text: 'erp促销编码',
    },
    {
        link: '//conecli.com/article/755.html',
        text: '拼购ID',
    },
    null,
]
const sku = (($) => {
    let DefaultConfig = {
        dataType: 1,
        oldDelete: true,
        type: 1,
        limit: 100,
    }
    let DefaultDialogConfig = {
        title: '录入商品',
        width: 1100,
        content: '',
        draggable: false,
        type: Modal.ModalType.TYPE_NORMAL,
    }
    class sku {
        constructor(config) {
            this._config = {
                ...DefaultConfig,
                ...config,
            }
            this.skus = new Set(config.skus)
            this.list = []
            this.selectSkus = []
            this._init()
        }
        async _init() {
            await this._loadCategoryData()
            await this._renderModal()
            this.skus = new Set(await this._loadSkusData())
            
            this._addEvent()
            await this._renderSkusList()
            await this._loadListData()
        }
        _renderModal() {
            let { dataType, node, type } = this._config
            let HELP = HELP_LINK[dataType - 1]
            let button = node
                ? ''
                : `<div class="cd-sku-bottom" style="position: relative;">
                              <div style="position: absolute;left: 0;line-height: 30px;">${
                                  HELP
                                      ? `<a style="font-size: 12px;color: #29f;" target="_blank" href="${HELP.link}">点击查看${HELP.text}获取方式>></a>`
                                      : ''
                              }</div>
                              <button class="cd-big-black-border-btn J_cancel">取消</button>
                              <button class="cd-big-red-btn J_submit">确定</button>
                            </div>`
            let isYaoB2B = IsYaoB2B()
            let content = `<div class="cd-sku">
                            ${MAIN_RENDER({
                                category1,
                                dataType,
                                type,
                                isYaoB2B,
                            })}
                            ${button}
                        </div>`
            if (node) {
                this.root = this._config.node.html(content)
            } else {
                this.dialog = new Modal({
                    ...DefaultDialogConfig,
                    content,
                })
                this.root = this.dialog.$dialog
            }
            this.root.find('select').simSelect()
            this.listRoot = this.root.find('.J_list-con')[0]
            this.skusRoot = this.root.find('.J_select-con')[0]
        }
        async _renderList() {
            if (!this.listRoot) {
                return
            }
            let skus = [...this.skus]
            if (skus.length > this._config.limit) {
                skus.length = this._config.limit
                Message.warn(`最多选择${self._config.limit}个商品!`)
            }
            dom.innerHTML = RENDER[this._config.dataType - 1]({
                list: this.list,
                skus,
                isAll: !differenceWith(
                    this.list,
                    skus,
                    function (item1, item2) {
                        return item1.id === item2.id
                    },
                ).length,
                status4,
                status1,
                dataType: this._config.dataType,
            })
            dd.apply(this.listRoot, dd.diff(this.listRoot, dom))
        }
        async _renderSkusList() {
            dom.innerHTML = SKUS_RENDER({
                skus: [...this.skus],
                limit: this._config.limit,
                selectSkus: this.selectSkus,
                isAll: !differenceWith(
                    this.finalSkus,
                    this.selectSkus,
                    function (item1, item2) {
                        return item1.id === item2.id
                    },
                ).length,
            })
            dd.apply(this.skusRoot, dd.diff(this.skusRoot, dom))
            $('.J_EldTooltips').remove()
        }
        renderPagination() {
            let mainData = this.mainData
            let self = this
            if (pageObj) {
                pageObj.dispose()
            }
            pageObj = new LongPagination({
                node: this.root.find('.J_page'),
                current:
                    mainData.pageInfo.pageNo || mainData.pageInfo.currentPageNo,
                total: mainData.pageInfo.pageCount,
                middleDisplay: 5,
                eachPageNum: mainData.pageInfo.pageSize,
                totalItem: mainData.pageInfo.totalCount,
                pageChange: function (param) {
                    query.pageNo = param.current
                    self._loadListData({
                        cateId: self._getCatId().join(','),
                    })
                },
            })
        }
        async _loadCategoryData(id) {
            let { dataType } = this._config
            if (dataType !== 1 && dataType !== 5 && dataType !== 6) {
                return
            }
            try {
                var res = await send({
                    url: API.category,
                    query: {
                        categoryId: id || 0,
                    },
                })
                if (id) {
                    category2 = res.data
                } else {
                    category1 = res.data
                }
            } catch (e) {
                console.log(e)
            }
        }
        async _loadListData(param, isSearch) {
            let { dataType } = this._config
            const isMainPushNewProduct = dataType === 7 
            let postQuery = {
                ...query,
                ...param,
                dataType,
            }
            if (dataType == 2) {
                return
            }
            if (dataType == 4) {
                postQuery.pageSize = 300
            }
            postQuery.channel = getChannelId() 
            if (this.root.find('.J_search-input').length > 0) {
                postQuery.keyWord = this.root
                    .find('.J_search-input')
                    .val()
                    .trim()
            }
            postQuery.forceMerge = !!this.root.find('.J_goodsQueryType').val()
            if (isMainPushNewProduct) {
                delete postQuery.cateId
                delete postQuery.dataType
                delete postQuery.channel
                delete postQuery.keyWord
                delete postQuery.forceMerge
            }
            try {
                let res = await send({
                    url: isMainPushNewProduct ? API.getSuperSkus : API.sku,
                    query: postQuery,
                })
                if (res) {
                    for (let item of res.data) {
                        item.wname = item.wname.replace(/<[^>]+>/g, '')
                    }
                }
                this.mainData = res
                this.list = res.data
                this._renderList()
                if (isMainPushNewProduct && this.skus.size === 0) {
                    $('.J_sku-tab-con-item tbody tr:lt(5)')
                        .map((index, item) =>
                            item.querySelector('.J_ui-checkbox'),
                        )
                        .trigger('click')
                }
                if (isSearch && this.list.length === 0) {
                    Message.warn('没有搜索到商品!')
                }
                if (this.mainData.pageInfo.pageCount > 1) {
                    this.root.find('.J_page').show()
                    this.renderPagination()
                } else {
                    this.root.find('.J_page').hide()
                    this.root
                        .find('.cd-version-table-warp')
                        .css('height', '415px')
                }
            } catch (e) {
                console.log(e)
            }
        }
        async _loadSkusData(ids) {
            let { dataType } = this._config
            if (!ids) {
                ids = [...this.skus].map((item) => item.id).join(',')
            }
            if (!ids) {
                return []
            }
            let res = await send({
                url: API.skus,
                query: {
                    ids,
                    dataType,
                    pingouShop: page_data.pingouShop,
                    channel: getChannelId(), 
                },
            })
            if (res.data.errorIds && res.data.errorIds.length) {
                Message.warn(`${res.data.errorIds}没查到商品，请检查`)
                this.root
                    .find('.J_sku-textarea')
                    .val(res.data.errorIds)
                    .addClass('sku-error')
                this.root
                    .find('.J_sku-error-msg')
                    .show()
                    .find('i')
                    .text(res.data.errorIds.split(',').length)
            } else {
                this.root
                    .find('.J_sku-textarea')
                    .removeClass('sku-error')
                    .val('')
            }
            this.root.find('.J_sku-nums').hide()
            if (window.page_data && window.page_data.yaoB2B === 'true') {
                res.data.goodList.map((item) => (item.jdPrice = item.op))
            }
            return res.data.goodList
        }
        _getCatId() {
            let val1 = this.root.find('.J_category1-select').val()
            let val2 = this.root.find('.J_category2-select').val()
            let cateId = []
            val1 && cateId.push(val1)
            val2 && cateId.push(val2)
            return cateId
        }
        _addEvent() {
            let self = this
            let root = this.root
            let { dataType } = this._config
            root.on('click', function (e) {
                e.stopPropagation()
            })
            $(document).on('click', '.J_modalOverlay', function (e) {
                e.stopPropagation()
            })
            root.on('click', '.J-sku-select-type-con span', function () {
                let index = $(this).index()
                $(this)
                    .addClass('sku-tab-active')
                    .siblings()
                    .removeClass('sku-tab-active')
                root.find('.J_sku-tab-con-item')
                    .eq(index)
                    .show()
                    .siblings('.J_sku-tab-con-item')
                    .hide()
            })
            root.on('change', '.J_category1-select', async function () {
                await self._loadCategoryData($(this).val())
                let listHtml = '<option value="">请选择二级分类</option>'
                category2.forEach((item) => {
                    listHtml += `<option value="${item.id}">${item.title}</option>`
                })
                root.find('.J_category2-select')
                    .html(listHtml)
                    .next()
                    .remove()
                    .end()
                    .data('simSelect', null)
                    .simSelect()
            })
            root.on('click', '.J_search-btn', async function () {
                await self._loadListData(
                    {
                        cateId: self._getCatId().join(','),
                        pageNo: 1,
                    },
                    true,
                )
            })
            root.on('blur', '.J_sku-textarea', function () {
                var jInput = $(this),
                    value = $.trim(jInput.val())
                jInput.val(
                    $.trim(value)
                        .replace(/\n/g, ',')
                        .replace(/，/g, ',')
                        .replace(/\s/g, '')
                        .replace(/,+/g, ',')
                        .replace(/^,|,$/g, ''),
                )
            })
            root.on('click', '.J_add-sku', async function () {
                let skus = root.find('.J_sku-textarea').val().trim(),
                    beforeSkuListNum = self.skus.size
                if (beforeSkuListNum > self._config.limit) {
                    Message.warn(`最多录入${self._config.limit}个商品!`)
                    return
                }
                if (skuReg.test(skus)) {
                    Message.warn(`输入格式有误，请检查！`)
                    return
                }
                if (dataType == 1 && skus.length === 0) {
                    return
                }
                if (skus.length === 0) {
                    let tipsMsg = 'skuID'
                    if (dataType == 2) {
                        tipsMsg = 'erp促销编码'
                    }
                    if (dataType == 3) {
                        tipsMsg = '拼购id'
                    }
                    Message.warn(`请输入正确的${tipsMsg}!`)
                    return
                }
                let newSkus = await self._loadSkusData(skus)
                if (beforeSkuListNum + newSkus.length > self._config.limit) {
                    Message.warn(`最多录入${self._config.limit}个商品!`)
                    return
                }
                self.skus = new Set(
                    unionWith([...self.skus], newSkus, function (item1, item2) {
                        return item1.id === item2.id
                    }),
                )
                self._renderSkusList()
                self._renderList()
            })
            root.on('click', 'thead .J_ui-checkbox', function () {
                let checked = !$(this).hasClass('checked')
                if (checked) {
                    self.skus = new Set(
                        unionWith(
                            [...self.skus],
                            self.list,
                            function (item1, item2) {
                                return item1.id === item2.id
                            },
                        ),
                    )
                } else {
                    self.skus = new Set([
                        ...differenceWith(
                            [...self.skus],
                            self.list,
                            function (item1, item2) {
                                return item1.id === item2.id
                            },
                        ),
                    ])
                }
                if (
                    checked &&
                    self._config.limit &&
                    self.skus.size >= self._config.limit
                ) {
                    Message.warn(`最多选择${self._config.limit}个商品!`)
                    self.skus = new Set(
                        [...self.skus].splice(0, self._config.limit),
                    )
                }
                self._renderList()
                self._renderSkusList()
            })
            root.on('click', 'tbody .J_ui-checkbox', function (e) {
                let index = $(this).closest('tr').index()
                let checked = !$(this).hasClass('checked')
                if ($(this).hasClass('disabled')) {
                    e.stopPropagation()
                    return
                }
                if (
                    checked &&
                    self._config.limit &&
                    self.skus.size >= self._config.limit
                ) {
                    Message.warn(`最多选择${self._config.limit}个商品!`)
                    return false
                }
                if (checked) {
                    self.skus.add(self.list[index])
                } else {
                    self.skus.forEach((item, value, set) => {
                        if (item.id === self.list[index].id) {
                            set.delete(value)
                        }
                    })
                }
                self._renderList()
                self._renderSkusList()
            })
            root.on('click', '.J_delete-sku-item', function () {
                let index = $(this).closest('li').attr('data-index')
                self.skus.delete([...self.skus][index])
                self._renderList()
                self._renderSkusList()
            })
            root.on('keyup keydown', '.J_search-input', function (e) {
                if (e.which == 13) {
                    root.find('.J_search-btn').trigger('click')
                }
            })
            root.on('keyup', '.J_sku-textarea', function () {
                let skus = $(this).val().trim()
                if (!skus.length) {
                    root.find('.J_sku-error-msg')
                        .hide()
                        .siblings('.J_sku-nums')
                        .hide()
                    return
                }
                if (skuReg.test(skus)) {
                    root.find('.J_sku-error-msg')
                        .hide()
                        .siblings('.J_sku-nums')
                        .hide()
                } else {
                    $(this).removeClass('sku-error')
                    root.find('.J_sku-error-msg')
                        .hide()
                        .siblings('.J_sku-nums')
                        .show()
                        .find('i')
                        .text(skus.split(',').length)
                }
            })
            root.on('click', '.J_empty-textarea', function () {
                root.find('.J_sku-textarea').val('')
                root.find('.J_sku-error-msg')
                    .hide()
                    .siblings('.J_sku-nums')
                    .hide()
            })
            
            root.on('click', '.J_delete-skus', function () {
                if (self.skus.size > 0) {
                    root.find('.J_skus-delete-overlay').show()
                }
            })
            root.on('click', '.J_cancel-delete-skus', function () {
                root.find('.J_skus-delete-overlay').hide()
            })
            root.on('click', '.J_do-delete-skus', function () {
                
                self.skus = new Set([])
                self._renderSkusList()
                self._renderList()
                root.find('.J_skus-delete-overlay').hide()
            })
            root.on('click', '.J_cancel', function () {
                self.dialog.close()
            })
            root.on('click', '.J_submit', function () {
                if (self.skus.size > 0) {
                    self._config.onSelect &&
                        self._config.onSelect([...self.skus])
                    self.dialog.close()
                } else {
                    Message.error(`您还未选择或录入商品!`)
                }
            })
        }
        
        dispose() {
        }
    }
    return {
        open: (opt) => {
            return new sku(opt)
        },
    }
})($)
export default sku