<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"
                        />
                        <FormSearchGroup :search-list="searchList" 
                            @searchChange="HandleSearchChange"></FormSearchGroup>
                    </div>
                    <div class="conent_right">
                        <el-button class="button_background" @click="OpenQuestionnaireDialog">
                            <img :src="questionnaireCardUploadFileIcon" alt="">
                            创建评价
                        </el-button>
                    </div>
                </div>
            </div>

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

            <SearchBlock 
                :searchList="statusSearchList" 
                @searchChange="HandleSearchChange">
            </SearchBlock>

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

            <!-- 视图展示数据 -->
            <QuestionnaireCard 
                v-if="defaultViewMode == 'view' && questionnaireViewList?.length > 0"
                :questionnaireList="questionnaireViewList"
                :cardStatusMsg="reviewManageCardStatusMsg" 
                :cardTypeMsg="reviewManageTaskTypeMsg"
                cardType="reviewManage"
                @switchOnOff="HandleCardSwitchOnOff"

                :pageSize="viewPageSize" 
                :totalNum="totalNum"
                :scrollAimDom="scrollDom"
                @loadMorePage="LoadMoreQuestionnaireTaskList"



            >
                <template #default="{row}">
                    <el-button @click="GoToQuestionnaireReviewDetail(row)"  class="button_background">查看详情</el-button>
                    <el-button 
                        :class="['button_border']"
                        @click="OpenQuestionnaireDialog(row)"    
                    >编辑</el-button>

                    <!-- row.status 0 可以删除/修改    1 不可以 删除/修改 -->
                    <el-button 
                        :class="[!row.status  ? 'delete_button_border' : 'is-disabled' ]"
                        @click="!row.status  ? 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 #evaluationType="{row}">
                    {{ reviewManageTaskTypeMsg.find(item=>{return item.type === row.evaluationType})?.title }}
                </template>

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

                <template #openStatus="{row}">
                    <span v-if="row.evaluationType === 0">
                        <el-switch
                            :model-value="Boolean(row.openStatus)"
                            @change="(val)=>HandleCardSwitchOnOff({id:row.id,onOffVal:val})"
                            style="--el-switch-on-color: #2e64fa; --el-switch-off-color: #bbbbbb"
                        />
                    </span>
                    <span v-else>-</span>
                </template>

                <template #evaluationStartDatetime="{row}">
                    {{ row.evaluationStartDatetime ?  row.evaluationStartDatetime : '-' }}
                </template>

                <template #evaluationEndDatetime="{row}">
                    {{ row.evaluationEndDatetime ?  row.evaluationEndDatetime : '-'  }}
                </template>

                <template #operation="{row}">
                    <div class="table_row_option">

                        <span  @click="GoToQuestionnaireReviewDetail(row)" :class="['option_button_editor']">查看详情</span>
                        <span  
                            :class="['el_button_editor']"
                            @click="OpenQuestionnaireDialog(row)"    
                        >编辑</span>
                        <span 
                            :class="[!row.status ?  'el_button_delete' : 'editor_disable' ]"
                            @click="!row.status ?  OpenDeleteDialog(row) :  '' "
                        >删除</span>
                    </div>
                </template>
            </Table>
        </div>


        <!-- 创建评价弹窗 -->
         <FormDialog   
            width="590px"
            :visible="formDialogVisible"
            :submitLoading="formSubmitLoading" 
            :title="formDialogTitle" 
            :formItemList="formDialogItmList" 
            :defaultFormData="defaultFormData" 
            @formItemChange="HandleFormItmChange"
            @close="CloseFormDialog" 
            @confirm="AddQuestionnaireTask">
        </FormDialog>


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


    </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

import Table from '@/baseComponents/Table.vue';
import TabSearch from '@/baseComponents/TabSearch.vue';
import TableRowStatus from '@/baseComponents/TableRowStatus.vue';
import Dialog from '@/baseComponents/Dialog.vue';
import FormDialog from '@/baseComponents/FormDialog.vue';
import FormSearchGroup from '@/baseComponents/FormSearchGroup.vue';
import SearchBlock from '@/baseComponents/SearchBlock.vue';

import QuestionnaireCard from '@/components/questionnaireCard/QuestionnaireCard.vue';
import {reviewManageRowStatusConvert, reviewManageTaskTypeMsg, reviewManageCardStatusMsg} from '@/components/statusDict'

