<template>
    <div>
        <loader class="m-3" v-if="loading"></loader>
        <Form v-show="!loading" class="row" @submit="onSubmit" :validation-schema="schema"
            v-slot="{ errors, isSubmitting }">
            <div class="col-lg-12">
                <PackageAdd @submit="addPackage" ref="addPackageRef"></PackageAdd>
                <div class="table-responsive">
                    <table class="table mg-b-0 text-md-nowrap">
                        <thead>
                            <tr>
                                <th class="wd-10p">Ảnh</th>
                                <th class="wd-30p">Hàng hóa</th>
                                <th class="wd-20p">Trọng lượng đơn vị</th>
                                <th class="wd-10p">Số kiện</th>
                                <th class="wd-20p">Trọng lượng tính cước</th>
                                <th class="wd-10p"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in items">
                                <th scope="row">
                                    <img :src="item.Picture">
                                </th>
                                <td>
                                    <p>{{ item.Name }}</p>
                                    <small><b>Ghi chú:</b> <i>{{ item.Note }}</i></small>
                                </td>
                                <td>
                                    <div class="d-flex">
                                        <i class="fas fa-weight mg-r-5 mg-t-2"></i>
                                        <span>{{ item.Weight }}</span>
                                        <span class="mg-l-5">(kg)</span>
                                    </div>
                                    <div class="d-flex mg-t-10">
                                        <i class="fas fa-text-height mg-r-5 mg-t-2"></i>
                                        <div>
                                            <div>{{ item.Length }} x {{ item.Width }} x {{ item.Height }} (cm)</div>
                                            <div class="mg-t-5">
                                                <small class="text-muted">
                                                    ({{ item.Length }} x {{ item.Width }} x {{ item.Height }} )
                                                    ÷ 6000 = {{ (item.Length * item.Width * item.Height /
                                                        6000).toFixed(2) }} kg
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td>{{ item.Quantity }}</td>
                                <td>{{ item.SubTotalWeight }} kg</td>
                                <td>
                                    <div class="d-flex">
                                        <a class="btn btn-sm tx-14" href="javascript:void(0)"
                                            @click="editPackage(item)">
                                            <i class="fa fa-edit"></i>
                                        </a>
                                        <a class="btn btn-sm tx-14" href="javascript:void(0)"
                                            @click="removePackage(item.Id)">
                                            <i class="fa fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="items.length > 0">
                                <td :colspan="colspan - 3" class="text-end">
                                    TỔNG
                                </td>
                                <td>
                                    {{ totalPackages }} kiện
                                </td>
                                <td colspan="2">
                                    {{ totalWeight }} kg
                                </td>
                            </tr>
                            <tr v-if="items.length <= 0">
                                <td :colspan="colspan">
                                    <Empty message="Hiện chưa có bản ghi nào" :border="false"></Empty>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer">
                <div class="row">
                    <div class="col-12 ">
                        <div class="d-flex">
                            <button @click="cancel" type="button" class="btn btn-main-default">
                                Bỏ qua
                            </button>
                            <button type="submit" class="btn ms-auto btn-main-primary" :disabled="isSubmitting">
                                <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                                Xác nhận
                            </button>
                        </div>
                    </div>
                </div>
            </div>

        </Form>


    </div>

</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';


import { Empty } from '@/components';
import PackageAdd from "@/views/orders/shared/updatePackages/updatePackageCru.vue";

//#region Services
import orderPackageService from "@/services/orderPackageService";
//#endregion

const props = defineProps({
    orderId: Number
});

const emit = defineEmits(['cancel']);

//#region Validations
const schema = Yup.object().shape({
    // Name: Yup.string().required('Họ và tên không để trống'),
    // PhoneNumber1: Yup.string().required('Số điện thoại không để trống'),
    // Address1: Yup.string().required('Địa chỉ không để trống'),
    // //WardId: Yup.string().required('Vui lòng nhập đầy đủ tỉnh, quận, phường'),
});
//#endregion

//#region Toast
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion


//#region DATA
const loading = ref(false);
var addPackageRef = ref(null);

var items = reactive([]);
//var totalWeight = ref(0);
const colspan = 6;
//#endregion

//#region Methods

async function getByOrderId() {
    loading.value = true;
    var result = await orderPackageService.getByOrderId(props.orderId);
    if (result != null && result.OrderId > 0) {
        if (result.Packages != null) {
            result.Packages.forEach(item => items.push(item));
        }
    }

    loading.value = false;
}


async function addPackage(packageModel) {
    if (packageModel.Id <= 0) {
        var newpackage = {};
        Object.assign(newpackage, packageModel);
        items.push(newpackage);
    } else {
        let existPackage = items.find(item => item.Id === packageModel.Id);
        if (existPackage) {
            Object.assign(existPackage, packageModel);
        }
    }

}

async function removePackage(id) {
    let index = items.findIndex(item => item.Id === id);
    if (index > -1) {
        items.splice(index, 1);
    }
}

async function editPackage(item) {
    addPackageRef.value.init(item);
}



async function onSubmit() {
    loading.value = true;

    var updatePackageModel = {
        OrderId: props.orderId,
        Packages: items
    }

    console.log(updatePackageModel);

    loading.value = true;
    var result = await orderPackageService.update(updatePackageModel);
    if (result != null && result.Result === 1) {
        toast.success('Thành công!');
        cancel();

    } else {
        toast.error('Thất bại: ' + result.Message);
    }
    loading.value = false;


}


//#endregion

const totalPackages = computed(() => {
    var rs = 0;
    if (items != null && items.length > 0) {
        items.forEach(packageItem => {
            rs += parseInt(packageItem.Quantity || 0);
        });
    }
    return rs;
})

const totalWeight = computed(() => {
    var rs = 0;
    if (items != null && items.length > 0) {
        items.forEach(packageItem => {
            rs += parseFloat(packageItem.SubTotalWeight || 0);
        });
    }
    return Math.round(rs);
})



function cancel() {
    emit('cancel');
}


//#region Events
onMounted(async () => {
    if (props.orderId != null && props.orderId > 0) {
        await getByOrderId();
    } else {
        alert("Yêu cầu không hợp lệ");
        cancel();
    }
})
//#endregion

</script>

<style scoped>
.section-icon {
    display: flex;
    text-align: center;
}

.section-icon i {
    width: 3rem;
    font-size: 18px;
    line-height: 3rem;
    height: 3rem;
    background-color: #ffcb05;
    color: #ffffff;
    border-radius: 50%;
}
</style>