/*
function addloadevent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}*/



//给所有的选择按钮加上颜色
function buttonColor() {
    var buttonQuery = document.getElementsByClassName("queryOptions");
    var normalButton = [];
    var singleButton = [];
    var buttonCheckArray = new Array();
    for (var j = 0; j < buttonQuery.length; j++) {
        if (!buttonQuery[j].getAttribute("id")) {
            normalButton[normalButton.length] = buttonQuery[j];
            continue;
        }
        if (buttonQuery[j].getAttribute("id").indexOf("Time") == -1) {
            normalButton[normalButton.length] = buttonQuery[j];
        }  else {
            singleButton[singleButton.length] = buttonQuery[j];
        }
        buttonQuery[j].title = "unSelected";
    }

    for (var i = 0; i < normalButton.length; i++) {
        buttonCheckArray[i] = false;
        normalButton[i].index = i;
        normalButton[i].onclick = function () {
            if (buttonCheckArray[this.index] == false) {
                this.style.background = "#00B3B3";
                this.style.color = "white";
                this.title = "selected";
                buttonCheckArray[this.index] = true;
            }
            else {
                this.style.background = "#fff";
                this.style.color = "black";
                this.title = "unSelected";
                buttonCheckArray[this.index] = false;
            }
        }
    }
    for (var k = 0; k < singleButton.length; k++) {

        singleButton[k].onclick = function () {
            for (var q = 0; q < singleButton.length; q++) {
                singleButton[q].style.background = "#fff";
                singleButton[q].style.color = "black";
                singleButton[q].title = "unSelected";
            }
            this.style.background = "rgb(0,179,179)";
            this.style.color = "white";
            this.title = "selected";

        }
    }
    initPage();
}
//时间去掉 时分秒
function timeFormat(data) {
    if (!data) return false;
    return (/\d{4}-\d{1,2}-\d{1,2}/g).exec(data);
}


//页面初始化，给查询按钮加上点击事件。
function initPage() {

    var InNextWeekTime = document.getElementById("InNextWeekTime");

    InNextWeekTime.style.background = "rgb(0,179,179)";
    InNextWeekTime.style.color = "white";
    InNextWeekTime.title = "selected";

    document.getElementById("rentbackSearchBtn").onclick = function () {
        gatheringSearchAction();
    }

}



//选择时间段查询条件
function gatheringSearchAction(){

    var queryTimeSolt = null;
    var UntilTodayTime = document.getElementById("UntilTodayTime").getAttribute("title");
    var InNextWeekTime = document.getElementById("InNextWeekTime").getAttribute("title");
    var InNextMonthTime = document.getElementById("InNextMonthTime").getAttribute("title");
    if(UntilTodayTime == "selected"){
        queryTimeSolt=1;
        accountAgeAnalyze(contextPath,queryTimeSolt);
    }else if(InNextWeekTime == "selected"){
        queryTimeSolt=7;
    }else if(InNextMonthTime == "selected"){
        queryTimeSolt=30;
    }

    var due_date_statop = $("#beginDate").val();
    var due_date_out = $("#endDate").val();

    if((due_date_statop != null && due_date_statop != "") || (due_date_out != null && due_date_out != "")){
        queryTimeSolt = null;
    }

    //选择合同状态查询条件
    var OverdueStatus = "";
    var Overdue = document.getElementById("Overdue").getAttribute("title");
    var NotOverdue = document.getElementById("NotOverdue").getAttribute("title");

    if(Overdue == "selected"&&NotOverdue != "selected") {
        OverdueStatus = 'Y';
    }else if(NotOverdue == "selected"&&Overdue != "selected"){
        OverdueStatus =  'N';
    } else{
        OverdueStatus =   "";
    }
    // 合同信息searh
    var contractInfo = document.getElementById("contractInfo").value;
    var queryCondition = {};
    queryCondition.queryTimeSolt=queryTimeSolt;
    queryCondition.due_date_statop=due_date_statop;
    queryCondition.due_date_out=due_date_out;
    queryCondition.OverdueStatus=OverdueStatus;
    queryCondition.contractInfo=contractInfo;
    //  此处往下进行grid关联查询
    /*gatheringInfoGird(due_date_statop,due_date_out,queryTimeSolt,OverdueStatus,contractInfo,contextPath);*/
    rollTableDataSource.read(queryCondition);

    //  未逾期展开按钮失效
/*    if(NotOverdue == "selected"){
        for(var i=0;i<$(".onclick_remove").length;i++){
            $(".onclick_remove")[i].setAttribute("onclick","");
        }
    }*/
}

