<template>
    <div class="space-y-4">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-medium">问卷列表</h3>
        </div>
        <div class="space-y-4">
            <div v-for="(survey, surveyIndex) in surveys" :key="surveyIndex"
                class="bg-white rounded-lg p-4 shadow-sm border-l-4 mb-4" :class="{
                'border-blue-500': survey.status === '未完成',
                'border-green-500': survey.status === '已完成'
            }">
                <div class="flex justify-between items-start">
                    <div class="flex-1">
                        <h4 class="font-medium text-lg mb-2">{{ survey.title }}</h4>
                        <p class="text-sm text-gray-600 line-clamp-2">{{ survey.remark || '' }}</p>
                    </div>
                    <div class="flex flex-col items-end gap-2 ml-4 min-w-[100px]">
                        <div class="flex items-center gap-2">
                            <el-tag :type="survey.status === '已完成' ? 'success' : 'warning'" size="small">
                                {{ survey.status }}
                            </el-tag>
                            <el-tag v-if="survey.phoneAnswerTotal > 0" type="info" size="small">
                                {{ survey.phoneAnswerTotal }}次填报
                            </el-tag>
                        </div>
                        <div v-if="survey.status === '已完成'" class="whitespace-nowrap">
                            <span v-if="survey.totalScore >= 0" class="text-lg font-medium" :style="{color: survey.labelColor || 'red' }">{{
                `${survey.surveyScoreLabel || ''} ${survey.totalScore === null ? '' : survey.totalScore}` }}</span>
                            <!-- <span class="text-lg font-medium" :class="{
                                'text-red-500': calculateScore(survey) <= 2,
                                'text-orange-500': calculateScore(survey) > 2 && calculateScore(survey) <= 5,
                                'text-yellow-500': calculateScore(survey) > 5 && calculateScore(survey) <= 7,
                                'text-green-500': calculateScore(survey) > 7
                            }">{{ calculateScore(survey) }}</span> -->
                        </div>
                    </div>
                </div>
                <div v-if="survey.historicalResponses?.length > 0 && survey.isExpanded" class="mb-4 mt-2">
                    <div class="flex items-center justify-between mb-2">
                        <h4 class="font-medium text-sm text-gray-600">历史填报记录</h4>
                        <div class="flex gap-2">
                            <el-select v-if="survey.historicalResponses?.length > 0"
                                v-model="survey.currentResponseIndex" size="small" placeholder="选择历史记录"
                                @change="(index) => viewHistoricalResponse(survey, index)" style="min-width: 200px">
                                <el-option v-for="(response, index) in survey.historicalResponses" :key="index"
                                    :label="`${response.createtime} - 得分: ${response.totalScore}`" :value="index" />
                            </el-select>
                            <el-button v-if="survey.status !== '已完成' && survey.currentResponseIndex >= 0" type="success" size="small" class="!rounded-button whitespace-nowrap"
                                @click="startNewResponse(survey)">
                                新填报
                            </el-button>
                        </div>
                    </div>
                </div>
                <div v-if="survey.isExpanded" class="mt-4 p-2" style="max-height: 600px; overflow-y: auto;">
                    <div class="space-y-3">
                        <fillOut :ref="(el) => surveyRefs[survey.surveyId] = el" :surveyId="survey.surveyId" :sheetId="survey.currentSheetId" />
                    </div>
                    <div class="flex justify-end mt-2 mr-2" v-if="survey.status !== '已完成' && !survey.currentSheetId">
                        <el-button type="primary" @click="submitSurvey(surveyIndex)" class="!rounded-button">
                            <el-icon class="mr-1">
                                <Check />
                            </el-icon>
                            提交问卷
                        </el-button>
                    </div>
                </div>
                <div class="flex justify-center mt-4">
                    <a href="javascript:void(0)" class="text-blue-500 hover:text-blue-600 text-sm flex items-center"
                        @click="toggleSurvey(surveyIndex)">
                        {{ survey.isExpanded ? '收起问卷' : '展开问卷' }}
                        <el-icon class="ml-1">
                            <ArrowDown :class="{ 'transform rotate-180': survey.isExpanded }" />
                        </el-icon>
                    </a>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick, getCurrentInstance, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import { getPageListData, createPageData } from '@/api/main/system/system';

import fillOut from '@/views/main/survey/fill.vue';
import moment from 'moment';

const { proxy } = getCurrentInstance();

const surveyRefs = ref<Record<number, any>>({});

const emit = defineEmits(['setVisit']);

