<!--<apex:page standardcontroller="Maintenance_Contract_Estimate__c" extensions="SelectAssetEstimateController" sidebar="false" showHeader="true" id="allPage" action="{!init}"> -->
<apex:page controller="SelectAssetEstimateController" tabStyle="Maintenance_Contract_Estimate__c" sidebar="false" showHeader="true" id="allPage" action="{!init}">
    <apex:stylesheet value="{!URLFOR($Resource.blockUIcss)}"/>
    <apex:includeScript value="{!URLFOR($Resource.jquery183minjs)}"/>
    <apex:includeScript value="{!URLFOR($Resource.PleaseWaitDialog)}"/>
    <apex:includeScript value="/soap/ajax/29.0/connection.js"/>
    <apex:includeScript value="/soap/ajax/29.0/apex.js"/>
<style type="text/css">
    table { border-collapse: collapse; }
    
    .container {
        overflow:auto;
        width:100%;
        height:304px;
    }
    .container2 {
        overflow:auto;
        width:100%;
        height:404px;
    }
    .btntable .dateFormat  {
        display: none;
    }
</style>
<script type="text/javascript">
var oxygenPriceAdj = {!oxygenPriceAdj};
var Session_ID = '{!$Api.Session_ID}';
var Confirm_ChangedAfterPrint = '打印后行信息有变化，是否继续操作（报价编码会变新）？';
var isNewAddMonth = {!isNewAddMonth};
var Confirm_EstimateRefresh = '已超过创建日3个月，是否更新报价？';
window.sfdcPage.appendToOnloadQueue(function() { calonLoad() });

function unblockUI(){
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var isChange = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    if (isChange=='true') {
        j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('false');
        var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
        refreshAsset(rowCnt);
    }
    j$("#sbArea").fadeOut(500, function(){
        j$("#sbArea").remove();
    });
}
//<!-- HWAG-B4R3SS  START 20181026-->
function clearAndSearch() {
    document.getElementById("allPage:allForm:allBlock:text1").value = "";
    document.getElementById("allPage:allForm:allBlock:cond1").value = "equals";
    document.getElementById("allPage:allForm:allBlock:val1").value = "";
    blockme();
    searchfunc();
}
function searchJs() {
    blockme();
    searchfunc();
}
//<!-- HWAG-B4R3SS  END 20181026-->
// 初始化设定画面项目不可用
function pageSetDisabled(){
    var isDisabled = {!PageDisabled};
    if (isDisabled) {
        j$(escapeVfId('allPage:allForm:allBlock:contract:depart')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:startdate')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).attr("disabled", true);
        var rowCnt = {!productCount};
        for (var i = 0; i < rowCnt; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert'));
                a.attr("disabled", true);
            }
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).attr("disabled", true);
        }
        j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:discountReason')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:improveConsumptionRateIdea')).attr("disabled", true);
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", true);
        var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
        if (target != '医院') {
            j$(escapeVfId('allPage:allForm:allBlock:contract:dealer')).attr("disabled", true);
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).attr("disabled", false);
    }
}
// 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk star
// function disable1(){
//     var isDisabled ;
//     if(isDisabled){
//         var rowCnt = {!productCount};
//         for (var i = 0; i < rowCnt; i++) {
//             // 保有设备名
//             var assN = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':assetName')).text();
//             var assN1 = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:'+ i +':Assert')).val();
//             // alert('1234567'+assN +'----'+assN1);
//             if(!assN1 && !assN){
//                 // alert('23456789'+assN);
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", true);
//             }else{
//                 j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetCheck'   )).attr("disabled", false);
//             }
//         }
//     }
// }
// 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end
var winOpenObj;
function closeWin(flg) {
    winOpenObj.close();
    if (flg==2) {
        window.location.href="/{!URLENCODE(estimate.Id)}/e?completion=2"; 
    }
}
function controlDisabled() {
    winOpenObj = window.open("/apex/ChangeDealerApproval?eid=" + '{!URLENCODE(estimate.Id)}','ChangeDealerApproval','height=300,width=700,toolbar=no,menubar=no,left=20%,top=30%,scrollbars=yes,resizable=no,location=no,status=no');
}
// 見積もり作成後、３ヶ月以内であれば見積もりの内容を継続使用可能
function calonLoad() {
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk star
    // disable1();
    // 2021、8、26 合同报价页面的优化，无保有设备点检对象选择框变黑 fxk end
    pageSetDisabled();
    var createdDate = new Date('{!estimate.CreatedDate}');
    // 20201103 gzw bug 对应 没有 nowDate JS出现问题
    var nowDate = new Date();
    // 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    var aLLManual = 'true';
    var cntWithKara = {!productCount};
        
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            aLLManual = 'false';
            break;
        }
    }
    if (aLLManual == 'false') {
        createdDate = createdDate.setMonth(createdDate.getMonth() + 3);
        // FIX liang JSの時間って addMonthsないですか？ そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            
            if (confirm(Confirm_EstimateRefresh)) {
                window.location.href="/apex/SelectAssetEstimate?copyid={!URLENCODE(targetEstimateId)}"; 
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }else{
        createdDate = createdDate.setMonth(createdDate.getMonth() + 6);
        // FIX liang JSの時間って addMonthsないですか？ そかも 1/1 なら、 4/1もだめですよ。
        if (createdDate < Date.parse(nowDate)) {
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:savebtntop')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:saveAndCancelBtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:allBlock:blocktop:approvalbtntop')).attr("class", 'btnDisabled');
            
            j$(escapeVfId('allPage:allForm:savebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("disabled", true);
            // 最初は、Decideの同時に保存もあります、それを防ぐため、保存とDecideを同時に無効にする
            // 考えてみると、クラスにDecideの判断があり、Decideの時明細変更チェックもあります、3ヶ月のチェックもあります、ここで無効にする意味がありません
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("disabled", true);
            j$(escapeVfId('allPage:allForm:savebtn')).attr("class", 'btnDisabled');
            j$(escapeVfId('allPage:allForm:approvalbtn')).attr("class", 'btnDisabled');
            //j$(escapeVfId('allPage:allForm:decidebtn')).attr("class", 'btnDisabled');
            
            if (confirm('已超过创建日6个月，是否更新报价？')) {
                window.location.href="/apex/SelectAssetEstimate?copyid={!URLENCODE(targetEstimateId)}"; 
                return true;
            } else {
                if ('{!DecideBtnDisabled}' == 'false') {
                    // decide可能の場合、別途decideのチェックが必要、
                    // チェック後再度画面refreshされるため、decide可能の場合、decideボタンが使えるようになります。
                    changeContractStartdate('{!estimate.Contract_Start_Date__c}');
                }
                return false;
            }
        }
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).val(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text());
    }
}

function checkAll(checker) {
    var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    for (var i = 0; i < cnt; i++) {
        if (j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox')).size() == 0) {
            break;
        }
        document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetRowCheckbox').checked = checker.checked;
    }
}

function checkAll2(checker) {
    var cnt2 = j$(escapeVfId('allPage:allForm:allBlock:assetSection2:productCnt2')).val();
    var outer = 0;
    for (var i = 0; i < cnt2; i++) {
        outer = Math.floor(i / 1000);
        if (document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').disabled == false) {
            document.getElementById('allPage:allForm:allBlock:assetSection2:outassetTable2:' + outer +':assetTable2:' + (i-(1000*outer)) + ':assetRowCheckbox2').checked = checker.checked;
        }
    }
}

function checkPercentage(val) {
    if (val == null || val == "") {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(0.00);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(0.00);
        return;
    }
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(0.00);
        return;
    }
    val = localParseFloat(val);
    val = Math.round(val * 100) / 100;
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(toNumComma(val));
    //if (val> 100.00 || val < 0) {
    //    alert("请输入0.00到99.99之间的数值");
    //    j$(escapeVfId('allPage:allForm:allBlock:disBlock:disPercent')).val("");
    //    return;
    //}
    
    makeRealPrice();
}

function checkDiscount(val) {
    if (val == null || val == "") {
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(0.00);
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(0.00);
        return;
    }
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(0.00);
        return;
    }
    val = localParseFloat(val);
    val = Math.round(val * 100) / 100;
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(toNumComma(val));
    //if (val < 0) {
    //    alert("优惠价格不能低于0元");
    //    j$(escapeVfId('allPage:allForm:allBlock:disBlock:disMoney')).val("");
    //    return;
    //}

   makeRealPrice(1);
}