//--------------------------------------------------------------------------------------

// 逾期与未逾期（以现金流的应收日期为主）
function gatheringInfoGird(due_date_statop,due_date_out,queryTimeSolt,OverdueStatus,contractInfo,contextPath){

    var gathering_url = contextPath+"/con/conHomepage/selectRentBackInfo";
    var queryConditionList = {};

    // 日期和时间段只能二选一
    if(queryTimeSolt){
        queryConditionList.queryTimeSolt = queryTimeSolt;
    }
    else {
        if((due_date_statop != null && due_date_statop != "")){
            queryConditionList.due_date_statop = due_date_statop;
        }
        if((due_date_out != null && due_date_out != "")){
            queryConditionList.due_date_out = due_date_out;
        }
    }
    if(OverdueStatus){
        queryConditionList.overdueStatus = OverdueStatus;

    }
    if(contractInfo){
        queryConditionList.contractInfo = contractInfo;
    }

    var gathering_divgrid = document.getElementById("rentbackInfoGrid");

    mdata = queryConditionList ? queryConditionList : {};

    gridQuery(gathering_url,gathering_divgrid,mdata);
}


// 租金信息二次查询
function addGridQuery() {
    var sobj = document.getElementById("searchCon");
    sobj.onclick = function () {
        clickAction();
    }
    $('#conSearchInfo').keydown(function (e) {
        if (e.keyCode == 13) {
            e.target.blur();
            clickAction();
        }
    });
}

function clickAction() {
    var conSearchInfo = document.getElementById("conSearchInfo");
    if (!conSearchInfo) return;
    if (!conSearchInfo.getAttribute("class") || conSearchInfo.getAttribute("class") == "hide-input") {
        conSearchInfo.parentNode.setAttribute("class", "input-wrap");
        conSearchInfo.setAttribute("class", "show-input");
    }
    else {
        var queryCondition = conSearchInfo.value;
        if (!queryCondition) {
            conSearchInfo.setAttribute("class", "hide-input");
            if (conSearchInfo.width == "0") {
                conSearchInfo.parentNode.setAttribute("class", "input-wrap-noborder");
            }
        }
        var gathering_divgrid = document.getElementById("rentbackInfoGrid");
        var gathering_url = contextPath+"/con/conHomepage/selectRentBackInfo";

        mdata.contractInfo = queryCondition;
        gridQuery(gathering_url,gathering_divgrid,mdata);
    }
}


//   grid查询
function gridQuery(url, divObject,mdata) {
    if (!url || url == "") return false;
/*    $.ajax({
        type: 'GET',
        url: url,
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType:'json',
        data:mdata,
        success: function (datas) {
            loadGrid(divObject, datas);
        }
    });*/
}

