/**
 * 目录采购-各商场比价首页
 *
 * Created by li.kui on 2020/12/28.
 */
'use strict';
var el  = {
    searchForm: '#searchForm',
    skuName: '#skuName',
    onlineMall: '.online-mall',
    skuData: '#skuData',
    search: '#search',
    skuDetail: '#skuDetail',
    footerPage: '#footerPage',
    totalPage: '#totalPage',
    totalNum: '#totalNum',
    currPage: '#currPage',
    choseBuy: '.chose-buy',
    choseBuySku: [],
    accessToken: '#accessToken',
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    var searchHeight = $(el.searchForm).outerHeight() + 10;
    $(el.skuData).css('height', (el.bodyHeight - searchHeight) + 'px');

    $(el.searchForm).keydown(function(e) {
        if (e.keyCode === 13) {
            buttonSearch();
        }
    });
});

$(el.search).click(function () {
    buttonSearch();
})

/**
 * 查询按钮
 */
function buttonSearch() {
    //el.choseBuySku = [];
    commodityDataSearch(1);
}


/**
 * 数据查询
 *
 * @param pageNum 当前页码
 */
function commodityDataSearch(pageNum) {
    /*var omCheckBox = $(el.onlineMall), choseOm = [];
    for (var i = 0; i < omCheckBox.length; i++) {
        if($(omCheckBox[i]).prop('checked')) {
            choseOm.push($(omCheckBox[i]).data('source'));
        }
    }
*/
  /*  if(choseOm.length === 0){
        topWin.layer.alert('请至少选择一个商城', {icon: 0});
        return false;
    }*/

    var skuName = $(el.skuName).val();
    if(!skuName){
        topWin.layer.alert('请填写商品名称', {icon: 0});
        return false;
    }

    var query = {};
    query.sources = "ZKH";
    query.product_name = skuName;
    query.pageNum = pageNum;
    query.pageSize = 14;

    var loading = layer.msg('数据查询中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: '/pc/mall/shopping/rest/find/commodity',
        data: query,
        success: function (res) {
            dataRender(res, loading, pageNum);
        },
        error: function (data) {
            layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 数据渲染
 *
 * @param queryData 查询出来的数据
 * @param loading 加载中
 * @param pageNum 当前页码
 */
function dataRender(queryData, loading, pageNum) {
    $(el.accessToken).val(queryData.accessToken);
    var skuData = queryData.result.records, pageHtml = [];
    for (var n = 0; n < skuData.length; n++) {
        var sku = skuData[n], skuKey = sku.source + sku.skuNo;
         if("ZKH" == sku.source){
             sku.sourceName = "震坤行";
         }

        /*if(sku.product_img === 'https://image-c.ehsy.com') {
            sku.product_img = '/static/img/nopic.jpg'
        }*/

        /*if("XY" == sku.source){
            pageHtml.push('<div class="item">');
            pageHtml.push('<a href="' + sku.product_desc_url + '" target="_blank" title="' + sku.product_name + '">');
            pageHtml.push('<img style="width: 208px; height: 208px; border: none;" alt="' + sku.product_name + '" src="' + sku.product_img + '">');
            pageHtml.push('</a>');
            pageHtml.push('<p class="sku-title">');
            pageHtml.push('<a href="' + sku.product_desc_url + '" title="' + sku.product_name + '" target="_blank">');
            pageHtml.push(sku.product_name + '</a>');
            pageHtml.push('</p>');
            pageHtml.push('<p class="sku-price">');
            pageHtml.push('<span><b>¥' + sku.product_price + '</b><b>/' + sku.product_unit + '</b></span>');
            pageHtml.push('<span class="span-chose-buy">');
        }*/
        if("ZKH" == sku.source){
                pageHtml.push('<div class="item">');
                pageHtml.push('<a   onclick =orderSubmit("' + sku.skuNo + '") >');
                pageHtml.push('<img style="width: 208px; height: 208px; border: none;" onerror="this.onerror=null; this.src=\'/static/img/zwtp.png\'" src="' + sku.primaryImage + '">');
                pageHtml.push('</a>');
                pageHtml.push('<p class="sku-title">');
                pageHtml.push('<a  title="' + sku.skuName + '"  onclick =orderSubmit("'+sku.skuNo+'") >');
                pageHtml.push(sku.skuName + '</a>');
                pageHtml.push('</p>');
                pageHtml.push('<p class="sku-price">');
                pageHtml.push('<span><b>¥' + sku.price + '</b><b>/' + sku.unit + '</b></span>');
                pageHtml.push('<span class="span-chose-buy">');
            }


                if(!checkWaitData(skuKey)){
                    pageHtml.push('<input type="checkbox" class="chose-buy" data-source="' + sku.source + '" data-sn="' + sku.sourceName + '" data-pc="' + sku.skuNo + '" data-pn="' + sku.skuName + '" data-pp="' + sku.price + '"  data-np="' + sku.nakedPrice + '" data-pu="' + sku.unit + '" onclick="changeCheckBox(this)" />');
                }else {
                    pageHtml.push('<input type="checkbox" checked class="chose-buy" data-source="' + sku.source + '" data-sn="' + sku.sourceName + '" data-pc="' + sku.skuNo + '" data-pn="' + sku.skuName + '" data-pp="' + sku.price + '"  data-np="' + sku.nakedPrice + '"  data-pu="' + sku.unit + '" onclick="changeCheckBox(this)" />');
                }

                pageHtml.push('</span>');
                pageHtml.push('</p>');
                pageHtml.push('<span class="sku-source">' + sku.sourceName + '</span>');
                pageHtml.push('</div>');
            }
            pageHtml.push('<div style="clear: both;"></div>');
            $(el.skuDetail).empty();
            $(el.skuDetail).append(pageHtml.join(''));

            if(pageHtml.length !== 0){
                $(el.footerPage).css('display', 'inline-block');
                // 渲染分页
                var pageRows = 14, totalNum = queryData.totalCount;
                var pageTotal = totalNum % pageRows !== 0 ? parseInt(totalNum / pageRows) + 1 : parseInt(totalNum / pageRows);
                $(el.totalNum).html('共 ' + totalNum + ' 记录');
                $(el.totalPage).html('共 ' + pageTotal + ' 页');
                $(el.totalPage).attr('data-tp', pageTotal);
                $(el.currPage).val(pageNum);
            }

            layer.close(loading);
        }


function orderSubmit(skuNo){

    var checkShoppingPayDialog = openDialog('checkShoppingPay', g.ctx+'pc/mall/shopping/page/cpDetail?sku='+ skuNo, {
        title: '商品详细信息',
        width: '60%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            checkShoppingPayDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    checkShoppingPayDialog.dialog('close');
                }
            }
        ]
    });
}