function checkContractRange(val, cnt) {
    if (isNaN(parseInt(val))) {
        alert("请输入数值");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    if (val <= 0) {
        alert("合同月数必须大于0");
        j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val("");
        return;
    }
    // HWAG-BA73ZP
    contractStartDateChange();
    refreshAsset(cnt);
}

function checkContractEstiStartDate(val, cnt) {
    if (val == null || val == "") {
        return;
    }
    for (var i = 0; i < cnt; i++) {
        var instaldate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':InstallDate')).text();
        if (instaldate != null && instaldate != '') {
            var listprice = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
            if (isnew == "true") {
                listprice = listprice / {!isNewPriceAdj};
            }
            var startdate = new Date(val);
            startdate.setMonth(startdate.getMonth() + isNewAddMonth);
            instaldate = new Date(instaldate);
            if (startdate < instaldate) {
                listprice = listprice * {!isNewPriceAdj};
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(listprice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNew')).attr('checked',true);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val('true');
            } else {
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(listprice));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(listprice);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNew')).attr('checked',false);
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val('false');
            }
        }
    }
    
    refreshAsset(cnt);
}

function refreshAsset(cnt) {
    // row金額合計
    var repairSum = 0;
    var listSum = 0;
    // 合同月数乗算
    var month = j$(escapeVfId('allPage:allForm:allBlock:contract:monthRange')).val();
    if (month == undefined || month == "") {
        month = 1;
    }
    var month2 = 0;
    if (month > 12) {
        month2 = month - 12;
        month = 12;
    }
    for (var i = 0; i < cnt; i++) {
        var strMoney = 0;
        var repairMoney = 0;
        
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
                if (isnew == 'true') {
                    strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
                } else {
                    strMoney = month * strMoney + month2 * strMoney;
                }
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
                
                repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
            } else {
                // TODO 一時的な対応、なんで別行の金額リフレッシュされた？
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text("");
                j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val();
            }
        }
        else {
            strMoney = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
            if (isnew == 'true') {
                strMoney = month * strMoney + month2 * strMoney / {!isNewPriceAdj};
            } else {
                strMoney = month * strMoney + month2 * strMoney;
            }
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPrice')).text(toNumComma(strMoney));
            j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPricePageHidden')).val(strMoney);
            
            repairMoney = j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value());
        }
        repairSum = repairSum + localParseFloat(repairMoney);
        listSum = listSum + localParseFloat(toNum(strMoney));
    }
    j$(escapeVfId('allPage:allForm:allBlock:assetRepairSumNum')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:assetListSumNum')).text(toNumComma(listSum));
    
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text(toNumComma(listSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPriceHidden')).val(toNum(listSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text(toNumComma(repairSum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPriceHidden')).val(toNum(repairSum));
    
    NotUseOxygenatedWaterAmount(1);
    examinationPriceCal(cnt);
}

function NotUseOxygenatedWaterAmount(t) {
    var sum = 1 * localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text());
    var sumAdj = 0;
    
    if (document.getElementById('allPage:allForm:allBlock:appendCondition:notUseOxygen').checked == true) {
        sumAdj = -1 * sum * oxygenPriceAdj;
    }
    j$(escapeVfId('allPage:allForm:allBlock:NotUseOxygenatedWaterAmount')).text(toNumComma(sumAdj));
    
    // 付加条件総額欄
    var examPrice = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationReal')).text());
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text(toNumComma(sumAdj + examPrice));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPriceHidden')).val(toNum(sumAdj + examPrice));
    
    makeRealPrice(1);
}

function examinationPriceCal(cntWithKara) {
    var examinationCount = localParseInt(j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val());
    var examinationCountStr = number_format_common(examinationCount, 0, ".", ",");
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:Examination_Count')).val(examinationCountStr);
    var cnt = 0;
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert')).value();
            if (a != '') {
                cnt++;
            }
        }
        else {
            cnt++;
        }
    }
    var examinationPrice = 0;
// 今後復活かも
//    var cntLot = Math.ceil(cnt / 20);
//    if (cntLot == 0) {
//        examinationPrice = 0;
//    }
//    else if (cntLot == 1) {
//        examinationPrice = 2000;
//    }
//    else if (cntLot == 2) {
//        examinationPrice = 3800;
//    }
//    else if (cntLot == 3) {
//        examinationPrice = 5400;
//    }
//    else if (cntLot == 4) {
//        examinationPrice = 6800;
//    }
//    else if (cntLot == 5) {
//        examinationPrice = 8000;
//    }
//    else if (cntLot >= 6) {
//        examinationPrice = 1600 * cntLot;
//    }
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationReal')).text(toNumComma(examinationPrice * examinationCount));
    j$(escapeVfId('allPage:allForm:allBlock:appendCondition:examinationRealHidden')).val(toNum(examinationPrice * examinationCount));
    
    // 付加条件総額欄
    var oxygenPrice = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:NotUseOxygenatedWaterAmount')).text());
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text(toNumComma(oxygenPrice + examinationPrice * examinationCount));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPriceHidden')).val(toNum(oxygenPrice + examinationPrice * examinationCount));
    
    makeRealPrice(1);
}

/*
 * @param t   1: 金額により割引
 */
function makeRealPrice(t) {
    // 実際金額合計
    var sum1 = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSumPrice')).text();
    var sum2 = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetRepairSumPrice')).text();
    var append = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:appendPrice')).text();
    var sum = localParseFloat(sum1) + localParseFloat(append);
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSum2')).text(toNumComma(sum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:assetSum2Hidden')).val(toNum(sum));

    var disM = localParseFloat(j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val());
    var disMP = toNum(disM / sum * 100);
    // 割引金額から割引率を計算
    if (t == 1) {
        var disP = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val();
        if (disMP != disP) {
            j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val(disMP);
        }
    }
    // 割引率から割引金額を計算
    else {
        var disP = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disPercent')).val();
        if (disMP != disP) {
            disM = sum * disP / 100;
            j$(escapeVfId('allPage:allForm:allBlock:contractInfo:disMoney')).val(toNum(disM));
        }
    }
    sum = sum - disM;
    
    // 修理総額を計上
    sum = sum + localParseFloat(sum2);
    
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text(toNumComma(sum));
    j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).val(toNum(sum));
}

function resetDealer() {
    var target = j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).val();
    var obj = document.getElementById('allPage:allForm:allBlock:contract:dealer');
    var obj_lkwgt = document.getElementById('allPage:allForm:allBlock:contract:dealer_lkwgt');
    if (target == '医院') {
        obj.style.display = "none";
        obj_lkwgt.style.display = "none";
    } else {
        obj.style.display = "block";
        obj_lkwgt.style.display = "block";
    }
}

function changeAllCheckResult(val) {
    var cnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    for (var i = 0; i < cnt; i++) {
        if (val == ' ') {
            document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult').value = '';
        } else {
            document.getElementById('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult').value = val;
        }
    }
}
function alertMsg() {
    // body...
    if('{!isPaymentSet}' == 'false'){
        alert('请填写付款计划');
        return false;
    }else if('{!isPaymentSet}' == 'Denied'){
        alert('付款计划金额与实际不符，请重新填写');
        return false;
    }else{
        return true;
    }
}
function onclickCheckchangedAfterPrint(saveBtnDisabled, saveOrApproval) {
    if(saveBtnDisabled == 'Pttrue'){
        var rs = alertMsg();
        if(rs){
        }else {
            return false;
        } 
    }
   
    var cntWithKara = {!productCount};
    var alerts = 0;
    var today = new Date();
    today.setMonth(today.getMonth() - 3);

    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual == 'true') {
            var plkid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
            var pid = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (plkid.size() > 0 && pid.size() > 0) {
                if (pid.value() != '' && plkid.value() != pid.value().substring(0, 15)) { 
                    alert('请使用产品放大镜按钮设定手动产品');
                    return false;
                }
            }
        }
        if (isManual == 'false') {
            var strDate = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':finalExaminationDate')).value();
            strDate = strDate.replace(/(^\s*)|(\s*$)/g, ""); 
            if (strDate == "" || Date.parse(strDate) < Date.parse(today)) {
                alerts = 1;
            }
        }
    }
    if (alerts == 1) {
        if (confirm("选择的保有设备[最后点检日]为空或已经超过三个月之前，是否继续？")) {
            
        } else {
            return false;
        }
    }
    blockme();
    if (saveOrApproval == "true") {
        if (saveBeforeCheckPriceChange()) {
            if (confirm("行信息有变化(维修合同价格)，是否更新报价？")) {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('true');
            } else {
                j$(escapeVfId('allPage:allForm:changedSubmitPrice')).val('fasle');
                unblockUI();
                return false;
            }
        }
        j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    }

    return true;
    // if ((saveBtnDisabled == "true"||saveBtnDisabled == "Pttrue" )&& checkchangedAfterPrint()) {
    //     if (confirm(Confirm_ChangedAfterPrint)) {
    //         if (saveOrApproval == "true") {
    //             j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //         }
    //         return true;
    //     } else {
    //         unblockUI();
    //         return false;
    //     }
    // } else {
    //     if (saveOrApproval == "true") {
    //         j$(escapeVfId('allPage:allForm:isSaveOrApproval')).val('true');
    //     }
    //     return true;
    // }
}