//　加载grid
function loadGrid(divObject, datas) {
    page = new paging();
    page.setDataSourse(datas.rows);
    page.setParentDiv(divObject);
    //覆盖原型上的modifyEvent方法
    page.modifyEvent = function (t, e, i, width, propertyName) {
        if ("template" == e)for (var s = 0; s < this.span.length; s++) {
            i(this.datas[s], s, width, t, propertyName);

        }else {
            for (var s = 0; s < this.span.length; s++) {
                var n = this;
                this.span[s][t].addEventListener(e, function () {
                    i(n.datas[this.index])
                })
            }
        }
    }

    //封装格式化函数
    function gridRowFormat(rowdata, rowIndex, pWidth, t, propertyArr) {
        var str = '';
        var img = "<img  src=" + contextPath + "/resources/images/CONT/overdue.png style='display:inline-block;margin-right:5px;height:21px;width:21px;'/>";
        $.each(propertyArr, function (index, element) {
            var styleString = 'width:' + pWidth + 'px;max-height:32px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;';

            var colData = (rowdata[this.propertyName] == 0 || rowdata[this.propertyName]) ? rowdata[this.propertyName] :  '--';
            if (this.dataType && this.dataType.toUpperCase() === 'DATE') {
                colData = timeFormat(colData);
                styleString = styleString + 'text-align:left;'
            }
            if (this.dataType && this.dataType.toUpperCase() === 'CURRENCY') {
                colData = formatCurrencyUnsigned(colData);
                styleString = styleString + 'text-align:right;'
            }
            if (index != 0) styleString += 'color:#9f9f9f;';

            str = str + '<div style=" ' + styleString + ' ">' + colData + '</div>'

        });
        page.modifyField(t, str, "template", rowIndex);
    }

    if (divObject.getAttribute("title") == "rentbackInfoGrid") {
        var pageSize = 5;

        page.setPageSize(pageSize);

        page.setFeildsName(["","合同编号", "合同名称", '承租人', '产品线', '合同类型', '催收记录', '展开']);
        page.setFeilds(["","contract_number", "contract_name", "bp_name", "description", "document_type", "",""]);
        page.init();


        page.modifyEvent(0, "template", addImgcon);
        function addImgcon(rowdata,rowIndex) {
            if(rowdata.counts>0) {
                page.modifyField(0, "<img  src=" + contextPath +
                    "/resources/images/CONT/overdue.png style='display:inline-block;margin-right:5px;height:21px;width:21px;'/>", "template", rowIndex)
            }
            else {
                page.modifyField(0, "<span  style='margin-right:5px;height:21px;width:21px; display:inline-block;'></span>", "template", rowIndex)
            }
        }

        /*
         *  参数4 : 该列属性的宽度
         *  参数5 : 要显示的属性名、类型
         *
         */
        page.modifyEvent(1, "template", gridRowFormat, 120, [{propertyName: "contract_number"}]);
        page.modifyEvent(2, "template", gridRowFormat, 180, [{propertyName: "contract_name"}]);

        page.modifyEvent(3, "template", gridRowFormat, 160, [{propertyName: "bp_name"}]);


        page.modifyEvent(4, "template", gridRowFormat, 80, [{propertyName: "description"}]);
        page.modifyEvent(5, "template", gridRowFormat, 80, [{propertyName: "document_type"}]);

        page.modifyField(6, "<img  src=" + contextPath +
            "/resources/images/CSH/edit.png style='cursor:pointer;display:inline-block;margin-right:5px;height:21px;width:21px;'/>", true);


        // 展开框
        function addAndDel(rowdata, rowIndex) {
            page.modifyField(7, '<p style="cursor:pointer;" class="onclick_remove" onclick="spread_win(' + rowdata.contract_id + ',' + rowIndex + ')">' +
                '<img id="spreadWin_' + rowdata.contract_id + '" style="cursor: pointer;width: 24px;height: 24px;margin-top: 0px;" ' +
                'src="' + contextPath + '/resources/images/VAT/u87.png" type="unSelected"/></p>', "template", rowIndex);
        }
        page.modifyEvent(7, "template", addAndDel);

        var last = document.getElementById("b_last");
        var next = document.getElementById("b_next");
        var allowStep = datas.rows.length / pageSize; //允许向右边走的步数

        girdPageSkip(last, next, allowStep, page);

        function throwDetail(rowdata) {
            //进入到催收记录
            if (rowdata.contract_id)
                addFunction(rowdata.contract_id);
        }

        page.modifyEvent(6, "click", throwDetail);

    }
}
//  现金流展开事件
function spread_win(id, rowIndex) {
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    td.colSpan = "8";
    var divAll = document.createElement("div");
    divAll.style.background = "rgb(245,245,245)";
    divAll.style.width = "817px";
     divAll.style.marginLeft = "0px";
     divAll.style.textAlign="left";
  //  div.innerHTML = "<span>测试</span>";
    tr.appendChild(td);
    td.appendChild(divAll);

    if (!page.addTr(rowIndex, tr)) {
     $("#spreadWin_" + id).css("transform", "rotate(0deg)");
     page.deleteTr(rowIndex);
     }
     else {
     $("#spreadWin_" + id).css("transform", "rotate(90deg)");

     var datas = queryASTCashFlowDetail(id);
     if (datas.rows.length > 0) {
     for (var i = 0; i < datas.rows.length; i++) {
     var div = document.createElement("div");
     var p = new Array();
     for (var j = 0; j < 8; j++) {
         p[j] = document.createElement("span");
         if(j == 0 || j == 1 || j == 6 ){
             p[j].className = "spanInfo2";
         }
         else if(j==4 || j == 5){
             p[j].className = "spanInfo3";
         }else if( j==7 )
         {
             p[j].className = "spanInfo4";
             p[j].style.color = "red";
         }
         else {
             p[j].className = "spanInfo1";
         }

         div.appendChild(p[j]);
     }
         p[0].innerHTML = "租金" ;
         p[1].innerHTML = "第"+datas.rows[i].times + "期";
         p[2].innerHTML = "应收日期：" + datas.rows[i].due_date;
         p[3].innerHTML = "应收金额：" +"￥"+ datas.rows[i]. due_amount;
         p[4].innerHTML = "本金：" + datas.rows[i].principal;
         p[5].innerHTML = "利息：" + datas.rows[i].interest;
         p[6].innerHTML = datas.rows[i].write_off_flag;
         if(datas.rows[i].due_diffTime > 0){
             p[7].innerHTML = "逾期：" + datas.rows[i].due_diffTime + "天";
         }else {
             p[7].innerHTML = "";
         }
            divAll.appendChild(div);
     }
     }
     }
}

