var skuTableHolder;
var skuFields, skuTableData, productSkus = null;

String.format = function () {

    if (arguments.length == 0)
        return "";

    if (arguments.length == 1)
        return arguments[0];

    var reg = /{(\d+)?}/g;
    var args = arguments;
    var result = arguments[0].replace(
  reg,
  function ($0, $1) {
      return args[parseInt($1) + 1];
  }
 );
    return result;
};
$(document).ready(function () {
    skuTableHolder = $("#skuTableHolder"); //属性中的值skuTableHolder
    skuFields = new Array();
   
});

function EnsureProductSkus() {
    if (productSkus == null) {
        productSkus = new Array();
    }
}

function AddNewSkuItem(itemIdentity, price, quantity, sku) {
    var skuIndex = productSkus.length;
    productSkus[skuIndex] = new Array(4);
    productSkus[skuIndex][0] = itemIdentity;
    productSkus[skuIndex][1] = price;
    productSkus[skuIndex][2] = quantity;
    productSkus[skuIndex][3] = sku;
}

function FindSkuItem(itemIdentity) {
    if (productSkus == null)
        return -1;

    for (j = 0; j < productSkus.length; j++) {
        if (productSkus[j] != undefined && productSkus[j][0] == itemIdentity) {
            return j;
        }
    }
    return -1;
}
// 根据页面上选择的规格及规格值更新显示规格列表
function UpdateSkuTable() {
   
    $(skuTableHolder).empty();
    if (!CollectSelectedSkus()) {
        $("#skushow").hide();
              return;
          }

    $("#skushow").show();
 //  CollectSelectedSkus();
          // 根据已选中的规格值计算规格列表的总行数

        //  alert(skuFields[0][2].length);
          var totalRows = skuFields[0][2].length;
        
    for (var fieldIndex = 1; fieldIndex < skuFields.length; fieldIndex++) {
        totalRows = totalRows * skuFields[fieldIndex][2].length;
    }

    // 根据已选中的规格值生成规格表数据
    GenerateTableData(totalRows);
    // 重新生成规格列表
    var skuTable = $("<table width=\"100%\" border=\"0\" cellSpacing=\"0\" cellPadding=\"0\" class=\"tb-color\"><\/table>");
    var tableBody = $("<tbody><\/tbody>");
    var tableHeader = $("<tr class=\"table_title\"><\/tr>");

    for (index = 0; index < skuFields.length; index++) {
        var fieldCell = $(String.format("<th align=\"center\" class=\"Property_border Property_border2\">{0}<\/th>", skuFields[index][1]));
        tableHeader.append(fieldCell);
    }

    tableHeader.append($("<th align=\"center\" class=\"Property_border Property_border2\"><em>*<\/em>价格<\/th>")); // 金额
    tableHeader.append($("<th align=\"center\" class=\"Property_border Property_border2\"><em>*<\/em>库存<\/th>")); // 库存
    tableHeader.append($("<th align=\"center\" class=\"Property_border Property_border2\"><em>*<\/em>商家编码<\/th>")); // 商家编码
    tableBody.append(tableHeader);

  EnsureProductSkus();

    for (index = 0; index < skuTableData.length; index++) {
        var dataRow = $("<tr><\/tr>");
        var rowIdentity = "";

        for (i = 0; i < skuFields.length; i++) {
            var cellIdentity = skuFields[i][0] + ":" + skuTableData[index][i][0];
            rowIdentity += cellIdentity + "_";
            dataRow.append($(String.format("<td align=\"center\" data-sku=\"{0}\" class=\"Property_border\">{1}<\/td>", cellIdentity, skuTableData[index][i][1])));
        }

        rowIdentity = rowIdentity.substring(0, rowIdentity.length - 1);
        var valueIndex = FindSkuItem(rowIdentity);
        if (valueIndex == -1) {
            valueIndex = productSkus.length;
            AddNewSkuItem(rowIdentity, $("#txtprice").text(), "0", "");
        }

        dataRow.attr("data-value", rowIdentity);
        dataRow.attr("class", "skudatastr");
        dataRow.append(CreatePriceCell(rowIdentity, valueIndex));
        dataRow.append(CreateQuantityCell(rowIdentity, valueIndex));
        //  dataRow.append(CreateAlertQuantityCell(rowIdentity, valueIndex));
        dataRow.append(CreateSkuCell(rowIdentity, valueIndex));
        // dataRow.append(CreateUpsellingCell(rowIdentity, valueIndex));
        tableBody.append(dataRow);
    }

    skuTable.append(tableBody);
    skuTableHolder.append(skuTable);
  //  InsertSku();//////////////////////////////////////////////
    UpdateTotalQuantity();
}

