<template>
    <div class="drawer-content h-full flex flex-col">
        <!-- 上半部分：问卷列表 -->
        <div class="survey-list-container p-6 bg-white border-b">
            <div class="overflow-x-auto whitespace-nowrap pb-4">
                <div class="inline-flex gap-4">
                    <div v-for="(survey, index) in surveys" :key="index" @click="toggleSurvey(index)"
                        :data-survey-id="survey.surveyId" :class="[
                        'survey-card cursor-pointer p-6 rounded-lg border min-w-[300px]',
                        survey.surveyId === selectedSurvey.surveyId ? 'border-blue-500 bg-blue-50' : 'border-gray-200'
                    ]">
                        <h3 class="text-lg font-medium mb-2 truncate">{{ survey.title }}</h3>
                        <div class="flex items-center text-sm text-gray-500 mb-2">
                            <el-tag size="small" :type="survey.status === '已完成' ? 'success' : 'warning'">
                                {{ survey.status }}
                            </el-tag>
                            <span class="ml-2" v-if="survey.phoneAnswerTotal > 0">{{ survey.phoneAnswerTotal
                                }}次填报</span>
                        </div>
                        <!-- <div class="flex items-center mb-2">
                            <div class="flex-1">
                                <el-progress :percentage="survey.progress"
                                    :color="survey.progress === 100 ? '#67C23A' : '#409EFF'" />
                            </div>
                            <span class="ml-2 text-sm">{{ survey.progress }}/10</span>
                        </div> -->
                        <div v-if="survey.status === '已完成'" class="text-sm text-gray-600">
                            当前得分:
                            <span v-if="survey.totalScore >= 0" :style="{ color: survey.labelColor || 'red' }">{{
                        `${survey.totalScore === null ? '' : `${survey.totalScore} 分`} ${survey.surveyScoreLabel
                                ? `(${survey.surveyScoreLabel})`: ''} ` }}</span>
                        </div>
                        <div v-else class="text-sm text-gray-600">
                            当前得分:
                            <span>暂无</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 下半部分：问卷详情 -->
        <div class="survey-detail flex-1 overflow-hidden flex flex-col">
            <div class="p-4 bg-gray-50 border-b">
                <div class="text-sm text-gray-500 mb-2">切换查看历史填报记录</div>
                <div class="mb-4">
                    <el-select v-model="selectedSurvey.currentResponseIndex" placeholder="选择历史记录" class="w-full" clearable
                    @change="(index) => viewHistoricalResponse(selectedSurvey, index)">
                        <el-option v-for="(response, index) in selectedSurvey.historicalResponses" :key="index"
                            :label="response.createtime" :value="index">
                            <span :style="{color: response.yjColor}">
                                {{ response.createtime }} - {{ response.totalScore }}分({{ response.yjName }})
                            </span>
                        </el-option>
                    </el-select>
                </div>
            </div>
            <div class="flex-1 overflow-y-auto p-6 relative">
                <div v-if="selectedSurvey.currentResponseIndex >=0 && selectedSurvey.historicalResponses[selectedSurvey.currentResponseIndex]"
                    class="fixed right-8 top-[300px] p-4 rounded-lg bg-white/5 hover:bg-white/40 backdrop-blur-none hover:backdrop-blur-sm transition-all duration-300">
                    <div class="text-3xl font-bold mb-2" :style="{ color: selectedSurvey.historicalResponses[selectedSurvey.currentResponseIndex].yjColor }">
                        {{ selectedSurvey.historicalResponses[selectedSurvey.currentResponseIndex].totalScore }}分
                    </div>
                    <div class="text-sm" :style="{ color: selectedSurvey.historicalResponses[selectedSurvey.currentResponseIndex].yjColor }">
                        {{ selectedSurvey.historicalResponses[selectedSurvey.currentResponseIndex].yjName }}
                    </div>
                </div>
                <div v-if="selectedSurvey">
                    <fillOut :ref="(el) => surveyRefs[selectedSurvey.surveyId] = el" :surveyId="selectedSurvey.surveyId" :sheetId="selectedSurvey.currentSheetId" />
                </div>
                <div v-else class="text-center text-gray-500 mt-10">
                    请选择一个问卷开始填写
                </div>
            </div>
            <!-- 固定在底部的提交按钮 -->
            <div class="p-6 border-t bg-white" v-if="selectedSurvey.status !== '已完成' && !selectedSurvey.currentSheetId">
                <button @click="submitSurvey"
                    class="w-full py-3 bg-blue-600 text-white !rounded-button whitespace-nowrap hover:bg-blue-700 transition-colors"
                    :disabled="!selectedSurvey">
                    提交问卷
                </button>
            </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 selectedSurvey: any = ref({});

// const selectedSurvey = ref(null);
const toggleSurvey = (index: number) => {
    selectedSurvey.value = surveys.value[index];
    if (!selectedSurvey.value.historicalResponse?.length) {
        getHistory(selectedSurvey.value);
    }
};

// const currentResponse = ref(null);

const viewHistoricalResponse = (survey: any, index: number) => {
    if (index >=0) {
        survey.currentResponseIndex = index;
        // currentResponse.value = survey.historicalResponses[index];
        survey.currentSheetId = survey.historicalResponses[index].answersheetId;
    } else {
        survey.currentResponseIndex = '';
        survey.currentSheetId = 0;
    }
   
};
const wranSurveys = ref([]);

// 提交问卷方法
const submitSurvey = () => {
    const currentSurvey = selectedSurvey.value;
    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,
                        tagSign: res.data.tagSign,
                    });

                    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(selectedSurvey.value);
            } 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;

        if (!selectedSurvey.value?.surveyId) {
            selectedSurvey.value = surveys.value[0];
            getHistory(selectedSurvey.value);
        }

        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) {
                // currentResponse.value = survey.historicalResponses[index];
                survey.currentResponseIndex = index;
                survey.currentSheetId = survey.historicalResponses[index].answersheetId;
            }
        }

    })
}

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


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

defineExpose({
    getWarnSurvey,
});

</script>

<style scoped lang="scss">
/* 针对Webkit浏览器（如Chrome和Safari） */
/* *::-webkit-scrollbar {
    display: none;
} */

.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.survey-list-container {
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
}

.survey-detail {
  background: #f9fafb;
}
</style>