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

const props = defineProps({
  action: String,
  info: Object
})

const route = useRoute()
const organizationId = useCookie('logship_organization_id')
const warehouses = useCookie('logship_warehouses')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')

const { data: preferences } = await useFetch('/api/preferences/143', {
  headers: useRequestHeaders(['cookie'])
})

const preference = (attribute) => {
  //console.log(preferences.value)
  return preferences.value[attribute] || {}
}

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 || '',
  promotion: props.info?.name || '',
  promotionId: props.info?.id || '',
  isActive: true,
  promotionCounter: 50,
  promotionUsageLimit: 0,
  startDate: date.now(''),
  endDate: date.now(''),
  seqNo: '',
  promotionCode: '',
  partnerGroup: '',
  partnerGroupId: '',
  warehouse: warehouse.value?.Name || '',
  warehouseId: warehouseId.value || '',
  priceList: preference('M_PriceList_ID')?.identifier || '',
  priceListId: preference('M_PriceList_ID')?.id || '',
  activity: '',
  activityId: '',
  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.promotion = props.info?.name || ''
  form.value.promotionId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const showAddressModal = 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 || '',
    promotion: props.info?.name || '',
    promotionId: props.info?.id || '',
    isActive: true,
    promotionCounter: 50,
    promotionUsageLimit: 0,
    startDate: date.now(''),
    endDate: date.now(''),
    seqNo: '',
    promotionCode: '',
    partnerGroup: '',
    partnerGroupId: '',
    warehouse: warehouse.value?.Name || '',
    warehouseId: warehouseId.value || '',
    priceList: preference('M_PriceList_ID')?.identifier || '',
    priceListId: preference('M_PriceList_ID')?.id || '',
    activity: '',
    activityId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}