import {
    getGradeListApi,getQuestionnaireTaskListApi,addQuestionnaireTaskListApi,
    getSchoolYearListApi,oppenOrCloseQuestionnaireTaskApi,
    editQuestionnaireTaskListApi,deleteQuestionnaireTaskApi

} from '@/api/reviewManagement'

import { unioformDateTransform } from '@/utils/dateTransform';

import {searchList, viewModeTabList, statusSearchList} from './searchListConfig'
import { questionnaireTableColumns } from './table';

import { formDialogItmList } from './formDialog'

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


interface QuestionnaireItm {
    id:Number | String,
    evaluationName:String,  //标题
    teacherName:String,  //创建人
    evaluationStartDatetime:String,   //开始时间
    evaluationEndDatetime:String,   //结束时间
    time:String,  //开始时间 + 结束时间
    evaluationStatus:Number,   // 评价状态，1-进行中，2-已结束
    cardStatus:Number,
    openStatus:Boolean,    // 0 关闭   1 开启 
    evaluationType:Number|String,  //评价方式，0-线上匿名，1-线下答卷，2-线上导入，3-线上实名
    evaluationGrade:Array<String>,
    status:Boolean,


}
const router = useRouter()

// 1. 视图模式切换
const defaultViewMode = ref('view')
const  HandleTabChage = (val)=>{    
    console.log('当前模式',val)
    defaultViewMode.value = val
    GetQuestionnaireTaskList()
}

// 2. 查询参数
const searchParams = ref({
    evaluationStatus:'',
    evaluationName:'',
    schoolYear:'',
})
const HandleSearchChange = async (params,key)=>{
    // console.log('获取到的查询参数',params)
    searchParams.value = {
        ...searchParams.value,
        ...params
    }
    await GetQuestionnaireTaskList()
}
// 获取学年列表信息 
const GetSchoolYearList =  async()=>{
    let res = await getSchoolYearListApi()
    let schoolYearOpt = []
    if(res?.code == 200){
        schoolYearOpt = res?.data?.map(item=>{
            return {
                label:item.schoolYearName,
                value:item.schoolYearCode
            }
        }) || []
    }
    searchList.value = searchList.value.map(item=>{
        if(item.key == 'schoolYear'){
            return {
                ...item,
                options:[{
                            label:'全部',
                            value:'all'
                        },...schoolYearOpt],
                defaultValue:'all'
            }
        }else{
            return item  
        }
    })
}




//.3. 问卷列表
const addMoreUnit = ref(10)  //加载更多时，每次添加的量
const scrollDom = ref()  //目标滚动元素
const totalNum = ref(0)

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

const viewPageSize = ref(10)  //视图页单页大小
const questionnaireViewList = ref<QuestionnaireItm[]>([]);

// 获取评价管理视图列表信息
const GetViewQuestionnaireTaskList = async ()=>{
    let params = {
        pageNum:1,
        pageSize: viewPageSize.value,
        evaluationStatus: searchParams.value.evaluationStatus == 'all' ? '' : searchParams.value.evaluationStatus,
        evaluationName: searchParams.value.evaluationName,
        schoolYearCode: searchParams.value.schoolYear == 'all' ? '' : searchParams.value.schoolYear,
    }
    let res = await getQuestionnaireTaskListApi(params)

    if(res?.code == 200){
        questionnaireViewList.value = res.data.records.map(item=>{
            return {
                ...item,
                cardStatus:item.evaluationStatus,
                title:item.evaluationName,
                time:item.evaluationStartDatetime + ' 至 ' + item.evaluationEndDatetime
            }
        })
        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 LoadMoreQuestionnaireTaskList()
    }
}

// 获取评价管理表格列表信息
const GetTableQuestionnaireTaskList = async ()=>{
    let params = {
        pageNum:tableCurrentPage.value,
        pageSize: tablePageSize.value,
        evaluationStatus: searchParams.value.evaluationStatus == 'all' ? '' : searchParams.value.evaluationStatus,
        evaluationName: searchParams.value.evaluationName,
        schoolYearCode: searchParams.value.schoolYear == 'all' ? '' : searchParams.value.schoolYear,
    }
    let res = await getQuestionnaireTaskListApi(params)

    if(res?.code == 200){
        questionnaireTableList.value = res.data.records.map(item=>{
            return {
                ...item,
                cardStatus:item.evaluationStatus,
                title:item.evaluationName,
                time:item.evaluationStartDatetime + ' 至 ' + item.evaluationEndDatetime
            }
        })
        totalNum.value = res.data.total
    }
}

