<template>
    <div  ref="scrollDom" class="main_container">
        <div  class="page_item end_item">
            <div class="page_search">
                <div class="search_content">
                    <div class="conent_left">
                        <TabSearch 
                            :tabList="viewModeTabList" 
                            tabType="box" 
                            :defaultTabKey="defaultViewMode" 
                            @tabChange="HandleTabChage"
                        />
                    </div>
                    <div class="conent_right">
                        <el-button class="button_background" @click="GoToCreateQuestionnaire">
                            <img :src="questionnaireCardUploadFileIcon" alt="">
                            创建问卷
                        </el-button>
                    </div>
                </div>
            </div>

            <div class="page_jg_20"></div>

            <!-- 视图展示数据 -->
            <QuestionnaireCard 
                v-if="defaultViewMode == 'view' && questionnaireCardList?.length > 0"
                :questionnaireList="questionnaireCardList"
                :cardStatusMsg="surveyManagementCardStatusMsg"
                cardType="questionnareManage"
                :pageSize="viewPageSize" 
                :totalNum="totalNum"
                :scrollAimDom="scrollDom"
                @loadMorePage="LoadMoreQuestionnaireList"

            >
                <template #default="{row}">
                    <el-button 
                        :class="[Number(row.useStatus) === 1 ? 'is-disabled' : 'button_background']"
                        @click="Number(row.useStatus) === 1 ?  '' : GoToCreateQuestionnaire(row)"    
                    >编辑</el-button>
                    <el-button class="button_border" @click="GoToPreviewQuestionnaire(row)">预览</el-button>
                    <el-button class="button_refresh" @click="CopyQuestionnaire(row)">复制</el-button>
                    <el-button 
                        :class="[Number(row.useStatus) === 1 ? 'is-disabled' : 'delete_button_border']"
                        @click="Number(row.useStatus) === 1 ?  '' : OpenDeleteDialog(row)"
                    >删除</el-button>
                </template>
            </QuestionnaireCard>


            <!-- 列表展示数据 -->
            <Table v-else-if="defaultViewMode == 'list'"
                :currentPage="tableCurrentPage" 
                :pageSize="tablePageSize" 
                :totalNum="totalNum"
                :tableData="questionnaireTableList"
                :tableColumns="questionnaireTableColumns"
                @paginationChange="HandlePaginationChange"
            >
                <template #num="{currentIndex}">
                    {{ currentIndex + tablePageSize * (tableCurrentPage - 1)}}
                </template>

                <template #useStatus="{row}">
                    <TableRowStatus :useStatus="row.useStatus" :statusMsg="surveyManagementRowStatusConvert"></TableRowStatus>
                </template>

                <template #operation="{row}">
                    <div class="table_row_option">
                        <span  
                            :class="[Number(row.useStatus) === 1 ? 'editor_disable' : 'el_button_editor']"
                            @click="Number(row.useStatus) === 1 ?  '' : GoToCreateQuestionnaire(row)"    
                        >编辑</span>
                        <span class="el_button_editor" @click="GoToPreviewQuestionnaire(row)">预览</span>
                        <span class="el_button_editor"  @click="CopyQuestionnaire(row)">复制</span>
                        <span 
                            :class="[Number(row.useStatus) === 1 ? 'editor_disable' : 'el_button_delete']"
                            @click="Number(row.useStatus) === 1 ?  '' : OpenDeleteDialog(row)"
                        >删除</span>
                    </div>
                </template>
            </Table>
        </div>

        <Dialog 
            :visible="dialogVisible" 
            :submitLoading="dialogSubmitLoading"
            @close="HandleDialogClose"
            @confirm="HandleDialogConfirm"
        >
            <span class="dialog_alert">确定删除 [ <span class="title">{{  currentOperationRow?.assessmentTitle}}</span> ] 吗</span>
        </Dialog>


    </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import { useRouter } from 'vue-router';
import Table from '@/baseComponents/Table.vue';
import TabSearch from '@/baseComponents/TabSearch.vue';
import TableRowStatus from '@/baseComponents/TableRowStatus.vue';
import QuestionnaireCard from '@/components/questionnaireCard/QuestionnaireCard.vue';

import { getQuestionnaireListApi , copyQuestionnaireApi,deleteQuestionnaireApi} from '@/api/surveyManagement'

import { viewModeTabList } from './tabSearch';  //视图项配置
import { questionnaireTableColumns } from './table';
import {surveyManagementCardStatusMsg,surveyManagementRowStatusConvert} from '@/components/statusDict'

import questionnaireCardUploadFileIcon from '@/assets/evaluateTeaching/questionnaire_card_upload_file_icon.png'




import { ElMessage } from 'element-plus';
import Dialog from '@/baseComponents/Dialog.vue';
interface QuestionnaireItm {
    id:Number,
    assessmentTitle:String,  //标题
    assessmentScore:Number|String,  //总分
    teacherName:String,  //创建人
    createdAt:String,   //创建时间
    useStatus:Number,   //1 已使用   0 未使用
    cardStatus:Number,
    time:String  //卡片 展示的时间
}
const router = useRouter()

