var checkList = (function () {
    'use strict';
    var CheckList = function (params) {
        var p = this;
        p.params = {
            appid: '',
            id: '',
            accountsId: '',
            cfApp: null,
            devMode: false,
            localStorage: [],
            dataApi: G.baseUri() + '/mobile/auth/appform/getitem',
            submitApi:G.baseUri() + '/mobile/auth/appform/submitTypeAppform',
            vt: ''
        };
        for (var param in params) {
            p.params[param] = params[param];
        }
        var cfApp = p.params.cfApp;

        if (p.params.devMode) {

        }
        p.pageSize = 10;
        p.pageNo = 0;
        p.channelData = [];
        p.appPrice=0;
        /**
         * 判断app字段
         * @returns 是否app有值
         */
        var validAppField = function () {
            if (!p.params.appid || p.params.appid == '') {
                return false;
            } else {
                return true;
            }
        };

        /**
         * 确认初始化的app 和tokenId 两个值是否都存在
         * 如果不存在则获取一次,获取不到则初始化失败
         * @returns 初始化基础字段是否成功
         */
        var initBaseFields = function () {
            if (!validAppField()) {
                p.params.appid = cfApp.getQueryString('appid');
                p.params.id = cfApp.getQueryString('id');
                p.params.accountsId = cfApp.getQueryString('accountsId');
                p.typeformId = cfApp.getQueryString('typeformId');
                p.useId = cfApp.getQueryString('useId');
                if(!p.typeformId || p.typeformId==null || p.typeformId==''){
                    $.modal({
                        title: "",
                        text: "参数错误",
                        buttons: [
                            { text: "确定OK", onClick: function () {
                                return false;
                            } }
                        ]
                    });
                }
                if(!p.useId || p.useId==null || p.useId==''){
                    $.modal({
                        title: "",
                        text: "参数错误",
                        buttons: [
                            { text: "确定OK", onClick: function () {
                                return false;
                            } }
                        ]
                    });
                }
            }



            //如果获取不到app和tokenId,则直接从传入的CfApp中获取值
            if (!validAppField()) {
                if (p.params.cfApp) {
                    p.params.appid = cfApp.getAppId();
                    //p.params.tokenId = cfApp.getTokenId();
                }
            }
            p.empInfo = cfApp.getMpInfo();
            p.params.accountsId = p.empInfo.accountsId;
            return validAppField();
        };

        /**
         * 初始化组件
         * @returns {boolean}
         */


        p.init = function () {
            if (initBaseFields()) {
                loadData();
                event();
                submit();
                return true;
            } else {
                return false;
            }
            log();
        };

        var log = function () {
            var formdata = {
                openid: p.empInfo.openId,
                module: "促销品申请",
                modulename: '选择申请项',
                keyword: '选择申请项',
                keywordid: '',
                vt: new Date().getTime(),
                appid: cfApp.getQueryString('appid'),
                url: location.href
            };
            G.ajax(G.devModePost, '/schaeffler/mobile/testAsync/doLOg', formdata, function (retdata) {


            });
        }

        var loadData = function () {
            var formData = {
                id:p.useId,
                page:0,
                pageSize:0
            }
            G.ajax('post', p.params.dataApi, formData, function (retdata) {
                if(retdata.errorNo=="0"){
                     var datas = retdata.datas;
                    if(datas && datas.length>0){
                        for(var i =0;i<datas.length;i++){
                            var spe = datas[i].specifications;
                            if(spe && spe!=null && spe!=''){
                                datas[i].isSpecifications=true;
                            }else{
                                datas[i].isSpecifications=false;
                            }
                        }
                    }
                    var content = $('#list-template').html();
                    p.template = Handlebars.compile(content);
                    var htmlStr = p.template(retdata);
                    $('.goods-list').html(htmlStr);
                }
            });

        }

        var zeroDefault = function(value){
                return  !isNaN(value);
        }

        var event = function(){
            $(".goods-list").on("click",'.goods-box .r .add',function(){
                var num = $(this).siblings(".num").val();
                var inventedstock = $(this).siblings(".num").attr("data-inventedstock");
                num = parseInt(num)+1;
                if(num>parseInt(inventedstock)){//已超出最大库存数，不可再加
                    return false;
                }
                $(this).siblings(".num").val(num);
                var price =$(this).siblings(".num").attr("data-price");
                p.appPrice=(parseFloat(p.appPrice)+parseFloat(price)).toFixed(2);
                $("#price").text("￥"+p.appPrice);
            })
            $(".goods-list").on("click",'.goods-box .r .cut',function(){
                var num = $(this).siblings(".num").val();
                num = parseInt(num)-1;
                if(num>=0){
                    $(this).siblings(".num").val(num);
                    var price =$(this).siblings(".num").attr("data-price");
                    p.appPrice=(parseFloat(p.appPrice)-parseFloat(price)).toFixed(2);
                    $("#price").text("￥"+p.appPrice);
                }
            })

            $(".goods-list").on("input",'.goods-box .r .num',function(){
                p.appPrice=0;
              var objs =$(".num");
              var value = $(this).val();
              if(!zeroDefault(value)){
                  $(this).val("0");
                  return ;
              }
              value = $(this).val();
              var inventedstock = $(this).attr("data-inventedstock");
              if(parseInt(value)>parseInt(inventedstock)){
                  $(this).val(inventedstock);
              }
              for(var i=0;i<objs.length;i++){
                  var num = $(objs[i]).val();
                  if(num && num!=null &&  num!='' &&  num>=0){
                      var price = $(objs[i]).attr("data-price");
                      p.appPrice=(parseFloat(p.appPrice)+parseFloat(price)*num).toFixed(2);
                  }
              }
                $("#price").text("￥"+p.appPrice);
            })


        }

        var submit = function(){
            $("#next_step").click(function(){
                $("#next_step").css("pointer-events","none");
                var formDataStr = localStorage.getItem("common-order"+p.params.appid);
                if(formDataStr && formDataStr!=null && formDataStr!='') {
                    var formData = JSON.parse(formDataStr);
                    var nums =$(".num");
                    var items = [];
                    var isSelected = false;
                    for(var i =0;i<nums.length;i++){
                        var num =$(nums[i]).val();
                        if(parseInt(num)>0){
                            var obj = {};
                            isSelected = true;
                            obj.num = $(nums[i]).val();
                            obj.price = $(nums[i]).attr("data-price");
                            obj.id = $(nums[i]).attr("data-id");
                            obj.name = $(nums[i]).attr("data-name");
                            // obj.authenticStock = $(nums[i]).attr("data-authenticStock");
                            // obj.disStock = $(nums[i]).attr("data-disStock");
                            obj.num = $(nums[i]).val();
                            obj.cover = $(nums[i]).attr("data-cover");
                            obj.specifications = $(nums[i]).attr("data-specifications");
                            items.push(obj);
                        }
                    }
                    if(!isSelected){
                        $.modal({
                            title: "",
                            text: "提示！您还没有添加促销品。Hint! You haven’t add any promotional items.",
                            buttons: [
                                { text: "确定OK", onClick: function () {
                                        $("#next_step").css("pointer-events","inherit");
                                        return false;
                                    } }
                            ]
                        });
                    }else{
                        $.modal({
                            title: "",
                            text: "是否确定要提交申请?<br/>Are you sure you want to submit this application?",
                            buttons: [
                                {
                                    text: "是 Yes", onClick: function () {
                                        $("#next_step").css("pointer-events","inherit");
                                        formData.items = JSON.stringify(items);
                                        formData.appPrice = p.appPrice;
                                        G.ajax('post', p.params.submitApi, formData, function (retdata) {
                                            $("#next_step").css("pointer-events","inherit");
                                            if(retdata.errorNo=="0"){
                                                $.modal({
                                                    title: "",
                                                    text: "提交成功",
                                                    buttons: [
                                                        { text: "确定OK", onClick: function () {
                                                                localStorage.removeItem("common-order" + p.params.appid);
                                                                WeixinJSBridge.call('closeWindow');
                                                            } }
                                                    ]
                                                });
                                            }
                                        });
                                    }
                                },{
                                    text: "否 No", onClick: function () {
                                        $("#next_step").css("pointer-events","inherit");
                                        return false;
                                    }
                                }
                            ]
                        });

                    }
                }else{
                    $.modal({
                        title: "",
                        text: "请重新填写数据",
                        buttons: [
                            { text: "确定OK", onClick: function () {
                                    location.href="check_form.html?appid="+p.params.appid+"&typeformId="+p.typeformId;
                                } }
                        ]
                    });
                }
            });
        };


        var submitOK= function(){


        };
    };

    return CheckList;
})();
