const Kuc = Kucs['1.19.0'];

let notificationEl;
function getHeaderSpace(className, isDetailPage) {
  const headerSpace = kintone.mobile.app.getHeaderSpaceElement();
  if (!headerSpace) {
    throw new Error('このページではヘッダー要素が利用できません。');
  };

  const _className = isDetailPage ? 'customized-record-header-space' : 'customized-header-space';

  headerSpace.className += (' ' + _className + ' ' + className);
  headerSpace.parentElement.className += (' ' + _className + '-wrapper ' + className);

  return headerSpace;
}

const classItems = [
  { label: "にじ", value: "にじ" },
  { label: "ほし", value: "ほし" },
  { label: "つき", value: "つき" },
  { label: "ゆり", value: "ゆり" },
]

const termItems = [
  { label: "０歳児", value: "０歳児" },
  { label: "１歳児", value: "１歳児" },
  { label: "２歳児", value: "２歳児" },
  { label: "３歳児", value: "３歳児" },
  { label: "４歳児", value: "４歳児" },
  { label: "５歳児", value: "５歳児" },
]


function createBtnGroupArea(groupId, btnLabel, btnOnClick, { btnElId = false, yearElId = false, monthElId = false, dateElId = false, termElId = false, defaultThisMonth = false, }) {
  const result = {};

  if (document.getElementById(groupId)) {
    return;
  }

  const btnGroupAreaEl = document.createElement('div');
  btnGroupAreaEl.id = groupId;
  btnGroupAreaEl.className = 'btn-group-area'
  result[groupId] = btnGroupAreaEl;

  if (yearElId) {
    const yearEl = new Kuc.MobileText({
      value: "" + new Date().getFullYear(),
      id: yearElId,
      label: '年',
      className: 'year input'
    });
    result[yearElId] = yearEl;
    btnGroupAreaEl.appendChild(yearEl);
  }

  if (monthElId) {
    const monthEl = new Kuc.MobileDropdown({
      value: defaultThisMonth ? monthItems[new Date().getMonth()].value : undefined,
      id: monthElId,
      className: 'month input',
      label: '月',
      items: monthItems,
    });
    result[monthElId] = monthEl;
    btnGroupAreaEl.appendChild(monthEl);
  }

  if (dateElId) {
    const dateEl = new Kuc.MobileDropdown({
      value: dateItems[new Date().getDate() - 1].value,
      id: dateElId,
      items: dateItems,
      label: '日',
      className: "date input",
    });
    result[dateElId] = dateEl;
    btnGroupAreaEl.appendChild(dateEl);
  }

  if (termElId) {

    const termEl = new Kuc.MobileDropdown({
      id: termElId,
      items: termItems,
      className: "term input",
      label: '学年',
    });
    result[termElId] = termEl;
    btnGroupAreaEl.appendChild(termEl);
  }

  const btnEl = new Kuc.MobileButton({
    text: btnLabel,
    type: "submit",
    className: "action-btn",
    id: btnElId,
  });
  result[btnElId] = btnEl;
  btnEl.addEventListener('click', (e) => {
    showError(false);
    const checkResult = checkInputData(result, { btnLabel, yearElId, monthElId, dateElId, termElId });
    if (checkResult) {
      btnOnClick(e, checkResult);
    }
  });
  btnGroupAreaEl.appendChild(btnEl);

  return result;
}

function checkInputData(map, { btnLabel, yearElId, monthElId, dateElId, termElId }) {
  const year = yearElId && map[yearElId].value;
  const month = monthElId && map[monthElId].value;
  const date = dateElId && (map[dateElId].value === 'end' ? getLastDate(year, month).getDate() : map[dateElId].value);
  const term = termElId && map[termElId].value;

  const errorMsgs = [];

  if (yearElId) {
    const yearRegex = /^\d+$/;
    if (!yearRegex.test(year)) {
      errorMsgs.push(' · 年は整数で入力してください。');
    }
  }
  if (monthElId && !month) {
    errorMsgs.push(' · 月を選択してください。');
  }
  if (dateElId && !date) {
    errorMsgs.push(' · 日を選択してください。');
  }
  if (termElId && !term) {
    errorMsgs.push(' · 学年を選択してください。');
  }
  if (errorMsgs.length > 0) {
    showError(true, btnLabel + 'エラー\n' + errorMsgs.join('\n'))
    return;
  }

  return {
    year,
    month,
    date,
    term,
  }
}

function createBtn(id, label, onClick) {
  const btnEl = new Kuc.MobileButton({
    text: label,
    type: "submit",
    className: "action-btn",
    id,
  });
  btnEl.addEventListener('click', onClick);
  return btnEl;
}

function hideSpaceField(ids) {
  ids.forEach(id => {
    const area = kintone.mobile.app.record.getSpaceElement(id);
    area.parentElement.style.minWidth = '0';
    area.parentElement.style.display = 'none';
  });
}

const statusFieldMap = {
  '指導教諭確認中': '担任',
  '主幹確認中': '指導',
  '園長確認中': '主幹',
  '完了': '園長'
}

function addApproveFlowAction() {
  return kintone.events.on("mobile.app.record.detail.process.proceed", (event) => {
    const field = statusFieldMap[event.nextStatus.value];
    if (field) {
      event.record[field].value = kintone.getLoginUser().name;
    }
    return event;
  });
}

function showError(show, text) {
  if (show) {
    buildNotification('danger', text);
    notificationEl.open();
    console.error(text);
  } else {
    notificationEl && notificationEl.close();
  }
}

function buildNotification(type, text, duration = -1) {
  const param = {
    type,
    text,
    duration
  }
  if (!notificationEl) {
    notificationEl = new Kuc.MobileNotification(param);
  } else {
    Object.assign(notificationEl, param);
  }
}
