import Swal from 'sweetalert2';
import AllMapDataStore from '@/stores/allMapData.js';
import ConformanceStore from '@/stores/conformance.js';
import FilesStore from '@/stores/files.js';

const customClass = {
  container: '!z-[99999]',
  popup: '!w-[564px]',
  title: '!text-xl !font-semibold !mb-2',
  htmlContainer: '!text-sm !font-normal !h-full !mb-4 !leading-5',
  inputLabel: '!text-sm !font-normal',
  input: '!h-8 !text-sm !font-normal !shadow-inner !shadow-black !border-neutral-200',
  validationMessage: '!bg-neutral-10 !text-danger',
  confirmButton: '!inline-block !rounded-full !text-sm !font-medium !text-center !align-middle !transition-colors !duration-300 !px-5 !py-2 !w-[100px] !h-[40px]',
  cancelButton: '!inline-block !rounded-full !text-sm !font-medium !text-center !align-middle !transition-colors !duration-300 !px-5 !py-2 !w-[100px] !h-[40px] ',
};
/**
 * Map Saved
 * @param { function } addFilterId
 */
export async function saveFilter(addFilterId) {
  let fileName = '';
  const { value, isConfirmed } = await Swal.fire({
    title: 'SAVE NEW FILTER',
    input: 'text',
    inputPlaceholder: 'Enter Filter Name.',
    inputValue: fileName,
    inputValidator: (value) => {
      if (!value) return 'You need to write something!';
      fileName = value;
    },
    icon: 'info',
    iconHtml: '<span class="material-symbols-outlined !text-[58px]">cloud_upload</span>',
    iconColor: '#0099FF',
    reverseButtons:true,
    confirmButtonColor: '#0099FF',
    showCancelButton: true,
    cancelButtonColor: '#94a3b8',
    customClass: customClass,
  });
  // 存檔成功
  if(isConfirmed) await addFilterId(fileName);
  // 顯示儲存完成
  if (value) savedSuccessfully(value);
  // 清空欄位
  fileName = '';
}
/**
 * Saved Success
 * @param { string } value
 */
export async function savedSuccessfully(value) {
  value = value ? value : '';
  await Swal.fire({
    title: 'SAVE COMPLETE',
    html: `<span class="text-primary">${value}</span> has been saved in Lucia.`,
    timer: 5000, // 停留5秒後自動關閉
    showConfirmButton: false,
    icon: 'success',
    iconColor: '#0099FF',
    customClass: customClass
  })
};
/**
 * leave Map page
 * @param { function } next
 * @param { function } addFilterId
 * @param { string } toPath
 * @param { function } logOut
 */
export async function leaveFilter(next, addFilterId, toPath, logOut) {
  const allMapDataStore = AllMapDataStore();
  const result = await Swal.fire({
    title: 'SAVE YOUR FILTER?',
    html: 'If you want to continue using this filter in any other page, please select [Yes].',
    icon: 'warning',
    iconColor: '#FF3366',
    reverseButtons:true,
    confirmButtonText: 'Yes',
    confirmButtonColor: '#FF3366',
    showCancelButton: true,
    cancelButtonText: 'No',
    cancelButtonColor: '#94a3b8',
    customClass: customClass
  })
  if(result.isConfirmed) {
    if(allMapDataStore.createFilterId) {
      await allMapDataStore.updataFilter();
      if(allMapDataStore.isUpdataFilter) await savedSuccessfully(allMapDataStore.filterName);
    } else {
      await saveFilter(addFilterId);
    }
    logOut ? logOut() : next(toPath);
  } else if(result.dismiss === 'cancel') {
    allMapDataStore.tempFilterId = null;
    logOut ? logOut() : next(toPath);
  } else if(result.dismiss === 'backdrop') {
    logOut ? null : next(false);
  }
};
/**
 * Conformance Saved
 * @param { function } addConformanceCreateCheckId
 */
