<template>
    <div class="page_item  end_item">
        <div class="page_search">
            <div class="search_content">
                <div class="content_left">
                    <div class="grade_title">参数设置</div>
                </div>
                <div class="content_right">
                    <el-button  class="button_border" @click="StartOrSaveEdit">{{!isEdit ? '开始编辑' : '保存编辑'}}</el-button>
                    <el-button  class="button_background" @click="FinishParamaterSetting">设置完成</el-button>

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

        <Form :inlineLayout="false" 
            v-model:formRef="paramsSettingFormDom"
            :formItemList="paramsConfigFormItemList" 
            :defaultFormData="defaultParamsConfigFormData"
            :formDisabled="!isEdit"
        >
            <template #lowScoreDeleteRatio="{}">
                <div class="low_score_delete_ratio">
                    <el-radio-group :disabled="!isEdit"
                        v-model="defaultParamsConfigFormData.lowScoreDeleteRatio">
                        <el-radio v-for="radioItem in lowScoreDeleteRatioList" :key="radioItem.value" 
                            :value="radioItem.value">
                            {{ radioItem.label }}
                        </el-radio>
                    </el-radio-group>

                    <el-input v-if="defaultParamsConfigFormData.lowScoreDeleteRatio == 'custom'"  
                                type="number" :disabled="!isEdit" :step="0.01" :min="0" :max="100"
                                v-model="defaultParamsConfigFormData.customLowScoreDeleteRatio"   
                                @change="HandleInputNumberChange"
                            placeholder="请输入"/>
                </div>
                

            </template>
        </Form>

        <Table :tableColumns="tableColumns" 
            :tableData="tableData"
            :hidePagination="true">
            <template #subjectData="{row}">
                <div class="subject_tag">
                    <el-tag
                        v-for="item in row.subjectData"
                        :key="item"
                        :disable-transitions="true"
                        type="info"
                        effect="plain"
                    >
                    {{ item.name }}
                    </el-tag>
                </div>
            </template>
            <template #operation="{row}">
                <div class="table_row_option">
                    <span :class="[isEdit ?  'el_button_editor' : 'editor_disable']" @click="isEdit ?  OpenSubjectCompositionForm(row) : ''">编辑</span>
                    <span :class="[isEdit ?  'el_button_delete' : 'editor_disable']" @click="isEdit ?   OpenDeleteDialog(row) : ''">删除</span>
                </div>
            </template>
        </Table>
        <div class="page_jg_20"></div>
        <div v-if="isEdit" class="add_subject_option" @click="OpenSubjectCompositionForm">
            <img :src="addIcon" alt="">
            增加科目组合
        </div>
    </div>

    <FormDialog 
        width="640px"
        :visible="compositionSubjectFormVisible" 
        :defaultFormData="defaultCompositionSubjectFormData" 
        :title="compositionSubjectFormTitle" 
        :submitLoading="compositionSubjectFormLoading" 
        :formItemList="formItemList" 
        @close="CloseSubjectCompositionForm" 
        @confirm="HandleAddCompositionSubject">
    </FormDialog>

    <Dialog  :visible="deleteDialogVisible" 
        :submitLoading="deleteSubmitLoading" 
        @close="CloseDeleteDialog" @confirm="HandleDeleteConfirm"></Dialog>

</template>



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

import { useStore } from 'vuex';


import Table from '@/baseComponents/Table.vue';
import Form from '@/baseComponents/Form.vue';
import FormDialog from '@/baseComponents/FormDialog.vue';

import {paramsConfigFormItemList} from './form'
import { tableColumns } from './table';
import {formItemList} from './formDialog'

import {
    getParameterSettingListApi,getSubjectDataListApi,deleteCompositionSubjectApi,
    addOrUpdateCompositionSubjectApi,finishParamaterSettingApi,saveParamaterSettingApi
} from '@/api/parameterSettingComponent'
import { ElMessage } from 'element-plus';
import Dialog from '@/baseComponents/Dialog.vue';


import addIcon from '@/assets/icon/add.svg'


const route = useRoute()
const router = useRouter()
const store = useStore()

// 1. 参数设置 表单
const defaultParamsConfigFormData = ref({})

