<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý chi nhánh</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý chi nhánh</li>
                </ol>
            </div>
        </div>
        <div class="row row-sm">

            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
                <div class="card card-search shadow-none">
                    <form class="card-body" @submit.prevent="search">
                        <div class="row">
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Từ khóa</label>
                                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword"
                                    class="form-control" placeholder="từ khóa...">
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Ngày tạo</label>
                                <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false" range
                                    multi-calendars auto-apply :format="format" @update:model-value="handleDate">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Trạng thái</label>
                                <v-select label="Name" :options="statuses"
                                    v-model="searchModel.Search.PredicateObject.Status"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>

                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Chi nhánh / khu vực cha</label>
                                <v-select label="Label" :options="parents"
                                    v-model="searchModel.Search.PredicateObject.ParentId"
                                    :reduce="(option) => option.Id">
                                    <template v-slot:no-options="{ search, searching }">
                                        <template v-if="searching">
                                            Không có kết quả cho <em>{{ search }}</em>.
                                        </template>
                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                    </template>
                                </v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Loại chi nhánh</label>
                                <v-select label="Name" :options="agencyTypes"
                                    v-model="searchModel.Search.PredicateObject.AgencyType"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>

                        </div>
                        <div class="row">
                            <div class="col-lg mb-3">
                                <button type="submit" class="btn btn-dark" :disabled="loading">
                                    <i v-show="!loading" class="fe fe-search"></i>
                                    <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                                    <span>Tìm kiếm</span>
                                </button>
                            </div>
                        </div>

                    </form>
                </div>


                <div class="card card-table shadow-none">
                    <div class="card-body card-table-body">
                        <div class="d-flex flex-row justify-content-between mg-b-10">
                            <button @click="fnCreateOrUpdate(0)" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1">
                                <i class="fe fe-plus me-2"></i>
                                Tạo chi nhánh
                            </button>
                            <!-- <button type="button" class="btn btn-outline-success mx-2 button-icon mb-1">
                                <i class="fe fe-download me-2"></i>Xuất excel</button> -->
                        </div>
                        <div class="table-responsive border-top mg-b-10">
                            <table class="table table-vcenter mb-0" style="min-height:300px">
                                <thead>
                                    <tr>
                                        <th class="wd-lg-12p min-width-1"><span>Tên chi nhánh</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Thông tin</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Người đại diện</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Thứ tự</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Trạng thái</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Loại chi nhánh</span></th>
                                        <th class="wd-lg-8p"></th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="7" class="tx-semibold text-center text-default">
                                            <span class="spinner-border spinner-border-sm"></span>
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && items.length <= 0">
                                    <tr>
                                        <td colspan="7" class="tx-semibold text-center text-danger">
                                            Không tìm thấy bản ghi nào!
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && items.length > 0">

                                    <tr v-for="item in items" :key="item.Id">

                                        <td class="text-wrap align-top">

                                            <div>
                                                {{ item.Name }}
                                            </div>
                                            <div>
                                                <small>Mã: <b>{{ item.Code }}</b></small>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.Description }}
                                            <div> <small>Địa chỉ: <b>{{ item.Address }}, {{ item.Ward }}, {{
                                                item.District
                                                        }}, {{ item.City }}</b></small></div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <div> {{ item.RepName }}</div>
                                            <div> <small>SĐT: <b>{{ item.RepPhone }}</b></small> </div>
                                            <div> <small>Địa chỉ: <b>{{ item.RepAddress }}</b></small></div>
                                        </td>

                                        <td class="text-wrap align-top">
                                            {{ item.CreatedTime }}
                                        </td>

                                        <td class="text-wrap align-top">
                                            {{ item.DisplayOrder }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span class="tag" :class="getTagClass(item.Status)">
                                                {{ item.StatusName }}
                                            </span>

                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.AgencyTypeName }}

                                        </td>
                                        <td class="align-top pt-2">

                                            <button type="button" data-bs-toggle="dropdown"
                                                class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm"
                                                aria-expanded="false"><i class="fas fa-cog"></i> Quản lý
                                            </button>
                                            <div class="dropdown-menu dropdown-menu-arrow">
                                                <a @click="fnCreateOrUpdate(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                                    <span class="mg-l-6">Cập nhật</span>
                                                </a>
                                                <a @click="fnManageCoverage(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-map"></i>
                                                    <span class="mg-l-6">Quản lý vùng phủ</span>
                                                </a>
                                                <a @click="updateStatus(item.Id, 3, 'Đang hoạt động')"
                                                    v-if="item.Status == 1 || item.Status == 4 || item.Status == 5"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-check"></i>
                                                    <span class="mg-l-6">Kích hoạt</span></a>
                                                <a @click="updateStatus(item.Id, 4, 'Khóa 1 chiều')"
                                                    v-if="item.Status == 1 || item.Status == 3 || item.Status == 5"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-lock"></i>
                                                    <span class="mg-l-6">Khóa 1 chiều</span></a>
                                                <a @click="updateStatus(item.Id, 5, 'Dừng hoạt động')"
                                                    v-if="item.Status == 1 || item.Status == 3 || item.Status == 4"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-power"></i>
                                                    <span class="mg-l-6">Dừng hoạt động</span></a>
                                                <div class="dropdown-divider"></div>
                                                <a @click="fnDelete(item.Id)"
                                                    class="dropdown-item text-danger" href="javascript:void(0);">
                                                    <i class="fe fe-trash"></i>
                                                    <span class="mg-l-6">Xóa</span>
                                                </a>

                                            </div>
                                        </td>
                                    </tr>

                                </tbody>
                            </table>
                        </div>
                        <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="PageSizeChanged"
                            @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total"
                            :TotalCurrent="items.length">
                        </pager>
                    </div>
                </div>
            </div><!-- COL END -->
        </div>
        <LadaDialog :visible="modalControl.CreateOrUpdate">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title" v-if="selectedId <= 0">Tạo chi nhánh</h5>
                    <h5 class="modal-title" v-if="selectedId > 0">Cập nhật chi nhánh</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate @cancel="closeModal" :id="selectedId"></CreateOrUpdate>
            </template>
        </LadaDialog>

        <LadaDialog :visible="modalControl.Coverage" variant="modal-xl">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Quản lý vùng phủ chi nhánh</h5>
                    <button @click="closeCoverageModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <Coverage @cancel="closeCoverageModal" :agencyId="selectedAgencyId"></Coverage>
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
//#region Imports
//#endregion

