<script setup>
import { SelectBox } from 'tedir-select'

const props = defineProps({
  modelValue: Object
})

const emit = defineEmits(['update:modelValue', 'save'])

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
})

const form = ref({
  id: props.modelValue.id || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  isActive: props.modelValue.isActive ?? true,
  iso_code: props.modelValue.iso_code || '',
  stdPrecision: props.modelValue.stdPrecision || 2,
  description: props.modelValue.description || '',
  costingPrecision: props.modelValue.costingPrecision || 4,
  curSymbol: props.modelValue.curSymbol || '',
  isEuro: props.modelValue.isEuro ?? false,
  isEMUMember: props.modelValue.isEMUMember ?? false,
  emuRate: props.modelValue.emuRate || 0,
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || ''
  }
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    /*if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }*/
    
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
})

const save = () => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id)
  } else {
    emit('save', form.value, '')
  }
}
</script>

<template>
  <form @submit.prevent="save">
    <div class="row m-3 mt-0">
      <div v-if="form.alert.status" class="col-md-12 mb-3">
        <div class="alert" :class="Number(form.alert.status) >= 400 ? 'alert-danger' : 'alert-success'">
          <div class="alertContent">
            <h3 class="alertTitle">{{ form.alert.status }}</h3>
            <p class="alertText">{{ form.alert.message }}</p>
          </div>
          <div class="alertAction" @click="form.alert.status = ''"><i class="menu-icon tf-icons ti ti-x"></i></div>
        </div>
      </div>

      <div class="col-md-6 mb-3">
        <label class="label">Tenant *</label>
        <input type="text" :value="clientName" class="input" readonly />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Organization *</label>
        <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">ISO Currency Code *</label>
        <input type="text" v-model="form.iso_code" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">ISO Symbol</label>
        <input type="text" v-model="form.curSymbol" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Standard Precision *</label>
        <input type="text" v-model="form.stdPrecision" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Costing Precision *</label>
        <input type="text" v-model="form.costingPrecision" class="input" />
      </div>
      <div class="col-md-12 mb-3">
        <label class="label">Description *</label>
        <textarea v-model="form.description" class="input"></textarea>
      </div>
      <div class="col-md-12 mb-3">
        <label class="label d-block mb-2">Status</label>
        <div class="check">
          <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive">
          <label class="checkLabel" for="isActive">Active</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isEuro" class="checkInput" id="isEuro" :checked="form.isEuro">
          <label class="checkLabel" for="isEuro">Euro</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isEMUMember" class="checkInput" id="isEMUMember" :checked="form.isEMUMember">
          <label class="checkLabel" for="isEMUMember">EMU Member</label>
        </div>
      </div>
      <div v-if="form.isEMUMember" class="col-md-12 mb-3">
        <label class="label">EMU Rate</label>
        <input type="text" v-model="form.emuRate" class="input" />
      </div>
    </div>
    <div class="row m-3">
      <div class="col-md-12 mb-3">
        <button type="submit" class="btn btn-primary waves-effect waves-light" :class="(form.iso_code === '' || form.description === '' || form.stdPrecision === '' || form.costingPrecision === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
      </div>
    </div>
  </form>
</template>