/**
         * 商品明细勾选或取消勾选
         *
         * @param ele 当前操作DOM节点
         */
function changeCheckBox(ele) {
    var source = $(ele).data('source'), sourceName = $(ele).data('sn'), productCode = $(ele).data('pc'), 
        productName = $(ele).data('pn'), productPrice = $(ele).data('pp') ,nakedPrice = $(ele).data('np'),unit=$(ele).data('pu');
    var skuKey = source + productCode;
    if($(ele).prop('checked')){
        var item = {};
        item.source = source;
        item.sourceName = sourceName;
        item.productCode = productCode;
        item.productName = productName;
        item.productPrice = productPrice;
        item.nakedPrice = nakedPrice;
        item.unit =unit;
        item.qty = 1;
        item.skuKey = skuKey;
        if(!checkWaitData(skuKey)){
            el.choseBuySku.push(item);

        }
    }else {
        for (var i = el.choseBuySku.length - 1; i >= 0; i--) {
            var obj = el.choseBuySku[i];
            if(obj.skuKey === skuKey){
                el.choseBuySku.splice(i, 1);
            }
        }
    }
}

/**
 * 选购
 */
function choseBuy() {
    var sameOmFlag = true, omCode = '';
    for (var i = 0; i < el.choseBuySku.length; i++) {
        var item = el.choseBuySku[i];
        if(omCode && omCode !== item.source){
            sameOmFlag = false;
        }

        omCode = item.source;
    }

    if(el.choseBuySku.length === 0){
        topWin.layer.alert('请至少选择一个商品', {icon: 0});
        return false;
    }

    if(!sameOmFlag){
        topWin.layer.confirm('选购的商品中存在不同商城的商品, 是否继续?', {icon: 3}, function (index) {
            topWin.layer.close(index);

            openChoseBuyConfirmDialog();
        });
    }else {

        openChoseBuyConfirmDialog();
    }
}

