
function modes(){
    return ["日計表", "月計表", "年計表"];
}

function hospitalId(){
    // patientEditor から呼ばれる
    return parent().hospitalId();
}

function setLayout(answer){
	// レイアウトを DB から読み出し FRONT 内容を表示
    //alert("showLayout->"+answer);//###
    var obj1 = eval('(' + answer + ')');
    //alert("== obj1->"+encodeObject(obj1));//##
    var timezones = ["全日"];
    if (obj1.timezones){
        // obj1.timezones: ",,0000,0600,深夜^,,2200,2400,深夜^,日,0000,2400,休日^,,0845,1215,時間内^,,1445,1715,時間内^" 形式
        //alert("timezones->"+obj1.timezones);//##
        var array = obj1.timezones.split("^");
        for (num in array){
            var st = array[num];
            var ary = st.split(",");
            if (ary.length < 5) continue;
            
            var from = ary[2];
            var to = ary[3];
            var zone = ary[4];
            if (zone == "時間内"){
                timezones.push(from + ".." + to);
            }
        }
    }
    //alert("timezones->"+encodeObject(timezones));//##
    
    // 年月ポップアップ・メニューを表示
    // このポップアップ表示とともにサーバへデータを取りにゆくので ここに置く
    showDatePop(timezones);
}
function getTimeZone(){
	// レイアウトをサーバへリクエスト
    var args = new Object();
    args['owner'] = parent().owner(); // NOA から引き継いだもの
    args['hospitalId'] = parent().hospitalId(); // NOA から引き継いだもの
    
    _callServer("GET_LAYOUT_PARTS", "frontServer.php", args, setLayout);
}

function matchInOut(inOut){
    // inOut が「外来/入院」チェックボックスと一致するなら true を返す
    var td = document.getElementById("inpatient");
    if (!td) return true; // inpatient が指定されていなければ true
    
    // inOut が「外来/入院」チェックボックスと一致する場合のみ表示
    // rec.inout = ["on", ""|"0"]
    if ((inOut == "on") || (inOut * 1 > 0)){ // 入院チェックボックス
        return document.getElementById("inpatient").checked;
    }
    else { // 外来チェックボックス
        return document.getElementById("outpatient").checked;
    }
}

