(function () {
  "use strict";
  const APP_ENV = env["2歳以上日誌出力用"];

  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 dateStr = record['登園日'].value;
    if (!dateStr) {
      showError('登園日が設定されていません');
      loading(false);
      return e;
    }
    const date = new Date(dateStr);

    const excelName = APP_ENV.excelName;
    await createExcelAndDownload({
      api,
      excelName,
      exportName: getExcelName(excelName, record['学年'].value + '_' + getFormatDateString(date).replaceAll('-', '')),
      bizLogic: writeExcel(record, getJapaneseEraDate(date)),
    });
    loading(false);
  }

  function writeExcel(record, { era, year, month, day }) {
    return async (api, worksheet) => {
      const baseCells = findCellsInfo(worksheet, ['園長', '行　事', '主な活動', 'クラス名']);
      fillPage1(baseCells, worksheet);
      fillPage2(baseCells, worksheet);
    }

    function fillPage1(baseCells, worksheet) {
      fillApproveArea(baseCells, worksheet, record);

      updateCell(worksheet, { base: { row: 1, col: 1 } }, `${era}　${year}年　${month}月　${day}日　${record['曜日'].value}日　天候(${record['天気']?.value || '　　　　　'})`);
      updateCell(worksheet, { base: baseCells['行　事'][0], right: 1 }, record['行事'].value);

      const headerRow = baseCells['主な活動'][0].row;
      const cols = getLabelColsMapping(worksheet, headerRow, ['活動', '子どもの様子', '反省評価']);
      const row = headerRow + 1;
      const inputMergedData = getMergedInfo(worksheet, { row, col: baseCells['主な活動'][0].col });
      const inputMergedRowCnt = inputMergedData.bottom - inputMergedData.top + 1;

      for (let i = 0; i < 4; i++) {
        cols.forEach(col => {
          updateCell(worksheet, { base: { row: row + i * inputMergedRowCnt, col: col.index } }, record[col.field + (i + 1)]?.value);
        });
      }

      worksheet.getRow(baseCells['クラス名'][0].row - 2).addPageBreak();
    }

    function fillPage2(baseCells, worksheet) {
      const baseForDetail = baseCells['クラス名'][0];
      const records = record['園児別テーブル'].value.map((e) => e.value);
      const pageSize = 10;
      const totalPages = Math.ceil(records.length / pageSize);
      const inputMergedObject = getMergedInfo(worksheet, { row: baseForDetail.row + 1, col: baseForDetail.col });
      const inputMergedRowCnt = inputMergedObject.bottom - inputMergedObject.top + 1;

      // make new copy
      if (totalPages > 1) {
        const lastPage = 1;
        const copyPageRowStart = baseForDetail.row - 1;
        const copyPageRowEnd = baseForDetail.row + (pageSize * inputMergedRowCnt);

        createCopyFromTemplate(worksheet, {
          startPage: lastPage + 1,
          totalPages,
          copyPageRowStart,
          copyPageRowEnd,
          callback: (newPage, rowCount) => {
            ['クラス名'].forEach((label) => {
              const last = baseCells[label][newPage - 2];
              baseCells[label].push({
                col: last.col,
                row: last.row + rowCount
              });
            });
          }
        });
      }

      const cols = getLabelColsMapping(worksheet, baseForDetail.row, ['クラス名', '名前', '子どもの様子', '反省評価_園児別テーブル']);
      for (let i = 0; i < totalPages; i++) {
        const childLabelCell = baseCells['クラス名'][i];
        let currentRow = childLabelCell.row + 1;

        for (let j = 0; j < pageSize; j++) {
          const index = i * pageSize + j;
          const record = records[index];
          if (!record) {
            break;
          }
          const row = worksheet.getRow(currentRow);
          cols.forEach(col => {
            updateCell(row, { base: { row: currentRow, col: col.index } }, record[col.field].value);
          });
          currentRow += inputMergedRowCnt;
        }

        worksheet.getRow(childLabelCell.row + pageSize * inputMergedRowCnt).addPageBreak();
      }
    }

  }
})();