<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 || '',
  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 || '',
  isInPayroll: props.modelValue.isInPayroll ?? false,
  isSalesLead: props.modelValue.isSalesLead ?? false,
  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 || '',
  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 = (saveType = '') => {
  //form.value.alert.processing = true
  if(form.value.image.includes(';base64,')) {
    avatarHandler(form.value.image)
  }
  emit('update:modelValue', form.value)
  emit('save', form.value)
  /*if(props.modelValue.id) {
    emit('save', form.value, tabEntries.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, tabEntries.value, '', saveType)
  }*/
}
</script>

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

      <template v-if="tab === 'contact'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Name *</label>
                  <input type="text" v-model="form.name" class="input" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Search Key</label>
                  <input type="text" v-model="form.value" class="input" />
                </div>
              </div>
            </div>

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

            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend mt-2">
                  <label class="label">Business Partner</label>
                  <!--<input type="text" :value="form.partner" class="input" readonly />-->
                  <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')" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Email</label>
                  <input type="email" v-model="form.eMail" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Title</label>
                  <input type="text" v-model="form.title" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Phone</label>
                  <input type="text" v-model="form.phone" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Fax</label>
                  <input type="text" v-model="form.fax" class="input" />
                </div>
                
                <div class="legend mt-2">
                  <label class="label">Notification Type *</label>
                  <select v-model="form.notificationTypeId" class="select">
                    <option value="E">EMail</option>
                    <option value="B">EMail+Notice</option>
                    <option value="X">None</option>
                    <option value="N">Notice</option>
                  </select>
                </div>
              </div>
              <div class="column is-half">
                <div class="legend mt-2">
                  <label class="label">Partner Location</label>
                  <!--<input type="text" :value="form.partnerLocation" class="input" readonly />-->
                  <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" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Password</label>
                  <input type="password" v-model="form.password" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Birthday</label>
                  <input type="text" :value="form.birthday" class="input" />
                </div>
                <!--<DatePicker v-model="form.birthday" />-->

                <div class="legend mt-2">
                  <label class="label">2nd Phone</label>
                  <input type="text" v-model="form.phone2" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Position</label>
                  <!--<input type="text" :value="form.job" class="input" readonly />-->
                  <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" />
                  </ClientOnly>
                </div>
              </div>
            </div>

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

            <div class="legend mt-2">
              <label class="label">Organization *</label>
              <!--<input type="text" :value="form.organization" class="input" readonly />-->
              <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="legend mt-2">
              <label class="label">Tenant *</label>
              <input type="text" :value="clientName" class="input" readonly />
            </div>

            <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">
                <label class="checkLabel" for="isActive">Active</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isFullBPAccess" class="checkInput" id="isFullBPAccess" :checked="form.isFullBPAccess">
                <label class="checkLabel" for="isFullBPAccess">Full BP Access</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isShipTo" class="checkInput" id="isShipTo" :checked="form.isShipTo">
                <label class="checkLabel" for="isShipTo">Ship Contact</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isBillTo" class="checkInput" id="isBillTo" :checked="form.isBillTo">
                <label class="checkLabel" for="isBillTo">Invoice Contact</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'internal'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Trx Organization</label>
                  <!--<input type="text" v-model="form.orgTrx" class="input" readonly />-->
                  <SelectBox v-model="form.orgTrxId" :options="organizations" prop="name" dataprop="id" datatype="string" :size="5" />
                </div>

                <div class="legend mt-2">
                  <label class="label">EMail User ID</label>
                  <input type="email" v-model="form.eMailUser" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Auto expand menu</label>
                  <select v-model="form.isMenuAutoExpandId" class="select">
                    <option value="Y">Yes</option>
                    <option value="N">No</option>
                  </select>
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Supervisor</label>
                  <!--<input type="text" v-model="form.supervisor" class="input" readonly />-->
                  <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" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">LDAP User Name</label>
                  <input type="text" v-model="form.LDAPUser" class="input" />
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Internal User Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isSupportUser" class="checkInput" id="isSupportUser" :checked="form.isSupportUser">
                <label class="checkLabel" for="isSupportUser">Support User</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'external'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Greeting</label>
                  <!--<input type="text" v-model="form.greeting" class="input" readonly />-->
                  <ClientOnly>
                    <SelectBox v-model="form.greetingId" :options="getOptions?.['greetings']?.records || [{id: form.greetingId, Name: form.greeting}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_greeting', 'greetings')" :loading="loading?.['greetings'] ?? true" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">EMail Verify</label>
                  <input type="text" v-model="form.eMailVerifyDate" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Verification Info</label>
                  <input type="text" v-model="form.eMailVerify" class="input" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Default mail template</label>
                  <!--<input type="text" v-model="form.mailText" class="input" />-->
                  <ClientOnly>
                    <SelectBox v-model="form.mailTextId" :options="getOptions?.['mailtexts']?.records || [{id: form.mailTextId, Name: form.mailText}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_mailtext', 'mailtexts')" :loading="loading?.['mailtexts'] ?? true" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Last Contact</label>
                  <!--<input type="text" v-model="form.lastContact" class="input" readonly />-->
                  <DatePicker v-model="form.lastContact" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Last Result</label>
                  <input type="text" v-model="form.lastResult" class="input" readonly />
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Mail Text Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isAddMailTextAutomatically" class="checkInput" id="isAddMailTextAutomatically" :checked="form.isAddMailTextAutomatically">
                <label class="checkLabel" for="isAddMailTextAutomatically">Add Mail Text Automatically</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'locking'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Date Password Changed</label>
                  <input type="text" v-model="form.datePasswordChanged" class="input" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Failed Login Count</label>
                  <input type="text" v-model="form.failedLoginCount" class="input" />
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Mail Text Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isLocked" class="checkInput" id="isLocked" :checked="form.isLocked">
                <label class="checkLabel" for="isLocked">Locked</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isNoPasswordReset" class="checkInput" id="isNoPasswordReset" :checked="form.isNoPasswordReset">
                <label class="checkLabel" for="isNoPasswordReset">No Password Reset</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isExpired" class="checkInput" id="isExpired" :checked="form.isExpired">
                <label class="checkLabel" for="isExpired">Expired</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isNoExpire" class="checkInput" id="isNoExpire" :checked="form.isNoExpire">
                <label class="checkLabel" for="isNoExpire">No Expire</label>
              </div>
            </div>
          </div>
        </div>
      </template>

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