<script setup>
import { date } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
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 || '',
  name: props.modelValue.name || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  isAccrual: props.modelValue.isAccrual ?? false,
  autoPeriodControl: props.modelValue.autoPeriodControl ?? false,
  periodOpenHistory: props.modelValue.periodOpenHistory || 0,
  periodOpenFuture: props.modelValue.periodOpenFuture || 0,
  separator: props.modelValue.separator || '-',
  hasAlias: props.modelValue.hasAlias ?? true,
  hasCombination: props.modelValue.hasCombination ?? false,
  isTradeDiscountPosted: props.modelValue.isTradeDiscountPosted ?? false,
  isDiscountCorrectsTax: props.modelValue.isDiscountCorrectsTax ?? false,
  isAdjustCOGS: props.modelValue.isAdjustCOGS ?? false,
  isPostServices: props.modelValue.isPostServices ?? false,
  isExplicitCostAdjustment: props.modelValue.isExplicitCostAdjustment ?? false,
  isAllowNegativePosting: props.modelValue.isAllowNegativePosting ?? true,
  isPostIfClearingEqual: props.modelValue.isPostIfClearingEqual ?? true,
  gaap: props.modelValue.gaap || '',
  gaapId: props.modelValue.gaapId || '',
  costingMethod: props.modelValue.costingMethod || '',
  costingMethodId: props.modelValue.costingMethodId || '',
  currency: props.modelValue.currency || '',
  currencyId: props.modelValue.currencyId || '',
  period: props.modelValue.period || '',
  periodId: props.modelValue.periodId || '',
  costType: props.modelValue.costType || '',
  costTypeId: props.modelValue.costTypeId || '',
  costingLevel: props.modelValue.costingLevel || '',
  costingLevelId: props.modelValue.costingLevelId || '',
  commitmentType: props.modelValue.commitmentType || '',
  commitmentTypeId: props.modelValue.commitmentTypeId || '',
  taxCorrectionType: props.modelValue.taxCorrectionType || '',
  taxCorrectionTypeId: props.modelValue.taxCorrectionTypeId || '',
  orgOnly: props.modelValue.orgOnly || '',
  orgOnlyId: props.modelValue.orgOnlyId || '',
  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 = (saveType = '') => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, '', saveType)
  }
}
</script>

