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

const props = defineProps({
  modelValue: Object,
  tab: String
})

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 || '',
  uid: props.modelValue.uid || '',
  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 || '',
  password: props.modelValue.password || '',
  eMail: props.modelValue.eMail || '',
  isFullBPAccess: props.modelValue.isFullBPAccess ?? false,
  value: props.modelValue.value || '',
  isActive: props.modelValue.isActive ?? true,
  isInPayroll: props.modelValue.isInPayroll ?? false,
  isSalesLead: props.modelValue.isSalesLead ?? true,
  isLocked: props.modelValue.isLocked ?? false,
  failedLoginCount: props.modelValue.failedLoginCount || 0,
  isNoPasswordReset: props.modelValue.isNoPasswordReset ?? false,
  isExpired: props.modelValue.isExpired ?? false,
  isAddMailTextAutomatically: props.modelValue.isAddMailTextAutomatically ?? false,
  isNoExpire: props.modelValue.isNoExpire ?? false,
  isSupportUser: props.modelValue.isSupportUser ?? false,
  isShipTo: props.modelValue.isShipTo ?? false,
  isBillTo: props.modelValue.isBillTo ?? false,
  isVendorLead: props.modelValue.isVendorLead ?? false,
  eMailUser: props.modelValue.eMailUser || '',
  phone2: props.modelValue.phone2 || '',
  birthday: props.modelValue.birthday || date.now('date'),
  phone: props.modelValue.phone || '',
  fax: props.modelValue.fax || '',
  lastResult: props.modelValue.lastResult || '',
  lastContact: props.modelValue.lastContact || date.now('date'),
  title: props.modelValue.title || '',
  comments: props.modelValue.comments || '',
  eMailVerify: props.modelValue.eMailVerify || 0,
  eMailVerifyDate: props.modelValue.eMailVerifyDate || '',
  LDAPUser: props.modelValue.LDAPUser || '',
  datePasswordChanged: props.modelValue.datePasswordChanged || '',
  supervisor: props.modelValue.supervisor || '',
  supervisorId: props.modelValue.supervisorId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  notificationType: props.modelValue.notificationType || '',
  notificationTypeId: props.modelValue.notificationTypeId || 'X',
  greeting: props.modelValue.greeting || '',
  greetingId: props.modelValue.greetingId || '',
  partnerLocation: props.modelValue.partnerLocation || '',
  partnerLocationId: props.modelValue.partnerLocationId || '',
  orgTrx: props.modelValue.orgTrx || '',
  orgTrxId: props.modelValue.orgTrxId || '',
  job: props.modelValue.job || '',
  jobId: props.modelValue.jobId || '',
  isMenuAutoExpand: props.modelValue.isMenuAutoExpand || '',
  isMenuAutoExpandId: props.modelValue.isMenuAutoExpandId || '',
  mailText: props.modelValue.mailText || '',
  mailTextId: props.modelValue.mailTextId || '',
  image: props.modelValue.image || '',
  imageData: props.modelValue.imageData || '',
  imageId: props.modelValue.imageId || '',
  location: props.modelValue.location || '',
  locationId: props.modelValue.locationId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  leadSource: props.modelValue.leadSource || '',
  leadSourceId: props.modelValue.leadSourceId || '',
  leadStatus: props.modelValue.leadStatus || '',
  leadStatusId: props.modelValue.leadStatusId || '',
  leadSourceDescription: props.modelValue.leadSourceDescription || '',
  leadStatusDescription: props.modelValue.leadStatusDescription || '',
  companyname: props.modelValue.companyname || '',
  URL: props.modelValue.URL || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false,
  }
})

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
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
  if(props.modelValue.imageData) {
    form.value.image = 'data:text/plain;charset=US-ASCII;base64,'+props.modelValue.imageData //image/png
  }
})

const avatarHandler = (val) => {
  const base64Val = val.split(',')[1]
  if(base64Val) {
    form.value.imageData = base64Val
  }
}

const save = () => {
  if(form.value.image?.includes(';base64,')) {
    avatarHandler(form.value.image)
  }
  emit('update:modelValue', form.value)
  emit('save', form.value)
}
</script>

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

      <template v-if="tab === 'basic'">
        <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">Name *</label>
                <input type="text" v-model="form.name" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Search Key</label>
                <input type="text" v-model="form.value" class="input" @keyup="save" readonly/>
              </div>
            </div>

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

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Phone</label>
                <input type="text" v-model="form.phone" class="input" @keyup="save" />

                <label class="label d-block mt-2">Email</label>
                <input type="email" v-model="form.eMail" class="input" @keyup="save" />

<!--                <label class="label d-block mt-2">Address</label>-->
<!--                <ClientOnly>-->
<!--                  <SelectBox v-model="form.locationId" :options="getOptions?.['addresses']?.records || [{id: form.locationId, Address1: form.location}]" prop="Address1" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_location', 'addresses')" :loading="loading?.['addresses'] ?? true" @change="save" />-->
<!--                </ClientOnly>-->