var _entryDate;
function gotMonthlyList(answer){
    // 月計表を表示
    //alert("gotMonthlyList-> "+answer); //##

    if (answer && (answer.length > 0)){
        // var records = JSON.parse(answer);
        var records = eval('(' + answer + ')');
        //console.log("gotMonthlyList: records-> "+encodeObject(records)); //##
        
        // 日毎のレコードを表示
        var elm = document.getElementById("contentsArea");
        elm.innerHTML = "";
        var tbl = newTABLE(elm, "/base-table");
        tbl.style.fontSize = "9pt";
        tbl.style.margin = "10px 0";
        
        // TITLE =======================================
        var tr = newTR(tbl, "", "");
        tr.style.borderBottom = "thin solid #aaa";
        var td = newTD(tr, "", "日付");
        var td = newTD(tr, "/valueCol", "人数");
        var td = newTD(tr, "/valueCol", "本人");
        var td = newTD(tr, "/valueCol", "家族");
        var td = newTD(tr, "/valueCol", "国保");
        var td = newTD(tr, "/valueCol", "自費");
        var td = newTD(tr, "/valueCol", "合計");
        
        // TABLE ========================================
        var rows = 0;
        var membTotal = 0;
        var jihiTotal = 0;
        var insTotal = 0;
        var sumTotal = 0;
        
        for (num in records){
            var cols = records[num];
            if (cols && (cols.length > 0)){
                var sum = 0;
                var date = cols[1].substr(8);
                var week = weekOfDate(cols[1], true);
                var members = "" + cols[0];
                var honin = "" + cols[2]; sum += honin * 1;
                var kazoku = "" + cols[3]; sum += kazoku * 1;
                var kokuho = "" + cols[4]; sum += kokuho * 1;
                var jihi = "" + cols[5]; sum += jihi * 1;
                membTotal += members * 1;
                jihiTotal += jihi * 1;
                insTotal += honin * 1 + kazoku * 1 + kokuho * 1;
                sumTotal += sum * 1;
                // 6:未収 7:受取額 8:入院/外来 9:新患数 10:点数 は表示省略
                
                var tr = newTR(tbl, "/even-color", "");
                var td = newTD(tr, "", date + " " + week);
                var td = newTD(tr, "/valueCol", members);
                var td = newTD(tr, "/valueCol", honin);
                var td = newTD(tr, "/valueCol", kazoku);
                var td = newTD(tr, "/valueCol", kokuho);
                var td = newTD(tr, "/valueCol", jihi);
                var td = newTD(tr, "/valueCol", "" + sum);
                
                rows++;
            }
        }
        
        // TOTAL =========================================
        var tr = newTR(tbl, "", "");
        tr.style.borderTop = "thin solid #aaa";
        var td = newTD(tr, "", "合計");
        var td = newTD(tr, "/valueCol", "" + membTotal);
        var td = newTD(tr, "/valueCol", "(" + rows + "日)");
        var td = newTD(tr, "/valueCol", "" + insTotal);
        td.setAttribute("colspan", "2");
        var td = newTD(tr, "/valueCol", "" + jihiTotal);
        var td = newTD(tr, "/valueCol", "" + sumTotal);
        // AVERAGE =======================================
        var tr = newTR(tbl, "", "");
        var td = newTD(tr, "", "平均");
        var td = newTD(tr, "/valueCol", "" + Math.round(membTotal / rows));
        var td = newTD(tr, "/valueCol", "");
        var td = newTD(tr, "/valueCol", "" + Math.round(insTotal / rows));
        td.setAttribute("colspan", "2");
        var td = newTD(tr, "/valueCol", "" + Math.round(jihiTotal / rows));
        var td = newTD(tr, "/valueCol", "" + Math.round(sumTotal / rows));
    } else {
		var elm = document.getElementById("contentsArea");
        elm.innerHTML = "";
        var sp = newSPAN(elm, "");
        sp.innerHTML = "Loading monthlyList ...";
        sp.style.color = "#f88";
        sp.style.fontSize = "10pt";
        sp.style.padding = "20px";
    }
}
function getMonthlyList(entryDate){
	// 指定月の受診者リストをリクエスト
    _entryDate = entryDate;
    
    //console.log("getMonthlyList", entryDate); //##
    
    // まだ zonePop が生成されていないタイミングでは "0000-2400" を使用
    var zone = "0000-2400";
    var elm = elmFor("zonePop");
    if (elm){
        var st = elm.value;
        var from = "0000";
        var to = "2400";
        var ary = st.split("..");
        if (ary.length > 1){
            from = ary[0];
            to = ary[1];
        }
        zone = from + "-" + to;
    }
    
    var args = new Object();
    args['hospitalId'] = parent().hospitalId();
    args['timeZone'] = zone;
    args['entryDate'] = encodeSTRING(entryDate);
    args['in'] = (elmFor("inpatient").checked) ? 1 : 0; // 入院は無視
    args['out'] = (elmFor("outpatient").checked) ? 1 : 0; // 外来のみ表示
    
    _callServer("GET_MONTHLY_LIST", "frontServer.php", args, gotMonthlyList);
}

function open_chart(patientId){
    // 指定された patientId のカルテを開く
    // parent().openChart(patientId); 形式だと現在開いてるカルテを上書き表示するので
    // 現在開いているカルテと別タグでひらくには以下のように記述
    window.open("../NOA/top.php?patientId=" + patientId);
}
function open_editor(dateTime, patientId){
    // 指定された患者会計レコードの編集パネルを開く
    var url = "./patientEditor.php?dateAndId=" + dateTime + "^" + patientId;
    
    var w = window.open(encodeURI(url),
                        "patientEditor",
                        "width=300,height=550,resizable=yes");
}

