(function () {
  "use strict";
  const APP_ENV = env["0,1歳日誌出力用"];

  addApproveFlowAction();

  kintone.events.on("app.record.detail.show", (event) => {
    const headerSpace = getHeaderSpace('', true);

    const elements = createBtnGroupArea('extract-action-area', '日誌作成', handleButtonClick, {
      btnElId: 'extract-btn',
    })

    if (!elements) {
      return;
    }

    headerSpace.appendChild(elements['extract-action-area']);
  });

  async function handleButtonClick(e) {
    loading(true, '帳票出力中...');
    showError(false);
    const api = new KintoneRestAPIClient();
    // 本アプリからデータを読み取る
    const record = kintone.app.record.get().record;
    if (!record) {
      // エラー
      loading(false);
      return e;
    }

    const yearStr = record['年'].value;
    const monthInput = record['月'].value;
    if (!yearStr || !monthInput) {
      showError('年/月が設定されていません');
      loading(false);
      return e;
    }
    const monthStr = String(monthInput).padStart(2, '0');

    const className = record['クラス'].value;
    if (!className) {
      showError('クラスが設定されていません');
      loading(false);
      return e;
    }

    const excelName = APP_ENV.excelName;
    await createExcelAndDownload({
      api,
      excelName,
      exportName: getExcelName(excelName, yearStr + monthStr + '_' + className + '組_' + record['園児名'].value),
      bizLogic: writeExcel(record, className, getJapaneseEraDate(new Date(yearStr, monthInput - 1, 1))),
    });
    loading(false);
  }


  function writeExcel(record, className, { era, year, month }) {
    return async (api, worksheet) => {
      const baseCells = findCellsInfo(worksheet, ['園長', '出欠', '食事量', '睡眠時間', '1', '11', '21']);
      fillApproveArea(baseCells, worksheet, record);

      const totalPages = baseCells['出欠'].length;
      for (let i = 0; i < totalPages; i++) {
        updateCell(worksheet, { base: baseCells['出欠'][i], up: 1 }, era + '　' + year + '年　' + month + '月');
        updateCell(worksheet, { base: baseCells['食事量'][i], up: 1 }, 'クラス　' + className);
        updateCell(worksheet, { base: baseCells['睡眠時間'][i], up: 1 }, '園児名　' + record['園児名'].value);
      }

      fillMainPage(baseCells, worksheet)
    }

    function fillMainPage(baseCells, worksheet) {
      const records = record['帳票出力用_テーブル'].value.map((e) => e.value);
      const inputMergedObject = getMergedInfo(worksheet, baseCells['1'][0]);
      const inputMergedRowCnt = inputMergedObject.bottom - inputMergedObject.top + 1;

      [[baseCells['1'][0], 1, 10], [baseCells['11'][0], 11, 10], [baseCells['21'][0], 21, 11]].forEach((obj) => {
        const baseForDetail = obj[0];
        const from = obj[1];
        const count = obj[2];
        const cols = getLabelColsMapping(worksheet, baseForDetail.row - 1, ['日付', '出欠', '降園', '体温', '食事量', '排便', '睡眠時間', '保護者から', '園での様子_伝達事項', '評価反省']);

        let currentRow = baseForDetail.row;
        for (let i = 0; i < count; i++) {
          const index = from + i - 1;
          const record = records[index];
          if (!record) {
            break;
          }
          const row = worksheet.getRow(currentRow);
          cols.forEach(col => {
            const base = { row: currentRow, col: col.index };
            if (col.field === '体温') {
              for (let j = 0; j < 3; j++) {
                const val1 = record["検温時刻" + (j + 1)].value || '  :   ';
                const val2 = (record["体温" + (j + 1)].value || '   .  ').padStart(4, ' ');
                updateCell(worksheet, { base, down: j }, val1 + ' , ' + val2 + ' ℃');
              }
            } else if (col.field === '睡眠時間') {
              for (let j = 0; j < 2; j++) {
                const val1 = record["睡眠開始時間" + (j + 1)].value || ':　 ';
                const val2 = record["睡眠終了時間" + (j + 1)].value || '　 :';
                updateCell(worksheet, { base, down: j }, val1 + '  ～ ' + val2);
              }
            } else {
              updateCell(row, { base }, record[col.field].value);
            }
          });
          currentRow += inputMergedRowCnt;
        }
        worksheet.getRow(currentRow - 1).addPageBreak();
      });


    }

  }
})();