<template>
  <q-page padding>
    <m-edit-header title="Bordro Eşleme"/>

    <q-card>
      <q-card-section>
        <q-select v-model="ld.companyID"
                  map-options
                  emit-value
                  :label="t('selectCompany')"
                  :options="ld.companies"
                  option-value="ID"
                  option-label="Name"
                  dense
                  options-dense
                  outlined
                  bg-color="white"
                  @update:model-value="load"
        >
          <template v-slot:after>
            <q-btn
              flat
              icon="business"
              dense
              size="sm"
              color="white"
              to="/company/new"
            >
              <q-tooltip>{{ t('createCompany') }}</q-tooltip>
            </q-btn>
          </template>
        </q-select>
      </q-card-section>

      <q-card-section v-if="ld.companyID && ld.canProcess">
        <div class="row q-gutter-y-sm q-col-gutter-md">
          <q-file
            dense
            class="col"
            v-model="ld.xlsFileName"
            label="Bordro Dosyası"
            clearable
            @update:modelValue="loadFile"
          />


          <q-select
            class="col"
            v-model="ld.bordroSheet"
            :options="ld.sheets"
            label="Bordro Sayfası"
            dense
            :disable="!ld.xlsFileName"
          >
            <template v-slot:after>
              <q-btn
                outline
                color="pcolor1"
                label="Bordro Fişi Oluştur"
                no-caps
                @click="doProcess"
                :disable="!ld.bordroSheet"
              />
            </template>
          </q-select>
        </div>
      </q-card-section>
    </q-card>
  </q-page>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { api } from 'boot/axios'
import { catchAxiosError, showAxiosError } from 'src/libjs/lib/axios'
import MEditHeader from 'src/libjs/comp/MEditHeader.vue'
import { read, utils, writeFile } from 'xlsx'
import { useQuasar } from 'quasar'

const { t } = useI18n()
const $q = useQuasar()

const ld = reactive({
  companyID: null,
  companies: [],

  sheets: [],
  bordroSheet: '',

  xlsFileName: null,
  selectedVal: '',
  alreadySelectedValFields: {},

  canProcess: false,
})

const tmpl = reactive({
  rawData: null,
  sheets: [],
  bordroSheet: '',

  baslikSatiri: 7,
  baslikSatirAdedi: 2,

  kontrolKolonu: -1,

  alanlar: [],
  kriterler: {},
  dagitim: {}
})

onMounted(() => {
  getCompanyList()
})

const getCompanyList = function () {
  api.get('/sy/companies').then(res => {
    if (res.data.Success) {
      ld.companies = res.data.Data || []
    } else {
      showAxiosError(res)
    }
  }).catch(err => {
    catchAxiosError(err)
  })
}

const load = function () {
  Object.keys(ld.alreadySelectedValFields).forEach(k => {
    delete ld.alreadySelectedValFields[k]
  })

  Object.keys(tmpl.kriterler).forEach(k => {
    delete tmpl.kriterler[k]
  })
  tmpl.sheets.splice(0)
  tmpl.alanlar.splice(0)
  tmpl.bordroSheet = ''

  $q.loading.show()
  api.get(`/tmpl/${ld.companyID}`).then(res => {
    if (res.data.Success) {
      if (res.data.Data === null) {
        ld.canProcess = false
        $q.dialog({
          title: 'Hata',
          message: 'Şirket için tanımlı şablon yok',
        }).onOk(() => {
          // console.log('OK')
        }).onCancel(() => {
          // console.log('Cancel')
        }).onDismiss(() => {
          // console.log('I am triggered on both OK and Cancel')
        })
        return
      }
      ld.canProcess = true

      Object.keys(res.data.Data).forEach(k => {
        tmpl[k] = res.data.Data[k]

        /*
        if (k !== 'alanlar') {
          tmpl[k] = res.data.Data[k]
        }

         */
      })
      //tmpl.rawData = new Uint8Array(res.data.Data.rawData)
      //workbook = read(tmpl.rawData)

      Object.keys(tmpl.kriterler).forEach(k => {
        tmpl.kriterler[k].valFields.forEach(f => {
          ld.alreadySelectedValFields[f] = 'x'
        })
      })

    } else {
      showAxiosError()
    }
  }).catch(err => {
    catchAxiosError(err)
  }).finally(() => {
    $q.loading.hide()
  })
}

let workbook = null

const loadFile = function () {
  const reader = new FileReader()
  /*
  reader.addEventListener('load', (event) => {
    console.log(event.target.result)
  });
  reader.readAsDataURL(ld.xlsFile);

   */

  reader.onload = function (e) {
    const uin = new Uint8Array(e.target.result)

    ld.sheets.splice(0)
    workbook = read(uin)
    ld.sheets.push(...workbook.SheetNames)
  }

  try {
    $q.loading.show()
    reader.readAsArrayBuffer(ld.xlsFileName)
  } catch (err) {
    console.log(err)
  } finally {
    $q.loading.hide()
  }
}