<!--                <label class="label d-block mt-2">Business Partner</label>-->
<!--                <ClientOnly>-->
<!--                  <SelectBox v-model="form.partnerId" :options="getOptions?.['partners']?.records || [{id: form.partnerId, Name: form.partner}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/partners', 'partners')" :loading="loading?.['partners'] ?? true" @change="(val, opt) => {setOptions('partners/partners/'+opt.id+'/locations', 'locations'); save();}" />-->
<!--                </ClientOnly>-->

                <label class="label d-block mt-2">Position</label>
                <ClientOnly>
                  <SelectBox v-model="form.jobId" :options="getOptions?.['positions']?.records || [{id: form.jobId, Name: form.job}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_job', 'positions')" :loading="loading?.['positions'] ?? true" @change="save" />
                </ClientOnly>
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Companyname</label>
                <input type="text" v-model="form.companyname" class="input" @keyup="save" />

                <label class="label d-block mt-2">URL</label>
                <input type="text" v-model="form.URL" class="input" @keyup="save" />

<!--                    <label class="label d-block mt-2">2nd Phone</label>-->
<!--                    <input type="text" v-model="form.phone2" class="input" @keyup="save" />-->

<!--                <label class="label d-block mt-2">2nd Phone</label>-->
<!--                <input type="text" v-model="form.phone2" class="input" @keyup="save" />-->

<!--                <label class="label d-block mt-2">Fax</label>-->
<!--                <input type="text" v-model="form.fax" class="input" @keyup="save" />-->

<!--                <label class="label d-block mt-2">Birthday</label>-->
<!--                <DatePicker v-model="form.birthday" @handler="save" />-->

<!--                <label class="label d-block mt-2">Partner Location</label>-->
<!--                <ClientOnly>-->
<!--                  <SelectBox v-model="form.partnerLocationId" :options="getOptions?.['locations']?.records || [{id: form.partnerLocationId, Name: form.partnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" :loading="false" @change="save" />-->
<!--                </ClientOnly>-->
              </div>
            </div>

            <label class="label d-block mt-2">Comments</label>
            <textarea v-model="form.comments" class="input" @keyup="save"></textarea>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Avatar</label>
            <ThumbBox v-model="form.image" type="base64" @handler="save">
              <span class="tf-icon ti ti-photo-plus ti-xl pt-8rem pb-6rem cursor-pointer"></span>
            </ThumbBox>

            <label class="label d-block mt-2">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">Contact Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" @change="save">
                <label class="checkLabel" for="isActive">Active</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isSalesLead" class="checkInput" id="isSalesLead" :checked="form.isSalesLead" @change="save">
                <label class="checkLabel" for="isSalesLead">Sales Lead</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isVendorLead" class="checkInput" id="isVendorLead" :checked="form.isVendorLead" @change="save">
                <label class="checkLabel" for="isVendorLead">Vendor Lead</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-full">
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Campaign</label>
                <ClientOnly>
                  <SelectBox v-model="form.campaignId" :options="getOptions?.['campaigns']?.records || [{id: form.campaignId, Name: form.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_campaign', 'campaigns')" :loading="loading?.['campaigns'] ?? true" @change="save" />
                </ClientOnly>

                <label class="label d-block mt-2">Lead Source</label>
                <select v-model="form.leadSourceId" class="select" @change="save">
                  <option value="CC">Cold Call</option>
                  <option value="CN">Conference</option>
                  <option value="EL">Email</option>
                  <option value="EM">Employee</option>
                  <option value="EC">Existing Customer</option>
                  <option value="PT">Partner</option>
                  <option value="TS">Trade Show</option>
                  <option value="WS">Web Site</option>
                  <option value="WM">Word of Mouth</option>
                </select>
                
                <label class="label d-block mt-2">Lead Status</label>
                <select v-model="form.leadStatusId" class="select" @change="save">
                  <option value="C">Converted</option>
                  <option value="E">Expired</option>
                  <option value="N">New</option>
                  <option value="R">Recycled</option>
                  <option value="W">Working</option>
                </select>
              </div>
              <div class="column is-half">
                <label class="label d-block">Sales Representative</label>
                <ClientOnly>
                  <SelectBox v-model="form.supervisorId" :options="getOptions?.['supervisors']?.records || [{id: form.supervisorId, Name: form.supervisor}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'supervisors')" :loading="loading?.['supervisors'] ?? true" @change="save" />
                </ClientOnly>

                <label class="label d-block mt-2">Lead Source Description</label>
                <input type="text" v-model="form.leadSourceDescription" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Lead Status Description</label>
                <input type="text" v-model="form.leadStatusDescription" class="input" @keyup="save" />
              </div>
            </div>
          </div>
          
        </div>
      </template>

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