<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Danh mục bảo trì</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">Danh mục bảo trì</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>Biển số</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 @update:model-value="handleCreateTime" v-model="createdTime"
                                    :enable-time-picker="false" range multi-calendars auto-apply :format="format"
                                    placeholder="Ngày tạo">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeCreatedTime"></DateRangeSidebar>
                                    </template>
                                </VueDatePicker>
                            </div>
                            <div class="col-lg-3 col-md-3 mb-3">
                                <label>Ngày sửa chữa cuối</label>
                                <VueDatePicker @update:model-value="handleLastRepairTime" v-model="lastRepairTime"
                                    :enable-time-picker="false" range multi-calendars auto-apply :format="format"
                                    placeholder="Ngày sửa chữa cuối">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeLastRepairTime"></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="statusOptions"
                                    v-model="searchModel.Search.PredicateObject.Status"
                                    :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="truckMaintModalOpen(new Object({ Id: 0 }), 0)" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1"><i
                                    class="fe fe-plus me-2"></i>Thêm
                                mới</button>
                            <button type="button" class="btn btn-outline-warning mx-2 button-icon mb-1"
                                data-bs-toggle="offcanvas" @click="truckMaintDrawer" data-bs-target="#truckMaintDrawer">
                                <i class="fe fe-codepen me-2"></i>Thuộc tính bảo trì</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>Biển số</span></th>
                                        <th class="wd-lg-12p min-width-1"><span>Chi nhánh</span></th>
                                        <th class="wd-lg-12p min-width-1"><span>Người lái</span></th>
                                        <th class="wd-lg-10p min-width-2"><span>Thời gian bảo trì</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Tiêu đề</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Garage</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">
                                            {{ item.TruckLicensePlate }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.AgencyName }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span>{{ item.FullName }}</span><span v-if="item.UserName">
                                                ({{ item.UserName }})</span>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span>{{ item.StartTimeStr }}</span><span v-if="item.EndTimeStr"> -
                                            </span><span>{{
                                                item.EndTimeStr }}</span>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span>{{ item.Title }}</span>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span>{{ item.GarageName }}</span><span v-if="item.GarageAddress">
                                                ({{ item.GarageAddress }})</span>
                                        </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="truckMaintModalOpen(item, 1)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                                    <span class="mg-l-6">Xem</span>
                                                </a>
                                                <a @click="truckMaintModalOpen(item, 2)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-trash"></i>
                                                    <span class="mg-l-6">Sửa</span></a>

                                                <a @click="truckMaintDelete(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-lock"></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="truckOpenModalFlag">
            <template #header>
                <div class="modal-header">
                    <div v-if="truckMaintViewFlag == 1">
                        <h5 class="modal-title">Xem chi tiết thông tin bảo trì</h5>
                    </div>
                    <div v-else>
                        <h5 class="modal-title" v-if="truckId <= 0">Thêm thông tin bảo trì</h5>
                        <h5 class="modal-title" v-else>Cập nhật thông tin bảo trì</h5>
                    </div>

                    <button @click="truckMaintModalClose" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <Form @submit="fnCreateTruckMaintenance" v-slot="{ errors, isSubmitting }" class="row">
                    <div class="col-lg-12 mb-3">
                        <div class="row mb-2">
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Chi nhánh trực thuộc:</label>
                                    <v-select :disabled="(truckMaintViewFlag == 1)" v-model="truckMaintModel.AgencyId"
                                        label="Name" :options="agencies" :reduce="(option) => option.Id"
                                        @search="getAgencies" @option:selected="getTruckByAgencyId">
                                        <template v-slot:no-options="{ search, searching }">
                                            <template v-if="searching">
                                                Không có kết quả cho <b>{{ search }}</b>.
                                            </template>
                                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                        </template>
                                    </v-select>
                                    <Field v-model="truckMaintModel.AgencyId" name="TruckAgency" type="hidden" />
                                    <ErrorMessage class="invalid-error" name="TruckAgency" />
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Biển số: </label>
                                    <v-select
                                        :disabled="truckMaintViewFlag == 1 || truckMaintModel.AgencyId <= 0 || truckMaintModel.AgencyId == undefined || !truckMaintModel.AgencyId"
                                        v-model="truckMaintModel.TruckId" label="LicensePlate" :options="truckes"
                                        :reduce="(option) => option.Id" @option:selected="selectTruckLicensePlate">
                                        <template v-slot:no-options="{ search, searching }">
                                            <template v-if="searching">
                                                Không có kết quả cho <b>{{ search }}</b>.
                                            </template>
                                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                        </template>
                                    </v-select>
                                    <Field v-model="truckMaintModel.TruckId" name="LicensePlate" type="hidden" />
                                    <ErrorMessage class="invalid-error" name="LicensePlate" />
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Người đi bảo trì</label>
                                    <v-select v-model="truckMaintModel.UserId" label="FullName" :options="users"
                                        :disabled="truckMaintViewFlag == 1 || truckMaintModel.AgencyId <= 0 || !truckMaintModel.AgencyId"
                                        :reduce="(option) => option.Id" @search="getUserByAgencyId">
                                        <template v-slot:no-options="{ search, searching }">
                                            <template v-if="searching">
                                                Không có kết quả cho <b>{{ search }}</b>.
                                            </template>
                                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                        </template>
                                    </v-select>
                                    <Field v-model="truckMaintModel.UserId" name="UserId" type="hidden" />
                                    <ErrorMessage class="invalid-error" name="UserId" />
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Tiêu đề</label>
                                    <Field v-model="truckMaintModel.Title" name="Title" type="text" class="form-control"
                                        :disabled="(truckMaintViewFlag == 1)" placeholder="Tiêu đề thông tin bảo trì"
                                        :class="{ 'is-invalid': errors.Title }" />
                                    <div class="invalid-feedback">{{ errors.Title }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Mô tả thông tin</label>
                                    <Field as="textarea" v-model="truckMaintModel.Description" name="Description"
                                        :disabled="(truckMaintViewFlag == 1)" type="text" class="form-control"
                                        placeholder="Mô tả thông tin bảo trì"
                                        :class="{ 'is-invalid': errors.Description }" />
                                    <div class="invalid-feedback">{{ errors.Description }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Tên garage bảo trì</label>
                                    <Field v-model="truckMaintModel.GarageName" name="GarageName" type="text"
                                        :disabled="(truckMaintViewFlag == 1)" class="form-control"
                                        placeholder="Garage bảo trì" :class="{ 'is-invalid': errors.GarageName }" />
                                    <div class="invalid-feedback">{{ errors.GarageName }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Địa chỉ garage</label>
                                    <Field v-model="truckMaintModel.GarageAddress" name="GarageAddress" type="text"
                                        :disabled="(truckMaintViewFlag == 1)" class="form-control"
                                        placeholder="Địa chỉ garage bảo trì"
                                        :class="{ 'is-invalid': errors.GarageAddress }" />
                                    <div class="invalid-feedback">{{ errors.GarageAddress }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Số điện thoại garage</label>
                                    <Field v-model="truckMaintModel.GaragePhone" name="GaragePhone" type="text"
                                        :disabled="(truckMaintViewFlag == 1)" class="form-control"
                                        placeholder="Số điện thoại garage bảo trì"
                                        :class="{ 'is-invalid': errors.GaragePhone }" />
                                    <div class="invalid-feedback">{{ errors.GaragePhone }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Tổng tiền phải thanh toán</label>
                                    <Field v-model="truckMaintModel.Cost" name="Cost" type="text" class="form-control"
                                        :disabled="(truckMaintViewFlag == 1)"
                                        placeholder="Tổng số tiền phải trả cho garage bảo trì"
                                        :class="{ 'is-invalid': errors.Cost }" />
                                    <div class="invalid-feedback">{{ errors.Cost }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Có xuất hóa đơn hay không?</label>
                                    <v-select v-model="truckMaintModel.IsHasInvoice" label="Name"
                                        :disabled="(truckMaintViewFlag == 1)"
                                        :options="[{ Id: 0, Name: 'Không' }, { Id: 1, Name: 'Có' }]"
                                        :reduce="(option) => option.Id">
                                        <template v-slot:no-options="{ search, searching }">
                                            <template v-if="searching">
                                                Không có kết quả cho <b>{{ search }}</b>.
                                            </template>
                                            <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                        </template>
                                    </v-select>
                                    <Field v-model="truckMaintModel.IsHasInvoice" name="IsHasInvoice" type="hidden" />
                                    <ErrorMessage class="invalid-error" name="IsHasInvoice" />
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Link tải hóa đơn</label>
                                    <Field as="textarea" v-model="truckMaintModel.InvoiceUrl" name="InvoiceUrl"
                                        type="text" :disabled="(truckMaintViewFlag == 1)" class="form-control"
                                        placeholder="Link tải hóa đơn Garage gửi lại"
                                        :class="{ 'is-invalid': errors.InvoiceUrl }" />
                                    <div class="invalid-feedback">{{ errors.InvoiceUrl }}</div>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Thời gian bắt đầu bảo trì</label>
                                    <VueDatePicker v-model="truckMaintModel.StartTime" :enable-time-picker="false"
                                        :disabled="(truckMaintViewFlag == 1)" auto-apply :format="format2"
                                        placeholder="Thời gian bắt đầu bảo trì">
                                    </VueDatePicker>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Thời gian kết thúc bảo trì</label>
                                    <VueDatePicker v-model="truckMaintModel.EndTime" :enable-time-picker="false"
                                        auto-apply :disabled="(truckMaintViewFlag == 1)" :format="format2"
                                        placeholder="Thời gian kết thúc bảo trì">
                                    </VueDatePicker>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="form-group mb-3">
                                    <label>Lần bảo trì dự kiến tiếp theo</label>
                                    <VueDatePicker v-model="truckMaintModel.NextTime" :enable-time-picker="false"
                                        auto-apply :disabled="(truckMaintViewFlag == 1)" :format="format2"
                                        placeholder="Lần bảo trì dự kiến tiếp theo">
                                    </VueDatePicker>
                                </div>
                            </div>
                        </div>
                    </div>
                    <br />
                    <div class="vtrWey"></div>
                    <div class="col-lg-12">
                        <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-4p"><span>#</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Thông số</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Giá trị</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Đơn vị</span></th>
                                        <th class="wd-lg-12p min-width-1" v-if="truckMaintViewFlag != 1">Quản lý</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 && truckMaintLinkItems.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 && truckMaintLinkItems.length > 0">
                                    <tr v-for="(item, index) in truckMaintLinkItems" :key="item.Id">
                                        <td class="align-top">
                                            <div class="mt-1">
                                                <span>{{ index + 1 }}</span>
                                            </div>
                                        </td>
                                        <td class="align-top">
                                            <div v-if="item.Id == 0">
                                                <v-select v-model="truckMaintLinkModel.TruckMaintAttributeId"
                                                    label="Name" :options="totalAttrs" :reduce="(option) => option.Id"
                                                    :disabled="item.Id != 0 || truckMaintViewFlag == 1"
                                                    :value="item.TruckMaintAttributeId">
                                                    <template v-slot:no-options="{ search, searching }">
                                                        <template v-if="searching">
                                                            Không có kết quả cho <b>{{ search }}</b>.
                                                        </template>
                                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                                    </template>
                                                </v-select>
                                                <Field v-model="truckMaintLinkModel.TruckMaintAttributeId"
                                                    name="TruckMaintAttributeId" type="hidden" />
                                                <ErrorMessage class="invalid-error" name="TruckMaintAttributeId" />
                                            </div>
                                            <div v-else>
                                                <v-select v-model="item.TruckMaintAttributeId" label="Name"
                                                    :options="totalAttrs" :reduce="(option) => option.Id"
                                                    :disabled="item.Id != 0 || truckMaintViewFlag == 1"
                                                    :clearable="false">
                                                    <template v-slot:no-options="{ search, searching }">
                                                        <template v-if="searching">
                                                            Không có kết quả cho <b>{{ search }}</b>.
                                                        </template>
                                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                                    </template>
                                                </v-select>
                                            </div>
                                        </td>
                                        <td class="align-top">
                                            <div v-if="item.Id == 0">
                                                <input class="form-control"
                                                    v-model="truckMaintLinkModel.TruckMaintenanceValue" />
                                            </div>
                                            <div v-else>
                                                <input disabled class="form-control"
                                                    :value="item.TruckMaintenanceValue" />
                                            </div>
                                        </td>
                                        <td class="align-top">
                                            <div v-if="item.Id == 0">
                                                <v-select v-model="truckMaintLinkModel.TruckMaintenanceUnit"
                                                    label="Name" :disabled="(truckMaintViewFlag == 1)"
                                                    :options="truckUnits" :reduce="(option) => option.Id">
                                                    <template v-slot:no-options="{ search, searching }">
                                                        <template v-if="searching">
                                                            Không có kết quả cho <b>{{ search }}</b>.
                                                        </template>
                                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                                    </template>
                                                </v-select>
                                                <Field v-model="truckMaintLinkModel.TruckMaintenanceUnit"
                                                    name="TruckMaintenanceUnit" type="hidden" />
                                                <ErrorMessage class="invalid-error" name="TruckMaintenanceUnit" />
                                            </div>
                                            <div v-else>
                                                <v-select v-model="item.TruckMaintenanceUnit" label="Name"
                                                    :options="truckUnits" :reduce="(option) => option.Id"
                                                    :disabled="item.Id != 0 || (truckMaintViewFlag == 1)"
                                                    :clearable="false">
                                                    <template v-slot:no-options="{ search, searching }">
                                                        <template v-if="searching">
                                                            Không có kết quả cho <b>{{ search }}</b>.
                                                        </template>
                                                        <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                                                    </template>
                                                </v-select>
                                            </div>
                                        </td>

                                        <td class="align-top pt-2" v-if="truckMaintViewFlag != 1">
                                            <a @click="fnCreateTruckMaintLink(item)" v-if="item.Id <= 0"
                                                class="dropdown-item" href="javascript:void(0);"><i
                                                    class="fe fe-plus"></i>
                                                <span class="mg-l-6">Lưu</span>
                                            </a>
                                            <a @click="fnDeleteTruckMaintLink(item.Id)" v-if="item.Id > 0"
                                                class="dropdown-item" href="javascript:void(0);">
                                                <i class="fe fe-trash"></i>
                                                <span class="mg-l-6">Xóa</span></a>

                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-lg-12 ">
                        <div class="d-flex flex-row-reverse">
                            <button @click="truckMaintModalClose" type="button" class="btn btn-main-default mg-l-15">
                                Bỏ qua
                            </button>
                            <button type="submit" class="btn btn-main-primary" :disabled="isSubmitting">
                                <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                                Xác nhận
                            </button>
                        </div>
                    </div>
                </Form>
            </template>
        </LadaDialog>
        <LadaDrawer :loading="loading" :drawerId="'truckMaintDrawer'" :title="'Thuộc tính bảo trì'">
            <template v-slot="{ isLoading }">
                <div class="table-responsive border-top mg-b-10">
                    <table class="table table-vcenter mb-0">
                        <thead>
                            <tr>
                                <th class="wd-lg-12p min-width-1"><span>TT</span></th>
                                <th class="wd-lg-12p min-width-2"><span>Tên thuộc tính</span></th>
                                <th class="wd-lg-8p"></th>
                            </tr>
                        </thead>
                        <tbody v-if="isLoading">
                            <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="!isLoading && attrItems.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="!isLoading && attrItems.length > 0">
                            <tr v-for="(item, index) in attrItems" :key="item.Id">
                                <td class="">
                                    <span v-if="item.Id == 0">#</span>
                                    <span v-else>{{ index }}</span>
                                </td>
                                <td class="">
                                    <input class="form-control" v-model="attrName" v-if="item.Id == 0" />
                                    <span v-else>{{ item.Name }}</span>
                                </td>
                                <td class="">
                                    <a v-if="item.Id == 0" type="button" class="mx-2 px-2 text-success"
                                        @click="attrCreateOrUpdate">
                                        <i class="fe fe-plus"></i>
                                    </a>
                                    <a v-if="item.Id != 0" type="button" class="mx-2 px-2 text-danger"
                                        @click="truckSpecAttrDelete(item.Id)">
                                        <i class="fe fe-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <pager ref="attrPager" v-show="!isLoading && attrItems.length > 0"
                        @PageSizeChanged="attrPageSizeChanged" @PageIndexChanged="attrPageIndexChanged"
                        :Total="attriTotalRecord" :TotalCurrent="attriTotalRecord"></pager>
                </div>
            </template>
        </LadaDrawer>
    </div>
</template>
<script setup>
//#region Imports
import moment from 'moment';
import { ref, reactive, onMounted, computed } from 'vue'
import truckService from "@/services/truckService";
import agencyService from "@/services/agencyService";
import userService from "@/services/userService";
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import { useToast } from "vue-toastification";
const toast = useToast();
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';


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}`;
}

const format2 = (date) => {
    let start = date;
    const dayStart = start.getDate();
    const monthStart = start.getMonth() + 1;
    const yearStart = start.getFullYear();

    return `${dayStart}/${monthStart}/${yearStart}`;
}

//#endregion



//#region Truck Maintenance
const ctrlPager = ref();
const items = reactive([]);
const agencies = reactive([]);
const truckes = reactive([]);
const users = reactive([]);
const truckMaintLinkItems = reactive([]);
const loading = ref(false);
const truckId = ref(0);
const truckOpenModalFlag = ref(false);
// = 1 --> Xem
// = 2 --> Sửa
// = 0 --> Tạo
const truckMaintViewFlag = ref(0);
const truckAgency = ref();
const truckLicensePlate = ref();
const statusOptions = reactive([
    { Id: null, Name: "Tất cả" },
    { Id: 1, Name: "Đang Dừng / Đỗ" },
    { Id: 2, Name: "Đang Hoạt Động" },
    { Id: 3, Name: "Bảo Trì / Sửa Chữa" }
]);
const truckUnits = reactive([
    { Id: 1, Name: "cm" },
    { Id: 2, Name: "m" },
    { Id: 3, Name: "km" },
    { Id: 4, Name: "kg" },
    { Id: 5, Name: "m3" }
]);
const createdTime = ref();
const lastRepairTime = ref();
const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
            LastRepairStart: null,
            LastRepairEnd: null,
            Status: null
        }
    }
});

const truckMaintModel = ref({
    Id: 0,
    TruckId: undefined,
    AgencyId: undefined,
    Title: '',
    Description: '',
    GarageName: '',
    GarageAddress: '',
    GaragePhone: '',
    UserId: undefined,
    Cost: 0,
    IsHasInvoice: 0,
    HasInvoice: false,
    InvoiceUrl: '',
    StartTime: '',
    EndTime: '',
    NextTime: '',
    TruckMaintLinkModels: []
});

const truckMaintLinkModel = ref({
    Id: 0,
    TruckMaintenanceId: 0,
    TruckMaintAttributeId: undefined,
    TruckMaintenanceValue: '',
    TruckMaintenanceUnit: undefined
})


async function onChangeCreatedTime(newDates) {
    createdTime.value = newDates;
    handleDate(newDates)
}

function handleCreateTime(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;
    }
}

async function onChangeLastRepairTime(newDates) {
    lastRepairTime.value = newDates;
    handleLastRepairTime(newDates)
}

function handleLastRepairTime(modelData) {
    console.log(moment(modelData[0]));
    if (modelData != null) {
        searchModel.Search.PredicateObject.LastRepairStart = modelData[0];
        searchModel.Search.PredicateObject.LastRepairEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.LastRepairStart = null;
        searchModel.Search.PredicateObject.LastRepairEnd = null;
    }
}

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

async function loadData() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await truckService.truckMaintSearch(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(item => {
            items.push(item);
        });
    }
    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();
}

async function truckMaintModalOpen(truckMaintItem, isView) {
    truckOpenModalFlag.value = true;
    truckMaintViewFlag.value = isView;
    await attrGetAll();
    if (isView != 0) {
        truckMaintModel.value.Id = truckMaintItem.Id;

        truckAgency.value = truckMaintItem.AgencyName;
        truckMaintModel.value.AgencyId = truckMaintItem.AgencyId;
        agencies.splice(0, agencies.length);
        agencies.push({ Id: truckMaintItem.AgencyId, Name: truckMaintItem.AgencyName });

        truckLicensePlate.value = truckMaintItem.TruckLicensePlate;
        truckMaintModel.value.TruckId = truckMaintItem.TruckId;
        truckes.splice(0, truckes.length);
        truckes.push({ Id: truckMaintItem.TruckId, LicensePlate: truckMaintItem.TruckLicensePlate });

        truckMaintModel.value.UserId = truckMaintItem.UserId;
        users.splice(0, users.length);
        users.push({ Id: truckMaintItem.UserId, FullName: truckMaintItem.FullName + ` (${truckMaintItem.UserName})` });

        truckMaintModel.value.Title = truckMaintItem.Title;
        truckMaintModel.value.Description = truckMaintItem.Description;
        truckMaintModel.value.GarageName = truckMaintItem.GarageName;
        truckMaintModel.value.GarageAddress = truckMaintItem.GarageAddress;
        truckMaintModel.value.GaragePhone = truckMaintItem.GaragePhone;
        truckMaintModel.value.Cost = truckMaintItem.Cost;
        truckMaintModel.value.IsHasInvoice = truckMaintItem.HasInvoice ? 1 : 0;
        truckMaintModel.value.InvoiceUrl = truckMaintItem.InvoiceUrl;
        truckMaintModel.value.StartTime = truckMaintItem.StartTime;
        truckMaintModel.value.EndTime = truckMaintItem.EndTime;
        truckMaintModel.value.NextTime = truckMaintItem.NextTime;
    } else {
        clearTruckMaintParam();
    }
    await truckMaintLinkLoad(truckMaintItem.Id);

}
function clearTruckMaintParam() {
    truckMaintModel.value.Id = 0;
    truckMaintModel.value.TruckId = undefined;
    truckMaintModel.value.AgencyId = undefined;
    truckMaintModel.value.Title = '';
    truckMaintModel.value.Description = '';
    truckMaintModel.value.GarageName = '';
    truckMaintModel.value.GarageAddress = '';
    truckMaintModel.value.GaragePhone = '';
    truckMaintModel.value.UserId = undefined;
    truckMaintModel.value.Cost = 0;
    truckMaintModel.value.IsHasInvoice = 0;
    truckMaintModel.value.InvoiceUrl = '';
    truckMaintModel.value.StartTime = '';
    truckMaintModel.value.EndTime = '';
    truckMaintModel.value.NextTime = '';
    truckMaintModel.value.TruckMaintLinkModels = [];

}
function truckMaintModalClose() {
    truckOpenModalFlag.value = false;
    truckMaintViewFlag.value = 0;
    clearTruckMaintParam();
}

async function truckMaintLinkLoad(id) {
    truckMaintLinkItems.splice(0, truckMaintLinkItems.length);
    var rs = await truckService.truckMaintLinkGetAll(id);
    if (rs.Result == 1 && rs.Items != null && rs.Items.length > 0) {
        if (truckMaintViewFlag.value != 1)
            truckMaintLinkItems.push({ Id: 0, TruckMaintenanceValue: 0, TruckMaintenanceUnit: undefined, TruckMaintAttributeId: undefined });
        rs.Items.forEach(item => {
            truckMaintLinkItems.push(item);
        });
    } else {

        if (truckMaintViewFlag.value != 1)
            truckMaintLinkItems.push({ Id: 0, TruckMaintenanceValue: 0, TruckMaintenanceUnit: undefined, TruckMaintAttributeId: undefined })

    }
}
function clearTruckMaintLinkParam() {
    truckMaintLinkModel.value.TruckMaintenanceUnit = undefined;
    truckMaintLinkModel.value.TruckMaintenanceValue = 0;
    truckMaintLinkModel.value.TruckMaintAttributeId = undefined;

}
async function fnCreateTruckMaintLink(model) {
    var param = {
        Id: Date.now(),
        TruckMaintenanceValue: truckMaintLinkModel.value.TruckMaintenanceValue,
        TruckMaintAttributeId: truckMaintLinkModel.value.TruckMaintAttributeId,
        TruckMaintenanceUnit: truckMaintLinkModel.value.TruckMaintenanceUnit
    };
    truckMaintLinkItems.push(param);
    if (!truckMaintLinkItems.indexOf(x => x.Id == 0)) {
        truckMaintLinkItems.push({ Id: 0, TruckMaintenanceValue: 0, TruckMaintenanceUnit: undefined, TruckMaintAttributeId: undefined });
    }
    clearTruckMaintLinkParam();
}
async function fnDeleteTruckMaintLink(model) {
    var index = truckMaintLinkItems.indexOf(x => x.Id == model.Id);
    truckMaintLinkItems.splice(index, 1);
}

async function getAgencies(model) {
    if (model) {
        var result = await agencyService.autoComplete(model);
        if (result != null && result.length > 0) {
            agencies.splice(0, agencies.length);
            Object.assign(agencies, result);
        }
    }
}

async function getTruckByAgencyId(model) {
    if (model.Id) {
        var result = await truckService.getTruckByAgencyId(model.Id);
        if (result != null && result.Result == 1) {
            truckes.splice(0, truckes.length);
            Object.assign(truckes, result.Items);
        }
    }
}
async function getUserByAgencyId(keyword) {
    if (truckMaintModel.value.AgencyId > 0) {
        if (keyword) {
            var result = await userService.autoCompleteByagency('?agencyId=' + truckMaintModel.value.AgencyId + '&keyword=' + keyword);
            if (result.length > 0) {
                users.splice(0, users.length);
                Object.assign(users, result);
            }
        }
    } else {
        toast.warning('Không xác định được chi nhánh');
    }
}
async function selectTruckLicensePlate(model) {
    truckMaintModel.value.TruckId = model.Id;
}


const hasInvoice = computed(() => {
    return truckMaintModel.value.IsHasInvoice == 1 ? true : false;
});

async function fnCreateTruckMaintenance() {
    if (truckMaintLinkItems && truckMaintLinkItems.length > 0) {
        let truckMaintLinkModels = [];
        Object.assign(truckMaintLinkModels, truckMaintLinkItems.filter(x => x.Id != 0))
        truckMaintLinkModels.forEach(x => {
            x.Id = 0;
        });
        truckMaintModel.value.HasInvoice = hasInvoice;
        truckMaintModel.value.TruckMaintLinkModels = truckMaintLinkModels;

        console.log(truckMaintModel.value);
        var rs = await truckService.truckMaintCreateOrUpdate(truckMaintModel.value);
        if (rs.Result == 1) {
            toast.success('Thành công');
            truckMaintLinkItems.splice(0, truckMaintLinkItems.length);
            if (!truckMaintLinkItems.indexOf(x => x.Id == 0)) {
                truckMaintLinkItems.push({ Id: 0, TruckMaintenanceValue: 0, TruckMaintenanceUnit: undefined, TruckMaintAttributeId: undefined });
            }
            truckMaintModalClose();
            await search();
        } else {
            toast.error(rs.Message);
        }

    } else {
        toast.error('Không xác định được thuộc tính cần bảo trì');
    }
};

async function truckMaintDelete(id) {
    if (id > 0) {
        var result = await truckService.truckMaintDelete({ Id: id });
        if (result != null && result.Result == 1) {
            toast.success('Thành công');
            await search();
        } else {
            toast.error(rs.Message);
        }
    }
}


//#endregion

//#region MaintAttr
const attrPager = ref();
const attriTotalRecord = ref(0);
const attrItems = reactive([]);
const totalAttrs = reactive([]);
const searchAttrModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: ''
        }
    }
});


const attrName = ref('');

async function truckMaintDrawer() {
    await attrSearch();
}

function attrPageSizeChanged(pagesize) {
    searchAttrModel.Pagination.PageSize = pagesize;
    searchAttrModel.Pagination.PageIndex = 1;
    attrSearch();
}
function attrPageIndexChanged(pageIndex) {
    searchAttrModel.Pagination.PageIndex = pageIndex;
    attrSearch();
}


async function attrCreateOrUpdate() {
    if (attrName.value) {
        var param = {
            Id: 0,
            Name: attrName.value
        };
        let resp = await truckService.truckMaintAttrCreateOrUpdate(param);
        if (resp.Result == 1) {
            toast.success("Thành công");

        } else {
            toast.error('Thất bại: ' + resp.Message);
        }
    }
    await attrSearch();
}
async function truckSpecAttrDelete(value) {
    var param = {
        Id: value,
        Name: ''
    };
    let resp = await truckService.truckMaintAttrDelete(param);
    if (resp.Result == 1) {
        toast.success("Thành công");
    } else {
        toast.error('Thất bại: ' + resp.Message);
    }
    await attrSearch();
}

async function attrSearch() {
    let resp = await truckService.truckMaintAttrSearch(searchAttrModel);
    if (resp.TotalRecord > 0) {
        attriTotalRecord.value = resp.TotalRecord;
        var arr = [{ Id: 0, Name: '' }];
        var items = reactive(arr.concat(resp.Items));
        attrItems.splice(0, attrItems.length);
        Object.assign(attrItems, items);
    } else {
        attriTotalRecord.value = 0;
        attrItems.splice(0, attrItems.length);
        attrItems.push({ Id: 0, Name: '' });
    }
}
async function attrGetAll() {
    let resp = await truckService.truckMaintAttrGetAll();
    if (resp.Result == 1) {
        totalAttrs.splice(0, totalAttrs.length);
        Object.assign(totalAttrs, resp.Items);
    } else {
        totalAttrs.splice(0, totalAttrs.length);
    }
}
//#endregion



onMounted(async () => {
    await search();
})
</script>