(function () {
  "use strict";
  const APP_ENV = env["個別配慮"];

  addApproveFlowAction();
  
  kintone.events.on("app.record.index.show", (event) => {
    const headerSpace = getHeaderSpace('single-label-line');

    const elements = createBtnGroupArea('extract-action-area', '帳票出力', handleButtonClick, {
      btnElId: 'extract-btn',
      yearElId: 'extract-year',
      monthElId: 'extract-month',
    })

    if (!elements) {
      return;
    }

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

  async function handleButtonClick(e, { year, month }) {
    loading(true, '帳票出力中...');
    showError(false);
    const api = new KintoneRestAPIClient();

    // 本アプリからデータを読み取る
    const currentAppRecords = await getRecords(api, year, month);
    if (!currentAppRecords) {
      // エラー
      loading(false);
      return e;
    }

    const excelName = APP_ENV.excelName;
    await createExcelAndDownload({
      api,
      excelName,
      exportName: getExcelName(excelName, year + month),
      bizLogic: writeExcel(currentAppRecords, year, month),
    });
    loading(false);
  }

  async function getRecords(api, year, month) {
    const firstDate = getFormatDateString(year, month, 1)
    const lastDate = getFormatDateString(getLastDate(year, month));
    try {
      return await api.record.getAllRecordsWithId({
        app: env["個別配慮"].appId,
        condition: `日付 >= "${firstDate}" and 日付 <= "${lastDate}"`
      });
    } catch (e) {
      showError(true, '本アプリのデータ読み取りエラー\n - ' + e);
    }
  }

  function writeExcel(records, year, month) {
    return async (api, worksheet) => {
      if (!records || !records.length) {
        return;
      }

      const baseCells = findCellsInfo(worksheet, ['月', '児童名']);

      const pageSize = 10;
      const totalPages = Math.ceil(records.length / pageSize);

      // make new copy
      if (totalPages > 2) {
        const lastPage = 2;
        const copyPageRowStart = baseCells['月'][lastPage - 1].row - 1;
        const copyPageRowEnd = baseCells['児童名'][lastPage - 1].row + pageSize;

        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, baseCells['児童名'][0].row, ['児童名', '子どもの姿', '保育者援助_配慮_環境構成']);
      const sortedRecords = sort(records);

      for (let i = 0; i < totalPages; i++) {
        const monthLabelCell = baseCells['月'][i];
        updateCell(worksheet, { base: monthLabelCell, left: 1 }, Number(month));

        const childLabelCell = baseCells['児童名'][i];
        let currentRow = childLabelCell.row + 1;

        for (let j = 0; j < pageSize; j++) {
          const index = i * pageSize + j;
          const record = sortedRecords[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++;
        }

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


    }
  }

  function sort(records) {
    // 1. sort by 出席番号
    const sortedRecords = records.sort((a, b) => Number(a['出席番号'].value) - Number(b['出席番号'].value));

    // 2. sort by 学年
    debugger;
    const termOrder = {};
    termItems.forEach((item, index) => {
      termOrder[item.value] = index;
    });
    sortedRecords.sort((a, b) => {
      return termOrder[a["学年"].value] - termOrder[b["学年"].value];
    });
    return sortedRecords;
  }

})();