function noBuy() {
    el.choseBuySku = [];
    commodityDataSearch(1);
}

/**
 * 打开选购商品确认弹框
 */
function openChoseBuyConfirmDialog() {
    var accessToken = $(el.accessToken).val();
    var pfn = '/pc/mall/shopping/page/compare/price/index';
    var url = '/pc/mall/shopping/page/chose/buy/confirm/page?accessToken='+accessToken+'&parentFrameName=' + pfn;
    el.cbcDialog = openDialog('choseBuyConfirm', url, {
        title: '选购商品确认',
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.cbcDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确认提交',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseBuyConfirm'].dataSave(function () {
                        el.cbcDialog.dialog('close');
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.cbcDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 获取选购商品信息(提供选购商品确认页面)
 *
 * @return {Array} 结果
 */
function findChoseBuyData() {
    return el.choseBuySku;
}


/**
 * 至首页
 */
function toFirstPage() {
    var currPage = $(el.currPage).val();
    if(Number(currPage) !== 1){
        commodityDataSearch(1);
    }else {
        layer.msg('已经是首页了');
    }
}


/**
 * 至尾页
 */
function toLastPage() {
    var currPage = $(el.currPage).val(), totalPage = $(el.totalPage).data('tp');
    if(Number(currPage) !== Number(totalPage)){
        commodityDataSearch(totalPage);
    }else {
        layer.msg('已经是最后一页了');
    }
}


/**
 * 上一页
 */
function prevPage() {
    var currPage = $(el.currPage).val();
    if(Number(currPage) !== 1){
        commodityDataSearch(Number(currPage) - 1);
    }else {
        layer.msg('已经是第一页了');
    }
}


/**
 * 下一页
 */
function nextPage() {
    var currPage = $(el.currPage).val(), totalPage = $(el.totalPage).data('tp');
    if(Number(currPage) !== Number(totalPage)){
        commodityDataSearch(Number(currPage) + 1);
    }else {
        layer.msg('已经是最后一页了');
    }
}


/**
 * 检查待保存的数据是否存在
 *
 * @param skuKey 待保存数据的主键
 * @return {boolean} existFlag 是否存在 false:不存在 true:存在
 */
function checkWaitData(skuKey) {
    var existFlag = false;
    for(var i = 0; i < el.choseBuySku.length; i++){
        if(el.choseBuySku[i].skuKey === skuKey){
            existFlag = true;
            break;
        }
    }

    return existFlag;
}

/**
 * 震坤行查看详情先免密登录
 *
 * @param productDescUrl 商品列表
 */
/*
function orderSubmit(productDescUrl){
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/mall/shopping/rest/get/url',
        data: {
            productDescUrl: productDescUrl
        },
        success: function (data) {
            const ele = document.createElement('a');
            ele.setAttribute('href',data); //设置下载文件的url地址
            ele.setAttribute('target',"_blank");
            ele.click();
            //window.open(data);
        }
    });
}*/
