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 { Messager } from '@core/component/msgDistribute';
import AUCTION_RENDER from './auction.tpl'
import ITEM_RENDER from './item.tpl'
import LinkTool from '../../linkTool';
import domain from '@core/util/domain';
import uniqWith from 'lodash/uniqWith'
import {
    send
} from "@core/lib/util";
const SKU_API = domain.opJshop + '/operations/skuGoods/getGoodListByCatesIds';
const CATEGORY_API = domain.opJshop + '/operations/skuGoods/getGoodCatesByFatherId';
const SKUS_INFO_API = domain.opJshop + '/operations/skuGoods/getGoodInfoBySkuId';
let category1 = []
let category2 = []
let PARAM = {
    channel: 1,
    dataType: 5,
    pageNo: 1,
    pageSize: 10
}
const AuctionProduct = (($) => {
    class AuctionProduct {
        constructor(config) {
            this._config = this._getConfig(config);
            this.el = this._config.node;
            this.$el = $(this.el);
            if (this._config.linkObj && this._config.linkObj.originalData) {
                try {
                    let originalData = JSON.parse(this._config.linkObj.originalData);
                    this.auctionId = originalData.auctionId || '';
                    this.skuId = originalData.skuId || '';
                } catch (error) {
                    this.auctionId = '';
                    this.skuId = '';
                }
            }
            this.render();
            let self = this;
            
            this._addEvent();
        }
        async render(){
            await this._loadCategoryData()
            let html = AUCTION_RENDER({ category1 })
            this.$el.html(html)
            this.$el.find('select').simSelect()
            await this._querySkus()
            await this._loadListData()
        }
        renderTable() {
            let self = this;
            if (this.skuInfo && !this.isSearch && this.pageInfo.pageNo === 1) {
                this.list.unshift(this.skuInfo)
                this.list = uniqWith(this.list, (a, b) => a.auctionId === b.auctionId)
            }
            let html = ITEM_RENDER({ list: this.list, auctionId: this.auctionId});
            this.$el.find('.J_table tbody').html(html);
            let pageConfig = {
                current: this.pageInfo.pageNo, 
                total: this.pageInfo.pageCount,
                pageChange: function ({current}) {
                    self._loadListData({pageNo:current})
                }
            }
            if (this.pageInfo.pageCount > 1) {
                if (this.pageTable) {
                    this.pageTable.dispose();
                }
                this.pageTable = new ShortPagination({
                    node: this.$el.find('.J_min_page'),
                    ...pageConfig
                })
            }
        }
        async _querySkus(ids){
            if (!ids && !this.skuId) {
                return;
            }
            try {
                var res = await send({
                    url: SKUS_INFO_API,
                    query: {
                        channel: 1,
                        dataType: 5,
                        ids: ids || this.skuId
                    }
                })
                if (res.data && res.data.goodList) {
                    if (res.data.goodList[0]) {
                        this.skuInfo = res.data.goodList[0];
                    }
                }
            } catch (error) {
                
            }
        }
        async _loadCategoryData(id) {
            try {
                var res = await send({
                    url: CATEGORY_API,
                    query: {
                        categoryId: id || 0
                    }
                })
                if (id) {
                    category2 = res.data;
                } else {
                    category1 = res.data;
                }
            } catch (e) { }
        }
        
        async _loadListData(param, isSearch = false) {
            
            if (this.$el.find('.J_search-input').length > 0) {
                PARAM.keyWord = this.$el.find('.J_search-input').val().trim();
            }
            PARAM.forceMerge = !!this.$el.find('.J_goodsQueryType').val();
            try {
                let res = await send({
                    url: SKU_API,
                    query: {
                        ...PARAM,
                        ...param
                    }
                })
                
                if (res) {
                    for (let item of res.data) {
                        item.wname = item.wname.replace(/<[^>]+>/g, '');
                    }
                }
                this.list = res.data;
                this.isSearch = isSearch;
                this.pageInfo = res.pageInfo;
                this.renderTable(res.data)
                if (isSearch && this.list.length === 0) {
                    Message.warn('没有搜索到商品!');
                }
            } catch (error) {
                
            }
        }
        _getCatId() {
            let val1 = this.$el.find('.J_category1-select').val();
            let val2 = this.$el.find('.J_category2-select').val();
            let cateId = [];
            val1 && cateId.push(val1);
            val2 && cateId.push(val2);
            return cateId;
        }
        
        _addEvent() {
            let self = this;
            this.$el.on('change.auctionLink', '.J_category1-select', async function () {
                let category1Id = $(this).val();
                await self._loadCategoryData(category1Id)
                let listHtml = '<option value="">请选择二级分类</option>';
                if (category1Id){
                    category2.forEach((item) => {
                        listHtml += `<option value="${item.id}">${item.title}</option>`
                    })
                }
                self.$el.find('.J_category2-select').html(listHtml).next().remove().end().data('simSelect', null).simSelect();
            });
            this.$el.on('click.auctionLink', '.J_search-btn', async function () {
                await self._loadListData({
                    cateId: self._getCatId().join(','),
                    pageNo: 1
                }, true);
            });
            this.$el.on('click.auctionLink','tbody tr',function (e) {
                let $target = $(this);
                let skuId = parseInt($target.attr('data-skuId'))
                let auctionId = parseInt($target.attr('data-auctionId'))
                $target.find('input').prop('checked', true);
                Messager.trigger('linkChange', {
                    link: `//${self._config.env.platformId == 0 ? '' : 'm'}paimai.conecli.com/${auctionId}`,
                    originalData: JSON.stringify({
                        skuId,
                        auctionId
                    }),
                    linkType: 15
                })
            });
            this.$el.on('click.auctionLink', '.J_ok', function () {
                Messager.trigger('confirm');
            })
        }
        
        _getConfig(config) {
            let result = $.extend(true, {}, config);
            return result;
        }
        
        dispose() {
            Messager.off(this.linkChangeKey);
            this.$el.off('change.auctionLink');
            this.$el.off('click.auctionLink');
        }
    }
    return AuctionProduct;
})($);
export default AuctionProduct;