<script setup>
import { date } from 'alga-js'
import { SelectBox } from 'tedir-select'
import { DatePicker } from 'tedir-calendar'

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 { data: greetings } = await useFetch('/api/partners/greetings', {
  headers: useRequestHeaders(['cookie'])
})

const { data: printFormats } = await useFetch('/api/admin/print-formats', {
  headers: useRequestHeaders(['cookie'])
})

const { data: paymentTerms } = await useFetch('/api/partners/payment-terms', {
  headers: useRequestHeaders(['cookie'])
})

const { data: partnerGroups } = await useFetch('/api/partners/partner-groups', {
  headers: useRequestHeaders(['cookie'])
})

const { data: priceLists } = await useFetch('/api/materials/price-lists', {
  headers: useRequestHeaders(['cookie'])
})

const { data: discountSchemas } = await useFetch('/api/materials/discount-schemas', {
  headers: useRequestHeaders(['cookie'])
})

const { data: dunnings } = await useFetch('/api/partners/dunnings', {
  headers: useRequestHeaders(['cookie'])
})*/

const priorityBases = ref([
  { value: 'H', text: 'Higher' },
  { value: 'L', text: 'Lower' },
  { value: 'S', text: 'Same' }
])

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) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

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 || '',
  name2: props.modelValue.name2 || '',
  value: props.modelValue.value || '',
  description: props.modelValue.description || '',
  salesVolume: props.modelValue.salesVolume || 0,
  numberEmployees: props.modelValue.numberEmployees || 0,
  isActive: props.modelValue.isActive ?? true,
  isSummary: props.modelValue.isSummary ?? false,
  isVendor: props.modelValue.isVendor ?? false,
  isCustomer: props.modelValue.isCustomer ?? false,
  isProspect: props.modelValue.isProspect ?? false,
  soCreditLimit: props.modelValue.soCreditLimit || 0,
  soCreditUsed: props.modelValue.soCreditUsed || 0,
  acqusitionCost: props.modelValue.acqusitionCost || 0,
  potentialLifeTimeValue: props.modelValue.potentialLifeTimeValue || 0,
  actualLifeTimeValue: props.modelValue.actualLifeTimeValue || 0,
  shareOfCustomer: props.modelValue.shareOfCustomer || 0,
  isEmployee: props.modelValue.isEmployee ?? false,
  isSalesRep: props.modelValue.isSalesRep ?? false,
  isOneTime: props.modelValue.isOneTime ?? false,
  isTaxExempt: props.modelValue.isTaxExempt ?? false,
  isDiscountPrinted: props.modelValue.isDiscountPrinted ?? false,
  sendEMail: props.modelValue.sendEMail ?? false,
  totalOpenBalance: props.modelValue.totalOpenBalance || 0,
  isPOTaxExempt: props.modelValue.isPOTaxExempt ?? false,
  isManufacturer: props.modelValue.isManufacturer ?? false,
  is1099Vendor: props.modelValue.is1099Vendor ?? false,
  firstSale: props.modelValue.firstSale || date.now('date'),
  poReference: props.modelValue.poReference || '',
  referenceNo: props.modelValue.referenceNo || '',
  rating: props.modelValue.rating || '',
  taxID: props.modelValue.taxID || '',
  URL: props.modelValue.URL || '',
  NAICS: props.modelValue.NAICS || '',
  DUNS: props.modelValue.DUNS || '',
  documentCopies: props.modelValue.documentCopies || 0,
  soDescription: props.modelValue.soDescription || '',
  flatDiscount: props.modelValue.flatDiscount || 0,
  shelfLifeMinPct: props.modelValue.shelfLifeMinPct || 0,
  dunningGrace: props.modelValue.dunningGrace || date.now('date'),
  deliveryRuleId: props.modelValue.deliveryRuleId || '',
  deliveryViaRuleId: props.modelValue.deliveryViaRuleId || '',
  invoiceScheduleId: props.modelValue.invoiceScheduleId || '',
  greetingId: props.modelValue.greetingId || '',
  printFormatId: props.modelValue.printFormatId || '',
  salesRepId: props.modelValue.salesRepId || '',
  paymentRulePOId: props.modelValue.paymentRulePOId || '',
  soCreditStatusId: props.modelValue.soCreditStatusId || '',
  partnerGroupId: props.modelValue.partnerGroupId || '',
  poPriceListId: props.modelValue.poPriceListId || '',
  poPaymentTermId: props.modelValue.poPaymentTermId || '',
  languageId: props.modelValue.languageId || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || ''
  }
})

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

