<script setup>
import { date } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'
import { AttachBox, 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 || '',
  isActive: props.modelValue.isActive ?? false,
  amtApproval: props.modelValue.amtApproval || 0,
  isManual: props.modelValue.isManual ?? false,
  isPersonalAccess: props.modelValue.isPersonalAccess ?? false,
  isShowAcct: props.modelValue.isShowAcct ?? false,
  isPersonalLock: props.modelValue.isPersonalLock ?? false,
  isCanReport: props.modelValue.isCanReport ?? false,
  isCanExport: props.modelValue.isCanExport ?? false,
  isCanApproveOwnDoc: props.modelValue.isCanApproveOwnDoc ?? false,
  isAccessAllOrgs: props.modelValue.isAccessAllOrgs ?? false,
  isChangeLog: props.modelValue.isChangeLog ?? false,
  overwritePriceLimit: props.modelValue.overwritePriceLimit ?? false,
  isUseUserOrgAccess: props.modelValue.isUseUserOrgAccess ?? false,
  confirmQueryRecords: props.modelValue.confirmQueryRecords || 0,
  maxQueryRecords: props.modelValue.maxQueryRecords || 0,
  allow_Info_Account: props.modelValue.allow_Info_Account ?? false,
  allow_Info_Asset: props.modelValue.allow_Info_Asset ?? false,
  allow_Info_BPartner: props.modelValue.allow_Info_BPartner ?? false,
  allow_Info_InOut: props.modelValue.allow_Info_InOut ?? false,
  allow_Info_Invoice: props.modelValue.allow_Info_Invoice ?? false,
  allow_Info_Order: props.modelValue.allow_Info_Order ?? false,
  allow_Info_Payment: props.modelValue.allow_Info_Payment ?? false,
  allow_Info_Product: props.modelValue.allow_Info_Product ?? false,
  allow_Info_Resource: props.modelValue.allow_Info_Resource ?? false,
  allow_Info_Schedule: props.modelValue.allow_Info_Schedule ?? false,
  isDiscountUptoLimitPrice: props.modelValue.isDiscountUptoLimitPrice ?? false,
  isDiscountAllowedOnTotal: props.modelValue.isDiscountAllowedOnTotal ?? false,
  isMenuAutoExpand: props.modelValue.isMenuAutoExpand ?? false,
  isMasterRole: props.modelValue.isMasterRole ?? false,
  isAccessAdvanced: props.modelValue.isAccessAdvanced ?? false,
  isClientAdministrator: props.modelValue.isClientAdministrator ?? false,
  amtApprovalAccum: props.modelValue.amtApprovalAccum || 0,
  daysApprovalAccum: props.modelValue.daysApprovalAccum || 0,
  userLevel: props.modelValue.userLevel || 'Client+Organization',
  userLevelId: props.modelValue.userLevelId || ' CO',
  currency: props.modelValue.currency || '',
  currencyId: props.modelValue.currencyId || '',
  preferenceType: props.modelValue.preferenceType || 'None',
  preferenceTypeId: props.modelValue.preferenceTypeId || 'N',
  treeMenu: props.modelValue.treeMenu || '',
  treeMenuId: props.modelValue.treeMenuId || '',
  roleType: props.modelValue.roleType || '',
  roleTypeId: props.modelValue.roleTypeId || '',
  treeOrg: props.modelValue.treeOrg || '',
  treeOrgId: props.modelValue.treeOrgId || '',
  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
})

