<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý người dùng</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ý người dùng</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="searchRefresh">
                        <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>
                                        <LeftSidebar @change-date="onChangeDate"></LeftSidebar>
                                    </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.IsLocked"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Chi nhánh / đại lý</label>
                                <v-select label="Label" :options="agencies"
                                    v-model="searchModel.Search.PredicateObject.AgencyId"
                                    :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>
                        <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="create" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1"><i class="fe fe-plus me-2"></i>Tạo
                                người dùng</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-15p min-width-2"><span>Tài khoản</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Họ và tên</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Số điện thoại</span></th>
                                        <th class="wd-lg-15p min-width-1"><span>Phòng ban</span></th>
                                        <th class="wd-lg-15p min-width-1"><span>Loại người dùng</span></th>
                                        <th class="wd-lg-20p min-width-1"><span>Vai trò</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>FinalDN</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-15p min-width-2"><span>Trạng thái</span></th>
                                        <th class="wd-lg-5p"></th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="9" 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="9" 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.UserName }}</div>
                                            <div>{{ item.Email }}</div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.FullName }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.PhoneNumber }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.AgencyName }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.UserType }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.PermissionName }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.FinalDN || '-' }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.CreatedTime }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span v-if="item.IsLocked" class="tag tag-indigo">Bị khóa</span>
                                            <span v-if="!item.IsLocked" class="tag tag-green">Đang hoạt động</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="update(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                                    <span class="mg-l-6">Thông tin chi tiết</span>
                                                </a>
                                                <a @click="lock(item.Id)" v-if="!item.IsLocked" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-lock"></i>
                                                    <span class="mg-l-6">Khóa tài khoản</span></a>
                                                <a @click="unlock(item.Id)" v-if="item.IsLocked" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-unlock"></i>
                                                    <span class="mg-l-6">Mở khóa tài khoản</span></a>
                                                <a v-if="!item.IsLocked" @click="setPermission(item.Id, item.Role)"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-user-check"></i>
                                                    <span class="mg-l-6">Gán vai trò</span></a>
                                                <a v-if="!item.IsLocked" @click="setPassword(item.Id)"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-refresh-cw"></i>
                                                    <span class="mg-l-6">Đặt mật khẩu</span>
                                                </a>
                                                <a @click="manageBankAccounts(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-credit-card"></i>
                                                    <span class="mg-l-6">Tài khoản ngân hàng</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 người dùng</h5>
                    <h5 class="modal-title" v-if="selectedId > 0">Cập nhật người dùng</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateOrUpdate @cancel="closeDialog" :id="selectedId"></CreateOrUpdate>
            </template>

        </LadaDialog>
        <LadaDialog :visible="modalControl.SetPassword">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Cập nhật mật khẩu</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <SetPassword @cancel="closeDialog" :id="selectedId"></SetPassword>
            </template>

        </LadaDialog>
        <LadaDialog :visible="modalControl.SetPermission">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Cập nhật quyền</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <SetPermission @cancel="closeDialog" :id="selectedId" :permission-id="selectedPermissionId">
                </SetPermission>
            </template>

        </LadaDialog>

        <LadaDialog :visible="modalControl.BankAccounts">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Quản lý tài khoản ngân hàng</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div class="p-3">
                    <UserBankAccounts :user-id="selectedId" />
                </div>
            </template>
        </LadaDialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import userService from "@/services/userService";
import agencyService from "@/services/agencyService";
import LeftSidebar from "@/components/daterange/left-sidebar.vue";
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog } from '@/components/index';
import { CreateOrUpdate, SetPassword, SetPermission, UserBankAccounts } from './components';

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

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

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

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

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



const modalControl = reactive({
    CreateOrUpdate: false,
    SetPassword: false,
    SetPermission: false,
    BankAccounts: false
});

const selectedId = ref(0);
const selectedPermissionId = ref(0);

function create() {
    selectedId.value = 0;
    modalControl.CreateOrUpdate = true;
}
function update(id) {
    selectedId.value = id;
    modalControl.CreateOrUpdate = true;

}

function setPassword(id) {
    selectedId.value = id;
    modalControl.SetPassword = true;

}

function setPermission(id, permissionId) {
    console.log('vao setrole: ' + id);
    selectedId.value = id;
    selectedPermissionId.value = permissionId;
    console.log(selectedPermissionId);
    modalControl.SetPermission = true;

}

async function lock(id) {
    var cf = confirm("Bạn chắc chắn muốn khóa?");
    if (cf) {
        var lockResult = await userService.lock(id);
        if (lockResult != null && lockResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + lockResult.ErrorList.join("\n"));
        }
        search();
    }
}
async function unlock(id) {
    var cf = confirm("Bạn chắc chắn muốn mở khóa?");
    if (cf) {
        var lockResult = await userService.unlock(id);

        if (lockResult != null && lockResult.Result === 1) {
            toast.success('Thành công!');
        } else {
            toast.error('Thất bại: ' + lockResult.ErrorList.join("\n"));
        }
        search();
    }
}

function closeDialog() {
    modalControl.CreateOrUpdate = false;
    modalControl.SetPassword = false;
    modalControl.SetPermission = false;
    modalControl.BankAccounts = false;
    search();
}

function manageBankAccounts(id) {
    selectedId.value = id;
    modalControl.BankAccounts = true;
}

const ctrlPager = ref();

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



const agencies = reactive([]);
async function getAgencies() {
    agencies.splice(0, agencies.length);
    var parentResult = await agencyService.getTree("");
    if (parentResult != null && parentResult.length > 0) {
        parentResult.forEach(agency => {
            agencies.push(agency);
        });
    }
}


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


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


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


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) {
    console.log('update gia tri moi');
    console.log(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;
    }

}





</script>