const salesReps = ref([])
const setSalesReps = async () => {
  if(form.organizationId || props.modelValue.organizationId || organizationId.value) {
    const res = await $fetch('/api/admin/users/organizations/'+(form.organizationId || props.modelValue.organizationId || organizationId.value), {
      headers: useRequestHeaders(['cookie'])
    })
    salesReps.value = res
  }
}
onMounted(setSalesReps)
watch(organizationId, setSalesReps)

const bulmaDropCaret = ref(false)
const bulmaDropDownHandler = (e) => {
  e.stopPropagation()
  if(e.target.parentElement.parentElement.classList.contains('is-active')) {
    e.target.parentElement.parentElement.classList.remove('is-active')
    bulmaDropCaret.value = false
  } else {
    e.target.parentElement.parentElement.classList.add('is-active')
    bulmaDropCaret.value = true
  }
}

const bulmaDropItemHandler = (e) => {
  e.stopPropagation()
  if(e.target.parentElement.parentElement.parentElement.classList.contains('is-active')) {
    e.target.parentElement.parentElement.parentElement.classList.remove('is-active')
    bulmaDropCaret.value = false
  } else {
    e.target.parentElement.parentElement.parentElement.classList.add('is-active')
    bulmaDropCaret.value = true
  }
}

const save = () => {
  form.value.processing = true
  if(!form.value.value) {
    form.value.value = form.value.name
  }
  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="columns is-desktop">
      <div class="column">1
        <button class="button">
          <span title="Badge top right" class="badge">8</span>
          Button
        </button>
      </div>
      <div class="column">2

        <!--        <div class="dropdown">-->
        <!--          <div class="dropdown-trigger">-->
        <!--            <button class="button" @click.self="bulmaDropDownHandler($event);" aria-haspopup="true" aria-controls="dropdown-menu">-->
        <!--              <span class="pointerEvents-none">Dropdown button</span>-->
        <!--              <span class="pointerEvents-none icon is-small">-->
        <!--                <i class="menu-icon tf-icons ti" :class="bulmaDropCaret ? 'ti-chevron-up' : 'ti-chevron-down'" aria-hidden="true"></i>-->
        <!--              </span>-->
        <!--            </button>-->
        <!--          </div>-->
        <!--          <div class="dropdown-menu" id="dropdown-menu" role="menu">-->
        <!--            <div class="dropdown-content">-->
        <!--              <a href="javascript:void(0)" class="dropdown-item" @click.prevent="bulmaDropItemHandler($event);">-->
        <!--                Dropdown item-->
        <!--              </a>-->
        <!--              <a href="javascript:void(0)" class="dropdown-item" @click.prevent="bulmaDropItemHandler($event);">-->
        <!--                Other dropdown item-->
        <!--              </a>-->
        <!--              <a href="javascript:void(0)" class="dropdown-item" @click.prevent="bulmaDropItemHandler($event);">-->
        <!--                Active dropdown item-->
        <!--              </a>-->
        <!--              <a href="javascript:void(0)" class="dropdown-item" @click.prevent="bulmaDropItemHandler($event);">-->
        <!--                Other dropdown item-->
        <!--              </a>-->
        <!--              <hr class="dropdown-divider">-->
        <!--              <a href="javascript:void(0)" class="dropdown-item" @click.prevent="bulmaDropItemHandler($event);">-->
        <!--                With a divider-->
        <!--              </a>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </div>-->

      </div>
      <div class="column">3
      </div>
      <div class="column">
        <div class="column is-fullwidth">
          <!--          <button type="submit" class="button is-success" :class="(form.name === '' || form.partnerGroupId === '' || form.soCreditLimit === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>-->
          <button type="submit" class="button is-success" :class="(form.name === '' || form.partnerGroupId === '' || form.soCreditLimit === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>

        </div>
      </div>
    </div>


    <div class="columns">
      <!--      <div v-if="form.alert.status" class="column is-full 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="column is-one-third">1
        <label class="label">Name *</label>
        <input type="text" v-model="form.name" class="input" />

        <label class="label">2nd Name</label>
        <input type="text" v-model="form.name2" class="input" />

      </div>

      <div class="column is-one-quarter">2
        <label class="label">Search Key</label>
        <input type="text" v-model="form.value" class="input" />

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

        <label class="label">Reference No</label>
        <input type="text" v-model="form.referenceNo" class="input" />

        <label class="label">URL</label>
        <input type="text" v-model="form.URL" class="input" />

        <label class="label">Rating</label>
        <input type="text" v-model="form.rating" class="input" />

        <label class="label">Tax ID</label>
        <input type="text" v-model="form.taxID" class="input" />

        <label class="label">D-U-N-S</label>
        <input type="text" v-model="form.DUNS" class="input" />

        <label class="label">NAICS</label>
        <input type="text" v-model="form.NAICS" class="input" />

        <label class="label">Employees</label>
        <input type="text" v-model="form.numberEmployees" class="input" />

        <label class="label">Actual Life Time Value</label>
        <input type="text" v-model="form.actualLifeTimeValue" class="input" />


        <template v-if="form.isCustomer">
          <h4 class="card-action-title bb-1px_solid_hexeee">Customer Information</h4>
          <div class="column is-one-third mb-3">
            <label class="label">Invoice Rule</label>
            <select v-model="form.invoiceRuleId" class="select">
              <option value="D">After Delivery</option>
              <option value="O">After Order delivered</option>
              <option value="S">Customer Schedule after Delivery</option>
              <option value="I">Immediate</option>
            </select>
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Payment Rule</label>
            <select v-model="form.paymentRuleId" class="select">
              <option value="B">Cash</option>
              <option value="S">Check</option>
              <option value="K">Credit Card</option>
              <option value="D">Direct Debit</option>
              <option value="I">Direct Deposit</option>
              <option value="P">On Credit</option>
            </select>
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Payment Term</label>
            <SelectBox v-model="form.paymentTermId" :options="paymentTerms.records.filter(i => i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Invoice Schedule</label>
            <SelectBox v-model="form.invoiceRuleId" :options="priceLists.records.filter(i => i.IsSOPriceList === true && i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Delivery Rule</label>
            <select v-model="form.deliveryRuleId" class="select">
              <option value="R">After Payment</option>
              <option value="A">Availability</option>
              <option value="L">Complete Line</option>
              <option value="O">Complete Order</option>
              <option value="F">Force</option>
              <option value="M">Manual</option>
            </select>
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Delivery Via</label>
            <select v-model="form.deliveryViaRuleId" class="select">
              <option value="D">Delivery</option>
              <option value="P">Pickup</option>
              <option value="S">Shipper</option>
            </select>
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Price List</label>
            <SelectBox v-model="form.priceListId" :options="priceLists.records.filter(i => i.IsSOPriceList === true && i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Discount Schema</label>
            <SelectBox v-model="form.discountSchemaId" :options="discountSchemas.records.filter(i => i.DiscountType.id !== 'P' && i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Flat Discount %</label>
            <input type="text" v-model="form.flatDiscount" class="input" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Dunning</label>
            <SelectBox v-model="form.dunningId" :options="dunnings.records.filter(i => i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Dunning Grace Date</label>
            <DatePicker v-model="form.dunningGrace" />
          </div>
          <div class="column is-one-third mb-3">
            <label class="label">Min Shelf Life %</label>
            <input type="text" v-model="form.shelfLifeMinPct" class="input" />
          </div>
        </template>
        <template v-if="form.isVendor">
          <h4 class="card-action-title bb-1px_solid_hexeee">Vendor Information</h4>
          <div class="column is-half mb-3">
            <label class="label">Payment Rule</label>
            <select v-model="form.paymentRulePOId" class="select">
              <option value="B">Cash</option>
              <option value="S">Check</option>
              <option value="K">Credit Card</option>
              <option value="D">Direct Debit</option>
              <option value="I">Direct Deposit</option>
              <option value="P">On Credit</option>
            </select>
          </div>
          <div class="column is-half mb-3">
            <label class="label">Payment Term</label>
            <SelectBox v-model="form.poPaymentTermId" :options="paymentTerms.records.filter(i => i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-half mb-3">
            <label class="label">PO Price List</label>
            <SelectBox v-model="form.poPriceListId" :options="priceLists.records.filter(i => i.IsSOPriceList === false && i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-half mb-3">
            <label class="label">PO Discount Schema</label>
            <SelectBox v-model="form.poDiscountSchemaId" :options="discountSchemas.records.filter(i => i.DiscountType.id !== 'P' && i.IsActive)" prop="Name" dataprop="id" datatype="string" :size="5" />
          </div>
          <div class="column is-full mb-3">
            <label class="label d-block mb-2">Vendor Status</label>
            <div class="check">
              <input type="checkbox" v-model="form.isManufacturer" class="checkInput" id="isManufacturer" :checked="form.isManufacturer">
              <label class="checkLabel" for="isManufacturer">Manufacturer</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.is1099Vendor" class="checkInput" id="is1099Vendor" :checked="form.is1099Vendor">
              <label class="checkLabel" for="is1099Vendor">1099 Vendor</label>
            </div>
          </div>
        </template>



      </div>

      <div class="column is-one-fifth ">3
        <label class="label">Organization *</label>
        <SelectBox v-model="form.organizationId" :options="organizations" prop="name" dataprop="id" datatype="string" :size="5" @change="(val, opt) => setSalesReps()" />

        <label class="label">Tenant *</label>
        <input type="text" :value="clientName" class="input" readonly />

        <label class="label">Business Partner Group *</label>
        <SelectBox v-model="form.partnerGroupId"  :options="getOptions?.['partner_groups']?.records || [{id: form.partnerGroupId, Name: form.partnerGroup}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/partner-groups', 'partner_groups')" :loading="loading?.['partner_groups'] ?? true" />

        <label class="label">Representative/Agent</label>
        <SelectBox v-model="form.salesRepId" :options="salesReps.records" prop="Name" dataprop="id" datatype="string" :size="5" />

        <label class="label">First Sale</label>
        <DatePicker v-model="form.firstSale" />

        <label class="label">Sales Volume in</label>
        <input type="text" v-model="form.salesVolume" class="input" />

        <label class="label">Potential Life Time Value</label>
        <input type="text" v-model="form.potentialLifeTimeValue" class="input" />

        <label class="label">Acquisition Cost</label>
        <input type="text" v-model="form.acqusitionCost" class="input" />

        <label class="label">Share</label>
        <input type="text" v-model="form.shareOfCustomer" class="input" />

        <label class="label">Order Description</label>
        <textarea v-model="form.soDescription" class="input"></textarea>

        <label class="label">Order Reference</label>
        <input type="text" v-model="form.poReference" class="input" />

        <label class="label">Document Copies</label>
        <input type="text" v-model="form.documentCopies" class="input" />

        <label class="label">Language</label>
        <select v-model="form.languageId" class="select">
          <option value="en_US">English (US)</option>
          <option value="es_CO">Spanish (Colombia)</option>
        </select>

        <label class="label">Credit Status</label>
        <select v-model="form.soCreditStatusId" class="select">
          <option value="H">Credit Hold</option>
          <option value="O">Credit OK</option>
          <option value="S">Credit Stop</option>
          <option value="W">Credit Watch</option>
          <option value="X">No Credit Check</option>
        </select>

        <div class="columns">
          <div class="column">
            <label class="label">Credit Limit *</label>
            <input type="text" v-model="form.soCreditLimit" class="input" />
          </div>


          <div class="column">
            <label class="label">Open Bal.</label>
            <input type="text" v-model="form.totalOpenBalance" class="input" readonly />
          </div>
        </div>

        <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>

        <label class="label d-block mb-2">Type</label>
        <div class="check">
          <input type="checkbox" v-model="form.isCustomer" class="checkInput" id="isCustomer" :checked="form.isCustomer">
          <label class="checkLabel" for="isCustomer">Customer</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isVendor" class="checkInput" id="isVendor" :checked="form.isVendor">
          <label class="checkLabel" for="isVendor">Vendor</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isEmployee" class="checkInput" id="isEmployee" :checked="form.isEmployee">
          <label class="checkLabel" for="isEmployee">Employee</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isProspect" class="checkInput" id="isProspect" :checked="form.isProspect">
          <label class="checkLabel" for="isProspect">Prospect</label>
        </div>

        <div class="check">
          <input type="checkbox" v-model="form.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary">
          <label class="checkLabel" for="isSummary">Summary Level</label>
        </div>

        <div class="field">
          <input v-model="form.isSalesRep" :checked="form.isSalesRep" class="is-checkradio is-block is-success" id="exampleCheckboxBlockSuccess" type="checkbox" name="exampleCheckboxBlockSuccess" >
          <label for="exampleCheckboxBlockSuccess">Is Sales Representative</label>
        </div>

        <div class="check">
          <input type="checkbox" v-model="form.isTaxExempt" class="checkInput" id="isTaxExempt" :checked="form.isTaxExempt">
          <label class="checkLabel" for="isTaxExempt">SO Tax Exempt</label>
        </div>

        <div class="check">
          <input type="checkbox" v-model="form.isPOTaxExempt" class="checkInput" id="isPOTaxExempt" :checked="form.isPOTaxExempt">
          <label class="checkLabel" for="isPOTaxExempt">PO Tax Exempt</label>
        </div>

        <label class="label d-block mb-2">Printed</label>
        <div class="check">
          <input type="checkbox" v-model="form.isDiscountPrinted" class="checkInput" id="isDiscountPrinted" :checked="form.isDiscountPrinted">
          <label class="checkLabel" for="isDiscountPrinted">Discount Printed</label>
        </div>

      </div>

      <div class="column ">Timeline

        <div class="timeline">
          <header class="timeline-header">
            <span class="tag is-medium is-primary">Start</span>
          </header>
          <div class="timeline-item is-primary">
            <div class="timeline-marker is-primary"></div>
            <div class="timeline-content">
              <p class="heading">January 2016</p>
              <p>Customer Created</p>
            </div>
          </div>
          <div class="timeline-item is-warning">
            <div class="timeline-marker is-warning is-image is-32x32">
              <img src="https://bulma.io/images/placeholders/32x32.png">
            </div>
            <div class="timeline-content">
              <p class="heading">February 2016</p>
              <p>New Order Amount 300 EUR</p>
            </div>
          </div>
          <header class="timeline-header">
            <span class="tag is-primary">2017</span>
          </header>
          <div class="timeline-item is-danger">
            <div class="timeline-marker is-danger is-icon">
              <i class="fa fa-flag"></i>
            </div>
            <div class="timeline-content">
              <p class="heading">March 2017</p>
              <p>Timeline content - Can include any HTML element</p>
            </div>
          </div>
          <header class="timeline-header">
            <span class="tag is-medium is-primary">End</span>
          </header>
        </div>

      </div>

    </div>
  </form>
</template>

<style scoped>
@use form {
  field: input, label;
}

.column {
  background: lightblue;
  margin:5px;
}
</style>