import { tools } from '../../store/Modules/tools'
import { CCardState } from '../CCardState'
import { CCopyBtn } from '../CCopyBtn'

import type { IOrder} from '@src/model';
import { IOperators, IProduct } from '@src/model'
import type { PropType} from 'vue';
import { defineComponent, toRef, ref, watch, onMounted } from 'vue'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { useProducts } from '@store/Products'
import { useI18n } from 'vue-i18n'
import { useQuasar } from 'quasar'
import { loadRouteLocation } from 'vue-router'

export default defineComponent({
  name: 'CSingleCart',
  props: {
    order: {
      type: Object as PropType<IOrder>,
      required: true,
    },
    editmode: {
      type: Boolean,
      required: false,
      default: false,
    },
    showall: {
      type: Boolean,
      required: false,
      default: false,
    },
    idOrdersCart: {
      type: String,
      required: false,
      default: '',
    },
    nomodif: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  components: { CTitleBanner, CCardState, CCopyBtn },
  setup(props, { emit }) {
    const products = useProducts()
    const order = toRef(props, 'order')
    const { t } = useI18n()

    const $q = useQuasar()

    const orderQuantity = ref(<number | undefined>undefined);
    const weight = ref(<number | undefined>undefined);
    const price = ref(<number | undefined>undefined);
    const orderQuantityPreordered = ref(<number | undefined>undefined);
    const orderTotalPriceProduct = ref(<number | undefined>undefined);

    const enableQty = ref(false)
    const endload = ref(false)
    const enableQtyPreordered = ref(false)
    const enableChangeTotalPrice = ref(false)

    watch(orderQuantity, (newValue: any) => {
      if (!newValue)
        order.value.quantity = 0
      else
        order.value.quantity = parseFloat(newValue);

      enableChangeTotalPrice.value = false
    });

    watch(weight, (newValue: any) => {
      if (order.value.product) {
        if (!newValue)
          order.value.product.productInfo.weight = 0
        else
          order.value.product.productInfo.weight = parseFloat(newValue);
      }
      enableChangeTotalPrice.value = false
    });

    watch(price, (newValue: any) => {
      if (order.value) {
        if (!newValue)
          order.value.price = 0
        else
          order.value.price = parseFloat(newValue);
      }
      enableChangeTotalPrice.value = false
    });

    watch(orderQuantityPreordered, (newValue: any) => {
      if (!newValue)
        order.value.quantitypreordered = 0
      else
        order.value.quantitypreordered = parseFloat(newValue);

      enableChangeTotalPrice.value = false
    });

    watch(orderTotalPriceProduct, (newValue: any) => {
      if (!newValue)
        order.value.TotalPriceProduct = 0
      else
        order.value.TotalPriceProduct = parseFloat(newValue);
    });

    watch(() => props.order.TotalPriceProduct, (newValue: any) => {
      if (!newValue)
        orderTotalPriceProduct.value = 0
      else
        orderTotalPriceProduct.value = parseFloat(newValue);
    });

    function myimgclass() {
      if (props.showall) {
        return 'imgNormal'
      } else {
        return 'imgSmall'
      }
    }

    async function addsubqty(addqty: boolean, subqty: boolean) {
      if (products.isQtyAvailableByOrder(props.order)) {
        if (addqty) {
          if (props.order.quantity >= 100)
            return false
        }

        if (subqty) {
          if (props.order.quantity === 0)
            return false
        }
      } else {

        if (products.isInPreorderByOrder(props.order)) {
          if (addqty) {
            if (props.order.quantitypreordered >= 100)
              return false
          }

          if (subqty) {
            if (props.order.quantitypreordered === 0)
              return false
          }
        }
      }

      return await products.addSubQtyToItem({
        addqty,
        subqty,
        order: props.order,
      }).then((res: any) => {
        if (res.risult) {
          if (res.myord) {
            order.value.quantity = res.myord.quantity
            order.value.quantitypreordered = res.myord.quantitypreordered
          }
        }
      })
    }

    function isApplicatoSconto() {
      const totalipotetico = order.value.product!.price * (order.value.quantity + order.value.quantitypreordered)
      if (totalipotetico.toFixed(2) > order.value.TotalPriceProduct.toFixed(2)) {
        return true
      }
      return false
    }

    function removeFromCard() {
      products.removeFromCart({ order: order.value })

    }

    async function updateOrder(paramstoupdate: any) {
      endload.value = false
      if (enableChangeTotalPrice.value) {
        paramstoupdate = { ...paramstoupdate, TotalPriceProduct: order.value.TotalPriceProduct }
      }
      const myOrdersCart = await products.updateOrderByOrder(props.idOrdersCart, order.value._id, paramstoupdate)
      emit('update')
      mounted()
    }

    function getRisparmio(): string {
      return ((order.value.product!.price * order.value.quantity) - order.value.TotalPriceProduct).toFixed(2)
    }

    function mounted() {
      endload.value = false
      weight.value = props.order.product?.productInfo.weight
      price.value = props.order.price
      if (props.order.quantity !== 0) {
        orderQuantity.value = props.order.quantity
        enableQty.value = true
      }
      if (props.order.quantitypreordered !== 0) {
        orderQuantityPreordered.value = props.order.quantitypreordered
        enableQtyPreordered.value = true
      }

      orderTotalPriceProduct.value = props.order.TotalPriceProduct
      endload.value = true
    }

    function changeTotalPrice() {
      console.log('changeTotalPrice')
      enableChangeTotalPrice.value = true
    }

    onMounted(mounted)

    return {
      myimgclass,
      addsubqty,
      removeFromCard,
      isApplicatoSconto,
      getRisparmio,
      tools,
      products,
      t,
      updateOrder,
      orderQuantity,
      weight,
      price,
      orderQuantityPreordered,
      enableQty,
      enableQtyPreordered,
      changeTotalPrice,
      orderTotalPriceProduct,
      endload,
    }
  },
})