export async function saveConformance(addConformanceCreateCheckId) {
  let fileName = '';
  const { value, isConfirmed } = await Swal.fire({
    title: 'SAVE NEW RULE',
    input: 'text',
    inputPlaceholder: 'Enter Rule Name.',
    inputValue: fileName,
    inputValidator: (value) => {
      if (!value) return 'You need to write something!';
      fileName = value;
    },
    icon: 'info',
    iconHtml: '<span class="material-symbols-outlined !text-[58px]">cloud_upload</span>',
    iconColor: '#0099FF',
    reverseButtons:true,
    confirmButtonColor: '#0099FF',
    showCancelButton: true,
    cancelButtonColor: '#94a3b8',
    customClass: customClass,
  });
  // 存檔成功
  if(isConfirmed) await addConformanceCreateCheckId(fileName);
  // 顯示儲存完成
  if (value) savedSuccessfully(value);
  // 清空欄位
  fileName = '';
}
/**
 * leave Conformance page
 * @param { function } next
 * @param { function } addConformanceCreateCheckId
 * @param { string } toPath
 * @param { function } logOut
 */
export async function leaveConformance(next, addConformanceCreateCheckId, toPath, logOut) {
  const conformanceStore = ConformanceStore();
  const result = await Swal.fire({
    title: 'SAVE YOUR RULE?',
    icon: 'warning',
    iconColor: '#FF3366',
    reverseButtons:true,
    confirmButtonText: 'Yes',
    confirmButtonColor: '#FF3366',
    showCancelButton: true,
    cancelButtonText: 'No',
    cancelButtonColor: '#94a3b8',
    customClass: customClass
  })
  if(result.isConfirmed) {
    if(conformanceStore.conformanceFilterCreateCheckId || conformanceStore.conformanceLogCreateCheckId) {
      await conformanceStore.updataConformance();
      if(conformanceStore.isUpdataConformance) await savedSuccessfully(conformanceStore.conformanceFileName);
    } else {
      await saveConformance(addConformanceCreateCheckId);
    }
    logOut ? logOut() : next(toPath);
  } else if(result.dismiss === 'cancel') {
    conformanceStore.conformanceFilterTempCheckId = null;
    conformanceStore.conformanceLogTempCheckId = null;
    logOut ? logOut() : next(toPath);
  } else if(result.dismiss === 'backdrop') {
    logOut ? null : next(false);
  }
};
/**
 * Upload failde First
 * @param { string } failureType
 * @param { string } failureMsg
 */
export async function uploadFailedFirst(failureType, failureMsg, failureLoc) {
  // msg: 'not in UTF-8' | 'insufficient columns' | 'the csv file is empty' | 'the filename does not ends with .csv'
  // type: 'encoding' | 'insufficient_columns' | 'empty' | 'name_suffix'
  let value = '';
  switch (failureType) {
    case 'size':
      value = 'File size exceeds 90MB.';
      break;
    case 'encoding':
      value = `Please use [UFT-8] for character encoding: (Row #${failureLoc})`;
      break;
    case 'insufficient_columns':
      value = 'Need at least five columns of data.';
      break;
    case 'empty':
      value = 'Need at least one record of data.';
      break;
    case 'name_suffix':
      value = 'File is not in [csv] format.';
      break;
    default:
      value = failureMsg;
      break;
  }
  await Swal.fire({
    title: 'UPLOAD FAILED',
    html: value,
    // timer: 5000, // 停留5秒後自動關閉
    showConfirmButton: false,
    icon: 'error',
    iconColor: '#FF3366',
    customClass: customClass
  })
};
/**
 * Upload failde Second
 * @param { array } detail
 */