const loading = ref({})
const filtering = 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 filterOptions = async (model, key, filter = '') => {
  if(filter) {
    await setOptions('filters/'+model+'/'+filter, key)
    filtering.value[key] = filter
  } else {
    if(!filtering.value?.[key] || filtering.value?.[key] === '') {
      await setOptions('models/'+model, key)
    }
  }
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/materials/promotions/'+route.params.id+'/pre-condition', {
      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 || '',
          promotion: item?.M_Promotion_ID?.identifier || '',
          promotionId: item?.M_Promotion_ID?.id || '',
          isActive: item?.IsActive ?? true,
          promotionCounter: item?.PromotionCounter || 50,
          promotionUsageLimit: item?.PromotionUsageLimit || 0,
          startDate: item?.StartDate || date.now(''),
          endDate: item?.EndDate || date.now(''),
          seqNo: item?.SeqNo || '',
          promotionCode: item?.PromotionCode || '',
          partnerGroup: item?.C_BP_Group_ID?.identifier || '',
          partnerGroupId: item?.C_BP_Group_ID?.id || '',
          warehouse: item?.M_Warehouse_ID?.identifier || warehouse.value?.Name || '',
          warehouseId: item?.M_Warehouse_ID?.id || warehouseId.value || '',
          priceList: item?.M_PriceList_ID?.identifier || preference('M_PriceList_ID')?.identifier || '',
          priceListId: item?.M_PriceList_ID?.id || preference('M_PriceList_ID')?.id || '',
          activity: item?.C_Activity_ID?.identifier || '',
          activityId: item?.C_Activity_ID?.id || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

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

  if(entry.id) {
    const res = await $fetch('/api/materials/promotions/'+entry.id+'/pre-condition', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const save = async () => {
  let newStartDate = form.value.startDate
  if(form.value.startDate) {
    newStartDate = new Date(form.value.startDate).toJSON().replace('.000', '')
  }
  let newEndDate = form.value.endDate
  if(form.value.endDate) {
    newEndDate = new Date(form.value.endDate).toJSON().replace('.000', '')
  }

  if(form.value.id !== '') {
    const res = await $fetch('/api/materials/promotions/'+route.params.id+'/pre-condition', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        promotionCounter: form.value.promotionCounter,
        promotionUsageLimit: form.value.promotionUsageLimit,
        startDate: newStartDate,
        endDate: newEndDate,
        seqNo: form.value.seqNo,
        promotionCode: form.value.promotionCode,
        partnerGroupId: form.value.partnerGroupId,
        warehouseId: form.value.warehouseId,
        priceListId: form.value.priceListId,
        activityId: form.value.activityId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 7500,
        position: 'bottom-right'
      })
    } 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: 7500,
        position: 'bottom-right'
      })
    }
  } else {
    const res = await $fetch('/api/materials/promotions/'+route.params.id+'/pre-condition', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        promotionCounter: form.value.promotionCounter,
        promotionUsageLimit: form.value.promotionUsageLimit,
        startDate: newStartDate,
        endDate: newEndDate,
        seqNo: form.value.seqNo,
        promotionCode: form.value.promotionCode,
        partnerGroupId: form.value.partnerGroupId,
        warehouseId: form.value.warehouseId,
        priceListId: form.value.priceListId,
        activityId: form.value.activityId,
        promotionId: form.value.promotionId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 7500,
        position: 'bottom-right'
      })
    } 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: 7500,
        position: 'bottom-right'
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Sequence</th>
            <th>Partner Group</th>
            <th>Price List</th>
            <th>Warehouse</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' ? 6 : 5" 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.seqNo }}</td>
            <td>{{ entry.partnerGroup }}</td>
            <td>{{ entry.priceList }}</td>
            <td>{{ entry.warehouse }}</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;" 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">Pre Condition</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">Sequence *</label>
                  <input type="text" v-model="form.seqNo" class="input" />

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Business Partner Group</label>
                      <ClientOnly>
                        <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="filterOptions('c_bp_group', 'partner_groups')" @search="(val) => filterOptions('c_bp_group', 'partner_groups', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['partner_groups'] ?? true" />
                      </ClientOnly>
                      
                      <label class="label d-block mt-2">Warehouse</label>
                      <ClientOnly>
                        <SelectBox v-model="form.warehouseId" :options="getOptions?.['warehouses']?.records || [{id: form.warehouseId, Name: form.warehouse}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_warehouse', 'warehouses')" @search="(val) => filterOptions('m_warehouse', 'warehouses', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['warehouses'] ?? true" />
                      </ClientOnly>

                      <label class="label d-block mt-2">Start Date *</label>
                      <DatePicker v-model="form.startDate" />

                      <label class="label d-block mt-2">Business Partner</label>
                      <input type="text" class="input" readonly />

                      <label class="label d-block mt-2">Promotion Code</label>
                      <input type="text" v-model="form.promotionCode" class="input" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Price List</label>
                      <ClientOnly>
                        <SelectBox v-model="form.priceListId" :options="getOptions?.['price_lists']?.records || [{id: form.priceListId, Name: form.priceList}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_pricelist', 'price_lists')" @search="(val) => filterOptions('m_pricelist', 'price_lists', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['price_lists'] ?? true" />
                      </ClientOnly>
                      
                      <label class="label d-block mt-2">Activity</label>
                      <ClientOnly>
                        <SelectBox v-model="form.activityId" :options="getOptions?.['activities']?.records || [{id: form.activityId, Name: form.activity}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_activity', 'activities')" @search="(val) => filterOptions('c_activity', 'activities', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['activities'] ?? true" />
                      </ClientOnly>
                      
                      <label class="label d-block mt-2">End Date</label>
                      <DatePicker v-model="form.endDate" :add="7" />

                      <label class="label d-block mt-2">Usage Counter</label>
                      <input type="text" :value="form.promotionCounter" class="input" readonly />

                      <label class="label d-block mt-2">Usage Limit</label>
                      <input type="text" v-model="form.promotionUsageLimit" class="input" />
                    </div>
                  </div>

                </div>
                <div class="column is-one-third">
                  <label class="label d-block">Promotion *</label>
                  <input type="text" :value="form.promotion" class="input" readonly />
                  
                  <label class="label d-block mt-2">Organization *</label>
                  <input type="text" :value="form.organization" class="input" readonly />
                  
                  <label class="label d-block mt-2">Tenant *</label>
                  <input type="text" :value="form.client" class="input" readonly />
                  
                  <label class="label d-block">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>
                </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.seqNo === '' || form.promotionId === '' || form.startDate === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>