// 图标事件
function con_img(id,rowIndex){

}

// 催收记录弹框
function addFunction(contract_id) {
    var dialog = $("#addDialog2").kendoWindow({

        width: 600,
        height: 400,
        modal: true,
        visible: false,
        iframe: true,
        close: function () {
            hlsWindowClose(this);
        }
    }).data("kendoWindow");
    dialog.title("催收记录");
    hlsWindow(dialog,'FULL',contextPath + '/ast/AST110A/rents_record.view?contractId=' + contract_id, "680")
}

function queryASTCashFlowDetail(contract_id) {
    var datas;
    $.ajax({
        url: contextPath + "/con/ast/detail/query?contract_id=" + contract_id,
        type: "POST",
        dataType: "json",
        async: false,
        contentType: "application/json",
        success: function (args) {
            datas = args;
        },
        error: function () {
        }
    });
    return datas;
}


//------------------------------------------------------------------------------------------


//事件段选项事件
function gatheringTimeClickEvent(){

    $(".dateTimeChoose input")[0].value="";
    $(".dateTimeChoose input")[1].value="";
    if(this.id == "UntilTodayTime"){
        rentBackTotalChart(null,null,1,contextPath)
    }
    else if(this.id == "InNextWeekTime"){
        rentBackTotalChart(null,null,7,contextPath)
    }
    else if(this.id == "InNextMonthTime"){
        rentBackTotalChart(null,null,30,contextPath)
    }
}

//  租金催收查询时间选择
function gatheringTimeChooseEvent() {


    for(var i=0;i<$(".todayTime").length;i++){
        $(".todayTime")[i].style.background = "#fff";
        $(".todayTime")[i].style.color = "black";
        $(".todayTime")[i].title = "unSelected";
    }

    var due_date_statop = $("#beginDate").val();
    var due_date_out = $("#endDate").val();

    var a = /^(\d{4})-(\d{2})-(\d{2})$/;
    if(due_date_statop){
        if (!a.test(due_date_statop)) {
            alert("应收开始日期格式不正确!");
            $("#beginDate").val("");
            return false;
        }
    }
    if(due_date_out){
        if (!a.test(due_date_out)) {
            alert("应收结束日期格式不正确!");
            $("#endDate").val("");
            return false;
        }
    }


    rentBackTotalChart(due_date_statop,due_date_out,null,contextPath);
}