export async function uploadFailedSecond(detail) {
  let srt = '';
  let manySrt = '';

  detail.forEach(i => {
    let content = '';

    switch (i.type) {
      case 'too_many':
        manySrt = 'There are more errors.';
        break;
      case 'unrecognized':
        content = `<li>Data unregnizable in [Status] Column: (Row #${i.loc[1]}, "${i.input}")</li>`;
        break;
      case 'malformed':
        content = `<li>Data malformed in [Timestamp] Column: (Row #${i.loc[1]}, "${i.input}")</li>`;
        break;
      case 'missing':
        content = `<li>Data missing in [${i.loc[2]}] Column: (Row #${i.loc[1]})</li>`;
      break;
    }
    srt += content;
  });
  await Swal.fire({
    title: 'UPLOAD FAILED',
    html: `<div class="text-left mx-3 space-y-1"><p>Error(s) detected:</p><ul class="list-disc ml-6">${srt}</ul><p>${manySrt} Please check.</p></div>`,
    // timer: 5000, // 停留5秒後自動關閉
    showConfirmButton: false,
    icon: 'error',
    iconColor: '#FF3366',
    customClass: customClass
  });
  srt = '';
};
/**
 * Upload Success
 * @param { string } value
 */
export async function uploadSuccess() {
  await Swal.fire({
    title: 'UPLOAD COMPLETED',
    timer: 5000, // 停留5秒後自動關閉
    showConfirmButton: false,
    icon: 'success',
    iconColor: '#0099FF',
    customClass: customClass
  })
};
/**
 * Confirm whether to upload the file
 * @param { object } fetchData
 */
export async function uploadConfirm(fetchData) {
  const filesStore = FilesStore();
  const result = await Swal.fire({
    title: 'ARE YOU SURE?',
    html: 'After uploading, you won’t be able to modify labels.',
    icon: 'warning',
    iconColor: '#FF3366',
    reverseButtons:true,
    confirmButtonText: 'Yes',
    confirmButtonColor: '#FF3366',
    showCancelButton: true,
    cancelButtonText: 'No',
    cancelButtonColor: '#94a3b8',
    customClass: customClass,
  });

  if(result.isConfirmed) {
    filesStore.uploadLog(fetchData);
  }
};
/**
 * Upload loader
 */
export async function uploadloader() {
  await Swal.fire({
    html: '<span class="loaderBar mt-7"></span>',
    showConfirmButton: false,
    allowOutsideClick: false,
    customClass: customClass,
  })
};
/**
 * Rename Modal
 * @param { function } rename
 * @param { string } type
 * @param { number } id
 */
export async function renameModal(rename, type, id) {
  let fileName = '';
  const { value, isConfirmed } = await Swal.fire({
    title: 'RENAME',
    input: 'text',
    inputPlaceholder: 'Enter File Name.',
    inputValue: fileName,
    inputValidator: value => {
      if(!value) return 'You need to write something!';
      fileName = value;
    },
    icon: 'info',
    iconHtml: '<span class="material-symbols-outlined !text-[58px]">edit_square</span>',
    iconColor: '#0099FF',
    reverseButtons: true,
    confirmButtonColor: '#0099FF',
    showCancelButton: '#94a3b8',
    customClass: customClass,
  });

  // 改名成功
  if(isConfirmed) await rename(type, id, value);
  // 清空欄位
  fileName = '';
}
/**
 * Delete File
 * @param { string } files 有關連的檔案
 * @param { string } type
 * @param { number } id
 * @param { string } name 原本的檔案
 */
export async function deleteFileModal(files, type, id, name) {
  const filesStore = FilesStore();
  let htmlText = files.length === 0 ? `Do you really want to delete <span class="text-primary">${name}</span>?` : `<div class="text-left mx-4 space-y-1"><p class="mb-2">Do you really want to delete <span class="text-primary">${name}</span>?</p><p>The following dependent file(s) will also be deleted:</p><ul class="list-disc ml-6">${files}</ul></div>`;
  const result = await Swal.fire({
    title: 'Confirm Deletion',
    html: htmlText,
    icon: 'warning',
    iconColor: '#FF3366',
    reverseButtons:true,
    confirmButtonText: 'Yes',
    confirmButtonColor: '#FF3366',
    showCancelButton: true,
    cancelButtonText: 'No',
    cancelButtonColor: '#94a3b8',
    customClass: customClass,
  });

  if(result.isConfirmed) {
    filesStore.deleteFile(type, id);
  }
};