function changeEstiStartdate(val) {
    if ('{!SaveBtnDisabled}' == 'false') {
        j$(escapeVfId('allPage:allForm:contractstartdate')).val(val);
        changeContractStartdate(val);
    }
}

function changeContractStartdate(val) {
    var oldDateStr = j$('#oldContractDate').value();
    var oldDate = new Date();
    if (oldDateStr != null && oldDateStr != '') {
        oldDate = new Date(oldDateStr);
    }
    if ('{!DecideBtnDisabled}' == 'false') {
        var monthStr = '00' + (oldDate.getMonth()+1);
        monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
        var dayStr = '00' + oldDate.getDate();
        dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
        var oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val(oldDateVal);
        if (saveBeforeCheckPriceChange()) {
            blockme();
            contractStartDateChange();
        }
    } else {
        var cntWithKara = {!productCount};
        var haveLine = 'false';
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':Assert_lkid'));
                if (a.size() > 0 && a.val() != "000000000000000") {
                    haveLine = 'true';
                }
            } else {
                haveLine = 'true';
            }
        }

        if (haveLine == 'false') {
            return false;
        }
        var contractStartDate = new Date(val);
        var strCreatedDate = '{!estimate.CreatedDate}';
        var createDate = new Date();
        if (strCreatedDate != '') {
            createDate = new Date(strCreatedDate);
        }
        createDate = new Date(createDate.toDateString());
        var threeMA = new Date(createDate.setMonth(createDate.getMonth() + 3));
        var isnewMA = new Date(createDate.setMonth(createDate.getMonth() - 3 - isNewAddMonth));
        
        if (oldDate >= isnewMA && contractStartDate >= isnewMA) {
            return false;
        }
        if (oldDate < threeMA && contractStartDate < threeMA) {
            return false;
        }
        
        if (contractStartDate >= isnewMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日6个月，所有合同对象设备不适用新品价格。\n请在画面刷新后确认维修合同价格，再继续其他操作。');
        } else if (contractStartDate >= threeMA) {
            alert('合同开始预定日或合同开始日发生变化并且大于创建日3个月，所有合同对象设备使用【合同开始日】重新计算维修合同价格。\n请在画面刷新后确认维修合同价格，再继续其他操作。');
        } else {
            alert('合同开始预定日或合同开始日发生变化并且在创建日3个月以内，所有合同对象设备使用【创建日】重新计算维修合同价格。\n请在画面刷新后确认维修合同价格，再继续其他操作。');
        }
        j$('oldContractDate').val(val);
        blockme();
        contractStartDateChange();
    }
}
function AlertPriceBtnJs(){

    var  VarAlert  = j$(escapeVfId('allPage:allForm:alertStringValue')).val();
    var  VarAlert2 = j$(escapeVfId('allPage:allForm:alertStringValue2')).val();
    var  VarAlert3 = j$(escapeVfId('allPage:allForm:alertStringValue3')).val();
    var  PStatus   = j$(escapeVfId('allPage:allForm:PriceStatus')).val();
    blockme();

    if(PStatus!='申请中'&&PStatus!='批准'){
        ComputeLTYRepair();
        //ShowLTYRepair();
    }else if(PStatus == '申请中'||PStatus == '批准'){
        ShowLTYRepair();
    }
   
}
function ComputeLTY() {
    var  urlNameJs = j$(escapeVfId('allPage:allForm:urlName')).val();
    urlNameJs = '{!$Label.ID_of_SelectAssetEstimate}'+urlNameJs ;
    var w = window.open(encodeURI(urlNameJs),'过去两年修理实绩','menubar=no,height=720,width=986');
    w.focus();
}
function recordNumChangeJs() {
    recordNumChangeAction();
}

