<template>
    <div>
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý lead</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);">CRM</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Quản lý lead</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 mb-5">
                    <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="datePickerStore.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>
                        <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 class="d-flex flex-row justify-content-end mg-b-20 mg-r-20">
                        <button @click="fnCreateOrUpdate(0)" type="button" class="btn btn-primary">
                            <i class="fe fe-plus me-2"></i>
                            Tạo lead
                        </button>

                    </div>


                    <div class="table-responsive">
                        <table class="table table-hover mg-b-0 text-md-nowrap">
                            <thead>
                                <tr>
                                    <th class="wd-20p">
                                        Lead
                                    </th>

                                    <th class="wd-20p">
                                        Lời nhắn
                                    </th>
                                    <th class="wd-10p">
                                        Trạng thái
                                    </th>
                                    <th class="wd-20p">
                                        Nội dung cập nhật
                                    </th>
                                    <th class="wd-20p">
                                        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 && 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>
                                <tr v-for="item in items">
                                    <td>
                                        Họ và tên: <b>{{ item.FullName }}</b><br />
                                        SĐT: <b>{{ item.PhoneNumber }}</b><br />
                                        Ngày tạo: <b>{{ item.CreatedTime }}</b><br />
                                        <span v-if="item.SourcePath">
                                            Nguồn:
                                            <b>
                                                <a :href="item.SourcePath" :title="item.SourcePath"
                                                    :alt="item.SourcePath" target="_blank">
                                                    Liên kết nguồn
                                                </a>
                                            </b>
                                        </span>

                                    </td>

                                    <td>
                                        {{ item.Message }}
                                    </td>
                                    <td>
                                        <LeadStatus :value="item.LeadStatus" :name="item.LeadStatusStr">
                                        </LeadStatus>
                                        <div v-if="item.PicId > 0">
                                            Phụ trách: <b>{{ item.PicUserName }}</b><br />
                                        </div>

                                    </td>
                                    <td>
                                        <p style="white-space: pre-line;">{{ item.StatusContent }}</p>
                                    </td>
                                    <td>
                                        <button v-if="item.LeadStatus === 1" @click="assignManager(item.Id)"
                                            type="button" class="btn btn-info btn-xs">
                                            <i class="fas fa-satellite-dish"></i>
                                            <span class="pd-l-5">Nhận</span>
                                        </button>
                                        <button v-if="item.LeadStatus === 2" @click="review(item.Id)" type="button"
                                            class="btn btn-outline-primary btn-xs">
                                            <i class="fas fa-satellite-dish"></i>
                                            <span class="pd-l-5">Cập nhật</span>
                                        </button>



                                    </td>
                                </tr>
                            </tbody>
                        </table>

                    </div>
                    <pager class="mb-3" ref="ctrlPager" v-show="!loading && items.length > 0"
                        @PageSizeChanged="PageSizeChanged" @PageIndexChanged="PageIndexChanged"
                        :Total="searchModel.Pagination.Total" :TotalCurrent="items.length"></pager>



                </div>


            </div><!-- COL END -->
        </div>
        <LadaDialog :visible="modalControl.Review">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Cập nhật trạng thái lead</h5>
                    <button @click="closeModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <Review @cancel="closeModal" :id="selectedId"></Review>
            </template>
        </LadaDialog>

        <LadaDialog :visible="modalControl.Create">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo lead mới</h5>
                    <button @click="closeCreateModal" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <CreateLead @cancel="closeCreateModal" @success="closeCreateModal"></CreateLead>
            </template>
        </LadaDialog>
    </div>
</template>

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

//#region Imports
import moment from "moment";
import { ref, reactive, onMounted } from 'vue'
import leadService from "@/services/crm/leadService";
import { useRouter } from 'vue-router';
const router = useRouter();
//#endregion

import { useDatePickerStore } from "@/stores";
const datePickerStore = useDatePickerStore();


//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import LeadStatus from './components/leadStatus.vue';
import Review from './components/review.vue';
import CreateLead from './components/CreateLead.vue';

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

//#endregion

//#region Actions
const selectedId = ref(0);
async function fnCreateOrUpdate(id) {
    console.log(id);
    selectedId.value = id;
    if (id > 0) {
        router.push({ name: 'lead-update', params: { id: selectedId.value } });
    } else {
        modalControl.Create = true;
    }
}


//#endregion


//#region SEARCH


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);

//#region Modals
const modalControl = reactive({
    Review: false,
    Create: false
});
function closeModal() {
    modalControl.Review = false;
    modalControl.Create = false;
    loadData();
}

function closeCreateModal() {
    modalControl.Create = false;
    loadData();
}
//#endregion


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


const statuses = reactive([
    { Id: 1, Name: 'Mới' },
    { Id: 2, Name: 'Đã tiếp nhận' },
    { Id: 3, Name: 'Thành công' },
    { Id: 4, Name: 'Thất bại' }
]);




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 leadService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
        searchResult.Items.forEach(post => {
            items.push(post);
        });
    }
    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

async function assignManager(id) {

    var cf = confirm("Bạn chắc chắn muốn nhận quản lý lead này?");
    if (cf) {
        var model = {
            Id: id,
            StatusContent: ''
        };
        var result = null;
        result = await leadService.assignManager(model);
        if (result != null && result.Result === 1) {
            toast.success('Thành công!');

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

    await loadData();

}

async function review(id) {
    selectedId.value = id;
    modalControl.Review = true;
}


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

</script>
<style lang="css">
.post-info {
    font-size: .83rem;
    font-style: italic;
    color: #090b0ed9;
}

a>span.tag {
    cursor: pointer;
}
</style>