const save = () => {
  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">User Level *</label>
                <select v-model="form.userLevelId" class="select" @change="save">
                  <option value=" C ">Client</option>
                  <option value=" CO">Client+Organization</option>
                  <option value="  O">Organization</option>
                  <option value="S  ">System</option>
                </select>
              </div>
            </div>

            <label class="label d-block mt-2">Description</label>
            <textarea v-model="form.description" class="input" @keyup="save"></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="clientName" class="input" readonly />

            <label class="label d-block mt-2">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.isMasterRole" class="checkInput" id="isMasterRole" :checked="form.isMasterRole" @change="save">
                <label class="checkLabel" for="isMasterRole">Master Role</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isManual" class="checkInput" id="isManual" :checked="form.isManual" @change="save">
                <label class="checkLabel" for="isManual">Manual</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isMenuAutoExpand" class="checkInput" id="isMenuAutoExpand" :checked="form.isMenuAutoExpand" @change="save">
                <label class="checkLabel" for="isMenuAutoExpand">Auto Expand Menu</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isChangeLog" class="checkInput" id="isChangeLog" :checked="form.isChangeLog" @change="save">
                <label class="checkLabel" for="isChangeLog">Change Log</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'workflow'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <label class="label d-block">Approval Amount</label>
            <input type="text" v-model="form.amtApproval" class="input" @keyup="save" />

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

            <label class="label d-block mt-2">Document Approval Status</label>
            <div class="check">
              <input type="checkbox" v-model="form.isCanApproveOwnDoc" class="checkInput" id="isCanApproveOwnDoc" :checked="form.isCanApproveOwnDoc" @change="save">
              <label class="checkLabel" for="isCanApproveOwnDoc">Can Approve Own Documents</label>
            </div>
          </div>
          <div class="column is-half">
            <label class="label d-block">Currency</label>
            <ClientOnly>
              <SelectBox v-model="form.currencyId" :options="getOptions?.['currencies']?.records || [{id: form.currencyId, ISO_Code: form.currency}]" prop="ISO_Code" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_currency', 'currencies')" :loading="loading?.['currencies'] ?? true" @change="save" />
            </ClientOnly>

            <label class="label d-block mt-2">Days Approval Accumulated</label>
            <input type="text" v-model="form.daysApprovalAccum" class="input" @keyup="save" />
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'access'">
        <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">Role Type</label>
                <select v-model="form.roleTypeId" class="select" @change="save">
                  <option value="E1">External App 1</option>
                  <option value="E2">External App 2</option>
                  <option value="E3">External App 3</option>
                  <option value="E4">External App 4</option>
                  <option value="E5">External App 5</option>
                  <option value="MO">Mobile</option>
                  <option value="SW">Swing</option>
                  <option value="SS">System Support</option>
                  <option value="WS">WebService</option>
                  <option value="ZK">WebUI</option>
                </select>

                <label class="label d-block mt-2">Menu Tree</label>
                <ClientOnly>
                  <SelectBox v-model="form.treeMenuId" :options="getOptions?.['menu_trees']?.records || [{id: modelValue.treeMenuId, Name: modelValue.treeMenu}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_tree', 'menu_trees')" :loading="loading?.['menu_trees'] ?? true" @change="save" />
                </ClientOnly>

                <label class="label d-block mt-2">Confirm Query Records *</label>
                <input type="text" v-model="form.confirmQueryRecords" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Preference Level *</label>
                <select v-model="form.preferenceTypeId" class="select" @change="save">
                  <option value="C">Client</option>
                  <option value="N">None</option>
                  <option value="O">Organization</option>
                  <option value="U">User</option>
                </select>

                <label class="label d-block mt-2">Organization Tree</label>
                <ClientOnly>
                  <SelectBox v-model="form.treeOrgId" :options="getOptions?.['org_trees']?.records || [{id: modelValue.treeOrgId, Name: modelValue.treeOrg}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_tree', 'org_trees')" :loading="loading?.['org_trees'] ?? true" @change="save" />
                </ClientOnly>

                <label class="label d-block mt-2">Max Query Records *</label>
                <input type="text" v-model="form.maxQueryRecords" class="input" @keyup="save" />
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Access Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isAccessAdvanced" class="checkInput" id="isAccessAdvanced" :checked="form.isAccessAdvanced" @change="save">
                <label class="checkLabel" for="isAccessAdvanced">Access Advanced</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isAccessAllOrgs" class="checkInput" id="isAccessAllOrgs" :checked="form.isAccessAllOrgs" @change="save">
                <label class="checkLabel" for="isAccessAllOrgs">Access all Orgs</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isUseUserOrgAccess" class="checkInput" id="isUseUserOrgAccess" :checked="form.isUseUserOrgAccess" @change="save">
                <label class="checkLabel" for="isUseUserOrgAccess">Use User Org Access</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isPersonalLock" class="checkInput" id="isPersonalLock" :checked="form.isPersonalLock" @change="save">
                <label class="checkLabel" for="isPersonalLock">Personal Lock</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isPersonalAccess" class="checkInput" id="isPersonalAccess" :checked="form.isPersonalAccess" @change="save">
                <label class="checkLabel" for="isPersonalAccess">Personal Access</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isCanReport" class="checkInput" id="isCanReport" :checked="form.isCanReport" @change="save">
                <label class="checkLabel" for="isCanReport">Can Report</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isCanExport" class="checkInput" id="isCanExport" :checked="form.isCanExport" @change="save">
                <label class="checkLabel" for="isCanExport">Can Export</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isClientAdministrator" class="checkInput" id="isClientAdministrator" :checked="form.isClientAdministrator" @change="save">
                <label class="checkLabel" for="isClientAdministrator">Tenant Administrator</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isShowAcct" class="checkInput" id="isShowAcct" :checked="form.isShowAcct" @change="save">
                <label class="checkLabel" for="isShowAcct">Show Accounting</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.overwritePriceLimit" class="checkInput" id="overwritePriceLimit" :checked="form.overwritePriceLimit" @change="save">
                <label class="checkLabel" for="overwritePriceLimit">Overwrite Price Limit</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'info'">
        <div class="columns is-desktop">
          <div class="column is-full">
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.allow_Info_Account" class="checkInput" id="allow_Info_Account" :checked="form.allow_Info_Account" @change="save">
                <label class="checkLabel" for="allow_Info_Account">Allow Info Account</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.allow_Info_Schedule" class="checkInput" id="allow_Info_Schedule" :checked="form.allow_Info_Schedule" @change="save">
                <label class="checkLabel" for="allow_Info_Schedule">Allow Info Schedule</label>
              </div>
            </div>
          </div>
        </div>
      </template>

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