<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý khách hà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ý khách hà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.Status"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>
                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Tài khoản</label>
                                <v-select label="Name" :options="accountOptions"
                                    v-model="searchModel.Search.PredicateObject.Account"
                                    :reduce="(option) => option.Id"></v-select>
                            </div>

                            <div class="col-lg-3 col-md-4 mb-3">
                                <label>Người quản lý</label>
                                <v-select label="Name" :options="managerOptions"
                                    v-model="searchModel.Search.PredicateObject.Manager"
                                    :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="create" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1"><i class="fe fe-plus me-2"></i>Tạo
                                khách hà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-1"><span>Thông tin chung</span></th>
                                        <th class="wd-lg-15p min-width-1"><span>Tài khoản</span></th>
                                        <th class="wd-lg-20p min-width-1"><span>Người quản lý</span></th>
                                        <th class="wd-lg-15p min-width-1"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-15p min-width-1"><span>Trạng thái</span></th>
                                        <th class="wd-lg-5p"></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" class="tx-13">

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

                                        <td class="text-wrap align-top">
                                            <div>{{ item.FullName }}</div>
                                            <div>{{ item.PhoneNumber }}</div>
                                            <div>{{ item.Email }}</div>
                                        </td>

                                        <td class="text-wrap align-top">
                                            <div v-if="item.UserId > 0">{{ item.UserName }}</div>
                                            <div v-if="item.UserId == 0" class="tx-12">
                                                <i><b>Chưa có</b></i>
                                            </div>
                                            <div>
                                                <a @click="registerAccount(item.Id)" class="tx-12"
                                                    href="javascript:void(0);"
                                                    v-if="item.UserId == 0 && item.Status === 1">
                                                    <i class="fe fe-user-plus"></i>
                                                    <span class="mg-l-3">Tạo</span>
                                                </a>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span v-if="item.ManagerId > 0">{{ item.ManagerUsername }}</span>
                                            <span v-if="item.ManagerId == 0" class="tx-12">
                                                <i><b>Chưa có</b></i>
                                            </span>
                                            <div>
                                                <a @click="assignManager(item.Id)" class="tx-12"
                                                    href="javascript:void(0);" v-if="item.Status === 1">
                                                    <i class="fe fe-at-sign"></i>
                                                    <span class="mg-l-3">Gán</span>
                                                </a>
                                            </div>
                                        </td>
                                        <td class="text-wrap align-top">
                                            {{ item.CreatedTime }}
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span v-if="item.Status === 2" class="tag tag-indigo">Bị khóa</span>
                                            <span v-if="item.Status === 1" 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 v-if="item.Status == 1" @click="lock(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-user-x"></i>
                                                    <span class="mg-l-6">Khóa tài khoản</span>
                                                </a>
                                                <a v-if="item.Status == 2" @click="unlock(item.Id)"
                                                    class="dropdown-item" href="javascript:void(0);">
                                                    <i class="fe fe-user-check"></i>
                                                    <span class="mg-l-6">Mở tài khoản</span>
                                                </a>
                                                <a v-if="item.UserId > 0" @click="setPassword(item.UserId)"
                                                    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>

                                            </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 khách hàng</h5>
                    <h5 class="modal-title" v-if="selectedId > 0">Cập nhật khách hà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.RegisterAccount">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo tài khoản</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <RegisterAccount @cancel="closeDialog" :customerId="selectedId"></RegisterAccount>
            </template>

        </LadaDialog>

        <LadaDialog :visible="modalControl.AssignManager">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Gán quản lý</h5>
                    <button @click="closeDialog" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <AssignManager @cancel="closeDialog" :id="selectedId"></AssignManager>
            </template>

        </LadaDialog>

    </div>
</template>

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

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

import { useRouter } from 'vue-router';
const router = useRouter();

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            CreatedStart: null,
            CreatedEnd: null,
            Status: null,
            Manager: null,
            Account: 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: 1, Name: "Đang hoạt động" }, { Id: 2, Name: "Bị khóa" }
]);
const managerOptions = reactive([
    { Id: null, Name: "Tất cả" }, { Id: 1, Name: "Đã có người quản lý" }, { Id: 2, Name: "Chưa có quản lý" }
]);
const accountOptions = reactive([
    { Id: null, Name: "Tất cả" }, { Id: 1, Name: "Đã có tài khoản" }, { Id: 2, Name: "Chưa có tài khoản" }
]);

const modalControl = reactive({
    CreateOrUpdate: false,
    SetPassword: false,
    SetRole: false,
    RegisterAccount: false,
    AssignManager: false
});

const selectedId = ref(0);

function create() {
    selectedId.value = 0;
    modalControl.CreateOrUpdate = true;
}
function update(id) {
    // selectedId.value = id;
    // modalControl.CreateOrUpdate = true;
    if (id > 0) {
        router.push({ name: 'crm-customer-detail', params: { id: id } });
    }
}

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

}
function registerAccount(id) {
    selectedId.value = id;
    modalControl.RegisterAccount = true;

}
function assignManager(id) {
    selectedId.value = id;
    modalControl.AssignManager = true;

}

async function lock(id) {
    var cf = confirm("Bạn chắc chắn muốn khóa?");
    if (cf) {
        var lockResult = await customerService.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) {
    console.log(id);
    var cf = confirm("Bạn chắc chắn muốn mở khóa?");
    if (cf) {
        var unlockResult = await customerService.unlock(id);

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

function closeDialog() {
    modalControl.CreateOrUpdate = false;
    modalControl.SetPassword = false;
    modalControl.SetRole = false;
    modalControl.RegisterAccount = false;
    modalControl.AssignManager = false;
    search();
}

const ctrlPager = ref();

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


// functions that mutate state and trigger updates
async function search() {
    loading.value = true;
    items.splice(0, items.length);
    var searchResult = await customerService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(customer => {
            items.push(customer);
        });
    }
    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(() => {
    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>
