<template>
    <div  ref="courseDom" 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">创建评价</el-button>
                    </div>
                </div>
            </div>

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

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

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

            <!-- 视图展示数据 -->
            <div v-if="defaultViewMode == 'view' && questionnaireList?.length > 0" 
                class="questionnaire_list">
                <template  
                    v-for="questionnaire in questionnaireList" 
                    :key="questionnaire.id" 
                >
                    <QuestionnaireCard 
                        :cardStatusMsg="reviewManageCardStatusMsg" 
                        :cardTypeMsg="reviewManageTaskTypeMsg"
                        :questionnaire="questionnaire"
                        cardType="reviewManage"
                        @switchOnOff="HandleCardSwitchOnOff"
                    >
                        <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>
                </template>
                
            </div>
            <!-- 列表展示数据 -->
            <Table v-else-if="defaultViewMode == 'list'"
                :currentPage="currentPage" 
                :pageSize="pageSize" 
                :totalNum="totalNum"
                :tableData="questionnaireList"
                :tableColumns="questionnaireTableColumns"
            >
                <template #num="{currentIndex}">
                    {{ currentIndex + pageSize * (currentPage - 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>
                        <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>
                </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'

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,
    evaluationGrade:Array<String>,
    status:Boolean,


}
const router = useRouter()

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

// 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 currentPage = ref(1)
const totalNum = ref(0)
const pageSize = ref(20)
const questionnaireList = ref<QuestionnaireItm[]>([]);
// 问卷开关切换
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 GetQuestionnaireTaskList = async ()=>{
    console.log('获取到的查询参数',searchParams.value)
    let params = {
        pageNum:currentPage.value,
        pageSize: pageSize.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){
        questionnaireList.value = res.data.records.map(item=>{
            return {
                ...item,
                cardStatus:item.evaluationStatus,
                title:item.evaluationName,
                time:item.evaluationStartDatetime + ' 至 ' + item.evaluationEndDatetime
            }
        })
    }
}

// 跳转问卷评价详情页
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
            }
        }
    })
}
// 更新 新增/修改 状态下，评价方式切换 所展示的 不同表单信息
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 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){
        // 修改
        defaultFormData.value = row
        // 要判断表单的显隐藏
        UpdataEditOrAddFormHideOfDifferReviewType(row.id, row.evaluationType);
    }else{
        // 新增
        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([''])
    }
}

// 创建问卷 _保存
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
    }
}



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



</script>

<style lang="scss" scoped>

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

    .simple_filter{
        gap:20px
    }
}

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