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

const { t } = useTranslation()

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

const organizationId = useCookie('logship_organization_id')

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 || '',
  isActive: true,
  name: '',
  phone: '',
  phone2: '',
  fax: '',
  ISDN: '',
  isBillTo: true,
  isShipTo: true,
  isPayFrom: true,
  isRemitTo: true,
  isPreserveCustomName: false,
  partner: '',
  partnerId: '',
  location: '',
  locationId: '',
  salesRegion: '',
  salesRegionId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const form2 = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  isActive: true,
  address1: '',
  address2: '',
  address3: '',
  address4: '',
  city: '',
  postal: '',
  regionName: '',
  isValid: true,
  country: '',
  countryId: '',
  region: '',
  regionId: '',
  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 || ''
})

const showDetailRecordModal = ref(false)
//const showAddressModal = ref(false)
const resetDetailRecordModal = () => {
  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    isActive: true,
    name: '',
    phone: '',
    phone2: '',
    fax: '',
    ISDN: '',
    isBillTo: true,
    isShipTo: true,
    isPayFrom: true,
    isRemitTo: true,
    isPreserveCustomName: false,
    partner: '',
    partnerId: '',
    location: '',
    locationId: '',
    salesRegion: '',
    salesRegionId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }

  form2.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    isActive: true,
    address1: '',
    address2: '',
    address3: '',
    address4: '',
    city: '',
    postal: '',
    regionName: '',
    isValid: true,
    country: '',
    countryId: '',
    region: '',
    regionId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

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

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+'/locations', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || item?.uid || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          isActive: item?.IsActive ?? true,
          name: item?.Name || '',
          phone: item?.Phone || '',
          phone2: item?.Phone2 || '',
          fax: item?.Fax || '',
          ISDN: item?.ISDN || '',
          isBillTo: item?.IsBillTo ?? true,
          isShipTo: item?.IsShipTo ?? true,
          isPayFrom: item?.IsPayFrom ?? true,
          isRemitTo: item?.IsRemitTo ?? true,
          isPreserveCustomName: item?.IsPreserveCustomName ?? false,
          partner: item?.C_BPartner_ID?.identifier || '',
          partnerId: item?.C_BPartner_ID?.id || '',
          location: item?.C_Location_ID?.identifier || '',
          locationId: item?.C_Location_ID?.id || '',
          salesRegion: item?.C_SalesRegion_ID?.identifier || '',
          salesRegionId: item?.C_SalesRegion_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]
        editLocation(form.value.locationId)
        showDetailRecordModal.value = true
      }
    }
  }
}
onMounted(retrieve)

const editLocation = async (id) => {
  if(id) {
    const res = await $fetch('/api/settings/locations/'+id, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      form2.value = {
        id: res?.id || res?.uid || '',
        client: res?.AD_Client_ID?.identifier || '',
        clientId: res?.AD_Client_ID?.id || '',
        organization: res?.AD_Org_ID?.identifier || '',
        organizationId: res?.AD_Org_ID?.id || '',
        isActive: res?.IsActive ?? true,
        address1: res?.Address1 || '',
        address2: res?.Address2 || '',
        address3: res?.Address3 || '',
        address4: res?.Address4 || '',
        city: res?.City || '',
        postal: res?.Postal || '',
        regionName: res?.RegionName || '',
        isValid: res?.IsValid ?? true,
        country: res?.C_Country_ID?.identifier || '',
        countryId: res?.C_Country_ID?.id || '',
        region: res?.C_Region_ID?.identifier || '',
        regionId: res?.C_Region_ID?.id || '',
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    }
  }
}

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

  if(entry.id && entry.locationId) {
    const res = await $fetch('/api/settings/locations/'+entry.locationId, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      const res2 = await $fetch('/api/partners/partners/'+entry.id+'/locations', {
        method: 'DELETE',
        headers: useRequestHeaders(['cookie'])
      })
      if(res2) {
        retrieve()
      }
    }
  }
}

