<template>
    <div class="common-layout">
        <el-container>
            <el-header class="header">
                <el-text class="header-text">抢点班作业后台管理</el-text>
                <el-button class="header-button" type="primary" text style="float: right;"
                    @click="logout">退出登录</el-button>
            </el-header>
            <el-main class="main">
                <div class="main-title">
                    <div class="main-title-text" style="float: left;">
                        作业详情
                    </div>
                    <div>
                        <el-button class="main-button" @click="back">返回上一页</el-button>
                    </div>
                </div>
                <div class="table-container">
                    <div class="search-bar" :v-model="form">
                        <el-input v-model="form.jwcode" type="text" placeholder="请输入精网号" style="width: 180px;"
                            size="large" />
                        <el-select v-model="form.deptId" placeholder="选择分店门部" size="large"
                            style="width: 180px; margin-left: 15px;" clearable @change="handleDeptSelect">
                            <el-option v-for="item in dept" :key="item.id" :label="item.deptName"
                                :value="item.deptId" />
                        </el-select>

                        <el-select v-model="form.shopId" placeholder="--请选择所属门店--" size="large"
                            style="width: 180px; margin-left: 15px" clearable>
                            <el-option v-for="item in shop" :key="item.id" :label="item.shopName"
                                :value="item.shopId" />
                        </el-select>
                        <el-button class="search-btn" type="primary" size="large" @click="searchData">搜索</el-button>
                        <div class="export">
                            <el-button class="export-btn" type="primary" size="large"
                                @click="exportData">导出数据</el-button>
                        </div>
                    </div>
                    <el-table :data="workdetailData" style="width: 100%">
                        <el-table-column label="序号">
                            <template #default="scope">
                                {{ scope.$index + (PageNo - 1) * PageSize + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="姓名"></el-table-column>
                        <el-table-column prop="jwcode" label="精网号"></el-table-column>
                        <el-table-column label="分布-门店">
                            <template v-slot="scope">
                                {{ scope.row.deptName }} - {{ scope.row.shopName }}
                            </template>
                        </el-table-column>
                        <el-table-column label="作业详情">
                            <template v-slot="{ $index }">
                                <el-popover placement="bottom" title="详情" :width="500" trigger="click">
                                    <template #reference>
                                        <el-button link type="primary">查看</el-button>
                                    </template>
                                    <div v-for="(r, subIndex) in getContent($index).replies" :key="subIndex">
                                        <div>{{ r.formTitle }}</div>
                                        <div>{{ r.contentTitle }}</div>
                                        <div>{{ r.content }}</div>
                                        <div style="margin-bottom: 10px;"></div>
                                    </div>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column prop="submitTime" label="提交时间">
                            <template v-slot="scope">
                                {{ scope.row.Reply[0].submitTime }}
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="page">
                        <el-pagination v-model:current-page="PageNo" v-model:page-size="PageSize"
                            :page-sizes="[20, 50, 100, 200]" :size="size" :disabled="disabled" :background="background"
                            layout="sizes,prev,next,jumper" :total="10" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" />
                    </div>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import ClassListApi from '../api/ClassListApi';
import { ElMessage } from 'element-plus';
import UpdateWorkApi from '../api/UpdateWorkApi';
import * as XLSX from 'xlsx';
import axios from 'axios';
import LoginApi from '../api/LoginApi';
import { useTokenStore } from '../stores/token';
import { useUserStore } from '../stores/user';

const router = useRouter();

const back = () => {
    window.history.back()
}
//获取门店列表
const shop = ref([]);
// 处理部门选择变化的事件函数
const handleDeptSelect = async (val) => {
    console.log(val);
    const res = await UpdateWorkApi.getshopinfo(val);
    shop.value = res.data;
    console.log(shop.value);
    form.value.shopId = "";
};

// 初始化页码，这里假设初始页码为1
const PageNo = ref(1);
// 初始化页面大小，这里假设初始页面大小为10
const PageSize = ref(20);

// 处理页面大小改变的事件函数，将新的页面大小赋值给PageSize变量
const handleSizeChange = (newPageSize) => {
    PageSize.value = newPageSize;
    ClassListApi.getWorkDetail(id.value, PageNo.value, PageSize.value);
};

// 处理当前页码改变的事件函数，将新的页码赋值给PageNo变量
const handleCurrentChange = (newPageNo) => {
    PageNo.value = newPageNo;
    ClassListApi.getWorkDetail(id.value, PageNo.value, PageSize.value);
};

const form = ref({
    jwcode: "",
    deptId: "",
    shopId: "",
});

// 搜索方法
const searchData = async () => {
    try {
        const params = {
            id: id.value,
            ...form.value
        };
        const res = await UpdateWorkApi.getrecordbycondition(params);
        console.log('搜索结果:', res);
        workdetailData.value = res.data;
    } catch (error) {
        console.error('搜索失败', error);
    }
    form.value.jwcode = "";
    form.value.deptId = "";
    form.value.shopId = "";
}
//获取门部列表
const dept = ref([]);
const getDept = async () => {
    try {
        const res = await UpdateWorkApi.getdeptinfo();
        dept.value = res.data;
        console.log(dept.value);
    } catch (error) {
        console.error('获取分部失败', error);
    }
};
getDept();


const route = useRoute();
const id = ref(route.params.id)
console.log(id.value + '============')

const workdetailData = ref([]);
// onMounted(async () => {
//     try {
//         const response = await ClassListApi.getWorkDetail(id.value, PageNo.value, PageSize.value);
//         workdetailData.value = response.data;
//         console.log(workdetailData.value);
//     } catch (error) {
//         console.error('接口请求出现错误:', error);
//     }
// });
onMounted(async () => {
    const refdata = {
        id: id.value,
        pageNo: PageNo.value,
        pageSize: PageSize.value
    }
    try {
        const response = await UpdateWorkApi.getrecordbycondition(refdata);
        workdetailData.value = response.data;
        console.log(workdetailData.value);
    } catch (error) {
        console.error('接口请求出现错误:', error);
    }
})
const getContent = (index) => {
    if (workdetailData.value && workdetailData.value[index] && workdetailData.value[index].Reply) {
        const replies = workdetailData.value[index].Reply;
        return {
            // 这里直接返回包含所有reply数据的数组
            replies: replies.map((reply) => ({
                formTitle: reply.formTitle,
                contentTitle: reply.contentTitle,
                content: reply.content
            }))
        };
    }
    return {
        replies: []
    };
};
const exportData = async () => {
    try {
        const params = {
            // 这里假设form.value和id.value是你已有的正确数据获取方式，按需替换成实际的准确值
            ...form.value,
            id: id.value,
        };
        const response = await axios.post('/api/api/homework_manage/export-record', params, {
            responseType: 'arraybuffer'
        });
        console.log('导出数据:', response);
        console.log('导出数据:', response.data);
        // 将返回的二进制数据转换为Blob对象，用于创建下载链接
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        // 尝试从响应头中获取Content-Disposition字段来解析文件名
        const contentDisposition = response.headers['content-disposition'];
        console.log('文件名:', contentDisposition);
        if (contentDisposition) {
            // 使用正则表达式匹配filename
            const fileNameMatch = contentDisposition.match(/filename=([^"]+)/);
            if (fileNameMatch && fileNameMatch.length > 1) {
                const fileName = fileNameMatch[1];
                a.download = fileName;
            } else {
                console.error('无法从Content-Disposition中解析出文件名');
                return;
            }
        } else {
            console.error('响应头中不存在Content-Disposition字段');
            return;
        }
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    } catch (error) {
        console.error('详细的请求错误信息：', error);
        ElMessage.error('导出失败');
    }
};

const tokenStore = useTokenStore();
// // 退出登录
// const logout = () => {
//     LoginApi.logout().then(res => {
//         console.log(tokenStore);
//         tokenStore.clear();
//         localStorage.removeItem('token');
//         console.log(tokenStore);
//         router.push('/');
//     }).catch(err => {
//         // 处理退出登录接口调用失败的情况，比如提示错误信息等
//         ElMessage.error('退出登录失败，请稍后重试');
//     })
// }


//退出
function logout(){
    //清除登录信息
    const tokenStore = useTokenStore();
    const userStore = useUserStore();
    tokenStore.clear();
    userStore.clear();
    LoginApi.logout().then(res => {
    console.log(res)
  })
  router.push('/')
}
</script>

<style scoped>
.look {
    color: rgb(69, 131, 254);
    cursor: pointer;
}

.table-container {
    margin: 6px 0 0;
    padding: 15px 60px;
}

.search-bar {
    margin-bottom: 10px;
    position: relative;
}

.search-btn {
    padding: 10px 20px;
    margin: 0 0 0 15px;
}

.export {
    position: absolute;
    right: 20px;
    top: 0px;
}

.export-btn {
    padding: 12px 20px;
    text-align: right;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    border: 1px solid #ccc;
    padding: 5px;
    text-align: left;
}

.pagination {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.pagination select {
    margin-right: 10px;
}

.pagination button {
    margin-right: 5px;
    cursor: pointer;
}



.header {
    height: 100px;
    line-height: 100px;
    padding: 0 80px;
}

.header-text {
    font-size: 22px;
    font-weight: 500;
    color: black;
    float: left;
}

.header-button {
    margin-top: 30px;
}

.main {
    padding: 30px 212px;
    background-color: #F8F8F8;
}

.main-title {
    font-size: 16px;
    background-color: white;
    font-weight: bold;
    height: 60px;
    border-bottom: 2px solid #ececec;
    padding: 0 60px;
    line-height: 52px;
}

.main-button {
    margin: 10px 15px 0 0;
    padding: 12px 20px;
    height: 40px;
    float: right;
}

.main-back {
    background-color: white;
}
</style>