function checkDecideDate() {
    var strSubmitDate = '{!estimate.Submit_quotation_day__c}';
    var submitDate = new Date();
    var nowDate = new Date();
    /// 报价中设备的机身编码为空时的新品合同有效期延长 20200710 gzw
    // 默认为3月，全是产品为6月；
    var monthGap = 6;
    var cntWithKara = {!productCount};
        
    for (var i = 0; i < cntWithKara; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        if (isManual != 'true') {
            monthGap = 3;
            break;
        }
    }
    if (strSubmitDate != '') {
        submitDate = new Date(strSubmitDate);
        submitDate = new Date(submitDate.setMonth(submitDate.getMonth() + monthGap));
    }
    if (strSubmitDate != '' && nowDate > submitDate) {
        alert('已超出报价申请日' + monthGap + '个月，不允许DECIDE。');
        return false;
    }
    return true;
}
function decideJs() {
    if (checkDecideDate() == true) {
        if (onclickCheckchangedAfterPrint('true','false') == true) {
            var oldDate = j$(escapeVfId('allPage:allForm:oldDecideContractDate')).value();
            var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            //var olDt = oldDate.getFullYear() + oldDate.getMonth() + oldDate.getDate();
            var monthStr = '00' + (contractDate.getMonth()+1);
            monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            var dayStr = '00' + contractDate.getDate();
            dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            var contractDateStr = contractDate.getFullYear() + '/' + monthStr + '/' + dayStr;

            //var neDt = contractDate.getFullYear() + contractDate.getMonth() + contractDate.getDate();
            //monthStr = '00' + (oldDate.getMonth()+1);
            //monthStr = monthStr.substring(monthStr.length-2, monthStr.length);
            //dayStr = '00' + oldDate.getDate();
            //dayStr = dayStr.substring(dayStr.length-2, dayStr.length);
            //oldDateVal = oldDate.getFullYear() + '/' + monthStr + '/' + dayStr;
            if (oldDate == contractDateStr) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                decide();
            } else {
                var oldp = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:oldMainteReal')).value();
                var newp = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteReal')).text();

                if (oldp != newp) {
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                    if (confirm('本次合同开始日的修改将导致合同金额发生变化，请您确认是否修改？')) {
                        decide();
                    } else {
                        alert('合同开始日未进行变更，请确认全部内容后点击Decide。');
                        j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                        j$(escapeVfId('allPage:allForm:oldDecideContractDate')).val('');
                        j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                        decideCancle();
                    }
                } else {
                    j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
                    if (confirm('本次合同开始日的修改不会导致合同金额发生变化，请您确认是否修改？')) {
                        decide();
                    } else {
                        j$(escapeVfId('allPage:allForm:contractstartdate')).val(oldDate);
                        alert('合同开始日未进行变更，请确认全部内容后点击Decide。');
                        unblockUI();
                    }
                }
            }
        }
    }
}
</script>
<apex:form id="allForm">
    <apex:inputHidden id="alertStringValue" value="{!alertString}" />
    <apex:inputHidden id="alertStringValue2" value="{!alertString2}" />
    <apex:inputHidden id="alertStringValue3" value="{!alertString3}" />
    <apex:inputHidden id="PriceStatus" value="{!estimate.Process_Status__c}"/>
    <apex:inputHidden id="urlName" value="{!estimate.Name}"/>
    <apex:inputHidden id="changedAfterPrint" value="{!changedAfterPrint}"/>
    <apex:inputHidden id="changedSubmitPrice" value="{!changedSubmitPrice}"/>
    <apex:inputHidden id="isSaveOrApproval" value="{!isSaveOrApproval}"/>
    <!-- HWAG-B4R3SS  START 20181026-->
    <apex:actionFunction name="searchfunc" action="{!searchBtn}" rerender="Form,Block,assetSection2,pageMessages,allBlock" onComplete="unblockUI();"></apex:actionFunction>
    <!-- HWAG-B4R3SS  END 20181026-->
    <apex:actionFunction name="ComputeLTYRepair" action="{!ComputeLTYRepair}"  oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="ShowLTYRepair" action="{!ShowLTYRepair}"  oncomplete="unblockUI();ComputeLTY();"/>
    <apex:actionFunction name="decide" action="{!decide}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:actionFunction name="decideCancle" action="{!decideCancle}" rerender="allForm" oncomplete="unblockUI();"/>
    <apex:inputHidden id="oldDecideContractDate" value="{!OldContractStartDate}" />
    <input type="hidden" id="oldContractDate" value="{!estimate.Contract_Start_Date__c}" />
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
</script>
    <apex:pageBlock title="维修合同报价" id="allBlock">
        <apex:pageBlockButtons id="blocktop" location="top">
            <apex:commandButton id="savebtntop" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();"/>
           <!--  <apex:commandButton id="LastTwoYearRepairShow" value="过去两年维修实绩Repaort"  action="{!ShowLTYRepair}" rerender="alertStringValue,alertStringValue2,alertStringValue3" oncomplete="AlertPrice();"/> -->
            <apex:commandButton id="LastTwoYearRepairComp" value="过去三年维修实绩计算" rerender="PriceStatus" onclick="AlertPriceBtnJs()"/>
            <apex:commandButton id="approvalbtntop" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();ComputeLTYRepair();"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
            &nbsp; <apex:outputText style="color:red;font-size:20px" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
            <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
            <apex:commandButton action="{!cancel}" value="不保存（返回）" style="float:right;" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/>
            <apex:commandButton id="saveAndCancelBtn" action="{!saveAndCancel}" value="保存（返回）" style="float:right;" rerender="allForm" oncomplete="unblockUI();" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" disabled="{!SaveBtnDisabled}"/>
        </apex:pageBlockButtons>
       
        <apex:pageMessages id="pageMessages"></apex:pageMessages>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 Star-->
        <apex:actionFunction name="refreshProductData" action="{!refreshProductData}" rerender="pageMessages, assetListPrice, assetListPriceHidden, productCount3, assetSection" oncomplete="refreshAsset({!productCount});unblockUI();">
            <apex:param assignTo="{!productIdx}" name="productIdx" value=""/>
        </apex:actionFunction>
        <!-- update 合同报价页面的优化 添加‘assetSection’ fxk 2021/9/10 End-->
        <apex:actionFunction name="contractStartDateChange" action="{!contractStartDateChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>

        <apex:actionFunction name="recordNumChangeAction" action="{!recordNumChange}" rerender="allForm" oncomplete="unblockUI();">
        </apex:actionFunction>
        
        <apex:pageblocksection title="{!$ObjectType.Maintenance_Contract__c.label}" id="contract">
            <apex:outputField value="{!estimate.Name}"/>
            <apex:outputField value="{!contract.Management_Code__c}" />
            <apex:outputField value="{!estimate.Process_Status__c}"/>
            <apex:outputField value="{!contract.Status__c}"/>
            <apex:outputField value="{!contract.Hospital__c}" />
            <apex:inputField value="{!estimate.Department__c}" id="depart"/>
            <apex:inputField value="{!estimate.Contract_Esti_Start_Date__c}" required="true" id="startdate" onchange="changeEstiStartdate(this.value);"/><!-- onchange="checkContractEstiStartDate(this.value, {!productCount})" -->
            <apex:inputField value="{!estimate.Contract_Range__c}" required="true" id="monthRange" onchange="checkContractRange(this.value, {!productCount})"/>
            <apex:outputField value="{!estimate.Contract_Esti_End_Date__c}"/>
            <apex:outputField label="制定日" value="{!estimate.CreatedDate}" id="createDateShow"/>

            <apex:outputPanel >
                <label class="labelCol vfLabelColTextWrap " style="margin-left:22%">报价提交对象</label>
                <apex:inputField value="{!estimate.Estimate_Target__c}" id="estimateTarget" onchange="resetDealer()" style="margin-left:5px"/>

                <apex:outputPanel rendered="{!DecideBtnDisabled==false}">
                    <input type="button" class="btn" value="变更" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                </apex:outputPanel>
                <apex:outputPanel rendered="{!DecideBtnDisabled==true}">
                    <input type="button" class="btnDisabled" value="变更" disabled="true" onclick="controlDisabled()" style="margin-left:20px;width:40px;padding:0 0;"/>
                </apex:outputPanel>
            </apex:outputPanel>

            <apex:inputField value="{!estimate.Dealer__c}" id="dealer" />
            <script type="text/javascript">
                j$(escapeVfId('allPage:allForm:allBlock:contract:estimateTarget')).children('option[value=]').remove();
                resetDealer();
            </script>
        </apex:pageblocksection>

        <apex:pageblocksection columns="1" title="合同对象设备" id="assetSection" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection:productCnt" value="{!productCount}" />
                <table width="100%">
                    <tr>
                        <td>&nbsp;</td>
                        <td width="100px"><span>全</span>
                            <select style="vertical-align:text-bottom" id="allCheckResult" size="1" onchange="changeAllCheckResult(this.value)">
                                <option value=" ">--无--</option>
                                <option value="OK">OK</option>
                                <option value="NG">NG</option>
                            </select>
                        </td>
                        <td width="150px">&nbsp;</td>
                    </tr>
                </table>
                
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll(this)'/></th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Installation_Site__c.label}</th> -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Management_Code__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.CurrentContract_End_Date__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price_All__c.label}</th>
                        <!--add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star-->
                        <th style="width:70px" class="headerRow  booleanColumn">
                        {!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Check_Object__c.label}</th>
                        <!--add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk end-->
                        <th style="width:40px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.IsNew__c.label}</th>
                        <!-- <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Last_inspection_day__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Check_Result__c.label}</th> -->
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Repair_Price__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Comment__c.label}</th>
                    </tr>
                </table>
                
                <apex:outputPanel layout="block" styleClass="container">
                    <apex:variable value="{!1}" var="cnt" />
                    <table class="list" style="border-top-width: 0px; font-size:12px;" border="0" cellspacing="0" cellpadding="0">
                        <apex:repeat value="{!checkedAssets}" var="ar" id="assetTable">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox" rendered="{!Not(ar.IsManual)}" disabled="{!PageDisabled}"/>
                                    <apex:outputText value="{!ar.IsManual}" id="IsManual" style="display:none;" />
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Name}" id="assetName" rendered="{!Not(ar.IsManual)}" />
                                    <apex:inputField value="{!ar.mcae.Product_Manual__c}" id="Assert" style="width:90%;" rendered="{!ar.IsManual}" onchange="blockme();refreshProductData({!ar.lineNo});"/>
                                    <apex:inputText id="ProductId" value="{!ar.mcae.Product_Manual__c}" style="display:none;" disabled="true"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputLink value="/{!ar.recId}" rendered="{!Not(ar.IsManual)}" >{!ar.rec.SerialNumber}</apex:outputLink>
                                    <apex:inputHidden id="AssetId" value="{!ar.recId}"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Department_Name__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Installation_Site__c}" rendered="{!Not(ar.IsManual)}" />
                                </td> -->
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Management_Code__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.CurrentContract_End_Date__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}" id="InstallDate" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}" rendered="{!Not(ar.IsManual)}" />
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}" rendered="{!Not(ar.IsManual)}" />
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputText value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPrice" style="padding-right:3px;" />
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price__c}" id="assetListPriceHidden"/>
                                        <apex:inputHidden value="{!ar.mcae.Estimate_List_Price_Page__c}" id="assetListPricePageHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.Estimate_List_Price__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetListPriceHidden"/>
                                    </apex:outputPanel>
                                </td>
                                 <!--add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk Star-->
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.Check_Object__c}" id="assetCheck" disabled="{!ar.CheckRows}"/>
                                </td>
                                <!--add点检改善：新增一个点检对象复选框字段，默认为true 2021.6.8 fxk end-->
                                <td class="dataCell" width="40px" style="text-align:center" >
                                    <apex:inputCheckbox value="{!ar.mcae.IsNew__c}" id="assetNew" disabled="true"/>
                                    <apex:outputPanel layout="none" rendered="{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.createable}" >
                                        <apex:inputHidden value="{!ar.mcae.IsNew__c}" id="assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputPanel layout="none" rendered="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable)}" >
                                        <input type="hidden" value="{!ar.mcae.IsNew__c}" id="allPage:allForm:allBlock:assetSection:assetTable:{!Text(cnt-1)}:assetNewHidden" />
                                    </apex:outputPanel>
                                    <apex:outputText value="{!ar.rec.Final_Examination_Date__c}" id="finalExaminationDate" rendered="{!Not(ar.IsManual)}" style="display:none"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Final_Examination_Date__c}" id="finalExaminationDate" rendered="{!Not(ar.IsManual)}"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:center" >
                                    <apex:inputField value="{!ar.mcae.Check_Result__c}" id="checkResult"/>
                                </td> -->
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Repair_Price__c}" id="repairPrice" style="ime-mode: disabled; width:95%; text-align:right;" onchange="refreshAsset({!productCount});"/>
                                </td>
                                <td class="dataCell" width="70px" style="text-align:right" >
                                    <apex:inputField value="{!ar.mcae.Comment__c}" id="comment" style="width:95%;"/>
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                    </table>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:pageblocksection>
        <!-- HWAG-B4R3SS  START 20181026-->
        <apex:outputPanel id="sumPanel"  onkeydown="if(event.keyCode==13){searchJs(); return false;}">
        <!-- HWAG-B4R3SS  END 20181026-->
            <table style="width:100%;">
                <tr>

                    <td>
                        <apex:commandButton value="行追加" action="{!addNewRows}" disabled="{!Not($ObjectType.Maintenance_Contract_Asset_Estimate__c.createable) || PageDisabled}"
                            style="margin-left:10px;float:left;" onclick="blockme();" oncomplete="unblockUI();" rerender="allForm" />
                        <apex:commandButton value="刷新选中的保有设备" disabled="{!SaveBtnDisabled || productCount2==0}" action="{!exchangeAsset}" onclick="blockme();" oncomplete="unblockUI();" rerender="allForm" />
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <!-- HWAG-B4R3SS  START 20181026-->
                        <apex:outputText value="选择条件"/>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!text1}" id="text1" size="1" style="width:80px"><apex:selectOptions value="{!textOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;
                        <apex:selectList value="{!cond1}" id="cond1" size="1" style="width:80px">
                        <apex:selectOptions value="{!equalOpts}"/>
                        </apex:selectList>
                        &nbsp;&nbsp;

                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao start -->
                        <!-- <apex:inputText value="{!val1}"
                        id="val1" style="width:100px"/> -->

                        <apex:inputText value="{!val1}" 
                        id="val1" style="width:100px; background-color:{!IF(contr == '1','#e3f3ff','white')}"/>
                        <!-- LJPH-BSS6E2  ---20200911 ---update by rentongxiao end -->
                        &nbsp;
                        <apex:commandButton value="检索" onclick="searchJs();" style="width:100px" rerender="dummy"/>
                        &nbsp;
                        <apex:commandButton value="清除条件" onclick="clearAndSearch();" style="width:100px" rerender="dummy"/>
                        <!-- HWAG-B4R3SS END 20181026-->
                    </td>
                    
                    <th width="90px" style="text-align:right">设备数量</th>
                    <td width="90px" style="text-align:right"><apex:outputtext value="{!productCount3}" id="productCount3"/></td>
                    <td width="25px">&nbsp;</td>
                    <th width="90px" style="text-align:right">报价总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetListSumNum" ></span></th>
                    <td width="25px">&nbsp;</td>
                    <th width="90px" style="text-align:right">修理总额</th>
                    <th width="90px" style="text-align:right"><span id="allPage:allForm:allBlock:assetRepairSumNum" ></span></th>
                    <td width="95px">&nbsp;</td>
                </tr>

            </table>
        </apex:outputPanel>
        
        <apex:pageblocksection columns="1" title="未选择的保有设备" id="assetSection2" >
            <apex:outputLabel />
            <apex:outputPanel >
                <input type="hidden" id="allPage:allForm:allBlock:assetSection2:productCnt2" value="{!productCount2}" />
                <table class="list" style="border-bottom-width: 0px; font-size:13px;" border="0" cellspacing="0" cellpadding="0">
                    <tr class="headerRow" height="30px">
                        <th style="width:25px" class="headerRow  booleanColumn"><input type='checkbox' onClick='checkAll2(this)'/></th>
                        <th style="width:29%" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Name.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_situation__c.label}</th>
                        <th style="width:70px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.SerialNumber.label}</th>
                        <th class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Department_Name__c.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Installation_Site__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.IF_Warranty__c.label}</th>

                        <!-- JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                        <th style="width: 90px" class="headerRow booleanColumn">主机/耗材</th>
                        <!-- JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->

                        <th style="width:150px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Reson_Can_not_Warranty__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.InstallDate.label}</th>
                        <!-- <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Asset_Owner__c.label}</th> -->
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Asset.fields.Accumulation_Repair_Amount__c.label}</th>
                        <th style="width:90px" class="headerRow  booleanColumn">{!$ObjectType.Maintenance_Contract_Asset_Estimate__c.fields.Estimate_List_Price__c.label}</th>
                    </tr>
                </table>
                
                <apex:outputPanel layout="block" styleClass="container2" style="max-height: 404px; height: auto;">
                    <apex:variable value="{!1}" var="cnt" />
                    <table class="list" style="border-top-width: 0px; font-size:12px;" border="0" cellspacing="0" cellpadding="0">
                    <apex:repeat value="{!unCheckedAssetsView}" var="assetsView" id="outassetTable2">
                        <apex:repeat value="{!assetsView}" var="ar" id="assetTable2">
                            <tr class="dataRow {!IF(MOD(cnt, 2)==0, 'odd', 'even')} {!IF(cnt==1, 'first', '')}" onmouseover="if (window.hiOn){hiOn(this);} " onmouseout="if (window.hiOff){hiOff(this);} " onblur="if (window.hiOff){hiOff(this);}" onfocus="if (window.hiOn){hiOn(this);}">
                                <td class="dataCell" width="25px">
                                    <apex:inputCheckbox value="{!ar.rec_checkBox_c}" id="assetRowCheckbox2" disabled="{!IF(ar.rec.Maintenance_Price_Month__c == 0 || ar.rec.IF_Warranty__c = '否', 'true', 'false')}"/>
                                </td>
                                <td class="dataCell" width="30%">
                                    <apex:outputField value="{!ar.rec.name}" id="assetName"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Asset_situation__c}"/>
                                </td>
                                <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.SerialNumber}"/>
                                </td>
                                <td class="dataCell">
                                    <apex:outputField value="{!ar.rec.Department_Name__c}"/>
                                </td>
                                <!-- <td class="dataCell" width="70px">
                                    <apex:outputField value="{!ar.rec.Installation_Site__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.IF_Warranty__c}"/>
                                </td>

                                <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---Start -->
                                <td class="dataCell" width="90px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.AssetMark__c}"/>
                                </td>
                                <!-- //JZHG-BSDUT4 ---20200825---update By rentongxiao---End -->

                                <td class="dataCell" width="150px" style="text-align:center">
                                    <apex:outputField value="{!ar.rec.Reson_Can_not_Warranty__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:center" >
                                    <apex:outputField value="{!ar.rec.InstallDate}"/>
                                </td>
                                <!-- <td class="dataCell" width="90px">
                                    <apex:outputField value="{!ar.rec.Asset_Owner__c}"/>
                                </td> -->
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Accumulation_Repair_Amount__c}"/>
                                </td>
                                <td class="dataCell" width="90px" style="text-align:right" >
                                    <apex:outputField value="{!ar.rec.Maintenance_Price_Month__c}" />
                                </td>
                            </tr>
                            <apex:variable value="{!cnt + 1}" var="cnt" />
                        </apex:repeat>
                        </apex:repeat>
                    </table>
                </apex:outputPanel>
                <apex:outputPanel >
                    <dir align="right">
                        <table>
                            <tr>
                                <td>{!(currPage-1)*selctRecordNum}&nbsp;-&nbsp;{!IF(currPage*selctRecordNum > totalRecords, totalRecords, currPage*selctRecordNum)}</td>
                                <td>&nbsp;&nbsp;共{!totalRecords}个</td>
                                <td align="right" width="115px">显示
                                    <apex:selectList value="{!selRecordOption}" id="selRecordOption" size="1" onchange="blockme();recordNumChangeJs();" disabled="{!IF(totalRecords<10,true,false)}"><apex:selectOptions value="{!recordNum}"/></apex:selectList>条记录
                                </td>
                                <td align="right" width="50px">第{!currPage}页</td>
                                <td align="right" width="45px">
                                    <apex:commandLink action="{!firstPage}" value="首页" id="firstPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="首页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="right" width="40px">
                                    <apex:commandLink action="{!previousPage}" value="上一页" id="previous" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(currPage==1,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="上一页" style="{!IF(currPage!=1,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td width="3px"></td>
                                <td align="left" width="40px">
                                    <!-- HWAG-B4R3SS  START 20181026-->
                                    <apex:commandLink action="{!nextPage}" value="下一页" id="next" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage ||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="下一页" style="{!IF(totalPage!=currPage && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <td align="left" width="45px">
                                    <apex:commandLink action="{!endPage}" value="尾页" id="endPg" onclick="blockme();" oncomplete="unblockUI();" reRender="allForm" style="{!IF(totalPage==currPage||totalPage == 0,'display: none;','')}color: blue;"/>
                                    <apex:outputText value="尾页" style="{!IF(totalPage!=currPage
                                        && totalPage != 0,'display: none;','')}color: gray;"></apex:outputText>
                                </td>
                                <!-- HWAG-B4R3SS  END 20181026-->
                                <td align="left">共{!totalPage}页</td>
                            </tr>
                        </table>
                    </dir>
                </apex:outputPanel>
            </apex:outputPanel>
        </apex:pageblocksection>
        
        <apex:pageblocksection columns="1" title="附加条件" id="appendCondition">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <th width="100" style="text-align:right">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.NotUse_Oxygenated_Water__c.label}</th>
                        <td width="100" style="text-align:center"><!-- <apex:inputField value="{!estimate.NotUse_Oxygenated_Water__c}" id="notUseOxygen" onclick="NotUseOxygenatedWaterAmount();"/> -->
                        <apex:inputCheckbox value="{!estimate.NotUse_Oxygenated_Water__c}" id="notUseOxygen" onclick="NotUseOxygenatedWaterAmount();" disabled="true"/>
                        </td>
                        <td width="100" style="text-align:right"><span id="allPage:allForm:allBlock:NotUseOxygenatedWaterAmount"></span></td>
                        <td width="100">&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <th style="text-align:right">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Service_contract_target_number__c.label}</th>
                        <td><apex:inputField value="{!estimate.Service_contract_target_number__c}" id="Examination_Count" style="ime-mode: disabled; text-align:right; width:100px" onchange="examinationPriceCal({!productCount})"/></td>
                        <th style="text-align:right;display:none;">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Examination_Price__c.label}</th>
                        <td style="text-align:right;display:none;">
                            <apex:outputField value="{!estimate.Examination_Price__c}" id="examinationReal" />
                            <apex:inputHidden value="{!estimate.Examination_Price__c}" id="examinationRealHidden"/>
                        </td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
            </apex:outputPanel>
        </apex:pageblocksection>
        
        <apex:pageblocksection title="合同信息" columns="1" id="contractInfo">
            <apex:outputLabel />
            <apex:outputPanel >
                <table style="width:100%">
                    <tr>
                        <td width="15%"></td>
                        <td width="14%"></td>
                        <td width="15%"></td>
                        <td width="28%"></td>
                        <td width="14%"></td>
                        <td width="14%"></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">1.维修合同设备报价总额</th>
                        <th style="text-align: center">2.附加条件总额</th>
                        <th style="text-align: center">3.此次合同报价总额</th>
                        <th style="text-align: center">4.优惠率（价格）</th>
                        <th style="text-align: center">5.修理总额</th>
                        <th style="text-align: center">6.合同价格</th>
                    </tr>
                    <tr>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Asset_Sum_Price__c}" id="assetSumPrice" />
                            <apex:inputHidden value="{!estimate.Asset_Sum_Price__c}" id="assetSumPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Append_Condition_Price__c}" id="appendPrice" />
                            <apex:inputHidden value="{!estimate.Append_Condition_Price__c}" id="appendPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Estimate_Trial_Money__c}" id="assetSum2" />
                            <apex:inputHidden value="{!estimate.Estimate_Trial_Money__c}" id="assetSum2Hidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:inputField value="{!estimate.Discount_Percentage__c}" id="disPercent" style="ime-mode: disabled; text-align:right; width:100px" onchange="checkPercentage(this.value);"/><font style="font-weight: bold">&nbsp;%&nbsp;（&nbsp;</font>
                            <apex:inputField value="{!estimate.Discount_Price__c}" id="disMoney" style="ime-mode: disabled; text-align: right; width:100px" onchange="checkDiscount(this.value);"/><font style="font-weight: bold">&nbsp;）</font>
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPrice" />
                            <apex:inputHidden value="{!estimate.Asset_Repair_Sum_Price__c}" id="assetRepairSumPriceHidden" />
                        </td>
                        <td style="text-align: center">
                            <apex:outputField value="{!estimate.Maintenance_Price__c}" id="mainteReal" />
                            <apex:inputHidden value="{!estimate.Maintenance_Price__c}" id="mainteRealHidden"/>
                            <apex:inputHidden value="{!OldMaintenancePrice}" id="oldMainteReal"/>
                        </td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Discount_reason__c.label}</th>
                        <td colspan="5"><apex:inputField value="{!estimate.Discount_reason__c}" id="discountReason" style="width:95%;height:50px;" /></td>
                    </tr>
                    <tr>
                        <th style="text-align: center">{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Improve_ConsumptionRate_Idea__c.label}</th>
                        <td colspan="5"><apex:inputField value="{!estimate.Improve_ConsumptionRate_Idea__c}" id="improveConsumptionRateIdea" style="width:95%;height:50px;" /></td>
                    </tr>
                </table>
            </apex:outputPanel>
        </apex:pageblocksection>
        
        <script type="text/javascript">
            refreshAsset({!productCount});
        </script>
    </apex:pageBlock>
    
    <table width="100%" border="0">
        <tr>
            <!-- <td width="40%" style="text-align: right;"> -->
            <td width="40%">
                <table border="0" style="background-color:#ffd6c1;">
                    <tr>
                        <th width="70px">打印报价</th>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_ListPrice__c}"/>报价</td>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_RepairPrice__c}"/>修理金额</td>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_SumPrice__c}"/>报价总额</td>
                        <td width="80px" style="display:none;"><apex:inputCheckbox value="{!estimate.Print_DiscountPercentage__c}"/>优惠折扣</td>
                        <td width="80px" style="display:none;"><apex:inputCheckbox value="{!estimate.Print_DiscountPrice__c}"/>优惠价格</td>
                        <td width="80px"><apex:inputCheckbox value="{!estimate.Print_MaintePrice__c}"/>合同价格</td>
                        
                    </tr>
                    <tr>
                        <th width="70px">打印合同配置</th>
                        <td width="80px">

                        <!-- 2018/10/26HWAG-B5C88S 医院和经销商合同任何时候都不能选择 start -->

                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox value="{!estimate.Print_Contract__c}" />
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                            医院合同
                        </td>
                        <!-- 2018/09/26 HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 start -->
                        <td width="70px">
                            <apex:outputPanel rendered="{!EnablePrintContract}">
                                <apex:inputCheckbox id="tripartite" value="{!estimate.Print_Tripartite__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        三方协议</td>
                        <td width="70px">
                            <apex:outputPanel rendered="false">
                                <apex:inputCheckbox id="agent" value="{!estimate.Print_Agent__c}"/>
                            </apex:outputPanel>
                            <apex:outputPanel rendered="{!Not(EnablePrintContract)}">
                                &nbsp;&nbsp;&nbsp;
                            </apex:outputPanel>
                        代理商合同</td>
                        <!-- 2018/09/26  HWAG-B4SCR3 三方和代理商合同在未decide前也不能选择 end -->
                        <!-- 2018/10/26 HWAG-B5C88S 医院和经销商合同任何时候都不能选择 end -->                        
                        <td colspan="3" style="text-align: right"><apex:commandButton action="{!print}" value="PDF印刷" rerender="allBlock,pdfPrint" disabled="{!PrintBtnDisabled}" onclick="if (!onclickCheckchangedAfterPrint('Pt{!SaveBtnDisabled}','false')) return false;" oncomplete="unblockUI();ComputeLTYRepair()"/></td>
                    </tr>
                </table>
            </td>
            <td>
                <table class="btntable" border="0">
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="20px">&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td width="30px">&nbsp;</td>
                        <td><apex:commandButton id="savebtn" action="{!save}" value="{!$Label.Save_Button}" disabled="{!SaveBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();"/></td>
                        
                        <td width="200px"><apex:commandButton id="approvalbtn" action="{!approvalProcess}" value="提交待审批" disabled="{!ApprovalBtnDisabled}" rerender="allForm" onclick="if (!onclickCheckchangedAfterPrint('true','true')) return false;" oncomplete="unblockUI();ComputeLTYRepair();"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 start-->
                        &nbsp; <apex:outputText style="color:red;font-size:20px;" value="请提交待审批" rendered="{!IS_Clone_After_Decide}"/>
                        <!-- HWAG-B399Q8 2018/08/20 新增请提交待审批 提示字段 end-->
                        </td>
                    </tr>
                    <tr>
                        <th>{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_Start_Date__c.label}</th>
                        <td><apex:inputField value="{!estimate.Contract_Start_Date__c}" id="contractstartdate" onchange="changeContractStartdate(this.value);"/></td>
                        <td>&nbsp;</td>
                        <th>&nbsp;&nbsp;{!$ObjectType.Maintenance_Contract_Estimate__c.fields.Contract_End_Date__c.label}</th>
                        <td><apex:outputField value="{!estimate.Contract_End_Date__c}" id="contractenddate"/></td>
                        <td>&nbsp;</td>
                        <td><apex:commandButton id="decidebtn" value="{!$Label.QuoteDecision_Button}" disabled="{!DecideBtnDisabled}" onclick="decideJs(); return false;"/></td>
                        <td style="text-align:right"><apex:commandButton id="undecidebtn" action="{!undecide}" value="取消{!$Label.QuoteDecision_Button}" disabled="{!UnDecideBtnDisabled}" rerender="allForm" onclick="blockme();" oncomplete="unblockUI();"/></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</apex:form>
