
(function () {
  "use strict";
  const FIELD_CODE = "ユニークキー";

  // ------------------- 詳細/印刷/編集画面表示時の処理 -------------------
  kintone.events.on(['app.record.detail.show', 'app.record.print.show'], function (event) {
    hideField(FIELD_CODE);
    return event;
  });

  kintone.events.on(['app.record.index.edit.show'], (event) => {
    disableField(event.record, FIELD_CODE);
    return event
  })

  // ------------------- 編集画面表示時の処理 -------------------
  kintone.events.on(['app.record.edit.show', 'app.record.create.show'], function (event) {
    const targetFieldEl = kintone.app.record.getSpaceElement("before-unique-key").parentElement.nextSibling;
    targetFieldEl.querySelector('.input-constraints-cybozu').style.display = 'none';

    if (event.type === "app.record.create.show") {
      event.record[FIELD_CODE].value = "";
    }
    hideField(FIELD_CODE);
    return event;
  });


  function hideField(fieldCode) {
    kintone.app.record.setFieldShown(fieldCode, false);
  }

  function disableField(record, fieldCode) {
    record[fieldCode]['disabled'] = true;
  }

  // ------------------- 保存時の処理 -------------------
  kintone.events.on(['app.record.create.submit.success'], async function (event) {
    const api = new KintoneRestAPIClient();
    await api.record.updateRecord({
      app: env["園児台帳"].appId,
      id: event.recordId,
      record: {
        [FIELD_CODE]: {
          value: event.recordId
        }
      }
    })
    return event;
  });

  // ------------------- 編集画面保存時の処理 -------------------
  // 保存成功後イベント
  kintone.events.on([
    'app.record.edit.submit.success',
    'app.record.index.edit.submit.success'
  ], async (event) => {
    loading(true, 'データを反映中...');
    const api = new KintoneRestAPIClient();
    const key = event.record[FIELD_CODE]['value'];
    const yearRange = getYearRange()
    const appName = "園児別出欠簿入力";

    const records = (await getAllRecords(api, appName, "園児ユニークキー", key, "登園日", yearRange))
    if (!records || records.length === 0) {
      loading(false)
      return event;
    }

    try {
      const updateResult = await api.record.updateAllRecords({
        app: env[appName].appId,
        records
      });
      updateResult.yearRange = yearRange;
      showSuccessDialog(updateResult)
    } catch (e) {
      showError(true, `アプリ「${appName}」のデータ上書で失敗エラー\n - ` + e);
    }
    loading(false)
    return event;
  });

  async function getAllRecords(api, appName, keyName, key, dateKey, yearRange) {
    try {
      const records = await api.record.getAllRecordsWithId({
        app: env[appName].appId,
        condition: `${keyName} = "${key}" and ${dateKey} >= "${yearRange.start}" and ${dateKey} <= "${yearRange.end}"`
      });
      await new Promise(resolve => setTimeout(resolve, 3000));

      return records.map((record) => {
        return {
          id: record.$id.value,
          record: {
            [keyName]: {
              value: record[keyName].value
            }
          }
        };
      });
    } catch (e) {
      showError(true, `アプリ「${appName}」のデータ読み取りエラー\n - ` + e);
    }
  }

  function showSuccessDialog(updateResult) {
    const contentEl = document.createElement('div');
    contentEl.style.fontSize = '16px';
    contentEl.innerHTML = `${updateResult.yearRange.start.split("-")[0]}年度の${updateResult.records.length}件のデータを更新しました。`;

    showDialog({
      title: '更新が完了しました',
      content: contentEl,
      cancel: false
    });
  }

})();