const props = defineProps({
    callid: {
        type: Number,
        default: 0,
    },
    phone: {
        type: String,
        default: '13241334761',
    },

})
// 问卷列表数据
const surveys: any = ref([
    // 
]);
// 提交问卷方法
const getScoreLevel = (score) => {
    if (score <= 2) return '高危';
    if (score <= 5) return '危险';
    if (score <= 7) return '一般';
    return '良好';
};
const toggleSurvey = (index: number) => {
    surveys.value.forEach((survey, idx) => {
        survey.isExpanded = idx === index ? !survey.isExpanded : false;
        if (surveys.value[index].isExpanded) {
            survey.fillTimes = {
                start: moment().format('YYYY-MM-DD HH:mm:ss'),
                end: moment().format('YYYY-MM-DD HH:mm:ss'),
            };
        }
    });

    if (surveys.value[index].isExpanded  && !surveys.value[index].historicalResponse?.length) {
        getHistory(surveys.value[index]);
    }
};
const viewHistoricalResponse = (survey: any, index: number) => {
    survey.currentResponseIndex = index;
    survey.currentSheetId = survey.historicalResponses[index].answersheetId;
};
const startNewResponse = (survey: any) => {
    
    // survey.status = 'pending';
    survey.currentResponseIndex = '';
    survey.currentSheetId = 0;
};

const wranSurveys = ref([]);

// 提交问卷方法
const submitSurvey = (surveyIndex: number) => {
    const currentSurvey = surveys.value[surveyIndex];
    const componentRef = surveyRefs.value[currentSurvey.surveyId];

    if (!componentRef || !props.phone || !props.callid) {
        proxy.$modal.msgWarning(`只有来电用户才可进行填报`);
        return;
    }
    // if (!componentRef) return;

    try {
        const params: any = componentRef.getParams();
        if (params === undefined) return;
        console.log('子组件数据:', params);

        params.enterphone = props.phone;
        params.callId = props.callid || 0;

        params.starttime = currentSurvey?.fillTimes?.start || moment().format('YYYY-MM-DD HH:mm:ss');
        params.endtime = moment().format('YYYY-MM-DD HH:mm:ss');
        console.log(params, 'params');
        createPageData('/survey/answersheet', params).then((res: any) => {
            console.log(res, 'res');
            if (res.state === 'success') {

                currentSurvey.status = '已完成';
                currentSurvey.phoneAnswerTotal = currentSurvey.phoneAnswerTotal + 1;
                currentSurvey.surveyScoreLabel = res.data?.labelName || '';
                currentSurvey.totalScore = res.data?.totalScore;
                currentSurvey.labelColor = res.data?.color;
                if (res.data?.isYj) {
                    
                    wranSurveys.value.push({
                        surveyId: currentSurvey.surveyId,
                        totalScore: res.data.totalScore,
                        sheetId: res.data.sheetId,
                        callId: props.callid || 0,
                    });

                    emit('setVisit', true);

                    // 说明有预警需要显示
                    proxy.$modal.msgWarning(`触发预警：${res.data.labelName}，得分: ${res.data.totalScore}`);
                } else {
                    if (currentSurvey.totalScore !== null) {
                        proxy.$modal.msgWarning(`等级：${res.data.labelName}，得分: ${res.data.totalScore}`);
                    } else {
                        proxy.$modal.msgSuccess('提交成功！');
                    }
                    
                }
                getHistory(currentSurvey);
            } else {
                proxy.$modal.msgError('提交失败');
            }
        })
    } catch (error) {
        console.error('获取子组件数据失败:', error);
    }



    // survey.status = 'completed';
    // const score = calculateScore(survey);
    // if (!survey.historicalResponses) {
    //     survey.historicalResponses = [];
    // }
    // // 保存当前填报记录
    // const currentResponse = {
    //     submitTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
    //     score,
    //     questions: survey.questions.map((q: any) => ({
    //         ...q,
    //         answer: JSON.parse(JSON.stringify(q.answer))
    //     }))
    // };
    // survey.historicalResponses.unshift(currentResponse);
    // survey.currentResponseIndex = 0;
    // ElMessage({
    //     message: `问卷提交成功！您的得分为：${score}/10`,
    //     type: 'success'
    // });
};


// 获取问卷列表
const getList = () => {
    const params = {
        callid: props.callid,
        phone: props.phone,
    };

    // if (!params.callid || !params.phone) return;

    getPageListData('/survey/survey/getcallsurvey', params).then(({ data }) => {
        surveys.value = data;

        console.log(surveys.value, '问卷列表');
    })
}

// 获取问卷提交历史记录
const getHistory = (survey: any) => {
    const params = {
        phone: props.phone,
        surveyid: survey.surveyId,
    };

    if (!params.phone || !params.surveyid) return;

    getPageListData('/survey/survey/getsurveyinfo', params).then(({ data }) => {
        survey.historicalResponses = data;
        if (survey.historicalResponses.length > 0 && survey.status === '已完成') {
            // survey.currentResponseIndex = 0;
            // survey.cur
            const index = survey.historicalResponses.findIndex((item: any) => {
                return item.callId.toString() === (props.callid || '').toString()
            });
            console.log(survey.historicalResponses, index, '问卷历史记录');
            if (index > -1) {
                survey.currentResponseIndex = index;
                survey.currentSheetId = survey.historicalResponses[index].answersheetId;
            }
        }
        
    })
}

const getWarnSurvey = () => {
    return wranSurveys.value;
}


onMounted(() => {
    wranSurveys.value  = [];
    getList();
});

defineExpose({
	getWarnSurvey,
});
</script>

<style></style>