<template>
    <div class="row">
        <div class="col-lg-12" v-if="loading">
            <div class="card card-search shadow-none">
                <div class="card-body" @submit.prevent="addWeightRange">
                    <div class="tx-semibold text-center text-default">
                        <span class="spinner-border spinner-border-sm"></span>
                    </div>

                </div>
            </div>
        </div>
        <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin" v-if="!loading">

            <div class="card card-search shadow-none">
                <form class="card-body" @submit.prevent="addWeightRange">
                    <div class="row">
                        <div class="col-12 mb-3">
                            <h5>{{ getTitle() }}</h5>
                        </div>
                        <div class="col-12 mb-3">
                            Khoảng trọng lượng
                        </div>
                        <div class="col-2 form-group">

                            <input placeholder="Lớn hơn hoặc bằng" class="form-control" type="text" v-model="weightMin" />
                        </div>

                        <div class="col-2 form-group">

                            <input placeholder="Nhỏ hơn" class="form-control" type="text" v-model="weightMax" />
                        </div>
                        <div class="col-2 form-group">

                            <button class="btn btn-primary" type="submit">
                                <i class="fe fe-plus"></i>
                                <span>Thêm</span>
                            </button>

                        </div>
                    </div>
                </form>
            </div>


            <div class="card card-table shadow-none">
                <div class="card-body card-table-body">
                    <div class="col-12 text-right mb-3">
                        <div class="d-flex flex-row justify-content-between">

                            <label class="ckbox">
                                <input v-model="editMode" type="checkbox" class="mb-2">
                                <span>Chế độ chỉnh sửa</span>
                            </label>

                            <button class="btn btn-success" type="submit">
                                <i class="fe fe-download"></i>
                                <span class="pl-2"> Xuất Excel</span>
                            </button>
                        </div>

                    </div>


                    <form @submit.prevent="save" class="table-responsive border-top mg-b-10">
                        <table class="table table-bordered table-vcenter mb-0" style="min-height:300px">
                            <thead>
                                <tr>
                                    <th style="min-width: 100px;">Tuyến</th>
                                    <th style="min-width: 150px;">Khoảng cách</th>
                                    <th v-for="(weight, index) in weightRanges" :key="index">
                                        {{ weight.MinWeight }} => {{ weight.MaxWeight }} kg

                                        <a v-if="editMode" class="tx-15" @click="deleteWeightRange(index)"
                                            href="javascript:void(0);">
                                            <i class="fe fe-trash"></i>
                                        </a>
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(route, routeIndex) in routes" :key="routeIndex">
                                    <td>{{ route.Name }}</td>
                                    <td>{{ route.Description }}</td>
                                    <td v-for="(weight, weightIndex) in weightRanges" :key="weightIndex">
                                        <input v-if="editMode" type="number" class="form-control"
                                            :value="findPriceValue(route, weight.MinWeight, weight.MaxWeight)"
                                            @input="(event) => updatePriceValue(route, weight.MinWeight, weight.MaxWeight, event.target.value)">
                                        <label v-if="!editMode">
                                            {{ vueNumberFormat(findPriceValue(route, weight.MinWeight,
                                                weight.MaxWeight),
                                                { precision: 0, prefix: '', suffix: ' đ', decimal: ',', thousand: '.' }) }}
                                        </label>

                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <div class="col-12 text-right mt-3" v-if="editMode">
                            <div class="d-flex flex-row-reverse">
                                <button class="btn btn-primary" type="submit">
                                    <i class="fe fe-save"></i>
                                    <span class="pd-l-5">Lưu</span>
                                </button>
                            </div>

                        </div>


                    </form>

                </div>
            </div>
        </div><!-- COL END -->
    </div>
</template>
<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue'

//#endregion

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


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


//#endregion

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

const getTitle = () => {

    switch (parseInt(props.priceType)) {
        case 1:
            return "Giá cố định trong khoảng"
        case 2:
            return "Bước giá trong khoảng"
        case 3:
            return "Giá xe máy";
        default:
            return "Không xác định";
    }
}


const loading = ref(false);

const routes = reactive([]);
const priceList = reactive([]);
const weightRanges = reactive([]);

