<!--
 * @Author: Kane
 * @Date: 2023-03-23 16:05:08
 * @LastEditors: Kane
 * @FilePath: /task_schedule/src/views/RewardManagement.vue
 * @Description:
 *
 * Copyright (c) ${2022} by Kane, All Rights Reserved.
-->
<template>
    <div
        v-if="ui.showUI"
        class="wrapper"
    >
        <div class="reward-wrapper">
            <div class="reward-gainer-wrapper">
                <el-divider content-position="left">
                    90俱乐部 & “消7灭6”包围战
                </el-divider>
                <div class="toolbutton-wrapper">
                    <el-button
                        type="primary"
                        icon="documentAdd"
                        @click="onAddRewardGainer"
                    >
                        新增
                    </el-button>
                    <el-button
                        type="danger"
                        icon="delete"
                        @click="onDeleteRewardGainer"
                    >
                        删除
                    </el-button>
                    <el-button
                        type="warning"
                        icon="Refresh"
                        @click="refresh"
                    >
                        刷新
                    </el-button>
                </div>
                <el-table
                    ref="rewardTelsalerTable"
                    border
                    stripe
                    style="width:100%;"
                    :data="rewardGainerData"
                >
                    <el-table-column type="selection" />
                    <el-table-column
                        label="坐席名称"
                        align="center"
                    >
                        <template #default="rewardGainer">
                            <span
                                class="reward-gainer-td"
                                @dblclick="onEditRewardGainer(rewardGainer.row.recID, rewardGainer.row.callerName, rewardGainer.row.rewardProjectCode)"
                            >{{ rewardGainer.row.callerName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="奖项名称"
                        align="center"
                    >
                        <template #default="rewardGainer">
                            <span
                                class="reward-gainer-td"
                                @dblclick="onEditRewardGainer( rewardGainer.row.recID, rewardGainer.row.callerName, rewardGainer.row.rewardProjectCode)"
                            >{{ rewardGainer.row.rewardProjectName }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-wrapper">
                    <el-pagination
                        v-model="ui.tablePageIndex"
                        class="pull_left"
                        size="small"
                        background
                        :page-size="ui.tablePageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="(ui.rewardGainerList ?? []).length"
                        @current-change="onCurrentPageIndexChange"
                        @size-change="onTablePageSizeChange"
                    />
                </div>
            </div>
        </div>
        <div
            v-if="ui.showEditRewardGainerDialog"
            class="dialog-wrapper"
        >
            <el-dialog
                v-model="ui.showEditRewardGainerDialog"
                title="编辑获奖人员"
                width="400px"
            >
                <RewardGainerDialog
                    :selected-rec-id="(ui.selectedRecID ?? -9999)"
                    :selected-reward-project-code="ui.selectedRewardProjectCode"
                    :selected-telsaler-name="ui.selectedTelsalerName"
                />
            </el-dialog>
        </div>
    </div>
</template>
<script lang="ts">
import { reactive, computed, onBeforeMount, ref } from "vue";
import { type RewardGainer, type RewardGainerResponse, requestRewardGainers, type DeleteRewardTelsalerResponse, deleteRewardTelsaler, type DeleteRewardTelsalerRequest } from "@/utils/reward.js";
import eventBus from "@/utils/api/EventBus.js";
import { ElMessage, ElMessageBox, type ElTable } from "element-plus";
import RewardGainerDialog from "@/views/reward/RewardTelsaler.vue";

interface UI
{
    showUI: boolean;
    showEditRewardGainerDialog: boolean;
    rewardGainerList: RewardGainer[] | null;
    tablePageIndex: number;
    tablePageSize: number;
    selectedRecID: number | null;
    selectedTelsalerName: string;
    selectedRewardProjectCode: number;
}

export default {
    name: "RewardManagement",
    components: { RewardGainerDialog, },
    setup()
    {
        const ui: UI = reactive({
            showUI: true,
            showEditRewardGainerDialog: false,
            rewardGainerList: null,
            tablePageIndex: 1,
            tablePageSize: 10,
            selectedRecID: null,
            selectedTelsalerName: "",
            selectedRewardProjectCode: -999,
        });
        const rewardTelsalerTable = ref<InstanceType<typeof ElTable>>();

        /** 请求数据相关 ***************************/
        const requestRewardTelsalerListHandler = ( response: RewardGainerResponse, error: any ): void =>
        {
            if ( !response.success )
            {
                console.log( error );

                ElMessageBox({
                    message: "请求获奖人列表失败，请查看日志！",
                    type: "error",
                    center: true,
                })
                    .then((): void => {})
                    .catch((): void => {});

                return;
            }

            ui.rewardGainerList = response.gainerList;

            console.log( "请求获奖人员列表", ui.rewardGainerList );

            refreshUI();
        };

        /** 表格相关 ***************************/
        const tableHeight = computed((): number =>
        {
            return ( ui.tablePageSize + 1 ) * 40;
        });

        /**
         * 用于根据分页组件的参数，生成表格用的数据。
         */
        const rewardGainerData = computed((): RewardGainer[] =>
        {
            // 防御性验证
            if ( ui.rewardGainerList === null )
            {
                return [];
            }

            const startIndex = ui.tablePageSize * ( ui.tablePageIndex - 1 );
            const endIndex = startIndex + ui.tablePageSize;
            const data = ui.rewardGainerList.slice( startIndex, endIndex );
            console.log( ui.tablePageSize, ui.tablePageIndex );
            console.log( "表格数据:", data );

            return data;
        });

        const onCurrentPageIndexChange = ( pageIndex: number ): void =>
        {
            ui.tablePageIndex = pageIndex;
        };

        const onTablePageSizeChange = ( pageSize: number ): void =>
        {
            ui.tablePageSize = pageSize;
        };

        /** 功能按钮相关 *******************************/
        /**
         * 添加获奖坐席
         */
        const onAddRewardGainer = (): void =>
        {
            ui.selectedRecID = -1;
            ui.selectedRewardProjectCode = 3;
            ui.selectedTelsalerName = "";
            ui.showEditRewardGainerDialog = true;
        };
        /**
         * 响应用户在表格中的双击
         * @param telsalerName 
         * @param rewardProjectName 
         */
        const onEditRewardGainer = ( recID: number, telsalerName: string, rewardProjectCode: number ): void =>
        {
            console.log( "编辑获奖清单", recID, telsalerName, rewardProjectCode );

            ui.selectedRecID = recID;
            ui.selectedTelsalerName = telsalerName;
            ui.selectedRewardProjectCode = rewardProjectCode;
            ui.showEditRewardGainerDialog = true;
        };
        /**
         * 响应点击删除按钮
         */
        const onDeleteRewardGainer = (): void =>
        {
            const selectedRecord: RewardGainer[] = rewardTelsalerTable.value?.getSelectionRows();
            const deleteRequest: DeleteRewardTelsalerRequest = {
                recordID: [],
            };

            if ( selectedRecord !== undefined )
            {
                selectedRecord.forEach(( item: RewardGainer ): void =>
                {
                    deleteRequest.recordID.push( item.recID );
                });
            }

            deleteRewardTelsaler( deleteRequest, deleteTelsalerRewardHandler );
        };

        /** 回调函数 ************************/
        const deleteTelsalerRewardHandler = ( response: DeleteRewardTelsalerResponse, error: any ): void =>
        {
            if ( response.success )
            {
                ElMessage({
                    message: response.message,
                    type: "success",
                });
            }
            else
            {
                ElMessage({
                    message: response.message,
                    type: "error",
                });
            }

            refresh();
        };

        /** 事件相关 ***************/
        /** 订阅新增和保存修改获奖者事件 */
        eventBus.on( "onSavedRewardTelsaler", (): void =>
        {
            // 关闭对话框后，重新请求获奖清单，刷新页面。
            ui.showEditRewardGainerDialog = false;

            refresh();
        });
        /**
         * 用于刷新页面
         */
        const refresh = (): void =>
        {
            requestRewardGainers( requestRewardTelsalerListHandler );
        };

        const refreshUI = (): void =>
        {
            ui.showUI = false;

            setTimeout(() =>
            {
                ui.showUI = true;
            }, 0 );
        };

        onBeforeMount((): void =>
        {
            refresh();
        });

        return {
            ui,
            tableHeight,
            rewardGainerData,
            rewardTelsalerTable,
            onCurrentPageIndexChange,
            onTablePageSizeChange,
            onEditRewardGainer,
            refresh,
            onAddRewardGainer,
            onDeleteRewardGainer,
        };
    },
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/public/_public.scss";

.wrapper {
    margin: 10px;
    // padding: 10px;

    // background-color: #fff;
    // border-radius: 5px;
    // box-shadow: $box-shadow;

    // &:hover {
    //     box-shadow: $box-shadow-hover;
    // }

    min-width: 800px;

    >*+* {
        margin-top: 10px;
    }
}

.reward-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;

    >div {
        background-color: #fff;
        border-radius: 5px;
        box-shadow: $box-shadow;

        padding: 10px;

        &:hover {
            box-shadow: $box-shadow-hover;
        }
    }

    >*+* {
        margin-left: 10px;
    }
}

.reward-gainer-wrapper {
    flex-grow: 1;
}

.dishonor-wrapper {
    flex-grow: 1;
}

.toolbutton-wrapper {
    text-align: left;
    margin-bottom: 10px;
    >*+* {
        margin-left: 15px;
    }
}

.pagination-wrapper {
    margin-top: 10px;

    display: flex;
    justify-content: flex-end;
}

.reward-gainer-td {
    cursor: pointer;

    display: block;
}
</style>