// 、获取问卷任务列表
const GetQuestionnaireTaskList = async ()=>{
    if(defaultViewMode.value == 'view'){
        GetViewQuestionnaireTaskList()
    }else if(defaultViewMode.value == 'list'){
        GetTableQuestionnaireTaskList()
    }
}


// 表格分页切换
const HandlePaginationChange = async (params)=>{
    const {type, val} = params
    if(type == 'currentPage'){
        tableCurrentPage.value = val
        await GetQuestionnaireTaskList()
    }
}

// 加载更多页面数据
const LoadMoreQuestionnaireTaskList= async()=>{
    if(defaultViewMode.value == 'view'){
        viewPageSize.value += addMoreUnit.value
        await GetQuestionnaireTaskList()
    }
}


// 问卷开关切换
const HandleCardSwitchOnOff = async(params)=>{
    console.log('当前传递的参数---params',params)
    const {id,onOffVal} = params
    let res = await oppenOrCloseQuestionnaireTaskApi(id,onOffVal ? 1 : 0)
    if(res?.code == 200){
        // 重新查询表列
        await GetQuestionnaireTaskList()
    }
}



// 跳转问卷评价详情页
const GoToQuestionnaireReviewDetail = (row)=>{
    router.push(`/main/reviewManagementDetail/evaluationData?id=${row.id}`)
}

//4. 新增/修改问卷任务
const formDialogTitle = ref('')
const formSubmitLoading = ref(false)
const formDialogVisible = ref(false)
const defaultFormData = ref({  //表单默认值
    evaluationType:0
})
const currentEditRow = ref({})  //当前编辑的行
const currentEditGradeList = ref([])   //当前编辑/新增 弹窗中 的年级列表数据


// 更新form表单的隐藏和展示项
const UpdataFormDialogItmHideList = (hideKeys:string[])=>{
    formDialogItmList.value = formDialogItmList.value.map(item=>{
        if(hideKeys.includes(item.key)){
            return {
                ...item,
                hidden:true
            }
        }else{
            return {
                ...item,
                hidden:false
            }
        }
    })
}
// 更新 新增/修改 状态下，评价方式切换 所展示的 不同表单信息
 //type :评价方式，0-线上匿名，1-线下答卷，2-线上导入，3-线上实名
const UpdataEditOrAddFormHideOfDifferReviewType = (id,type)=>{
    switch(Number(type)){
            case 0:
            case 2:{
                if(id){
                    UpdataFormDialogItmHideList(['evaluationGrade'])
                }else{
                    UpdataFormDialogItmHideList([])
                }
                break
            }
            case 1:{
                defaultFormData.value.evaluationStartDatetime = ''
                defaultFormData.value.evaluationEndDatetime = ''
                if(id){
                    UpdataFormDialogItmHideList(['evaluationStartDatetime','evaluationEndDatetime','evaluationGrade'])
                }else{
                    UpdataFormDialogItmHideList(['evaluationStartDatetime','evaluationEndDatetime'])
                }
                break
            }
        }
}


// 更新表单的禁选项
const UpdateFormDialogItmDisabledList = (disabledKeys:string[])=>{
    formDialogItmList.value = formDialogItmList.value.map(item=>{
        if(disabledKeys.includes(item.key)){
            return {
                ...item,
                disabled:true
            }
        }else{
            return {
                ...item,
                disabled:false
            }
        }
    })

}


// 切换问卷评价表单内容 _需要根据条件清空开始时间和结束时间
// 同时要判断 当前是 新增 还是 修改
const HandleFormItmChange = (params)=>{
    const {key,val,formData} = params
    if(key == 'evaluationType'){
        console.log('当前参数内容',val)
        UpdataEditOrAddFormHideOfDifferReviewType(defaultFormData.value?.id, val);
    }
}
// 打开创建问卷弹窗
const OpenQuestionnaireDialog = async (row?:any)=>{
    formDialogVisible.value = true
    if(row.id){
        formDialogTitle.value = '修改评价'
        // 修改
        defaultFormData.value = row
        // 要判断表单的显隐藏
        UpdataEditOrAddFormHideOfDifferReviewType(row.id, row.evaluationType);
        // row.status :  0 可以删除/修改 ；1 不可以 删除/修改 
        UpdateFormDialogItmDisabledList(row.status ?  ['evaluationType'] : [])
    }else{
        formDialogTitle.value = '创建评价'
        // 新增
        let gradeListOption = []
        let res = await getGradeListApi()
        // 赋值年级下拉
        if(res?.code == 200){
            currentEditGradeList.value = res.data || []
            gradeListOption = res.data.map(item=>{
                return {
                    label:item.gradeName,
                    value:JSON.stringify({
                        gradeCode:item.gradeCode,
                        gradeName:item.gradeName,
                        gradeId:item.gradeId,
                    })
                }
            })
            formDialogItmList.value = formDialogItmList.value.map(item=>{
                if(item.key == 'evaluationGrade'){
                    return {
                        ...item,
                        selectList:gradeListOption
                    }
                }else {
                    return item
                }
            })
        }
        UpdataFormDialogItmHideList([])
        UpdateFormDialogItmDisabledList([])
    }
}

