<script setup>
import {ref, defineProps, computed} from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import ConfigurationInputNumber from "@/components/displays/superuser/configuration/ConfigurationInputNumber.vue";
import ConfigurationInput from "@/components/displays/superuser/configuration/ConfigurationInput.vue";
import Swal from "sweetalert2";
import ConfigurationSelect from "@/components/displays/superuser/configuration/ConfigurationSelect.vue";

const props = defineProps({
  customer_number: {
    type: Number,
    required: true,
  },
});

// Define the reactive variables

// Define the response variables
const hasDefaultDepartment = ref(false);
const department_value = ref(null);

const getDefaultDepartment = async () => {
  // Get the fixed pricing
  await SessionUser.request('/customer/department/default', 'GET', {
    customer_number: props.customer_number,
  }).then((response) => {
    let responseData = response.data.data;
    console.log(response.data.data, 'Default department');
    department_value.value = responseData.department;
    hasDefaultDepartment.value = true;
  }).catch((error) => {
    console.error(error);
    hasDefaultDepartment.value = false;
  });
};

const onClickSubmit = async () => {
  // Submit the fixed pricing
  await SessionUser.request('/customer/department/default', 'POST', {
    customer_number: props.customer_number,
    department: department_value.value,
  }).then((response) => {
    console.log(response.data.data, 'Created default department');
    // Get the newly created fixed pricing
    getDefaultDepartment();
  }).catch((error) => {
    console.error(error);
  });
};

// Check if the input is valid
const isInputValid = computed(() => {
  // Check if the department is selected
  return department_value.value && department_value.value !== '' && department_value.value !== null;
});

const onClickDelete = async () => {
  // Show the confirmation dialog
  Swal.fire({
    title: SessionUser.objects.global.language.delete + ' ' + SessionUser.objects.global.language.default + ' ' + SessionUser.objects.departments.meta.labels.single + '?',
    text: SessionUser.objects.global.language.delete + ' ' + SessionUser.objects.global.language.default + ' ' + SessionUser.objects.departments.meta.labels.single + '?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: SessionUser.objects.global.language.yes,
    cancelButtonText: SessionUser.objects.global.language.no,
  }).then((result) => {
    if (result.isConfirmed) {
      onDeleteConfirmed();
    }
  });
};

const onDeleteConfirmed = async () => {
  // Delete the fixed pricing
  await SessionUser.request('/customer/department/default', 'DELETE', {
    customer_number: props.customer_number,
  }).then((response) => {
    console.log(response.data.data, 'Deleted default department');
    // Get the newly created fixed pricing
    getDefaultDepartment();
  }).catch((error) => {
    console.error(error);
  });
};

getDefaultDepartment();
const departmentOptions = ref([]);
const getDepartmentOptions = async () => {
  // Get the department options
  let tmp_options = await SessionUser.objects.department_variables.columns.department_id.options();
  tmp_options = tmp_options.map((option) => {
    return {
      label: option.label || option.name,
      value: option.value || option.id,
      icon: 'fas fa-building',
      children: [],
      hidden: !SessionUser.canAccessDepartment(option.value || option.id)
    };
  });
  departmentOptions.value = tmp_options;
};

getDepartmentOptions();
</script>

<template>
  <div>
    <!-- If the customer has a fixed price -->
      <ConfigurationCategory
          :module="SessionUser.objects.collectedOrderInvoices.meta.title"
          :title="SessionUser.objects.global.language.payment.method"
          :subtitle="SessionUser.objects.global.language.default + ' ' + SessionUser.objects.departments.meta.labels.single"
          icon="fas fa-tag"
        >
          <template #default>
            <!--
            <div class="notification is-warning">
              <p class="has-text-weight-bold">Denne funktion er endnu ikke implementeret i fakturering</p>
              <p>Du kan nu oprette fast pris aftaler, men disse vil endnu ikke blive anvendt i systemet.</p>
            </div>
            -->
            <!-- If the customer has a fixed price -->
            <template v-if="hasDefaultDepartment">
              <ConfigurationSelect
                  :icon="SessionUser.objects.departments.meta.icon"
                  :disabled="true"
                  :title="SessionUser.objects.departments.meta.labels.single"
                  v-bind:value="department_value"
                  :options="departmentOptions"
                  :on-select="(value) => {
                    department_value = value;
                  }"
                />
            </template>
            <!-- If the customer does not have a fixed price -->
            <template v-else>
              <ConfigurationSelect
                  :icon="SessionUser.objects.departments.meta.icon"
                  :title="SessionUser.objects.departments.meta.labels.single"
                  v-bind:value="department_value"
                  v-bind:on-select="(value) => {
                    department_value = value;
                  }"
                  :options="departmentOptions"
                />
            </template>
            <!-- Buttons -->
            <div class="buttons mt-5">
              <!-- If the customer has a fixed price -->
              <template v-if="hasDefaultDepartment">
                <button class="button is-fullwidth is-danger is-light" @click="onClickDelete">{{ SessionUser.objects.global.language.delete }} {{ SessionUser.objects.global.language.default.toLowerCase() }} {{ SessionUser.objects.departments.meta.labels.single.toLowerCase() }}</button>
              </template>
              <!-- If the customer does not have a fixed price -->
              <template v-else>
                <button class="button is-fullwidth" @click="onClickSubmit" v-bind:disabled="!isInputValid">{{ SessionUser.objects.global.language.add }} {{ SessionUser.objects.global.language.default.toLowerCase() }} {{ SessionUser.objects.departments.meta.labels.single.toLowerCase() }}</button>
              </template>
            </div>
          </template>
      </ConfigurationCategory>
  </div>
</template>

<style scoped>

</style>