function reverseOrder(){
    // 待受リストの表示順を逆にする
    var status = waitingListReverseOrder();
    if (status)
        setWaitingListReverseOrder("0");
    else
        setWaitingListReverseOrder("1");
    
    showDaylyList();
}

function gotDaylyList(answer){
    // 日計表を表示
    //console.log("gotDaylyList-> ", answer); //##

    if (answer && (answer.length > 0)){
        // var records = JSON.parse(answer);
        var obj = eval('(' + answer + ')');
        var records = obj.records;
        //console.log("gotDaylyList: records-> "+encodeObject(obj.records)); //##

        // 日毎のレコードを表示
        var elm = document.getElementById("contentsArea");
        elm.innerHTML = "";
        var tbl = newTABLE(elm, "/base-table");
        tbl.style.fontSize = "9pt";
        
        // TITLE =======================================
        var tr = newTR(tbl, "", "");
        tr.style.borderBottom = "thin solid #aaa";
        var td = newTD(tr, "/redLabel", "時刻");
        td.setAttribute("onclick", "reverseOrder()");
        var td = newTD(tr, "", "カルテID");
        var td = newTD(tr, "", "氏名");
        var td = newTD(tr, "/valueCol", "徴収額");
        var td = newTD(tr, "", "　");
        var td = newTD(tr, "", "保険証確認");
        td.style.textAlign = "right";

        // TABLE ========================================
        if (obj.sortOrder == "0"){
            // 受診日時の配列を生成
            var timeArray = [];
            for (dateAndId in records){
                timeArray.push(dateAndId);
            }
        }
        
        // 必要なら逆ソート
        if (waitingListReverseOrder() > 0){
            timeArray.sort(function(a,b){
                           if( a > b ) return -1;
                           if( a < b ) return 1;
                           return 0;
                           });
        }
        
        var rows = 0;
        var sum = 0;
        for (num in timeArray){
            var dateAndId = timeArray[num];
            var rec = records[dateAndId];
            if (! matchInOut(rec.inOut)) continue; // 入院・外来チェックボックスにマッチしなければ無視
                
            var ary = dateAndId.split("^");
            var dateTime = ary[0];
            var ary2 = dateTime.split(" ");
            var hhmm = ary2[1].substr(0,5);
            var cost = rec.insFee * 1 + rec.ownFee * 1;
            var scanDate = (rec.scanDateTime) ? rec.scanDateTime.substr(9,8) : "";
            var tr = newTR(tbl, "/even-color", "");
            // 受付時刻
            var td = newTD(tr, "", hhmm);
            // カルテID
            // 終了時刻が NULL なら「診療待ち」時刻があれば「診療済み」と判定
            var isFinished = (rec.endTime && rec.endTime.toString().length) ? true : false;
            var td = newTD(tr, "", "");
            var dv = newDIV(td, "");
            dv.innerHTML = rec.patientId;
            var action = "open_chart('" + rec.patientId + "')"
            dv.setAttribute("onclick", action);
            if (rec.reservedDate == rec.entryDate){ // 診療待ち予約患者
                dv.setAttribute("class", "accepted"); // 診療待ち：黄色のタグ
            } else if (isFinished){ // 診療済み
                dv.setAttribute("class", "finished2"); // 診療済み：白文字
            } else { // 診療待ち
                dv.setAttribute("class", "accepted"); // 診療待ち：黄色のタグ
            }
            // 氏名
            var td = newTD(tr, "", "");
            var dv = newDIV(td, "/listMember");
            dv.innerHTML = rec.kanjiName;
            var action = "open_editor('" + dateTime + "','" + rec.patientId + "')"
            dv.setAttribute("onclick", action);
            // 領収額
            var td = newTD(tr, "/valueCol", cost + "");
            var td = newTD(tr, "", "");
            // 保険証確認
            var td = newTD(tr, "", "");
            td.style.textAlign = "right";
            var st = scan_date(scanDate, dateTime);
            if (st == ""){
                var dv = newDIV(td, "");
                dv.innerHTML = "未確認";
                dv.style.backgroundColor = "#ff0";
                dv.style.borderRadius = "10px";
                dv.style.border = "thin solid #ccc";
            } else {
                var dv = newDIV(td, "");
                dv.innerHTML = st;
            }
            sum += cost;
            rows++;
        }
        
        // TOTAL =========================================
        var tr = newTR(tbl, "", "");
        tr.style.borderTop = "thin solid #aaa";
        var td = newTD(tr, "", "計");
        td.style.paddingLeft = "5px";
        var td = newTD(tr, "", rows + " 名");
        var td = newTD(tr, "", "");
        var td = newTD(tr, "/valueCol", sum + "");
        var td = newTD(tr, "", "");
        var td = newTD(tr, "", "");
    }
    
    function scan_date(scanDate, entryDate){
        // 保険証のコピー後の経過日数を返す
        if (!rec.scanDateTime) return "";
        
        var array = [];
        array.push(scanDate.substr(0,4));
        array.push(scanDate.substr(4,2));
        array.push(scanDate.substr(6,2));
        var dateTime = array.join("-");
        var pastDays = daysBetween(dateTime, entryDate);
        
        if (pastDays > 30) // 一定日数を越えたものは「経過日数」表示
            return pastDays + " 日経過";
        else
            return dateTime;
    }
}
function getDaylyList(){
    // 指定年月日の受診者リストをリクエスト
    var zone = "0000-2400";
    var elm = elmFor("zonePop");
    if (elm){
        var st = elm.value;
        var from = "0000";
        var to = "2400";
        var ary = st.split("..");
        if (ary.length > 1){
            from = ary[0];
            to = ary[1];
        }
        zone = from + "-" + to;
    }
    var entryDate = elmFor("datePop").value;
    
    var args = new Object();
    args['hospitalId'] = parent().hospitalId();
    args['timeZone'] = zone;
    args['entryDate'] = encodeSTRING(entryDate);
    if (elmFor("inpatient")){
        args['in'] = (elmFor("inpatient").checked) ? 1 : 0; // 入院
        args['out'] = (elmFor("outpatient").checked) ? 1 : 0; // 外来
    } else { // 入院・外来チェックボックスがなかった場合：初期化時に発生
        args['in'] = 0; // 入院は無視
        args['out'] = 1; // 外来のみ表示
    }
    
    _callServer("GET_DAILY", "frontServer.php", args, gotDaylyList);
}
function showDaylyList(){
    // 指定年月日の受診者リストをリクエスト
    if (elmFor("modePop").value != modes()[0]) return; // 日計表モードでなければ polling せず
    
    setNoMessage(true); // サーバ・アクセスのメッセージを表示しない
    getDaylyList();
    setNoMessage(false); // サーバ・アクセスのメッセージを表示に戻しておく

    var entryDate = elmFor("datePop").value;
    if (isSameDate(entryDate, today())){
        // 一定時刻ごとに polling
        setTimeout(showDaylyList, 3000);
    }
}