// 创建问卷 _保存
const AddQuestionnaireTask = async (params?:any)=>{
    const {formData,formRef} = params
    console.log('表单信息',formData)
    formSubmitLoading.value = true
    let selectedGradeData = formData.evaluationGrade?.map(item=>{
        return JSON.parse(item)
    }) || []

    let gradeData = currentEditGradeList.value.map(item=>{
        let exitAim = selectedGradeData.find(selectItm=>{
            return selectItm.gradeId == item.gradeId
        })
        return {
            ...item,
            selectStatus: exitAim ? 1 : 0
        }
    })
    let finalPrams = {
        evaluationName: formData.evaluationName,
        evaluationType: formData.evaluationType,
        evaluationStartDatetime: unioformDateTransform(formData.evaluationStartDatetime),
        evaluationEndDatetime: unioformDateTransform(formData.evaluationEndDatetime),
        gradeData:gradeData
    }
    let res = undefined
    try{
        if(formData.id){
            // 修改
            res = await editQuestionnaireTaskListApi({...finalPrams,id:formData.id})
        }else{
            res = await addQuestionnaireTaskListApi(finalPrams)
        }
    }catch{}

    if(res?.code == 200){
        ElMessage.success(res.msg)
        formRef.resetFields()
        CloseFormDialog()
        await GetQuestionnaireTaskList()   // 重查信息
    }else{
        formSubmitLoading.value = false
    }
}

// 关闭问卷弹窗
const CloseFormDialog = ()=>{
    defaultFormData.value = {
        evaluationType:0
    }
    currentEditRow.value = {}
    formDialogVisible.value = false
    formSubmitLoading.value = false
    currentEditGradeList.value = []
}




// 5. 删除问卷
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 deleteQuestionnaireTaskApi(currentOperationRow.value.id)
    }catch{}
    if(res?.code == 200){
        ElMessage.success(res?.msg)
        HandleDialogClose()
        await GetQuestionnaireTaskList()
    }else{
        dialogSubmitLoading.value = false
    }
}



//  6. 创建任务时候的时间范围限制
// 开始禁选时间
const startDisabledDate = (date)=>{
    if(defaultFormData.value.evaluationEndDatetime){
        // 开始时间 要早于 结束时间
        if(new Date(date).getTime() >= new Date(defaultFormData.value.evaluationEndDatetime).getTime()){
            return true
        }else{
            return false
        }
    }else{
        return false
    }
}

// 结束禁选时间
const endDisabledDate = (date)=>{
    if(defaultFormData.value.evaluationStartDatetime){
        // 开始时间 要大于结束时间
        if(new Date(date).getTime() <= new Date(defaultFormData.value.evaluationStartDatetime).getTime()){
            return true
        }else{
            return false
        }
    }else{
        return false
    }
}

onMounted(async()=>{
    await GetSchoolYearList()
    await GetQuestionnaireTaskList()


    // 初始化 新增/修改 评价弹窗的 时间禁选 赋值
    formDialogItmList.value = formDialogItmList.value.map(item=>{
        if(item.key == 'evaluationStartDatetime'){
            item.disabledDate = startDisabledDate
        }else if(item.key == 'evaluationEndDatetime'){
            item.disabledDate = endDisabledDate
        }
        return item
    })
})



</script>

<style lang="scss" scoped>

.conent_left{
    display: flex;
    gap:20px;
    align-items: center;

    .simple_filter{
        gap:20px
    }
}

.conent_right{
    :deep(.el-button){
        img{
            margin-right: 4px;
        }
    } 
}

: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;
    }
}

</style>