const lowScoreDeleteRatioList = ref([
    {
        label:'3%',
        value:'3'
    },
    {
        label:'5%',
        value:'5'
    },
    {
        label:'10%',
        value:'10'
    },
    {
        label:'自定义',
        value:'custom'
    },
])

interface TableData {
    id:string,
    groupSubjectName:string,
    subjectData:{
        name:string
    }[]
}
const tableData = ref<TableData[]>([])

//  获取参数设置 的信息
const GetParamaterSetting = async ()=>{
    let res = await getParameterSettingListApi(route.query.id)
    if(res?.code == 200){
        tableData.value = res.data.groupSubjects
        defaultParamsConfigFormData.value.id = res.data.id
        defaultParamsConfigFormData.value.isDeleteFullScore = res.data.fullScoreStatus
        defaultParamsConfigFormData.value.lowScoreDeleteRatio = res.data.lowScoreCustom ?  'custom' : res.data.lowScoreRadio
        defaultParamsConfigFormData.value.customLowScoreDeleteRatio = res.data.lowScoreCustom ? res.data.lowScoreRadio : ''
    }
}


// 2. 参数设置 操作
const isEdit = ref(false)
const paramsSettingFormDom = ref()  // 参数设置表单dom

// 开始/保存 编辑
const StartOrSaveEdit = async ()=>{
    if(isEdit.value){
        console.log('点击 了')
        console.log('参数设置表单的值__',defaultParamsConfigFormData.value)

        let params = {
            id: defaultParamsConfigFormData.value.id,
            evaluationId: route.query.id,
            fullScoreStatus: defaultParamsConfigFormData.value.isDeleteFullScore,
            lowScoreRadio: defaultParamsConfigFormData.value.lowScoreDeleteRatio == 'custom' ? defaultParamsConfigFormData.value.customLowScoreDeleteRatio : defaultParamsConfigFormData.value.lowScoreDeleteRatio,
            lowScoreCustom: defaultParamsConfigFormData.value.lowScoreDeleteRatio == 'custom' ? 1 : 0
        }
      
        let res  = await saveParamaterSettingApi(params)
        if(res?.code == 200){
            ElMessage.success(res?.msg)
            await GetParamaterSetting()
        }
    }
    isEdit.value = !isEdit.value
}
// 自定义删除比例的数字矫正
const HandleInputNumberChange = (val)=>{
    console.log('输入的值---',val)
    if(Number(val) > 100){
        defaultParamsConfigFormData.value.customLowScoreDeleteRatio = 100
    }else if(Number(val) < 0){
        defaultParamsConfigFormData.value.customLowScoreDeleteRatio = 0
    }else if(String(val).split('.')[1]?.length > 2){
        let splitArray =  String(val).split('.')
        defaultParamsConfigFormData.value.customLowScoreDeleteRatio = Number(splitArray[0] +'.' + splitArray[1].slice(0,2))
    }
}


// 3. 新增科目组合弹窗 及 操作
const compositionSubjectFormVisible = ref(false)
const compositionSubjectFormLoading = ref(false)
const compositionSubjectFormTitle = ref('')
const defaultCompositionSubjectFormData = ref({})
// 打开 新增/修改 弹窗
const OpenSubjectCompositionForm = async (row)=>{
    if(row?.id){
        compositionSubjectFormTitle.value = '修改科目组合'
        // 默认表单赋值
        defaultCompositionSubjectFormData.value = {
            groupSubjectName:row.groupSubjectName,
            subjectList:row.subjectData.map(item=>{
                return item.code
            }),
            id:row.id
        }
    }else{
        compositionSubjectFormTitle.value = '新增科目组合'
    }
    compositionSubjectFormVisible.value = true
    await GetSubjectDataList()
}

// 关闭弹窗
const CloseSubjectCompositionForm = ()=>{
    compositionSubjectFormVisible.value = false
    compositionSubjectFormLoading.value = false
    defaultCompositionSubjectFormData.value = {}
}