//#region Imports
import { ref, reactive, onMounted } from 'vue'
import agencyService from "@/services/agencyService";
//#endregion


//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import CreateOrUpdate from './components/CreateOrUpdate.vue';
import Coverage from './coverage.vue';

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

//#region Modals
const modalControl = reactive({
    CreateOrUpdate: false,
    Coverage: false
});
function closeModal() {
    modalControl.CreateOrUpdate = false;
    loadData();
}
function closeCoverageModal() {
    modalControl.Coverage = false;
    loadData();
}
//#endregion

//#region Actions
const selectedId = ref(0);
async function fnCreateOrUpdate(id) {
    selectedId.value = id;
    modalControl.CreateOrUpdate = true;
}

const selectedAgencyId = ref(0);
async function fnManageCoverage(agencyId) {
    selectedAgencyId.value = agencyId;
    modalControl.Coverage = true;
}


async function fnDelete(id) {
    var cf = confirm("Bạn chắc chắn muốn xóa chi nhánh này? Thao tác này không thể hoàn tác!");
    if (cf) {
        loading.value = true;
        var deleteResult = await agencyService.delete(id);
        if (deleteResult != null && deleteResult.Result === 1) {
            toast.success('Xóa chi nhánh thành công!');
        } else {
            toast.error('Xóa thất bại: ' + (deleteResult?.Message ?? 'Lỗi không xác định'));
        }
        loading.value = false;
        search();
    }
}