const doProcess = function () {
  try {
    $q.loading.show()
    processXLS()
  } catch (err) {
    console.log(err)
  } finally {
    $q.loading.hide()
  }
}

const hesapKodBul = function (row, fieldName) {
  // Hesap kodunu bulalım
  let hesapKod = ''
  Object.keys(tmpl.kriterler).forEach(k => {
    const kriter = tmpl.kriterler[k]

    let kriterVal = ''

    if (kriter.colNro >= 0) {
      // sabit kriter alanı
      kriterVal = row[kriter.colNro]
    } else {
      const tmpValues = []
      tmpl.kriterler[k].combinedFieldsNro.forEach(cf => {
        let tmpKriterVal = row[cf]
        if ((tmpKriterVal === null) || (tmpKriterVal === undefined)) {
          tmpKriterVal = ''
        }
        tmpValues.push(tmpKriterVal)
      })

      kriterVal = tmpValues.join(' ').trim()
    }

    const map = kriter.mappings[kriterVal]

    if ((map !== undefined) && (map !== null)) {
      const tmpHesapKod = map[fieldName]
      if (tmpHesapKod) {
        hesapKod = tmpHesapKod
      }
    } else {
      console.log(kriter)
    }
  })

  return hesapKod

}

const processXLS = function () {
  const sheet = workbook.Sheets[ld.bordroSheet]
  const rawData = utils.sheet_to_json(sheet, { header: 1 })

  const bordro = []

  const dagitimKeys = Object.keys(tmpl.dagitim)

  rawData.forEach((row, ndx) => {
    if (ndx <= tmpl.baslikSatiri - 1 + tmpl.baslikSatirAdedi) {

    } else {
      const kval = row[tmpl.kontrolKolonu]
      if ((kval !== null) && (kval !== undefined) && (kval !== '')) {

        const bordroRow = {}

        // sabit alanları verelim
        tmpl.alanlar.filter(a => {return a.showInSlip}).forEach(a => {
          if (a.colNro >= 0) {
            bordroRow[a.fieldName] = row[a.colNro]
          } else {
            const tmpValues = []
            a.combinedFieldsNro.forEach(cf => {
              let tmpVal = row[cf]
              if ((tmpVal === null) || (tmpVal === undefined)) {
                tmpVal = ''
              }
              tmpValues.push(tmpVal)
            })

            bordroRow[a.fieldName] = tmpValues.join(' ').trim()
          }
        })

        // veri alanlarını verelim
        tmpl.alanlar.filter(a => {return a.colType === 'veri'}).forEach(veri => {

          let dagitimYapildi = false
          if (dagitimKeys.length > 0) {
            dagitimKeys.forEach(bazAlan => {
              const degerler = Object.keys(tmpl.dagitim[bazAlan].kural)
              degerler.forEach(deger => {
                if (deger === row[tmpl.dagitim[bazAlan].bazAlanColNro]) {
                  dagitimYapildi = true
                  tmpl.dagitim[bazAlan].kural[deger].forEach(oran => {
                    //row'ın bir kopyasını oluşturalım çünkü hesap kodunu bu yeni row'a göre bulacağız
                    const tmpRow = [...row]
                    tmpRow[tmpl.dagitim[bazAlan].hedefAlanColNro] = oran.deger
                    bordroRow['Hesap'] = hesapKodBul(tmpRow, veri.fieldName)
                    bordroRow['Masraf Açıklama'] = veri.fieldName
                    bordroRow['Tutar'] = row[veri.colNro] * (oran.oran / 100)
                    bordroRow['B/A'] = veri.ba

                    const hedefAlan = tmpl.dagitim[bazAlan].hedefAlan
                    if (bordroRow[hedefAlan]) {
                      bordroRow[hedefAlan] = oran.deger
                    }

                    bordro.push({ ...bordroRow })
                  })
                }
              })
            })
          }

          if (!dagitimYapildi) {
            bordroRow['Hesap'] = hesapKodBul(row, veri.fieldName)
            bordroRow['Masraf Açıklama'] = veri.fieldName
            bordroRow['Tutar'] = row[veri.colNro]
            bordroRow['B/A'] = veri.ba

            bordro.push({ ...bordroRow })
          }
        })
      }
    }
  })

  const newSheet = utils.json_to_sheet(bordro)
  const newWB = utils.book_new()
  utils.book_append_sheet(newWB, newSheet, 'veri')
  writeFile(newWB, 'bordro.xlsx', { compression: true })
}


</script>