<template>
  <form @submit.prevent="save">
    <div class="my-5 mx-5">
      <AlertAction v-model='form.alert.status' :alert="form.alert" />

      <div class="columns is-desktop">
        <div class="column is-two-thirds">
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">GAAP *</label>
              <select v-model="form.gaapId" class="select">
                <option value="XX">Custom Accounting Rules</option>
                <option value="FR">French Accounting Standard</option>
                <option value="DE">German HGB</option>
                <option value="UN">International GAAP</option>
                <option value="US">US GAAP</option>
              </select>
            </div>
            <div class="column is-half">
              <label class="label d-block">Commitment Type *</label>
              <select v-model="form.commitmentTypeId" class="select">
                <option value="N">None</option>
                <option value="B">PO Commitment & Reservation</option>
                <option value="C">PO Commitment only</option>
                <option value="O">PO/SO Commitment</option>
                <option value="A">PO/SO Commitment & Reservation</option>
                <option value="S">SO Commitment only</option>
              </select>
            </div>
          </div>

          <label class="label d-block mt-2">Name *</label>
          <input type="text" v-model="form.name" class="input" />

          <label class="label d-block mt-2">Description</label>
          <textarea v-model="form.description" class="input"></textarea>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Costing Method *</label>
              <select v-model="form.costingMethodId" class="select">
                <option value="I">Average Invoice</option>
                <option value="A">Average PO</option>
                <option value="F">Fifo</option>
                <option value="i">Last Invoice</option>
                <option value="p">Last PO Price</option>
                <option value="L">Lifo</option>
                <option value="S">Standard Costing</option>
              </select>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Costing Level *</label>
              <select v-model="form.costingLevelId" class="select">
                <option value="B">Batch/Lot</option>
                <option value="C">Client</option>
                <option value="O">Organization</option>
              </select>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Cost Type *</label>
              <ClientOnly>
                <SelectBox v-model="form.costTypeId" :options="getOptions?.['cost_types']?.records || [{id: form.costTypeId, Name: form.costType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_costtype', 'cost_types')" :loading="loading?.['cost_types'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Currency *</label>
              <ClientOnly>
                <SelectBox v-model="form.currencyId" :options="getOptions?.['currencies']?.records || [{id: form.currencyId, Value: form.currency}]" prop="ISO_Code" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_currency', 'currencies')" :loading="loading?.['currencies'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <div v-if="form.autoPeriodControl" class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">History Days</label>
              <input type="text" v-model="form.periodOpenHistory" class="input" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Future Days</label>
              <input type="text" v-model="form.periodOpenFuture" class="input" />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Element Separator *</label>
              <input type="text" v-model="form.separator" class="input" />
            </div>
            <div v-if="form.autoPeriodControl" class="column is-half">
              <label class="label d-block mt-2">Period</label>
              <input type="text" :value="form.period" class="input" readonly />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Tax Correction *</label>
              <select v-model="form.taxCorrectionTypeId" class="select">
                <option value="D">Discount only</option>
                <option value="N">None</option>
                <option value="B">Write-off and Discount</option>
                <option value="W">Write-off only</option>
              </select>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Only Organization</label>
              <SelectBox v-model="form.orgOnlyId" :options="organizations" prop="name" dataprop="id" datatype="string" :size="5" />
            </div>
          </div>

        </div>
        <div class="column is-one-third">
          <label class="label d-block">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" />

          <label class="label d-block mt-2">Tenant *</label>
          <input type="text" :value="clientName" class="input" readonly />

          <label class="label d-block mt-2">Status</label>
          <div class="d-flex flexDirection-column">
            <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.isAccrual" class="checkInput" id="isAccrual" :checked="form.isAccrual">
              <label class="checkLabel" for="isAccrual">Accrual</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.autoPeriodControl" class="checkInput" id="autoPeriodControl" :checked="form.autoPeriodControl">
              <label class="checkLabel" for="autoPeriodControl">Automatic Period Control</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isExplicitCostAdjustment" class="checkInput" id="isExplicitCostAdjustment" :checked="form.isExplicitCostAdjustment">
              <label class="checkLabel" for="isExplicitCostAdjustment">Explicit Cost Adjustment</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isTradeDiscountPosted" class="checkInput" id="isTradeDiscountPosted" :checked="form.isTradeDiscountPosted">
              <label class="checkLabel" for="isTradeDiscountPosted">Post Trade Discount</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.hasAlias" class="checkInput" id="hasAlias" :checked="form.hasAlias">
              <label class="checkLabel" for="hasAlias">Use Account Alias</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isPostIfClearingEqual" class="checkInput" id="isPostIfClearingEqual" :checked="form.isPostIfClearingEqual">
              <label class="checkLabel" for="isPostIfClearingEqual">Post if Clearing Equal</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isAllowNegativePosting" class="checkInput" id="isAllowNegativePosting" :checked="form.isAllowNegativePosting">
              <label class="checkLabel" for="isAllowNegativePosting">Allow Negative Posting</label>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="m-3">
      <div class="d-flex gap-10px">
        <button type="submit" class="button" :class="(form.name === '' || form.separator === '' || form.gaapId === '' || form.costingMethodId === '' || form.currencyId === '' || form.costTypeId === '' || form.costingLevelId === '' || form.commitmentTypeId === '' || form.taxCorrectionTypeId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
        <button type="button" @click="save('preview')" class="button" :class="(form.name === '' || form.separator === '' || form.gaapId === '' || form.costingMethodId === '' || form.currencyId === '' || form.costTypeId === '' || form.costingLevelId === '' || form.commitmentTypeId === '' || form.taxCorrectionTypeId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Preview</button>
        <button type="button" @click="save('changes')" class="button" :class="(form.name === '' || form.separator === '' || form.gaapId === '' || form.costingMethodId === '' || form.currencyId === '' || form.costTypeId === '' || form.costingLevelId === '' || form.commitmentTypeId === '' || form.taxCorrectionTypeId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save Changes</button>
      </div>
    </div>
  </form>
</template>