// 新增科目弹窗确认
const HandleAddCompositionSubject = async (params)=>{
    compositionSubjectFormLoading.value = true
    const {formData,formRef} = params
    console.log('表单弹窗信息',formData)
    let subjectData = formData.subjectList.map(item=>{
        return {
            code:item
        }
    })
    let transferParams = {
        id: formData.id,
        evaluationId: route.query.id,
        // "evaluationGroupSubjectId": 0,
        groupSubjectName: formData.groupSubjectName,
        subjectData: subjectData
    }

    let res = undefined
    res = await addOrUpdateCompositionSubjectApi(transferParams)

    if(res?.code == 200){
        ElMessage.success(res?.msg)
        CloseSubjectCompositionForm()
        // 重查数据
        await GetParamaterSetting()

    }else{
        compositionSubjectFormLoading.value = false
    }
}

// 查询科目下拉数据
const GetSubjectDataList = async ()=>{
    let res = await getSubjectDataListApi(route.query.id)
    if(res?.code == 200){
         let subjectOptions = res?.data.map(item=>{
            return {
                label:item.name,
                value:item.code
            }
         })

         formItemList.value = formItemList.value.map(item=>{
            if(item.key == 'subjectList'){
                item.selectList = subjectOptions
            }
            return item
         })
    }
}


// 4. 删除科目组合
// 
const deleteDialogVisible = ref(false)
const deleteSubmitLoading = ref(false)
const currentDeleteRow = ref()
// 关闭删除弹窗
const CloseDeleteDialog = ()=>{
    deleteDialogVisible.value = false
    deleteSubmitLoading.value = false

}
// 打开删除弹窗
const OpenDeleteDialog = (row)=>{
    currentDeleteRow.value = row
    deleteDialogVisible.value = true
}

const HandleDeleteConfirm = async ()=>{
    deleteSubmitLoading.value = true
    let row = currentDeleteRow.value
    let res = undefined
    try{
        res= await deleteCompositionSubjectApi(row.id)
    }catch{}
    if(res?.code == 200){
        ElMessage.success(res?.msg)
        CloseDeleteDialog()
        // 重新查询
        await GetParamaterSetting()
    }
    deleteSubmitLoading.value = false
}


// 5. 完成参数设置
const FinishParamaterSetting = async ()=>{
    let params = {
        id: defaultParamsConfigFormData.value.id,
        evaluationId: route.query.id,
        fullScoreStatus: defaultParamsConfigFormData.value.isDeleteFullScore,
        lowScoreRadio: defaultParamsConfigFormData.value.lowScoreDeleteRatio == 'custom' ? defaultParamsConfigFormData.value.customLowScoreDeleteRatio : defaultParamsConfigFormData.value.lowScoreDeleteRatio,
        lowScoreCustom: defaultParamsConfigFormData.value.lowScoreDeleteRatio == 'custom' ? 1 : 0
    }
    let res = await finishParamaterSettingApi(params)
    if(res?.code == 200){
        isEdit.value = false
        // 更新全局状态 
        await store.dispatch('updateEvaluationManageStepData',route.query.id)

        // 并 跳转到下一步 
        
        // 线上匿名  
        // store.state.evaluationManageStepData.evaluationType   // 评价方式  0-线上匿名，1-线下答卷，2-线上导入，3-线上实名
        if(store.state.evaluationManageStepData.evaluationType === 0){
            store.commit('updateEvaluationManageStepData',{currentActiveStepName:'evaluationProgress'})  //更新全局活跃路由
            router.push(`evaluationProgress?id=${route.query.id}`)
        
        // 线下答卷 
        }else if(store.state.evaluationManageStepData.evaluationType === 1){
            store.commit('updateEvaluationManageStepData',{currentActiveStepName:'generateAnalysis'})  //更新全局活跃路由
            router.push(`generateAnalysis?id=${route.query.id}`)
        }
    }
}

onMounted(async ()=>{
    await GetParamaterSetting()
})
</script>



<style lang="scss" scoped>

.questionnaire_cell{
    gap:16px;
    word-break: keep-all;
}

.subject_tag{
    display: flex;
    gap:10px;
}

.add_subject_option{
    flex-grow: 0 !important;
    
    display: flex;
    justify-content: center;
    align-items: center;
    gap:8px;

    background: rgba(46,100,250,0.1);
    border-radius: 6px 6px 6px 6px;
    text-align: center;
    padding:4px 0;
    color:#2e64fa;
    font-size: 14px;
    cursor: pointer;

}

.low_score_delete_ratio{
    display: flex;
    width: 100%;
    :deep(.el-input){
        width: 80px;
        margin-left: 8px;
    }
}



</style>