<template>
    <div class="ai-contain" v-if="visible">
        <div class="bg-image"></div>
        <div class="ai-contain-header">
            <div class="logo-title">
                <img src="../static/logo.png" alt="" style="width: 48px; height: 48px">
                <span class="title-font">AI批阅</span>
            </div>
            <div class="icon-close" @click="closeMessage">
                <i class="el-icon-close"></i>
            </div>
        </div>
        <div class="message-wrap" v-if="sr_error_code">
            <div class="message-line">{{ sr_error_code }}</div>
        </div>
        <div class="wrap" v-else>
            <div class="filter-wrap" v-if="showFilter">
                <tab-filter :tab-data="listData"
                            :replyData="replyCache"
                            @on-filter-change="filterChange"
                            @on-close="tabFilterClose"/>
            </div>
            <div class="normal-wrap" :class="{'full-width': !showFilter }">
                <div class="label-wrap" style="margin-top: 16px" ref="labelContainer">
                    <div class="label-container">
                        <div class="label-item"
                             v-if="isPerson && !showFilter && showTableList.length > 10"
                             @click="showFilterMethod"
                             style="width: 32px; padding: 0; line-height: 42px">
                            <img src="../static/filter.png" style="width: 24px; height: 24px"/>
                        </div>
                        <div class="label-item" v-for="item in showTableList"
                             :key="item.id"
                             :title="item.title"
                             :class="{'label-item-active': item.active}"
                             @click="tabClick(item)">
                            {{ item.title }}
                            <div class="loading-block" v-if="!replyCache[item.id]">
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>
                    </div>
                    <div class="label-item label-down"
                         v-if="showMoreButton"
                         @click="stretchContainer"
                         style="width: 32px">
                        <span v-if="!stretch">...</span>
                        <i class="el-icon-d-arrow-left" style="transform: rotate(90deg)" v-else></i>
                    </div>
                </div>
                <div class="ai-main-content">
                    <read-over :exercises-data="activeItem"
                               :analyze-data="analyzeData"
                               @on-reanswer="onReanswer"
                               @on-noty-apply="notyApply"
                               @on-edit="onEditAnalyze"/>
                    <div class="member-table" v-if="stretch">
                        <member-table :check-data="showTableList"
                                      :show-data="tabList"
                                      :replyCache="replyCache"
                                      @on-select-member="selectMember" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import ReadOver from './read-over.vue';
import { getUserInfo } from '../utils/config';
// import {generateReview, registerSse, criticismApply, reanswerReview} from '../api/index';
import { generateReview, loopPoll, criticismApply, reanswerReview, analysisSave } from '../api/index';
import Cookies from "js-cookie";
import TabFilter from './tab-filter.vue';
import MemberTable from './member-table.vue';
import cache from "../plugins/cache";