<apex:outputPanel id="pdfPrint">
<script type="text/javascript">
//j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');

function saveBeforeCheckPriceChange() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    var rowCnt = j$(escapeVfId('allPage:allForm:allBlock:assetSection:productCnt')).val();
    var assIds = "";
    var proIds = "";
    var priceMap = new Map();
    var newProductMap = new Map();
    var newProductCheck = false;
    var nowDate = new Date();
    var createdDate = null;
    var createdDateShow = j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text();
    var contractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
    if (createdDateShow.trim() != '') {
        createdDate = new Date(createdDateShow);
        newProductCheck = true;
    } else {
        createdDate = new Date();
    }
    var threeMonthAfter = new Date(createdDate.setMonth(createdDate.getMonth() + 3));
    createdDate = new Date(createdDate.setMonth(createdDate.getMonth() - 3));
    for (var i = 0; i < rowCnt; i++) {
        var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
        var isnew = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetNewHidden')).val();
        var price = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':assetListPriceHidden')).val();
        if (isManual == 'true') {
            var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
            if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                if (proIds == "") {
                    proIds = "'" + a.value() + "'";
                } else {
                    proIds = proIds + ",'" + a.value() + "'";
                }
                if (isnew == "true") {
                    priceMap.set(a.value(), price/{!isNewPriceAdj});
                } else {
                    priceMap.set(a.value(), price);
                }
                newProductMap.set(a.value(), isnew);
                
            } else {
                continue;
            }
        }
        else {
            var aId = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value();
            if (assIds == "") {
                assIds = "'" + aId + "'";
            } else {
                assIds = assIds + ",'" + aId + "'";
            }
            if (isnew == "true") {
                priceMap.set(aId, price/{!isNewPriceAdj});
            } else {
                priceMap.set(aId, price);
            }
            newProductMap.set(aId, isnew);
        }
    }
    // 选择设备后价格变更check
    if (assIds.length > 0) {
        var sql = "SELECT Id, Maintenance_Price_Month__c, Posting_Date__c, InstallDate from Asset where Id In(" + assIds + ")";
        var rt = sforce.connection.query(sql);
        var asList = rt.getArray("records"); 
        if (asList != null) {
            for(var i=0;i<asList.length;i++) {
                var asvar = asList[i];
                var asId = asvar["Id"];
                var mprice = asvar["Maintenance_Price_Month__c"];
                var ptDt = asvar["Posting_Date__c"];
                var postingDate = null;
                if (ptDt != null && ptDt != '') {
                    postingDate = new Date(ptDt);
                }
                var inDt = asvar["InstallDate"];
                var installDate = null;
                if (inDt != null && inDt != '') {
                    installDate = new Date(inDt);
                }
                var priceShow = priceMap.get(asId);
                var isNew = newProductMap.get(asId);
                if ('{!DecideBtnDisabled}' == 'true') {
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
                // 新品check
                var sixCreateDate = new Date(createdDate.setMonth(createdDate.getMonth() + 6));
                createdDate.setMonth(createdDate.getMonth() - 6);
                if (contractDate >= sixCreateDate && newProductCheck) {
                    if (isNew=='true') {
                        needClearId = true;
                        j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                } else {
                    var threeCreateDate = new Date(createdDate.setMonth(createdDate.getMonth() + 3));
                    createdDate = new Date(createdDate.setMonth(createdDate.getMonth() - 3));
                    if (newProductCheck) {
                        var isNewDate = null;
                        var isNewProduct = 'false';
                        if (contractDate >= threeMonthAfter) {
                            isNewDate = new Date(contractDate);
                        } else {
                            isNewDate = new Date(createdDate);
                        }
                        if (postingDate != null && postingDate != '' && (installDate == null || installDate == '')) {
                            if (new Date(isNewDate.setMonth(isNewDate.getMonth()-6)) < postingDate) {
                                isNewProduct = 'true';
                            }
                        } else if (postingDate != null && postingDate != '' && installDate != null && installDate != '') {
                            // alert('postingDate:'+postingDate+'/installDate:'+installDate);
                            if (new Date(postingDate.setMonth(postingDate.getMonth()+6)) >= installDate) {
                                var dt = new Date(isNewDate.setMonth(isNewDate.getMonth()-6));
                                if (dt < installDate) {
                                    isNewProduct = 'true';
                                }
                            }
                        } else if ((postingDate == null || postingDate == '') && installDate != null && installDate != '') {
                            if (new Date(isNewDate.setMonth(isNewDate.getMonth()-6)) < installDate) {
                                isNewProduct = 'true';
                            }
                            // isNewDate.setMonth(isNewDate.getMonth()+6);
                        }
                        // alert('contract:'+contractDate+'/create:'+createdDate+'/install:'+installDate+'/date:'+isNewDate);
                        // alert('oldNew:'+isNew + 'isNew:'+isNewProduct);
                        if (isNew != isNewProduct) {
                            needClearId = true;
                            j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                            return needClearId;
                        }
                    }
                }
            }
        }
    }
    if (proIds.length > 0) {
        if ('{!DecideBtnDisabled}' == 'false') {
            var oldDateStr = j$('#oldContractDate').value();
            var oldDate = new Date();
            if (oldDateStr != null && oldDateStr != '') {
                oldDate = new Date(oldDateStr);
            }
            var crdt = new Date(j$(escapeVfId('allPage:allForm:allBlock:contract:createDateShow')).text());
            var newContractDate = new Date(j$(escapeVfId('allPage:allForm:contractstartdate')).value());
            var sixMonthAfter = new Date(crdt.setMonth(crdt.getMonth() + 6));
            if ((newContractDate > sixMonthAfter && oldDate <= sixMonthAfter) || (newContractDate <= sixMonthAfter && oldDate > sixMonthAfter)) {
                j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                return true;
            }
        } else {
            var sql = "SELECT Id, Maintenance_Price_Month__c from Product2 where Id In(" + proIds + ")";
            var rt = sforce.connection.query(sql);
            var pdList = rt.getArray("records");
            if (pdList != null) {
                for(var i=0;i<pdList.length;i++) {
                    var pdvar = pdList[i];
                    var pdId = pdvar["Id"];
                    var mprice = pdvar["Maintenance_Price_Month__c"];
                    var priceShow = priceMap.get(pdId);
                    if (Number(mprice).toFixed(2) != Number(priceShow).toFixed(2)) {
                        needClearId = true;
                        // j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
                        return needClearId;
                    }
                }
            }
        }
    }
    // var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // if (changedPrice=='true') {
    //     needClearId = true;
    // }
    return needClearId;
}

// SelectAssetEstimateController#checkchangedAfterPrint と同じロジックにする必要があります。
// true 変更あり、false 変更なし
function checkchangedAfterPrint() {
    sforce.connection.sessionId = Session_ID;
    var needClearId = false;
    //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('false');
    var changedPrice = j$(escapeVfId('allPage:allForm:changedSubmitPrice')).value();
    // 新規の場合、targetEstimateIdがない、判断いらない
    if ('{!targetEstimateId}' == '') return needClearId;
    if ('{!estimate.Quote_Date__c}' != '' || '{!estimate.Process_Status__c}' != '草案中') {
        // xud 20140529 ここは明細変更判断
        // xudan 20150729 ソート項目にIdを追加
        var sql = "SELECT Id, Asset__c, Asset__r.SerialNumber, Check_Result__c, Product_Manual__c,"
                + " Repair_Price__c, Comment__c, Maintenance_Contract_Estimate__r.Maintenance_Price__c"
                + "  FROM Maintenance_Contract_Asset_Estimate__c"
                + " WHERE Maintenance_Contract_Estimate__c = '{!targetEstimateId}'"
                + " ORDER BY id,Asset__c,Product_Manual__c, Asset__r.SerialNumber, Asset__r.Name, Asset__r.Department_Name__c, Asset__r.InstallDate";
        var result = sforce.connection.query(sql);
        var mcaeList = result.getArray("records");
        var inputingList = [];
        var finalPrice = 0;
        // 画面入力値を整理（いらないものを対象外にする）
        var cntWithKara = {!productCount};
        for (var i = 0; i < cntWithKara; i++) {
            var isManual = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':IsManual')).text();
            if (isManual == 'true') {
                var a = j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':ProductId'));
                if (a.size() > 0 && a.value() != "000000000000000000" && a.value() != "") {
                    inputingList.push(
                        {'id' : '',
                         'Product_Manual__c' : a.value(),
                         'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                         'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                         'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                        }
                    );
                } else {
                    continue;
                }
            }
            else {
                inputingList.push(
                    {'id' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':AssetId')).value(),
                     'Check_Result__c' : j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':checkResult')).value(),
                     'Repair_Price__c' : localParseFloat(j$.trim(j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':repairPrice')).value())),
                     'Comment__c': j$(escapeVfId('allPage:allForm:allBlock:assetSection:assetTable:' + i + ':comment')).value()
                    }
                );
            }
        }
        //针对inputingList的重新排序
        var arrayMap = [];
        var ArrayOrderPMCnt = [];
        for(var i=0;i<mcaeList.length;i++){
            var mcaeVar = mcaeList[i];
            var AssetIDOrPMC = mcaeVar["Asset__c"]!=null?mcaeVar["Asset__c"]:mcaeVar["Product_Manual__c"];
            if(arrayMap[AssetIDOrPMC]!=null){
                arrayMap[AssetIDOrPMC] = i;
                ArrayOrderPMCnt[AssetIDOrPMC] = i;
            }else{
                // Product_Manual__c相同的话怎么办
                if(ArrayOrderPMCnt[AssetIDOrPMC]==null){
                    ArrayOrderPMCnt[AssetIDOrPMC] = i;
                }else{
                    var cacheArray = new Array();
                    cacheArray = ArrayOrderPMCnt[AssetIDOrPMC];
                    ArrayOrderPMCnt[AssetIDOrPMC] = cacheArray+','+i;
                }
                
            }
            
        }
        var inputingListCache = inputingList;
        var cntLength = mcaeList.length>inputingListCache.length?mcaeList.length:inputingListCache.length;
        if(mcaeList.length!=inputingListCache.length){
            needClearId = true;
            //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
            return needClearId;
        }
        inputingList = new Array(cntLength);
        var inputingListOut = new Array();
        for(var i=0;i<inputingListCache.length;i++){
            var InputIdOrPMc = inputingListCache[i].id!=""?inputingListCache[i].id:inputingListCache[i].Product_Manual__c;
            var thisArray = ArrayOrderPMCnt[InputIdOrPMc];
            if(thisArray.length!=null){
                thisArray = thisArray.split(',');
                var ORDERCnt = thisArray[0];
                thisArray.shift(); 
                thisArray = thisArray.join(','); 
                ArrayOrderPMCnt[InputIdOrPMc] = thisArray;
            }else{
                var ORDERCnt = thisArray;
            }
            if( ORDERCnt !=null){
                inputingList[ORDERCnt] = inputingListCache[i];
            }else{
                inputingList[ORDERCnt] = inputingListCache[i];
                inputingListOut.push(inputingListCache[i]);
            }
        }
        if( inputingListOut.length>0){
            for(var i = 0; i<inputingListOut.length;i++){
                inputingList.push(inputingListOut[i]);
            }
        }
        //20161122,测试发现Check_Result__c已停用，故而修改对应的Js判断部分
        /*
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        //==================================================================================
                            && (((mcae["Check_Result__c"] == null || mcae["Check_Result__c"] == "")
                                  && (inputing["Check_Result__c"] == null || inputing["Check_Result__c"] == "")
                                )
                                || mcae["Check_Result__c"] == inputing["Check_Result__c"]
                               )
        */
        //原是代码保留
        if (inputingList.length == mcaeList.length && needClearId == false ) {
            for (var i = 0; i < mcaeList.length; i++) {
                var mcae = mcaeList[i];
                finalPrice = mcae["Maintenance_Contract_Estimate__r"]["Maintenance_Price__c"];
                var inputing = inputingList[i];
                if (mcae["Asset__c"] != null && mcae["Asset__c"] != "") {
                    if (inputing["id"] != "" && mcae["Asset__c"] == inputing["id"]
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                } else {
                    if (inputing["id"] == "" && mcae["Product_Manual__c"] != null && mcae["Product_Manual__c"] != ""
                            && mcae["Product_Manual__c"] == inputing["Product_Manual__c"]
                            
                            && localParseFloat(mcae["Repair_Price__c"]) == inputing["Repair_Price__c"]
                            && (((mcae["Comment__c"] == null || mcae["Comment__c"] == "")
                                  && (inputing["Comment__c"] == null || inputing["Comment__c"] == "")
                                )
                                || mcae["Comment__c"] == inputing["Comment__c"]
                               )
                    ) {
                        // 同じ
                    } else {
                        needClearId = true;
                        break;
                    }
                }
            }
        } else {
            needClearId = true;
        }
        
        // xud 20140529 ここは総金額変更判断（割引を変更したらまずい）
        var inputFinalPrice = j$(escapeVfId('allPage:allForm:allBlock:contractInfo:mainteRealHidden')).value();
        if (toNum(inputFinalPrice) != toNum(finalPrice)) {
            needClearId = true;
        }
        if (changedPrice=='true') {
            needClearId = true;
        }
    }
    if (needClearId) {
        //j$(escapeVfId('allPage:allForm:changedAfterPrint')).val('true');
    }
    return needClearId;
}
if ('{!printAsset}' == 'true') {
    //打印保有設備
    window.open('/apex/MaintenanceContractEstimatePDF?id={!targetEstimateId}', 'MaintenanceContractEstimatePDF');
} else if ('{!printContract}' == 'true') {
    // 打印医院合同配置
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printContract', 'MceConfigPDF');
} else if ('{!printTripartite}' == 'true') {
    //打印三方合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printTripartite', 'MceConfigPDF');
} else if ('{!printAgent}' == 'true') {
    //打印经销商合同
    window.open('/apex/MceConfigPDF?id={!targetEstimateId}&flag=printAgent', 'MceConfigPDF');
}else {}
</script>
</apex:outputPanel>
</apex:page>