function CreatePriceCell(inputId, valueIndex) {
    var cell = CreateInputCell();
    var priceCell = $(String.format("<input type=\"text\" name=\"{0}_p\" class=\"inputText\" \/>", inputId));
    priceCell.bind("blur", function () { UpdateSkuPrice($(this), valueIndex); });
    priceCell.val(productSkus[valueIndex][1]);
    cell.append(priceCell);
    return cell;
}
function CreateQuantityCell(inputId, valueIndex) {
    var cell = CreateInputCell();
    var quantityCell = $(String.format("<input type=\"text\" name=\"{0}_q\" class=\"inputText\" \/>", inputId));
    quantityCell.bind("blur", function () { UpdateSkuQuantity($(this), valueIndex); });
    quantityCell.val(productSkus[valueIndex][2]);
    cell.append(quantityCell);
    return cell;
}
function CreateInputCell() {
    return $("<td align=\"center\" class=\"Property_border\"><\/td>");
}
function CreateSkuCell(inputId, valueIndex) {
    var cell = CreateInputCell();
    var skuCell = $(String.format("<input type=\"text\" name=\"{0}_sku\" class=\"inputText\" \/>", inputId));
    skuCell.bind("blur", function () { UpdateSku($(this), valueIndex); });
    skuCell.val(productSkus[valueIndex][3]);
    cell.append(skuCell);
    return cell;
}

function UpdateSku(ctlSku, valueIndex) {
    var itemIdentity = $(ctlSku).attr("name").substring(0, $(ctlSku).attr("name").length - 4);

    // 匹配格式和长度范围
    if ($(ctlSku).val().length > 0) {
        if ($(ctlSku).val().length > 20) {
            // 商家编码的长度不能超过20个字符
            alert("商家编码的长度不能超过20个字符");
            $(ctlSku).val("");
            ///$(ctlSku).focus();
        }
        else {
            var exp = new RegExp("^(?!_)(?!.*?_$)(?!-)(?!.*?-$)[a-zA-Z0-9_-]+$", "i");
            if (!exp.test($(ctlSku).val())) {
                // 商家编码只能由字母、数字、下划线和减号组成，且不能以下划线和减号开头结尾！
                alert("\u5546\u5BB6\u7F16\u7801\u53EA\u80FD\u7531\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u51CF\u53F7\u7EC4\u6210\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u4E0B\u5212\u7EBF\u548C\u51CF\u53F7\u5F00\u5934\u7ED3\u5C3E\uFF01");
                $(ctlSku).val("");
               // $(ctlSku).focus();
            }
        }
    } else {
        alert("商家编码的不能为空");
       // $(ctlSku).focus();
    }
    productSkus[valueIndex][3] = $(ctlSku).val();
}
function UpdateSkuPrice(ctlPrice, valueIndex) {
    var itemIdentity = $(ctlPrice).attr("name").substring(0, $(ctlPrice).attr("name").length - 2);
    if ($(ctlPrice).val().length >= 0) {
        var exp = new RegExp("^(0|(0+(\\.[0-9]{1,6}))|[1-9]\\d*(\\.\\d{1,6})?)$", "i");
        if (!exp.test($(ctlPrice).val())) {
            // 请填写正确的商品价格！
            alert("请填写正确的商品价格");
            $(ctlPrice).val($("#txtprice").text());
        }
    } else {
        alert("请填写正确的商品价格");
      //  $(ctlPrice).focus();
    }
    productSkus[valueIndex][1] = $(ctlPrice).val();
}