export default {
    name: 'AiReadOver',
    components: {
        ReadOver,
        TabFilter,
        MemberTable
    },
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        listData: {
            type: Array,
            default: () => []
        },
        courseId: {
            type: String,
            default: '',
        },
        isPerson: {
            type: Boolean,
            default: false,
        },
        autoApply: {
            type: Boolean,
            default: false,
        },
        businessSource: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            stretch: false,
            showFilter: false,
            showMoreButton: false, // 是否显示下拉框
            replyCache: {}, // 记录所有回复信息
            activeItem: {}, // 当前记录的item
            analyzeData: {}, // 当前回复信息
            sseSessionId: '', // sse会话id,
            tabList: [],
            showTableList: [],
            cacheUserId: [],
            loopFlag: 0,
            replayId: {},
            sr_error_code: undefined,
            replayedCache: {}
            // sseState: {}
        }
    },
    watch: {
        visible() {
            if (this.visible) {
                this.listDataError();
                this.sseSessionId = new Date().getTime().toString();
                this.tabList = this.listData;
                setTimeout(() => {
                    this.dealTableList();
                    this.sendAiInfo();
                })
            } else {
                this.showFilter = false;
                this.cacheUserId = [];
                this.replayId = {};
                this.replayedCache = {};
                clearInterval(this.loopFlag);
                // this.sseState.close();
            }
        },
        listData: {
            handler() {
                // this.listDataError();
                if (this.listData && this.listData.length > 0) {
                    this.tabList = this.listData;
                }
            },
            immediate: true
        }
    },
    mounted() {
        if (!Cookies.get("token")) {
            return this.$message.warning('未获取到登录信息,请重新登录');
        }
        this.messageList = [];
        getUserInfo(Cookies.get("token"), this.businessSource);
    },
    methods: {
        resizeFirstActive() {
            if (!this.showTableList || this.showTableList.length < 1) {
                this.analyzeData = null;
                return;
            }
            this.showTableList.map((item) => item.active = false);
            this.showTableList[0].active = true;
            this.activeItem = this.showTableList[0];
            this.analyzeData = this.replyCache[this.showTableList[0].id];
        },
        closeMessage() {
            this.$emit('close');
        },
        tabClick(tab) {
            this.tabList.map((item) => item.active = false);
            tab.active = true;
            this.$forceUpdate();
            this.activeItem = tab;
            this.analyzeData = this.replyCache[tab.id];
        },
        stretchContainer() {
            this.stretch = !this.stretch;
        },
        // messageBack(message, type) {
        //     const { bizId, comments: [backData] } = message;
        //     const { content } = backData;
        //     let currentId = bizId;
        //     backData.jsonContent = JSON.parse(content);
        //     if (type === 'reanswer') {
        //         currentId = this.activeItem.id;
        //     }
        //     this.$set(this.replyCache, currentId, backData);
        //     // 更新当前值
        //     this.analyzeData = this.replyCache[this.activeItem.id];
        // },
        async sendAiInfo() {
            const paramsData = [];
            this.listData.map((item) => {
                paramsData.push({
                    bizId: item.id,
                    question: item.question,
                    score: item.score,
                    answer: item.answer,
                    answerer: item.title,
                    rightAnswer: item.rightAnswer,
                    businessSource: this.businessSource,
                })
                this.cacheUserId.push(item.id);
            });
            // this.sseState = await registerSse(this.sseSessionId, this.messageBack, ()=> {
            //     generateReview(paramsData, this.sseSessionId, this.courseId);
            // });
            await generateReview(paramsData, this.sseSessionId, this.courseId);
            this.sr_error_code = cache.session.getJSON('ERROR_SR_CODE')
            this.loopFlag = setInterval(async () => {
                this.loopInfo();
            }, 3000);
            this.loopInfo();
        },
        async loopInfo () {
            const loopRes = await loopPoll(this.cacheUserId);
            if (loopRes) {
                for (let message of loopRes) {
                    const { bizId, comments: [backData] } = message;
                    const { content, id } = backData;
                    const currentId = bizId;
                    // 说明是重新回答
                    if (this.replayId[currentId] && this.replayId[currentId] === id) {
                        continue;
                    }
                    backData.jsonContent = JSON.parse(content);
                    this.$set(this.replyCache, currentId, backData);
                    // 更新当前值
                    this.analyzeData = this.replyCache[this.activeItem.id] || {};
                    delete this.replayId[currentId];
                    if (!this.replayedCache[id] && this.autoApply) {
                        this.autoNotyApply(message, backData);
                        this.replayedCache[id] = true;
                    }
                }
                return ;
            }
            throw new Error('--loopRes--返回值为空');
        },
        // 批量自动应用
        autoNotyApply(message, backData) {
            const currentOrgData = this.listData.filter((item) => item.id === message.bizId)[0];
            this.notyApply(backData, currentOrgData);
        },
        async notyApply(data, orgData) {
            const { id } = data;
            await criticismApply(id);
            this.analyzeData.accepted = true;
            this.$emit('on-noty-apply', data, orgData);
        },
        async onReanswer(list) {
            this.replayId[this.activeItem.id] = list.id;
            this.analyzeData = {};
            this.replyCache[this.activeItem.id] = null;
            await reanswerReview(this.sseSessionId, list.id);
        },
        tabFilterClose(data) {
            this.showFilter = false;
            this.tabList = data;
            this.resizeFirstActive();
            setTimeout(() => {
                this.dealTableList();
            });
        },
        filterChange(data) {
            this.tabList = data;
            this.resizeFirstActive();
            this.stretch = false;
            setTimeout(() => {
                this.dealTableList();
            });
        },
        showFilterMethod() {
            this.showFilter = true;
            setTimeout(() => {
                this.dealTableList();
            });
        },
        dealTableList() {
            const labelContainer = this.$refs.labelContainer;
            if (!labelContainer) return;
            const BLOCK_WIDTH = 80; // 和 css 值保持一致
            let width = labelContainer.clientWidth;
            if (this.isPerson) {
                width -= 40;
            }
            const blockCount = Math.floor(width / BLOCK_WIDTH);
            this.showMoreButton = blockCount < this.tabList.length;
            this.showTableList = this.tabList.slice(0, blockCount - 2);
            this.resizeFirstActive();
        },
        selectMember(data) {
            this.showTableList = data;
            this.resizeFirstActive();
        },
        listDataError() {
            if (!this.listData || this.listData.length < 1) {
                throw new Error('list-data 不能为空或者长度不能为0');
            }
        },
        async onEditAnalyze(data) {
            this.$set(this.replyCache, this.activeItem.id, data);
            this.analyzeData = data;
            try {
                await analysisSave({
                    id: data.id,
                    analysis: JSON.stringify(data.jsonContent),
                    score: data.score,
                });
                this.$message.success('保存成功');
            } catch (e) {
                this.$message.error('保存失败，请重试');
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.ai-contain {
    width: 1000px;
    height: 100%;
    border-radius: 16px;
    box-shadow: 0 1px 8px rgba(32, 40, 64, 0.32);
    padding: 16px 16px 16px 16px;
    box-sizing: border-box;
    position: relative;
    background-color: rgba(232, 240, 248, 1);
}
.ai-contain-header {
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: space-between;
}
.logo-title {
    font-weight: 700;
    color: #202840;
    font-size: 18px;
}
.title-font {
    display: inline-block;
    vertical-align: top;
    margin-top: 12px;
    margin-left: 12px;
    color: rgb(40, 128, 240);
}
.icon-close {
    cursor: pointer;
    position: relative;
    right: 0;
    i {
        font-weight: bold !important;
    }
}
.ai-main-content {
    position: relative;
    width: 100%;
    height: calc(100% - 32px - 40px - 16px);
    display: flex;
    z-index: 1;
    padding: 16px 0 16px 8px;
}
.bg-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 248px;
    background: linear-gradient(to bottom, rgba(96, 96, 244, .1), rgba(44, 144, 240, 0));
    border-radius: 16px 0;
}
.label-wrap {
    display: flex;
    padding-left: 8px;
    padding-right: 24px;
    align-items: end;
    justify-content: space-between;
    .label-container {
        display: flex;
        flex-wrap: wrap;
        height: 40px;
        overflow: hidden;
    }
    .label-item {
        font-size: 14px;
        color: rgba(96, 96, 224, 1);
        border: 1px solid #797be4;
        width: 80px;
        cursor: pointer;
        height: 32px;
        line-height: 32px;
        padding: 0 8px;
        text-align: center;
        box-sizing: border-box;
        border-radius: 8px;
        margin-bottom: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        position: relative;
        &:hover {
            font-weight: 600;
            border-color: #6060e0;
        }
    }
    .loading-block {
        position: absolute;
        right: 2px;
        bottom: 14px;
        width: 16px;
        height: 16px;
    }
    .label-down {
        position: relative;
        bottom: 0;
    }
    .label-item-active {
        color: #fff;
        background: linear-gradient(90deg, rgba(0, 144, 240, 1) 0%, rgba(144, 48, 240, 1) 100%);
        &:hover {
            font-weight: 400;
            border-color: #797be4;
        }
    }
    .label-item {
        margin-right: 8px;
    }
}
.wrap {
    display: flex;
    height: calc(100% - 53px);
    position: relative;
    z-index: 1;
    .filter-wrap {
        width: 100px;
        height: 100%;
        padding-top: 64px;
        box-sizing: border-box;
    }
    .normal-wrap {
        width: calc(100% - 100px);
        height: 100%;
    }
    .full-width {
        width: 100%;
    }
    .member-table {
        position: absolute;
        top: 0;
        right: 12px;
        width: 320px;
        height: 100%;
        z-index: 999999;
    }
}
.message-wrap {
    height: calc(100%  - 53px );
    align-items: center;
    justify-content: center;
    display: flex;
    flex-direction: column;
}
.message-line {
    color: red;
    font-size: 25px;
    margin: 8px 0; /* 上下各 8px 的间距 */
}
</style>