// 图一  应收金额总计
var leftTwoChart = function () {
    return {
        init: function (element_v,datas) {
            Morris.Donut({
                element: element_v,
                data: datas,
                colors: ['#FFCD55','#A0D469'],
                formatter: function (y) {
                    return formatCurrency(y);
                }
            });
        }
    };
}();
function format(num) {
    num = parseFloat(num);
    return (num.toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}
function rentBackTotalChart(due_date_statop,due_date_out,queryTimeSolt,contextPath){

    var gathering_url = contextPath + "/con/conHomepage/selectDueAmountInDiff/query";
    var queryConditionList = {};


    if(queryTimeSolt != null){
            queryConditionList.queryTimeSolt = queryTimeSolt;
    }
    else {
        if(due_date_statop!=null){
            queryConditionList.due_date_statop = due_date_statop;
        }
        if(due_date_out != null) {
            queryConditionList.due_date_out = due_date_out;
        }
    }
    var mdata = queryConditionList ? queryConditionList : {};
    /*return JSON.stringify(mdata);*/
    $.ajax({
        type : 'post',
        url : gathering_url,
        async: false,
        contentType : "application/json; charset=utf-8",
        dataType : 'json',
        data :JSON.stringify(mdata),
        success : function(datas) {
            if(!datas) return ;
            var overdueAmount = datas.overdueAmount !=null ? datas.overdueAmount:0;
            var ioverdueAmount = datas.ioverdueAmount !=null ? datas.ioverdueAmount:0;
          /*  var receivableDatas = [
                {label: '逾期余额', value: overdueAmount },
                {label: '未逾期余额', value: ioverdueAmount }

            ];*/
            var countDueAmount = overdueAmount + ioverdueAmount;
            $('#countDueAmount').html(format(countDueAmount));
          /*  leftTwoChart.init('receivableTotal',receivableDatas);*/
        }
    });
    var a=queryTimeSolt;
    circleChartDataSource.read( {
        queryTimeSolt:a
    });
    circleChartDataSource2.read( {
        queryTimeSolt:a
    });
    // accountAgeAnalyze(contextPath,queryTimeSolt);
}




// 图二     阶段内到期应收金额统计

var analyse = function () {
    return {
        init: function (element_v,datas) {
            Morris.Donut({
                element: element_v,
                data: datas,
                colors: ['#FFCD55','#A0D469','#FA6A4D','#DF6832','#2EC3E8','#E75B8D'],
                formatter: function (y) {
                    return formatCurrency(y);

                }
            });
        }
    };
}();

function accountAgeAnalyze(contextPath,queryTimeSolt){

    var queryConditionList = {};

    if(queryTimeSolt != null){
        queryConditionList.queryTimeSolt = queryTimeSolt;
    }

    var mdata = queryConditionList ? queryConditionList : {};

 /*   $.ajax({
        type : 'post',
        url : contextPath+'/con/conHomepage/DueAmount/query',
        async: false,
        contentType : "application/json; charset=utf-8",
        dataType : 'json',
        data :JSON.stringify(mdata),
        /!*data:mdata,*!/
        success : function(datas) {
            if(!datas) return ;
            var steps1 = datas.orangeSum != null?datas.orangeSum:0;
            var steps2 = datas.greenSum != null?datas.greenSum:0;
            var steps3 = datas.redSum != null?datas.redSum:0;
            var steps4 = datas.yellowSum != null?datas.yellowSum:0;
            var steps5 = datas.blueSum != null?datas.blueSum:0;
            var steps6 = datas.purpleSum != null?datas.purpleSum:0;

            var accountAgeDatas = [
                {label: '7天内', value:steps1},
                {label: '30天内', value:steps2},
                {label: '90天内', value: steps3},
                {label: '180天内', value: steps4},
                {label: '1年', value: steps5},
                {label: '1年以上', value: steps6}
            ];
            analyse.init('analyze',accountAgeDatas);
        }});*/



}


//------------------------------------------------------------------------------------------

//  历史记录
function noticeBoard(contextPath) {
    $.ajax({
        type: 'GET',
        url: contextPath + "/con/contractcoll/selectHisOfRentBackIf",
        async: false, //设为同步
        contentType: "application/json; charset=utf-8",
        success: function (data1) {
            var datas = data1.rows;
            var noticeObj = document.getElementById("noticeConBoard");
            if (!noticeObj)return false;
            for (var i = 0; i < datas.length; i++) {
                var outDiv = document.createElement("div");
                var h = document.createElement("strong");
                var innerDiv = document.createElement("div");
                innerDiv.setAttribute("class", "notice-font");
                outDiv.setAttribute("class", "notice_row border-bottom-1 postion-relative section-row-height");

                h.innerHTML = datas[i].user_name;
                innerDiv.innerHTML =
                    "<img style='height:15px;width:15px;' src=" + contextPath + "/resources/images/CONT/clock2.png />&nbsp;&nbsp;&nbsp;&nbsp;"
                    + datas[i].colupdateTime + "&nbsp;&nbsp;&nbsp;&nbsp;" + "<span style='color: #2EC3E8;font-weight: 600'  >更新了催收记录</span>"
                    + "<img class='iremove' src=" + contextPath + "/resources/images/CONT/remove.png />"
                outDiv.appendChild(h);
                outDiv.appendChild(innerDiv);
                noticeObj.appendChild(outDiv);       // 右侧历史记录
            }
        }
    });
}


// 初始化查询启动
function contractInfoGrid(contextPath, contract_status) {
    var base_url = contextPath + "/con/conHomepage/selectRentBackInfo";
    var base_divgrid = document.getElementById("rentbackInfoGrid");
    mdata = {};
    mdata.queryTimeSolt = contract_status;
    gridQuery(base_url, base_divgrid,mdata);
}

//---------------------------------------------------------------------------------------------


function baseInfoInit(contextPath) {

    document.getElementById("UntilTodayTime").addEventListener("click", gatheringTimeClickEvent, false);
    document.getElementById("InNextWeekTime").addEventListener("click", gatheringTimeClickEvent, false);
    document.getElementById("InNextMonthTime").addEventListener("click", gatheringTimeClickEvent, false);

    rentBackTotalChart(null,null,7,contextPath);      // 应收总金额 饼图
  //  accountAgeAnalyze(contextPath,7);         //图二

    buttonColor();
    contractInfoGrid(contextPath, 7);
    /*addGridQuery(contextPath);     */     //给grid加上查询功能

   /* noticeBoard(contextPath);*/


}