async function updateStatus(id, newStatus, newStatusName) {
    var cf = confirm("Bạn chắc chắn muốn cập nhật trạng thái: " + newStatusName + "?");
    if (cf) {
        loading.value = true;
        var statusModel = {
            Id: id,
            NewStatus: newStatus
        };
        var statusResult = await agencyService.updateStatus(statusModel);
        if (statusResult != null && statusResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + statusResult.Message);
        }
        loading.value = false;
        search();
    }
}
async function unlock(id) {
    var cf = confirm("Bạn chắc chắn muốn mở khóa?");
    if (cf) {
        loading.value = true;
        var lockResult = await menuService.unlock(id);

        if (lockResult != null && lockResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + lockResult.Message);
        }
        loading.value = false;
        search();
    }
}
async function deleteMenu(id) {
    var cf = confirm("Bạn chắc chắn muốn xóa?");
    if (cf) {
        loading.value = true;
        var lockResult = await menuService.delete(id);

        if (lockResult != null && lockResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + lockResult.Message);
        }
        loading.value = false;
        search();
    }
}

//#endregion


//#region SEARCH
const statuses = [
    { Id: 1, Name: 'Chờ kích hoạt' },
    { Id: 3, Name: 'Đang hoạt động' },
    { Id: 4, Name: 'Khóa 1 chiều' },
    { Id: 5, Name: 'Dừng hoạt động' }
];
const agencyTypes = [
    { Id: 1, Name: 'Phòng ban của LADA' },
    { Id: 2, Name: 'Chi nhánh nhượng quyền' },
    { Id: 3, Name: 'Chi nhánh của LADA' }
];


const parents = reactive([]);

async function getParents() {
    parents.splice(0, parents.length);
    var parentResult = await agencyService.getTree("");
    if (parentResult != null && parentResult.length > 0) {
        parentResult.forEach(agency => {
            parents.push(agency);
        });
    }
}

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
            Status: null,

        }
    }
});
const items = reactive([]);
const loading = ref(false);

const date = ref();
const createDatePicker = ref(DatepickerInstance);

const statusOptions = reactive([
    { Id: null, Name: "Tất cả" }, { Id: false, Name: "Đang hoạt động" }, { Id: true, Name: "Bị khóa" }
]);

const format = (dates) => {
    let start = dates[0];
    let end = dates[1];
    const dayStart = start.getDate();
    const monthStart = start.getMonth() + 1;
    const yearStart = start.getFullYear();
    const dayEnd = end.getDate();
    const monthEnd = end.getMonth() + 1;
    const yearEnd = end.getFullYear();

    return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`;
}

async function onChangeDate(newDates) {
    console.log(newDates);
    date.value = newDates;
    createDatePicker.value.closeMenu();
    handleDate(newDates)
}

function handleDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.CreatedStart = modelData[0];
        searchModel.Search.PredicateObject.CreatedEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.CreatedStart = null;
        searchModel.Search.PredicateObject.CreatedEnd = null;
    }
}

const ctrlPager = ref();
async function search() {
    searchModel.Pagination.PageIndex = 1;
    ctrlPager.value.Refresh();
    loadData();
}


// functions that mutate state and trigger updates
async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await agencyService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(menu => {
            items.push(menu);
        });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
    loading.value = false;
}


function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    loadData();
}
function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    loadData();
}

//#endregion


//#region Utilities
function getTagClass(statusId) {
    switch (statusId) {
        case 1:
            return 'tag-default'

        case 3:
            return 'tag-green';

        case 4:
            return 'tag-yellow';

        case 5:
            return 'tag-red';

        default:
            return 'tag-default';
    }
}
//#endregion

onMounted(async () => {
    await getParents();
    await search();
})

</script>
