<template>
  <q-page padding>
    <q-card>
      <q-card-section>
        <div class="row">
          <div class="col">
            <q-select v-model="ld.companyID"
              label="Şirket"
              option-label="Name"
              option-value="Id"
              :options="ld.companies"
              map-options
              emit-value
            >
              <template v-slot:after>
                <q-btn
                  label="Düzenle"
                  color="primary"
                  @click="editCompany"
                  :disable="!ld.companyID"
                  no-caps
                />
                <q-btn
                  label="Yeni Şirket Ekle"
                  color="primary"
                  @click="createCompany"
                  no-caps
                />
              </template>
            </q-select>
            <!-- Debug Info -->
            <!-- <div class="q-mt-sm q-pa-sm bg-grey-2 text-black text-caption" style="border: 1px dashed gray;">
              Durum: {{ ld.errorMessage }} <br/>
              Şirket Sayısı: {{ ld.companies.length }}
              <div v-for="(c, idx) in ld.companies" :key="idx">
                #{{ idx }}: ID={{ c.Id }} (type: {{ typeof c.Id }}), Name={{ c.Name }} (type: {{ typeof c.Name }}), Raw: {{ JSON.stringify(c) }}
              </div>
            </div> -->
          </div>
        </div>
      </q-card-section>

      <q-card-section>
        <div class="row q-col-gutter-sm items-center">
          <div class="col-shrink">
            <q-btn label="Excel Yükle"
                   @click="upload"
                   no-caps
                   color="secondary"
            />
            <q-checkbox
                  label="Tarayıcı Görünmesin"
                  v-model="ld.right"
                  style="font-size : 15px"
            />
          </div>
          <div class="col-11 text-right">
            {{ ld.xlsFile }}
          </div>
          <div class="col-6">
            <q-select v-model="ld.year" :options="[2024, 2025, 2026, 2027, 2028]"
                      label="Aktarım Yıl"
            />
          </div>
          <div class="col-6">
            <q-select v-model="ld.month" :options="[1,2,3,4,5,6,7,8,9,10,11,12]"
                      label="Aktarım Ay"
            />
          </div>
          <div class="col-12">
            <q-btn
              no-caps
              label="Aktarıma Başla"
              color="warning"
              class="full-width"
              @click="doRpa"
              :disable="!ld.xlsFile || !ld.companyID"
            />
          </div>
        </div>
      </q-card-section>

      <q-card-section>
        <!-- <q-card>
        <q-tabs
          v-model="tab"
          dense
          class="text-grey"
          active-color="primary"
          indicator-color="primary"
          align="justify"
          narrow-indicator
        >
          <q-tab name="mails" label="Mails"></q-tab>
          <q-tab name="alarms" label="Alarms"></q-tab>
          <q-tab name="movies" label="Movies"></q-tab>
        </q-tabs>

        <q-separator></q-separator>

        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="mails">
            <div class="text-h6"></div>
            Lorem ipsum dolor sit amet consectetur adipisicing elit.
          </q-tab-panel>

          <q-tab-panel name="alarms">
            <div class="text-h6">Alarms</div>
            Lorem ipsum dolor sit amet consectetur adipisicing elit.
          </q-tab-panel>

          <q-tab-panel name="movies">
            <div class="text-h6">Movies</div>
            Lorem ipsum dolor sit amet consectetur adipisicing elit.
          </q-tab-panel>
        </q-tab-panels>
      </q-card> -->
        <div style="max-height: 200px; overflow: scroll; border: 1px gray solid; display: grid;" class="q-pa-xs">
          <span v-for="(ln, ndx) in ld.logProcess" :key="ndx">
            {{ ndx }} {{ ln }}
          </span>
        </div>
      </q-card-section>
    </q-card>

  </q-page>
</template>

<script setup>
import { onMounted, reactive,ref } from 'vue'
import Company from 'components/dlg/Company.vue'
import EditCompanyPage from 'components/dlg/EditCompany.vue'
import { useQuasar } from 'quasar'
import { Companies, CreateCompany, Rpa, UploadExcel ,EditCompany} from 'app/bindings/bordrobot/lib/srv/srv'
import * as wails from '@wailsio/runtime'

const $q = useQuasar()

const ld = reactive({
  companyID: null,
  companies: [],
  errorMessage: '',
  xlsFile: '',
  logProcess: [],
  year: 2026,
  month: 1,
  right : true
})
// let tab = ref('mails')

onMounted(() => {
  getCompanies()

  wails.Events.On('logProcess', function (ev) {
    ld.logProcess.push(ev.data)
  })
})

const editCompany = function () {
  const selectedCompanyID = ld.companyID;
  if (!selectedCompanyID) return;
  const selectedCompany = ld.companies.find(company => company.Id === selectedCompanyID);
  if (!selectedCompany) return;
  $q.dialog({
    component: EditCompanyPage,
    parent: this,
    componentProps: {
      id : parseInt(selectedCompany.Id),
      name: selectedCompany.Name,
      memberNumber: selectedCompany.MemberNumber,
      userName : selectedCompany.Username,
      password : selectedCompany.Password,
    },
    // ----------------------
    // props that are passed to component instance
  }).onOk(data => {
    EditCompany(data.id, data.name, data.memberNumber, data.userName, data.password).then(()=>{
      getCompanies()
    })
  })
}
const createCompany = function () {
  $q.dialog({
    component: Company,
    parent: this,
    // ----------------------
    // props that are passed to component instance
  }).onOk(data => {
    CreateCompany(data.name, data.memberNumber, data.username, data.password).then(()=>{
      getCompanies()
    })
  })
}

const getCompanies = function () {
  ld.companies.splice(0)
  ld.errorMessage = 'Yükleniyor...'
  Companies().then(res => {
    console.error("COMPANIES FETCHED:", JSON.stringify(res))
    ld.errorMessage = 'Başarılı. Gelen şirket sayısı: ' + (res ? res.length : 0)
    if (res) {
      ld.companies.push(...res)
    }
    console.log(ld.companies)
  }).catch(err => {
    console.error("COMPANIES FETCH ERROR:", err)
    ld.errorMessage = 'HATA OLUŞTU: ' + err.toString()
  })
}

const upload = function () {
  UploadExcel().then(res => {
    ld.xlsFile = res
  })
}

const doRpa = function () {
    ld.logProcess = []
    Rpa(ld.companyID, ld.month, ld.year,ld.right).catch(err => console.log(err))
}

</script>