const weightMin = ref('');
const weightMax = ref('');

const editMode = ref(false);

//#region Client Actions
const findPriceValue = (route, minWeight, maxWeight) => {
    const priceDetail = priceList.find(detail => detail.RouteId === route.Id && detail.MinWeight === minWeight && detail.MaxWeight === maxWeight);
    return priceDetail ? priceDetail.Value : '';
};
const updatePriceValue = (route, minWeight, maxWeight, value) => {
    const priceDetail = priceList.find(detail => detail.RouteId === route.Id && detail.MinWeight === minWeight && detail.MaxWeight === maxWeight);
    if (priceDetail) {
        priceDetail.Value = parseInt(value);
    }
};

const addWeightRange = () => {
    if (weightMin.value.trim() !== '' && weightMax.value.trim() !== '') {
        const min = parseInt(weightMin.value);
        const max = parseInt(weightMax.value);
        if (min < max) {
            routes.forEach(routeItem => {
                priceList.push({
                    Id: 0,
                    RouteId: routeItem.Id,
                    MinWeight: min,
                    MaxWeight: max,
                    Value: 0,
                    PriceType: props.priceType
                });
            });
            weightRanges.push({ MinWeight: min, MaxWeight: max });
        }
    }
    weightMin.value = '';
    weightMax.value = '';
};

const deleteWeightRange = (index) => {
    var weightRange = weightRanges[index];
    var tmpPriceList = [];
    priceList.forEach((priceItem, priceIndex) => {
        if (priceItem.MinWeight != weightRange.MinWeight || priceItem.MaxWeight != weightRange.MaxWeight) {
            tmpPriceList.push(priceItem);
        }
    });
    priceList.splice(0, priceList.length);
    tmpPriceList.forEach((priceItem) => {
        priceList.push(priceItem);
    });
    weightRanges.splice(index, 1);

};

//#endregion




const init = async () => {
    routes.splice(0, routes.length);
    priceList.splice(0, priceList.length);
    weightRanges.splice(0, weightRanges.length);
    loading.value = true;
    var model = await priceService.getDefaultPriceList(props.priceType);
    if (model != null && model.Routes != null && model.Routes.length > 0) {
        model.Routes.forEach(routeItem => {
            var min = routeItem.DistanceMin > 0 ? routeItem.DistanceMin / 1000 + " - " : "0 - ";
            var max = routeItem.DistanceMax > 0 ? routeItem.DistanceMax / 1000 + " km" : "0 km";
            var des = min + max;
            routes.push({
                Id: routeItem.Id,
                Name: routeItem.Name,
                Description: des
            })
        });
        model.PriceList.forEach(priceDetailModel => {
            var priceModel = {
                Id: priceDetailModel.Id,
                RouteId: priceDetailModel.RouteId,
                MinWeight: priceDetailModel.MinWeight / 1000,
                MaxWeight: priceDetailModel.MaxWeight / 1000,
                Value: priceDetailModel.Value
            }
            priceList.push(priceModel);
            var addWeightRange = true;
            weightRanges.forEach(weightRangeItem => {
                if (weightRangeItem.MinWeight == priceModel.MinWeight && weightRangeItem.MaxWeight == priceModel.MaxWeight) {
                    addWeightRange = false;
                }
            });
            if (addWeightRange) {
                weightRanges.push({ MinWeight: priceModel.MinWeight, MaxWeight: priceModel.MaxWeight });
            }

        });
    }
    loading.value = false;
};



const save = async () => {

    //console.log(priceList); return;

    loading.value = true;
    var result = null;
    var model = {
        PriceList: priceList,
        PriceType: props.priceType
    };
    result = await priceService.updateDefaultPriceList(model);

    if (result != null && result.Result === 1) {
        toast.success('Thành công!');

    } else {
        if (result.ErrorList != null && result.ErrorList.length > 0) {
            toast.error('Thất bại: ' + result.ErrorList.join("\n"));
        } else {
            toast.error('Thất bại: ' + result.Message);
        }

    }
    loading.value = false;
    await init();

    //updateDefaultPriceList
}




onMounted(async () => {
    console.log('vao day');
    await init();
})

</script>