const save = async () => {
  if(form.value.id !== '' && form2.value.id !== '') {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/locations', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        name: form.value.name,
        phone: form.value.phone,
        phone2: form.value.phone2,
        fax: form.value.fax,
        ISDN: form.value.ISDN,
        isBillTo: form.value.isBillTo,
        isShipTo: form.value.isShipTo,
        isPayFrom: form.value.isPayFrom,
        isRemitTo: form.value.isRemitTo,
        isPreserveCustomName: form.value.isPreserveCustomName,
        locationId: form.value.locationId || form2.value.id,
        salesRegionId: form.value.salesRegionId
      }
    })
    const res2 = await $fetch('/api/settings/locations/update', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form2.value.id,
        isActive: form2.value.isActive,
        address1: form2.value.address1,
        address2: form2.value.address2,
        address3: form2.value.address3,
        address4: form2.value.address4,
        city: form2.value.city,
        postal: form2.value.postal,
        regionName: form2.value.regionName,
        isValid: form2.value.isValid,
        countryId: form2.value.countryId,
        regionId: form2.value.regionId
      }
    })
    if(Number(res.status) === 200 && Number(res2.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: t.value?.record_saved || '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 || res2.message || t.value?.save_error || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/settings/locations/store', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form2.value.organizationId,
        isActive: form2.value.isActive,
        address1: form2.value.address1,
        address2: form2.value.address2,
        address3: form2.value.address3,
        address4: form2.value.address4,
        city: form2.value.city,
        postal: form2.value.postal,
        regionName: form2.value.regionName,
        isValid: form2.value.isValid,
        countryId: form2.value.countryId,
        regionId: form2.value.regionId
      }
    })
    if(res) {
      const res2 = await $fetch('/api/partners/partners/'+route.params.id+'/locations', {
        method: 'POST',
        headers: useRequestHeaders(['cookie']),
        body: {
          organizationId: form.value.organizationId || organizationId.value,
          isActive: form.value.isActive,
          name: form.value.name,
          phone: form.value.phone,
          phone2: form.value.phone2,
          fax: form.value.fax,
          ISDN: form.value.ISDN,
          isBillTo: form.value.isBillTo,
          isShipTo: form.value.isShipTo,
          isPayFrom: form.value.isPayFrom,
          isRemitTo: form.value.isRemitTo,
          isPreserveCustomName: form.value.isPreserveCustomName,
          partnerId: route.params.id,
          locationId: res.id,
          salesRegionId: form.value.salesRegionId,
        }
      })
      if(Number(res2.status) === 200) {
        closeDetailRecordModal()
        retrieve()
        toast({
          message: t.value?.record_saved || '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: res2.message || t.value?.save_error || 'Save error',
          type: 'is-danger',
          duration: 2000
        })
      }
    }
  }
  
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr>
            <th>{{ t.name }}</th>
            <th>{{ t.address }}</th>
            <th class="textAlignCenter">{{ t.ship_location }}</th>
            <th class="textAlignCenter">{{ t.bill_location }}</th>
            <th>{{ t.phone }}</th>
            <!--<th>Fax</th>
            <th>ISDN</th>-->
            <th class="w-100px">{{ t.active }}</th>
            <th v-if="action !== 'view'" class="w-100px">{{ t.action }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 7 : 6" class="align-center">{{ t.no_detail_record }}</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.name }}</td>
            <td>{{ entry.location }}</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 To</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 To</label>-->
              </div>
            </td>
            <td>{{ entry.phone }}</td>
            <!--<td>{{ entry.fax }}</td>
            <td>{{ entry.ISDN }}</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; editLocation(entry.locationId); 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; resetDetailRecordModal();" class="button">{{ t.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">{{ t.location }}</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">
                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block">{{ t.address_1 }} *</label>
                      <input type="text" v-model="form2.address1" class="input" />

<!--                      <label class="label d-block mt-2">Address 2</label>-->
<!--                      <input type="text" v-model="form2.address2" class="input" />-->

<!--                      <label class="label d-block mt-2">Address 3</label>-->
<!--                      <input type="text" v-model="form2.address3" class="input" />-->

<!--                      <label class="label d-block mt-2">Address 4</label>-->
<!--                      <input type="text" v-model="form2.address4" class="input" />-->

<!--                      <label class="label d-block mt-2">Address Status</label>-->
<!--                      <div class="d-flex flexWrap-wrap gap-10px">-->
<!--                        <div class="check">-->
<!--                          <input type="checkbox" v-model="form2.isActive" class="checkInput" id="isActive" :checked="form2.isActive">-->
<!--                          <label class="checkLabel" for="isActive">Active</label>-->
<!--                        </div>-->
<!--                        <div class="check">-->
<!--                          <input type="checkbox" v-model="form2.isValid" class="checkInput" id="isValid" :checked="form2.isValid">-->
<!--                          <label class="checkLabel" for="isValid">Valid</label>-->
<!--                        </div>-->
<!--                      </div>-->
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">{{ t.country }} *</label>
                      <ClientOnly>
                        <SelectBox v-model="form2.countryId" :options="getOptions?.['countries']?.records || [{id: form2.countryId, Name: form2.country}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_country', 'countries')" @change="(val, opt) => {setOptions('settings/regions/countries/'+opt.id, 'regions'); form2.country = opt.Name;}" :loading="loading?.['countries'] ?? true" />
                      </ClientOnly>

                      <label class="label d-block mt-2">{{ t.region }}</label>
                      <ClientOnly v-if="form2.countryId && (Number(getOptions?.['regions']?.records?.length || 0) >= 1 || form2.regionId)">
                        <SelectBox v-model="form2.regionId" :options="getOptions?.['regions']?.records || [{id: form2.regionId, Name: form2.region}]" prop="Name" dataprop="id" datatype="string" :size="5" @change="(val, opt) => {form2.region = opt.Name; form2.regionName = opt.Name;}" :loading="loading?.['regions'] ?? true" />
                      </ClientOnly>
                      <input v-else type="text" v-model="form2.regionName" class="input" />

                      <label class="label d-block mt-2">{{ t.city }}</label>
                      <input type="text" v-model="form2.city" class="input" />

                      <label class="label d-block mt-2">{{ t.zip }}</label>
                      <input type="text" v-model="form2.postal" class="input" />
                    </div>
                  </div>
                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block">{{ t.sales_region }}</label>
                      <ClientOnly>
                        <SelectBox v-model="form.salesRegionId" :options="getOptions?.['sales_regions']?.records || [{id: form.salesRegionId, Name: form.salesRegion}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_salesregion', 'sales_regions')" :loading="loading?.['sales_regions'] ?? true" />
                      </ClientOnly>

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

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

                      <label class="label d-block mt-2">{{ t.second_phone }}</label>
                      <input type="text" v-model="form.phone2" class="input" />
                    </div>
                    <div class="column is-half">
                      <!--<label class="label d-block">Location *</label>
                      <div class="select pickerToggler" @click="showAddressModal = true">
                        <span>{{ form.location || '-- Select Option --' }}</span>
                      </div>
                      <ClientOnly>
                        <SelectBox v-model="form.locationId" :options="getOptions?.['locations']?.records || [{id: form.locationId, Address1: form.location}]" prop="Address1" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_location', 'locations')" :loading="loading?.['locations'] ?? true" />
                      </ClientOnly>-->

                      <label class="label d-block">{{ t.customer_address_id }}</label>
                      <input type="text" class="input" readonly />

                      <label class="label d-block mt-2">{{ t.fax }}</label>
                      <input type="text" v-model="form.fax" class="input" />

                      <label class="label d-block mt-2">{{ t.isdn }}</label>
                      <input type="text" v-model="form.ISDN" class="input" />
                    </div>
                  </div>

                </div>
                <div class="column is-one-third">
                  <label class="label d-block">{{ t.location_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">{{ t.active }}</label>
                    </div>
<!--                    <div class="check">-->
<!--                      <input type="checkbox" v-model="form.isPreserveCustomName" class="checkInput" id="isPreserveCustomName" :checked="form.isPreserveCustomName">-->
<!--                      <label class="checkLabel" for="isPreserveCustomName">Preserve Custom Name</label>-->
<!--                    </div>-->
                    <div class="check">
                      <input type="checkbox" v-model="form.isBillTo" class="checkInput" id="isBillTo" :checked="form.isBillTo">
                      <label class="checkLabel" for="isBillTo">{{ t.invoice_address }}</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isShipTo" class="checkInput" id="isShipTo" :checked="form.isShipTo">
                      <label class="checkLabel" for="isShipTo">{{ t.ship_address }}</label>
                    </div>
<!--                    <div class="check">-->
<!--                      <input type="checkbox" v-model="form.isPayFrom" class="checkInput" id="isPayFrom" :checked="form.isPayFrom">-->
<!--                      <label class="checkLabel" for="isPayFrom">Pay-From Address</label>-->
<!--                    </div>-->
<!--                    <div class="check">-->
<!--                      <input type="checkbox" v-model="form.isRemitTo" class="checkInput" id="isRemitTo" :checked="form.isRemitTo">-->
<!--                      <label class="checkLabel" for="isRemitTo">Remit-To Address</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">{{ t.close }}</button>
              <button type="button" class="button" @click="save" :class="(form.name === '' || form2.address1 === '' || form2.countryId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">{{ t.submit }}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--<AddressModal v-model="showAddressModal" v-model:location="form.location" v-model:locationId="form.locationId" :info="form" />-->
  </Teleport>
</template>