function gotYearList(answer){
    // 年計表を表示
    if (answer && (answer.length > 0)){
        // var records = JSON.parse(answer);
        var records = eval('(' + answer + ')');
        
        // 日毎のレコードを表示
        var elm = document.getElementById("contentsArea");
        elm.innerHTML = "";
        var tbl = newTABLE(elm, "/base-table");
        tbl.style.fontSize = "9pt";
        tbl.style.margin = "10px 0";
        
        // TITLE =======================================
        var tr = newTR(tbl, "", "");
        tr.style.borderBottom = "thin solid #aaa";
        var td = newTD(tr, "", "月");
        var td = newTD(tr, "/valueCol", "人数");
        var td = newTD(tr, "/valueCol", "本人");
        var td = newTD(tr, "/valueCol", "家族");
        var td = newTD(tr, "/valueCol", "国保");
        var td = newTD(tr, "/valueCol", "自費");
        var td = newTD(tr, "/valueCol", "合計");
        
        // TABLE ========================================
        var rows = 0;
        var membTotal = 0;
        var jihiTotal = 0;
        var insTotal = 0;
        var sumTotal = 0;
        
        for (num in records){
            var cols = records[num];
            if (cols.length > 0){
                var sum = 0;
                var date = cols[1].substr(5, 2);
                var members = "" + cols[0];
                var honin = "" + cols[2]; sum += honin * 1;
                var kazoku = "" + cols[3]; sum += kazoku * 1;
                var kokuho = "" + cols[4]; sum += kokuho * 1;
                var jihi = "" + cols[5]; sum += jihi * 1;
                membTotal += members * 1;
                jihiTotal += jihi * 1;
                insTotal += honin * 1 + kazoku * 1 + kokuho * 1;
                sumTotal += sum * 1;
                // 6:未収 7:受取額 8:入院/外来 9:新患数 10:点数 は表示省略
                
                var tr = newTR(tbl, "/even-color", "");
                var td = newTD(tr, "", date + " ");
                var td = newTD(tr, "/valueCol", members);
                var td = newTD(tr, "/valueCol", honin);
                var td = newTD(tr, "/valueCol", kazoku);
                var td = newTD(tr, "/valueCol", kokuho);
                var td = newTD(tr, "/valueCol", jihi);
                var td = newTD(tr, "/valueCol", "" + sum);
                
                rows++;
            }
        }
        
        // TOTAL =========================================
        var tr = newTR(tbl, "", "");
        tr.style.borderTop = "thin solid #aaa";
        var td = newTD(tr, "", "合計");
        var td = newTD(tr, "/valueCol", "" + membTotal);
        var td = newTD(tr, "/valueCol", "(" + rows + "ケ月)");
        var td = newTD(tr, "/valueCol", "" + insTotal);
        td.setAttribute("colspan", "2");
        var td = newTD(tr, "/valueCol", "" + jihiTotal);
        var td = newTD(tr, "/valueCol", "" + sumTotal);
        // AVERAGE =======================================
        var tr = newTR(tbl, "", "");
        var td = newTD(tr, "", "平均");
        var td = newTD(tr, "/valueCol", "" + Math.round(membTotal / rows));
        var td = newTD(tr, "/valueCol", "");
        var td = newTD(tr, "/valueCol", "" + Math.round(insTotal / rows));
        td.setAttribute("colspan", "2");
        var td = newTD(tr, "/valueCol", "" + Math.round(jihiTotal / rows));
        var td = newTD(tr, "/valueCol", "" + Math.round(sumTotal / rows));
    } else {
        var elm = document.getElementById("contentsArea");
        elm.innerHTML = "";
        var sp = newSPAN(elm, "");
        sp.innerHTML = "Loading monthlyList ...";
        sp.style.color = "#f88";
        sp.style.fontSize = "10pt";
        sp.style.padding = "20px";
    }
}
function getYearList(entryDate){
    // 指定年の受診者リストをリクエスト
    // まだ zonePop が生成されていないタイミングでは "0000-2400" を使用
    var zone = "0000-2400";
    var elm = elmFor("zonePop");
    if (elm){
        var st = elm.value;
        var from = "0000";
        var to = "2400";
        var ary = st.split("..");
        if (ary.length > 1){
            from = ary[0];
            to = ary[1];
        }
        zone = from + "-" + to;
    }

    var args = new Object();
    args['hospitalId'] = parent().hospitalId();
    args['timeZone'] = zone;
    args['entryDate'] = encodeSTRING(entryDate);
    args['in'] = (elmFor("inpatient").checked) ? 1 : 0; // 入院は無視
    args['out'] = (elmFor("outpatient").checked) ? 1 : 0; // 外来のみ表示
    
    _callServer("GET_YEAR_LIST", "frontServer.php", args, gotYearList);
}

