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

const route = useRoute()
const url = useRequestURL()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

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 props = defineProps({
  action: String,
  info: Object,
  zoom: Object
})

const window = (from) => {
  let newParam = {}
  if(windowParam.value?.[from] && url.pathname.includes('windows/partners-partners-edit/')) {
    newParam = windowParam.value?.[from] || {}
  }
  return newParam
}

const entries = ref([])
const form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  partner: props.info?.name || '',
  partnerId: props.info?.id || '',
  isActive: true,
  name: '',
  description: '',
  password: '',
  eMail: '',
  isFullBPAccess: false,
  value: '',
  isInPayroll: false,
  isSalesLead: false,
  isLocked: false,
  failedLoginCount: 0,
  isNoPasswordReset: false,
  isExpired: false,
  isAddMailTextAutomatically: false,
  isNoExpire: false,
  isSupportUser: false,
  isShipTo: false,
  isBillTo: false,
  isVendorLead: false,
  eMailUser: '',
  phone2: '',
  birthday: date.now('date'),
  phone: '',
  fax: '',
  lastResult: '',
  lastContact: date.now('date'),
  title: '',
  comments: '',
  eMailVerify: 0,
  eMailVerifyDate: '',
  LDAPUser: '',
  datePasswordChanged: '',
  supervisor: '',
  supervisorId: '',
  notificationType: 'X',
  notificationTypeId: 'X',
  greeting: '',
  greetingId: '',
  partnerLocation: '',
  partnerLocationId: '',
  orgTrx: '',
  orgTrxId: '',
  job: '',
  jobId: '',
  isMenuAutoExpand: '',
  isMenuAutoExpandId: '',
  mailText: '',
  mailTextId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.partner = props.info?.name || ''
  form.value.partnerId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    partner: props.info?.name || '',
    partnerId: props.info?.id || '',
    isActive: true,
    name: '',
    description: '',
    password: '',
    eMail: '',
    isFullBPAccess: false,
    value: '',
    isInPayroll: false,
    isSalesLead: false,
    isLocked: false,
    failedLoginCount: 0,
    isNoPasswordReset: false,
    isExpired: false,
    isAddMailTextAutomatically: false,
    isNoExpire: false,
    isSupportUser: false,
    isShipTo: false,
    isBillTo: false,
    isVendorLead: false,
    eMailUser: '',
    phone2: '',
    birthday: date.now('date'),
    phone: '',
    fax: '',
    lastResult: '',
    lastContact: date.now('date'),
    title: '',
    comments: '',
    eMailVerify: 0,
    eMailVerifyDate: '',
    LDAPUser: '',
    datePasswordChanged: '',
    supervisor: '',
    supervisorId: '',
    notificationType: 'X',
    notificationTypeId: 'X',
    greeting: '',
    greetingId: '',
    partnerLocation: '',
    partnerLocationId: '',
    orgTrx: '',
    orgTrxId: '',
    job: '',
    jobId: '',
    isMenuAutoExpand: '',
    isMenuAutoExpandId: '',
    mailText: '',
    mailTextId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }

  if(window('sales-orders-zoom')?.path) {
    windowFrom.value = ''
    windowParam.value = {}
  }
}

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 retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/users', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          partner: item?.C_BPartner_ID?.identifier || '',
          partnerId: item?.C_BPartner_ID?.id || '',
          isActive: item?.IsActive ?? true,
          name: item?.Name || '',
          description: item?.Description || '',
          password: item?.Password || '',
          eMail: item?.EMail || '',
          isFullBPAccess: item?.IsFullBPAccess || false,
          value: item?.Value || '',
          isInPayroll: item?.IsInPayroll || false,
          isSalesLead: item?.IsSalesLead || false,
          isLocked: item?.IsLocked || false,
          failedLoginCount: item?.FailedLoginCount || 0,
          isNoPasswordReset: item?.IsNoPasswordReset || false,
          isExpired: item?.IsExpired || false,
          isAddMailTextAutomatically: item?.IsAddMailTextAutomatically || false,
          isNoExpire: item?.IsNoExpire || false,
          isSupportUser: item?.IsSupportUser || false,
          isShipTo: item?.IsShipTo || false,
          isBillTo: item?.IsBillTo || false,
          isVendorLead: item?.IsVendorLead || false,
          eMailUser: item?.EMailUser || '',
          phone2: item?.Phone2 || '',
          birthday: item?.Birthday || date.now('date'),
          phone: item?.Phone || '',
          fax: item?.Fax || '',
          lastResult: item?.LastResult || '',
          lastContact: item?.LastContact || date.now('date'),
          title: item?.Title || '',
          comments: item?.Comments || '',
          eMailVerify: item?.EMailVerify || 0,
          eMailVerifyDate: item?.EMailVerifyDate || '',
          LDAPUser: item?.LDAPUser || '',
          datePasswordChanged: item?.DatePasswordChanged || '',
          supervisor: item?.Supervisor_ID?.identifier || '',
          supervisorId: item?.Supervisor_ID?.id || '',
          notificationType: item?.NotificationType?.identifier || 'X',
          notificationTypeId: item?.NotificationType?.id || 'X',
          greeting: item?.C_Greeting_ID?.identifier || '',
          greetingId: item?.C_Greeting_ID?.id || '',
          partnerLocation: item?.C_BPartner_Location_ID?.identifier || '',
          partnerLocationId: item?.C_BPartner_Location_ID?.id || '',
          orgTrx: item?.AD_OrgTrx_ID?.identifier || '',
          orgTrxId: item?.AD_OrgTrx_ID?.id || '',
          job: item?.C_Job_ID?.identifier || '',
          jobId: item?.C_Job_ID?.id || '',
          isMenuAutoExpand: item?.IsMenuAutoExpand?.identifier || '',
          isMenuAutoExpandId: item?.IsMenuAutoExpand?.id || '',
          mailText: item?.R_DefaultMailText_ID?.identifier || '',
          mailTextId: item?.R_DefaultMailText_ID?.id || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
      if(props.zoom?.id && entries.value.filter(i => props.zoom?.id === i.id)?.[0]) {
        form.value = entries.value.filter(i => props.zoom?.id === i.id)[0]
        showDetailRecordModal.value = true
      }
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  entries.value.splice(index, 1)

  if(entry.id) {
    await $fetch('/api/partners/partners/'+entry.id+'/users', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
}

const save = async () => {
  //console.log(form.value)
  if(form.value.id !== '') {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/users', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        name: form.value.name,
        description: form.value.description,
        password: form.value.password,
        eMail: form.value.eMail,
        isFullBPAccess: form.value.isFullBPAccess,
        value: form.value.value,
        isInPayroll: form.value.isInPayroll,
        isSalesLead: form.value.isSalesLead,
        isLocked: form.value.isLocked,
        failedLoginCount: form.value.failedLoginCount,
        isNoPasswordReset: form.value.isNoPasswordReset,
        isExpired: form.value.isExpired,
        isAddMailTextAutomatically: form.value.isAddMailTextAutomatically,
        isNoExpire: form.value.isNoExpire,
        isSupportUser: form.value.isSupportUser,
        isShipTo: form.value.isShipTo,
        isBillTo: form.value.isBillTo,
        isVendorLead: form.value.isVendorLead,
        eMailUser: form.value.eMailUser,
        phone2: form.value.phone2,
        birthday: form.value.birthday,
        phone: form.value.phone,
        fax: form.value.fax,
        lastResult: form.value.lastResult,
        lastContact: form.value.lastContact,
        title: form.value.title,
        comments: form.value.comments,
        eMailVerify: form.value.eMailVerify,
        eMailVerifyDate: form.value.eMailVerifyDate,
        LDAPUser: form.value.LDAPUser,
        datePasswordChanged: form.value.datePasswordChanged,
        supervisorId: form.value.supervisorId,
        partnerId: form.value.partnerId,
        notificationTypeId: form.value.notificationTypeId,
        greetingId: form.value.greetingId,
        partnerLocationId: form.value.partnerLocationId,
        orgTrxId: form.value.orgTrxId,
        jobId: form.value.jobId,
        isMenuAutoExpandId: form.value.isMenuAutoExpandId,
        mailTextId: form.value.mailTextId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/users', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        name: form.value.name,
        description: form.value.description,
        password: form.value.password,
        eMail: form.value.eMail,
        isFullBPAccess: form.value.isFullBPAccess,
        value: form.value.value,
        isInPayroll: form.value.isInPayroll,
        isSalesLead: form.value.isSalesLead,
        isLocked: form.value.isLocked,
        failedLoginCount: form.value.failedLoginCount,
        isNoPasswordReset: form.value.isNoPasswordReset,
        isExpired: form.value.isExpired,
        isAddMailTextAutomatically: form.value.isAddMailTextAutomatically,
        isNoExpire: form.value.isNoExpire,
        isSupportUser: form.value.isSupportUser,
        isShipTo: form.value.isShipTo,
        isBillTo: form.value.isBillTo,
        isVendorLead: form.value.isVendorLead,
        eMailUser: form.value.eMailUser,
        phone2: form.value.phone2,
        birthday: form.value.birthday,
        phone: form.value.phone,
        fax: form.value.fax,
        lastResult: form.value.lastResult,
        lastContact: form.value.lastContact,
        title: form.value.title,
        comments: form.value.comments,
        eMailVerify: form.value.eMailVerify,
        eMailVerifyDate: form.value.eMailVerifyDate,
        LDAPUser: form.value.LDAPUser,
        datePasswordChanged: form.value.datePasswordChanged,
        supervisorId: form.value.supervisorId,
        partnerId: form.value.partnerId,
        notificationTypeId: form.value.notificationTypeId,
        greetingId: form.value.greetingId,
        partnerLocationId: form.value.partnerLocationId,
        orgTrxId: form.value.orgTrxId,
        jobId: form.value.jobId,
        isMenuAutoExpandId: form.value.isMenuAutoExpandId,
        mailTextId: form.value.mailTextId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <!--<th class="textAlignCenter">Ship Contact</th>
            <th class="textAlignCenter">Bill Contact</th>-->
            <th class="w-100px">Active</th>
            <th v-if="action !== 'view'" class="w-100px">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 7 : 6" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.name }}</td>
            <td>{{ entry.location }}</td>
            <td>{{ entry.phone }}</td>
            <!--<td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isShipTo" class="checkInput" :id="'isShipTo_'+index" :checked="entry.isShipTo" disabled>
                <label class="checkLabel" :for="'isShipTo_'+index">Ship Contact</label>
              </div>
            </td>
            <td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isBillTo" class="checkInput" :id="'isBillTo_'+index" :checked="entry.isBillTo" disabled>
                <label class="checkLabel" :for="'isBillTo_'+index">Bill Contact</label>
              </div>
            </td>-->
            <td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" disabled>
                <!--<label class="checkLabel" :for="'isActive_'+index">Active</label>-->
              </div>
            </td>
            <td v-if="action !== 'view'">
              <div class="d-flex justify-flexEnd gap-5px">
                <span @click="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                  <i class="menu-icon tf-icons ti ti-pencil"></i>
                </span>
                <span @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                  <i class="menu-icon tf-icons ti ti-trash"></i>
                </span>
              </div>
            </td>
          </tr>
          <tr v-if="action !== 'view'">
            <td colspan="5">
              <button type="button" @click="showDetailRecordModal = true; form.name = '';" class="button">Add Record</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Contact (User)</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody">
            <div class="my-5 mx-5">
              <AlertAction v-model='form.alert.status' :alert="form.alert" />
              <div class="columns">
                <div class="column is-two-thirds">
                  <label class="label d-block">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">
                    <div class="column is-half">
                      <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" @click="setOptions('partners/partners/'+form.partnerId+'/locations', 'locations')" :size="5" :loading="false" />
                      </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" />
                      </ClientOnly>

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

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

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

                      <label class="label d-block mt-2">Fax</label>
                      <input type="text" v-model="form.fax" class="input" />
                      
                      <label class="label d-block mt-2">Email Verify</label>
                      <input type="text" :value="form.eMailVerifyDate" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Greeting</label>
                      <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>

                      <label class="label d-block mt-2">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>

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

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

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

                      <label class="label d-block mt-2">Last Contact</label>
                      <input type="text" :value="form.lastContact" class="input" readonly />
                      
                      <label class="label d-block mt-2">Verification Info</label>
                      <input type="text" :value="form.EMailVerify" class="input" readonly />
                    </div>
                  </div>

                  <label class="label d-block mt-2">Last Result</label>
                  <input type="text" :value="form.lastResult" class="input" readonly />

                  <label class="label d-block mt-2">Comments</label>
                  <textarea v-model="form.help" class="input"></textarea>
                </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="form.client" class="input" readonly />

                  <label class="label d-block mt-2">Business Partner *</label>
                  <input type="text" :value="form.partner" 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.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">Bill Contact</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>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
              <button type="button" class="button" @click="save" :class="(form.name === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>