function UpdateSkuQuantity(ctlQuantity, valueIndex) {
    var itemIdentity = $(ctlQuantity).attr("name").substring(0, $(ctlQuantity).attr("name").length - 2);
    if ($(ctlQuantity).val().length >= 0) {
        var exp = new RegExp("^(0|([1-9]\\d{0,4}))$", "i");
        if (!exp.test($(ctlQuantity).val())) {
            // 请填写正确的库存数量，为零表示此规格商品目前无库存！
            alert("\u8BF7\u586B\u5199\u6B63\u786E\u7684\u5E93\u5B58\u6570\u91CF\uFF0C\u4E3A\u96F6\u8868\u793A\u6B64\u89C4\u683C\u5546\u54C1\u76EE\u524D\u65E0\u5E93\u5B58\uFF01");
            $(ctlQuantity).val("0");
           // $(ctlQuantity).focus();
        }
    } else {
        alert("请填写正确的商品库存");
      //  $(ctlQuantity).focus();
    }
    UpdateTotalQuantity();////////////////////////////////////////////改变文本框时改变总的数量
    productSkus[valueIndex][2] = $(ctlQuantity).val();
}


//根据单个颜色尺码行更新总的数量
function UpdateTotalQuantity() {
    var q = $(".tb-color input[name$='q']");
    var cp = 0;
    $.each(q, function (index, item) { cp += parseInt($(item).val()); });
    $("#txtnum").text(cp);
}


function CollectSelectedSkus() {
   
    var allFieldSelected = true;
    for (i = 0; i < skuFields.length; i++) {
        var skuItems = $(String.format("#enum-sale-props input[type='checkbox'][name='pid_{0}']", skuFields[i][0]));
        var selectedValues = new Array();
        var selectedIndex = 0;
        $.each(skuItems, function (itemIndex, skuItem) {
            if ($(skuItem).attr("checked")) {
                var selectedValue = new Array(2);
                selectedValue[0] = $(skuItem).attr("valueid");
                selectedValue[1] = $(skuItem).attr("valuestr");
                selectedValues[selectedIndex] = selectedValue;
                selectedIndex++;
            }
        });
        if (selectedValues.length == 0) {
            allFieldSelected = false;
        }

        skuFields[i][2] = selectedValues;
    }
    return allFieldSelected;
}

function GenerateTableData(totalRows) {
    skuTableData = new Array(totalRows);
    var rowIndex = 0;

    if (skuFields.length == 1) {
        for (index1 = 0; index1 < skuFields[0][2].length; index1++) {
            skuTableData[index1] = new Array();
            skuTableData[index1][0] = skuFields[0][2][index1];
        }
        return;
    }

    if (skuFields.length == 2) {
        for (index1 = 0; index1 < skuFields[0][2].length; index1++) {
            for (index2 = 0; index2 < skuFields[1][2].length; index2++) {
                skuTableData[rowIndex] = new Array();
                skuTableData[rowIndex][0] = skuFields[0][2][index1];
                skuTableData[rowIndex][1] = skuFields[1][2][index2];
                rowIndex++;
            }
        }
        return;
    }

    if (skuFields.length == 3) {
        for (index1 = 0; index1 < skuFields[0][2].length; index1++) {
            for (index2 = 0; index2 < skuFields[1][2].length; index2++) {
                for (index3 = 0; index3 < skuFields[2][2].length; index3++) {
                    skuTableData[rowIndex] = new Array();
                    skuTableData[rowIndex][0] = skuFields[0][2][index1];
                    skuTableData[rowIndex][1] = skuFields[1][2][index2];
                    skuTableData[rowIndex][2] = skuFields[2][2][index3];
                    rowIndex++;
                }
            }
        }
        return;
    }
}