function changeMode(){
    // 表の種類を変更し表を表示：changeMode(this) としては使わない
    var elm = elmFor("modePop");
    var label = elm.value;
    var ymd = elmFor("datePop").value;
    
    if (label == modes()[1]){
        getMonthlyList(ymd); // 月経表
    } else if (label == modes()[2]){
        getYearList(ymd); // 年計表
    } else { // 日計表
        showDaylyList(); // 日計表
    }
}
function changeZone(elm){
    // 変更された診療時間帯に合致したレコードのみを処理・表示
    changeMode();
}

function showDatePop(timezones){
    // 年月ポップアップ・メニューを表示
	var date = new Date();
	var yy = date.getYear();
	if (yy < 2000) { yy += 1900; }
	var mm = date.getMonth() + 1;
	var dd = date.getDate();
    
    var div = elmFor("monthPopArea");
    var dv = newDIV(div, "");

    // 日計表・月計表・年景表の切り替えポップアップ・メニュー
    var dp = newPopupMenu(dv, "modePop", modes(), "");
    dp.setAttribute("onchange", "changeMode()");

    // 年月ポップアップ・メニュー
    var sp = newSPAN(dv, "");
    sp.style.paddingLeft = "5px";
    var dp = newDatePopUp(sp, "datePop", "", yy, mm, dd, false, changeMode);
    
    var dv = newDIV(div, "");
    dv.style.marginTop = "5px";
    
    // 入院・外来チェックボックス
    var sp = newSPAN(dv, "");
    sp.style.marginRight = "10px";
    var status = 1; // 初期状態では外来レコードを表示
    var cb = newCHECKBOX(sp, "outpatient", "外来", status);
    cb.setAttribute("onclick", "changeMode()");
    status = 0; // 初期状態では入院レコードを表示せず
    var cb = newCHECKBOX(sp, "inpatient", "入院", status);
    cb.setAttribute("onclick", "changeMode()");
    
    // 診療時間帯ポップアップ・メニュー
    var dp = newPopupMenu(dv, "zonePop", timezones, "");
    dp.setAttribute("onchange", "changeZone(this)");
}

