<template>
  <div class="download-setting-popup" v-if="show">
    <Dialog :show="show" :dialogName="dialogName" :close="true">
      <!-- header -->
      <template #header>
        <p>{{ $t('compare.downloadOptions') }}</p>
      </template>

      <!-- content -->
      <div class="select-content">
        <div @click="saveNum = 2" class="option"><RadioBtnSel v-if="saveNum === 2" /><RadioBtnDis v-else />{{ $t('compare.downloadTwoFiles') }}</div>
        <div @click="saveNum = 1" class="option"><RadioBtnSel v-if="saveNum === 1" /><RadioBtnDis v-else />{{ $t('compare.downloadOneFile') }}</div>
      </div>

      <!-- footer -->
      <template #footer>
        <div class="rect-button white" @click="closeDialog">{{ $t('cancel') }}</div>
        <div class="rect-button blue" @click="handleFlatten">{{ $t('ok') }}</div>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'
import { saveAs } from 'file-saver';

const useViewer = useViewerStore()
const useDocument = useDocumentStore()

const dialogName = 'downloadSettingDialog'
const show = computed(() => useViewer.isElementOpen(dialogName))
const compareResult = computed(() => useDocument.getCompareResult)

const saveNum = ref(1)

const closeDialog = () => {
  useViewer.closeElement(dialogName)
}

const handleFlatten = async () => {
  const data = []
  if (saveNum.value === 1) {
    data.push(compareResult.value.mergeFile)
  } else if (saveNum.value === 2) {
    data.push(compareResult.value.oldFile, compareResult.value.newFile)
  }

  closeDialog()
  useViewer.setDownloading(true)
  try {
    data.forEach(file => {
      saveAs(file.url, file.filename)
    })
    useViewer.setDownloading(false)
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss">
.download-setting-popup {
  header {
    padding: 4px 0;
  }
  .dialog-container {
    width: 325px;
    padding: 30px 20px;
    main {
      margin-bottom: 20px;
    }
  }
}
.select-content {
  .option {
    padding: 5px 0;
    display: flex;
    align-items: center;
    cursor: default;
    font-size: 14px;
    line-height: 16px;
    svg {
      margin-right: 4px;
    }
    & + .option {
      margin-top: 8px;
    }
  }
}
</style>