// 1. 视图模式切换
const defaultViewMode = ref('view')
const  HandleTabChage = async (val)=>{    
    defaultViewMode.value = val
    await GetQuestionnaireList()
}



//. 问卷列表
const totalNum = ref(0)

const scrollDom = ref()  //目标滚动元素
const viewPageSize = ref(10)  //视图模式的单页大小
const addMoreUnit = ref(10)  //加载更多时，每次添加的量
const questionnaireCardList = ref<QuestionnaireItm[]>([]);

const tablePageSize = ref(10)  //表格模式的单页大小
const tableCurrentPage = ref(1)
const questionnaireTableList = ref<QuestionnaireItm[]>([]);




// 获取视图课程列表
const GetViewQuestionnaireList = async ()=>{
    let params = {
        pageNum:1,
        pageSize: viewPageSize.value
    }
    let res = await getQuestionnaireListApi(params)
    // __________________
    if(res?.code == 200){
        questionnaireCardList.value = res.data.records.map(itm=>{
            return {
                ...itm,
                cardStatus:itm.useStatus,
                time:itm.createdAt,
                title:itm.assessmentTitle,
            }
        })
        totalNum.value = res.data.total
    }
    // 获取完表格数据后，查看页面是否在滚动
    let domTotalHeight = scrollDom.value?.scrollHeight || 0
    let domClientHeight = scrollDom.value?.clientHeight || 0
    // 如果初始高度没有占满，就加载更多内容
    console.log('domTotalHeight',domTotalHeight,'domClientHeight',domClientHeight)

    if(domTotalHeight <= domClientHeight && totalNum.value > viewPageSize.value){
        console.log('emit-——more了')
        await LoadMoreQuestionnaireList()
    }
}

// 获取表格课程列表
const GetTableQuestionnaireList = async ()=> {
    let params = {
        pageNum:tableCurrentPage.value,
        pageSize: tablePageSize.value
    }
    let res = await getQuestionnaireListApi(params)
    if(res?.code == 200){
        questionnaireTableList.value = res.data.records.map(itm=>{
            return {
                ...itm,
                cardStatus:itm.useStatus,
                time:itm.createdAt,
                title:itm.assessmentTitle,
            }
        })
        totalNum.value = res.data.total
    }
}

// 获取问卷列表数据
const GetQuestionnaireList = async ()=>{
    if(defaultViewMode.value == 'view'){
        GetViewQuestionnaireList()
    }else if(defaultViewMode.value == 'list'){
        GetTableQuestionnaireList()
    }
}

// 表格分页切换
const HandlePaginationChange = async (params)=>{
    const {type, val} = params
    if(type == 'currentPage'){
        tableCurrentPage.value = val
        await GetQuestionnaireList()
    }
}
// 加载更多页面数据
const LoadMoreQuestionnaireList= async()=>{
    if(defaultViewMode.value == 'view'){
        viewPageSize.value += addMoreUnit.value
        await GetQuestionnaireList()
    }
}

// 2. 跳转创建问卷 /修改文件 
const GoToCreateQuestionnaire = (row?:any)=>{
    if(row.id){
        router.push(`/main/createQuestionnaire?id=${row.id}`)
    }else{
        router.push('/main/createQuestionnaire')
    }
}

// 预览问卷
const GoToPreviewQuestionnaire = (row)=>{
    router.push(`/main/previewQuestionnaire?id=${row.id}`)
}

// 复制问卷
const CopyQuestionnaire = async (row)=>{
    let res = await copyQuestionnaireApi(row.id)
    if(res?.code == 200){
        ElMessage.success(res?.msg)
        await GetQuestionnaireList()
    }
}



// 删除问卷
const dialogVisible= ref(false)
const dialogSubmitLoading = ref(false)
const currentOperationRow = ref()
// 打开删除弹窗
const OpenDeleteDialog = (row)=>{
    dialogVisible.value = true
    currentOperationRow.value = row
}
// 关闭删除弹窗
const HandleDialogClose = ()=>{
    dialogVisible.value = false
    currentOperationRow.value = null
    dialogSubmitLoading.value = false
}
// 确认删除操作
const HandleDialogConfirm = async ()=>{
    dialogSubmitLoading.value = true
    let res = undefined
    try{
        res =  await deleteQuestionnaireApi(currentOperationRow.value.id)
    }catch{}
    if(res?.code == 200){
        ElMessage.success(res?.msg)
        HandleDialogClose()
        await GetQuestionnaireList()
    }else{
        dialogSubmitLoading.value = false
    }
}



onMounted(async()=>{
    await GetQuestionnaireList()
})



</script>

<style lang="scss" scoped>

:deep(.box_tab){
   .selected{
        &.prefix{
            background:  #2E64FA;
            color: #fff;
            border:none 
        }
   } 
}
.dialog_alert{
    color:#666;
    display: flex;
    justify-content: center;
    align-items: center;
    .title{
        color: #333;
    }
}

.el-button{
    img{
        margin-right: 4px;
    }
}






</style>