function open_patientRegister(){
    // 患者登録パネルを開く
    var patientId = prompt("カルテID");
    if ((patientId.length != 8) || (isDigit(patientId) == false)){
        alert(patientId + " は正しいカルテIDではありません");
        return;
    }
    
    // 再来患者を登録する
    var args = new Object();
    args.owner = parent().owner();
    args.hospitalId = parent().hospitalId();
    args.patientId = patientId;
    args.entryDate = todayAndTime();
    args.userCode = parent().userCode();
    args.groupCode = groupCode();
    args.duplicate = "regist_mode";
    _callServer("PUT_PATIENT", "frontServer.php", args, alert);
}

function initMonthlyTable(){
    // 月計表を初期化：NOA の周辺ツールとして利用される月計表
	// テンプレートで FRONT のヘッダー部分を生成
	var elm = document.getElementById("base");
    var pframe = new PictureFrame(elm, "100%", "50%");
    // === HEADER =============================
    // LEFT-SIDE
    pframe.headerLeft.setAttribute("id", "monthPopArea");
    // === BODY ==============================
    pframe.body.setAttribute("id", "contentsArea");
    // === FOOTER ============================
    // LEFT-SIDE
    var bt = newDIV(pframe.footerLeft, "/listMember");
    bt.innerHTML = "再表示";
    bt.setAttribute("onclick", "initMonthlyTable()"); //###
    var bt = newDIV(pframe.footerLeft, "/listMember");
    bt.innerHTML = "受診者受付";
    bt.setAttribute("onclick", "open_patientRegister()"); //###
    // RIGHT-SIDE
    pframe.footerRight.innerHTML = version();

    // iFrame なら toggleButton にツール名を表示
    var bt = tools().elmFor("toggleButton");
    if (bt) bt.innerHTML = "日計表ツール";

    // DB へデータリクエスト・表示は newDatePopUp() がトリガーとなって実行される
    getTimeZone();
}

function version(){
    // since: 131022
    return "Ver.150912";
}