<template>
    <div class="app-container">

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="applyVClick">申请</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-position" size="mini"
                    @click="toInfo">点我前往完善个人信息</el-button>
            </el-col>
        </el-row>
        <el-table v-loading="loading" :data="tableData">
            <el-table-column label="#" align="center" prop="id" />
            <el-table-column label="学年" align="center" prop="stuYearName" />
            <el-table-column label="姓名" align="center" prop="stuName" />
            <el-table-column label="审核状态" align="center" prop="applyStatus">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.knzz_tufa_apply_status" :value="scope.row.applyStatus" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.applyStatus == '10'" size="mini" type="text" icon="el-icon-refresh"
                        @click="reApplyVClick(scope.row)">重新提交</el-button>
                    <el-button size="mini" type="text" icon="el-icon-view" @click="lookVClick(scope.row)">查看</el-button>
                    <el-button v-if="scope.row.applyStatus == '1'" size="mini" type="text" icon="el-icon-edit"
                        @click="editVClick(scope.row)">修改</el-button>
                    <el-button v-if="scope.row.applyStatus == '1'" size="mini" type="text" icon="el-icon-close"
                        @click="doCancel(scope.row)">取消申请</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <el-dialog @close="getList" title="申请" :visible.sync="applyV" :fullscreen="true" :destroy-on-close="true">
            <GlApply v-if="applyV" />
        </el-dialog>
        <el-dialog @close="getList" title="查看" :visible.sync="lookV" :fullscreen="true" :destroy-on-close="true">
            <el-row>
                <el-col :span="12">
                    <GlLook id="printDiv" v-if="lookV" :formData="lookForm" />
                </el-col>
                <el-col :span="12">
                    <el-button v-print="printContent">打印</el-button>
                    <hr />
                    <el-timeline>
                        <el-timeline-item v-if="lookForm.fdyCmt && lookForm.fdyDate" :timestamp="lookForm.fdyDate"
                            color="green" placement="top">
                            <el-card>
                                <div>
                                    <strong>辅导员审核</strong>
                                    <div>{{ lookForm.fdyCmt }}</div>
                                    <img v-if="lookForm.fdySign" :src="baseurl + lookForm.fdySign" alt="辅导员签名"
                                        style="max-width:100px;margin-top:8px;" />
                                </div>
                            </el-card>
                        </el-timeline-item>
                        <el-timeline-item v-if="lookForm.xwCmt && lookForm.xwDate" :timestamp="lookForm.xwDate"
                            color="green" placement="top">
                            <el-card>
                                <div>
                                    <strong>院系审核</strong>
                                    <div>{{ lookForm.xwCmt }}</div>
                                    <img v-if="lookForm.xwSign" :src="baseurl + lookForm.xwSign" alt="院系签名"
                                        style="max-width:100px;margin-top:8px;" />
                                </div>
                            </el-card>
                        </el-timeline-item>
                        <el-timeline-item v-if="lookForm.xgCmt && lookForm.xgDate" :timestamp="lookForm.xgDate"
                            color="green" placement="top">
                            <el-card>
                                <div>
                                    <strong>学工审核</strong>
                                    <div>{{ lookForm.xgCmt }}</div>
                                    <img v-if="lookForm.xgSign" :src="baseurl + lookForm.xgSign" alt="学工签名"
                                        style="max-width:100px;margin-top:8px;" />
                                </div>
                            </el-card>
                        </el-timeline-item>
                    </el-timeline>
                </el-col>
            </el-row>

        </el-dialog>

        <el-dialog @close="getList" title="修改" :visible.sync="editV" width="900px">
            <el-form label-width="200px" size="mini" class="lookForm">
                <el-form-item label="入学时间">
                    <el-input v-model="editForm.inTime" />
                </el-form-item>
                <el-form-item label="曾获资助/奖励">
                    <el-input type="textarea" v-model="editForm.helpHis" />
                </el-form-item>
                <el-form-item label="家庭人口数">
                    <el-input v-model="editForm.familyNum" />
                </el-form-item>
                <el-form-item label="家庭月总收入">
                    <el-input v-model="editForm.monthMoney" />
                </el-form-item>
                <el-form-item label="人均月收入">
                    <el-input v-model="editForm.perMoney" />
                </el-form-item>
                <el-form-item label="收入来源">
                    <el-input v-model="editForm.moneySrc" />
                </el-form-item>
                <el-form-item label="成绩专业排名">
                    <el-input v-model="editForm.majorRank" />
                </el-form-item>
                <el-form-item label="专业人数">
                    <el-input v-model="editForm.majorNum" />
                </el-form-item>
                <el-form-item label="实行综合考评排名">
                    <el-radio-group v-model="editForm.isCph">
                        <el-radio :label="'是'">是</el-radio>
                        <el-radio :label="'否'">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="综合考评班级排名">
                    <el-input v-model="editForm.classRank" />
                </el-form-item>
                <el-form-item label="班级人数">
                    <el-input v-model="editForm.classNum" />
                </el-form-item>
                <el-form-item label="必修课门数">
                    <el-input v-model="editForm.bxk" />
                </el-form-item>
                <el-form-item label="及格门数">
                    <el-input v-model="editForm.jg" />
                </el-form-item>
                <el-form-item label="申请理由">
                    <el-input type="textarea" v-model="editForm.applyReason" />
                </el-form-item>
                <el-form-item label="证明材料">
                    <FileUpload v-model="editForm.hardFile" />
                </el-form-item>
                <el-form-item label="申请人签名">
                    <el-upload style="display: inline;" :before-upload="boolImg"
                        accept="image/jpg,image/jpeg,image/png,image/bmp" :limit="1" class="avatar-uploader"
                        :action="upload.url" :headers="upload.headers" :show-file-list="false"
                        :file-list="upload.fileList" :on-success="handleAvatarSuccess">
                        <img v-if="editForm.applySign" :src="baseurl + editForm.applySign" width="200px" height="50px"
                            class="avatar">
                        <span v-else> 点击上传</span>
                    </el-upload>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" @click="doEdit" plain>提交修改</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


        <el-dialog @close="getList" title="重新提交" :visible.sync="reApplyV" width="900px">
            <el-form label-width="200px" size="mini" class="lookForm">
                <el-form-item label="入学时间">
                    <el-input v-model="reApplyForm.inTime" />
                </el-form-item>
                <el-form-item label="曾获资助/奖励">
                    <el-input type="textarea" v-model="reApplyForm.helpHis" />
                </el-form-item>
                <el-form-item label="家庭人口数">
                    <el-input v-model="reApplyForm.familyNum" />
                </el-form-item>
                <el-form-item label="家庭月总收入">
                    <el-input v-model="reApplyForm.monthMoney" />
                </el-form-item>
                <el-form-item label="人均月收入">
                    <el-input v-model="reApplyForm.perMoney" />
                </el-form-item>
                <el-form-item label="收入来源">
                    <el-input v-model="reApplyForm.moneySrc" />
                </el-form-item>
                <el-form-item label="专业排名">
                    <el-input v-model="reApplyForm.majorRank" />
                </el-form-item>
                <el-form-item label="专业人数">
                    <el-input v-model="reApplyForm.majorNum" />
                </el-form-item>
                <el-form-item label="实行综合考评排名">
                    <el-radio-group v-model="reApplyForm.isCph">
                        <el-radio :label="'是'">是</el-radio>
                        <el-radio :label="'否'">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="班级排名">
                    <el-input v-model="reApplyForm.classRank" />
                </el-form-item>
                <el-form-item label="班级人数">
                    <el-input v-model="reApplyForm.classNum" />
                </el-form-item>
                <el-form-item label="必修课门数">
                    <el-input v-model="reApplyForm.bxk" />
                </el-form-item>
                <el-form-item label="及格门数">
                    <el-input v-model="reApplyForm.jg" />
                </el-form-item>
                <el-form-item label="申请理由">
                    <el-input type="textarea" v-model="reApplyForm.applyReason" />
                </el-form-item>
                <el-form-item label="证明材料">
                    <FileUpload v-model="reApplyForm.hardFile" />
                </el-form-item>
                <el-form-item label="申请人签名">
                    <el-upload style="display: inline;" :before-upload="boolImg"
                        accept="image/jpg,image/jpeg,image/png,image/bmp" :limit="1" class="avatar-uploader"
                        :action="upload.url" :headers="upload.headers" :show-file-list="false"
                        :file-list="upload.fileList" :on-success="handleAvatarSuccess1">
                        <img v-if="reApplyForm.applySign" :src="baseurl + reApplyForm.applySign" width="200px"
                            height="50px" class="avatar">
                        <span v-else> 点击上传</span>
                    </el-upload>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" @click="doReApply" plain>重新提交</el-button>
                </el-form-item>
            </el-form>
            <hr />
            <el-timeline>
                <el-timeline-item v-if="reApplyForm.fdyCmt && reApplyForm.fdyDate" :timestamp="reApplyForm.fdyDate"
                    color="green" placement="top">
                    <el-card>
                        <div>
                            <strong>辅导员审核</strong>
                            <div>{{ reApplyForm.fdyCmt }}</div>
                            <img v-if="reApplyForm.fdySign" :src="baseurl + reApplyForm.fdySign" alt="辅导员签名"
                                style="max-width:100px;margin-top:8px;" />
                        </div>
                    </el-card>
                </el-timeline-item>
                <el-timeline-item v-if="reApplyForm.xwCmt && reApplyForm.xwDate" :timestamp="reApplyForm.xwDate"
                    color="green" placement="top">
                    <el-card>
                        <div>
                            <strong>院系审核</strong>
                            <div>{{ reApplyForm.xwCmt }}</div>
                            <img v-if="reApplyForm.xwSign" :src="baseurl + reApplyForm.xwSign" alt="院系签名"
                                style="max-width:100px;margin-top:8px;" />
                        </div>
                    </el-card>
                </el-timeline-item>
                <el-timeline-item v-if="reApplyForm.xgCmt && reApplyForm.xgDate" :timestamp="reApplyForm.xgDate"
                    color="green" placement="top">
                    <el-card>
                        <div>
                            <strong>学工审核</strong>
                            <div>{{ reApplyForm.xgCmt }}</div>
                            <img v-if="reApplyForm.xgSign" :src="baseurl + reApplyForm.xgSign" alt="学工签名"
                                style="max-width:100px;margin-top:8px;" />
                        </div>
                    </el-card>
                </el-timeline-item>
                <el-timeline-item v-if="reApplyForm.leaderCmt && reApplyForm.leaderDate"
                    :timestamp="reApplyForm.leaderDate" color="green" placement="top">
                    <el-card>
                        <div>
                            <strong>校领导审核</strong>
                            <div>{{ reApplyForm.leaderCmt }}</div>
                            <img v-if="reApplyForm.leaderSign" :src="baseurl + reApplyForm.leaderSign" alt="校领导签名"
                                style="max-width:100px;margin-top:8px;" />
                        </div>
                    </el-card>
                </el-timeline-item>
            </el-timeline>
        </el-dialog>

    </div>
</template>
<script>

import { boolImg, CheckImgExists, isEmpty, fullLoading } from "@/api/helpFunc";
import { getTokenKeySessionStorage as getToken } from "@/utils/auth";


import GlApply from "@/views/comprehensive/knzzGlApply/cpnt/GlApply.vue";
import GlLook from "@/views/comprehensive/knzzGlApply/cpnt/GlLook.vue";
import { selectTestStu } from "@/api/stuCQS/info-fill/sportTest";
import { getDicts } from "@/api/system/dict/data";
import { listDisciplinaryApplication } from "@/api/routine/disciplinaryApplication";
import { getOwnStuScoreMajorRank } from "@/api/comprehensive/biyeapply";

import {
    listOwnScoreClassRank
} from "@/api/stuCQS/good/apply";

import { listStu as listView, doEdit, doCancel, doReApply } from "@/api/comprehensive/knzzGlApply";

export default {
    name: "gl-stu",
    dicts: ['knzz_tufa_apply_status'],
    dicTypes: ['rt_penalty_status'],
    components: {
        GlApply,
        GlLook
    },
    data() {
        return {
            loading: true,
            tableData: [],
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },

            applyV: false,
            sportScore: null,
            getDicts: null,
            getDicts: [],
            penaltyStatusValue: null,

            lookForm: {},
            lookV: false,

            editV: false,
            editForm: {},
            editMode: false,

            upload: {
                headers: { Authorization: "Bearer " + getToken() },
                url: process.env.VUE_APP_BASE_API + "/common/upload",
                fileList: []
            },
            baseurl: process.env.VUE_APP_BASE_API + "/",
            boolImg,

            printContent: {
                id: 'printDiv',
                extraCss: "",
                extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
                previewBeforeOpenCallback() {
                    console.log('正在加载预览窗口')
                },
                previewOpenCallback() {
                    console.log('已经加载完预览窗口')
                },
                beforeOpenCallback(vue) {
                    vue.printLoading = true
                    console.log('打开之前')
                },
                openCallback(vue) {
                    vue.printLoading = false
                    console.log('执行了打印')
                },
                closeCallback() {
                    console.log('关闭了打印工具')
                },
                clickMounted(vue) {
                    console.log('点击了打印按钮')
                }
            },

            reApplyV: false,
            reApplyForm: {}

        }
    },
    created() {
        this.getList();
    },
    methods: {
        toInfo() {
            this.$router.push("/basedata/stuOwnInfo/edit");
        },
        async doReApply() {
            let sdata = { ...this.reApplyForm };
            console.log(sdata);
            if (isEmpty(sdata.inTime)) {
                this.$message.info("请填写入学时间");
                return;
            }
            if (isEmpty(sdata.helpHis)) {
                this.$message.info("请填写曾获奖励,没有写无");
                return;
            }
            if (isEmpty(sdata.familyNum)) {
                this.$message.info("请填写家庭人口数");
                return;
            }
            if (isEmpty(sdata.monthMoney)) {
                this.$message.info("请填写月收入");
                return;
            }
            if (isEmpty(sdata.perMoney)) {
                this.$message.info("请填写人均收入");
                return;
            }
            if (isEmpty(sdata.moneySrc)) {
                this.$message.info("请填写收入来源");
                return;
            }
            if (isEmpty(sdata.majorRank)) {
                this.$message.info("请填写专业排名");
                return;
            }
            if (isEmpty(sdata.majorNum)) {
                this.$message.info("请填写专业人数");
                return;
            }
            if (isEmpty(sdata.bxk)) {
                this.$message.info("请填写必修课门数");
                return;
            }
            if (isEmpty(sdata.jg)) {
                this.$message.info("请填写及格门数");
                return;
            }


            if (isEmpty(sdata.hardFile)) {
                this.$message.info("请上传证明材料");
                return;
            }

            let loading = fullLoading(this);
            let res = await doReApply(sdata);
            loading.close();
            if (res.code == 200) {
                this.$message.success("修改成功");
                this.reApplyV = false;
                this.getList();
            }
        },
        reApplyVClick(row) {
            this.reApplyForm = {};
            this.reApplyForm = { ...row };
            if ('xwCmt' in row) {
                this.$set(this.reApplyForm, 'xwCmt', row.xwCmt ?? '暂无审核意见');
            }
            if ('xwSign' in row) {
                this.$set(this.reApplyForm, 'xwSign', row.xwSign ?? '');
            }
            this.reApplyV = true;
        },
        handleAvatarSuccess1(response, file, fileList) {
            this.reApplyForm.applySign = response.fileName;
            this.upload.fileList = [];
            this.$forceUpdate();
        },
        handleAvatarSuccess(response, file, fileList) {
            this.editForm.applySign = response.fileName;
            this.upload.fileList = [];
            this.$forceUpdate();
        },
        async getList() {
            this.loading = true;
            let res = await listView(this.queryParams);
            this.loading = false;
            if (res.code == 200) {
                this.tableData = [...res.rows];
                this.total = res.total;
            }

        },
        /*         applyVClick() {
                    this.fetchcjpm()
                    this.fetchSportScoreData()
                    this.fetchcfwjc()
                },   */
        applyVClick() {
            this.checkAllConditions();
        },
        async checkAllConditions() {
            try {
                const [sportResult, disciplinaryResult, scoreResult] = await Promise.all([
                    this.fetchTestScoreData(),
                    this.fetchcfwjc(),
                    this.fetchcjpm()
                ]);
                this.applyV = sportResult && disciplinaryResult && scoreResult;
            } catch (error) {
                console.error("Error checking conditions:", error);
                this.applyV = false;
            }
        },
        async fetchTestScoreData() {
            const res = await selectTestStu().catch(() => {
                this.$message.info("体能测试数据获取失败");
                return { code: 500, rows: [] };
            });
            if (res.code === 200 && res.rows && res.rows.length > 0) {
                const testScore = res.rows[res.rows.length - 1].testScore;
                if (testScore >= 60) {
                    return true;
                } else if (testScore === 0) {
                    this.$message.info("当前学年没有您的体能成绩");
                    return false;
                } else {
                    this.$message.info("您的体能成绩不达标");
                    return false;
                }
            } else {
                this.$message.info("请先完成体能测试");
                return false;
            }
        },
        async fetchcfwjc() {
            try {
                const response1 = await getDicts('rt_penalty_status');
                const response2 = await listDisciplinaryApplication();
                if (Array.isArray(response2.rows) && response2.rows.length === 1) {
                    this.penaltyStatusValue = response2.rows[0].penaltyStatus;
                    if (response1.data[0].dictSort === this.penaltyStatusValue) {
                        this.$message.info("处分中");
                        return false;
                    } else if (response1.data[1].dictSort === this.penaltyStatusValue) {
                        return true;
                    } else if (response1.data[2].dictSort === this.penaltyStatusValue) {
                        this.$message.info("解除申请中");
                        return false;
                    } else if (response1.data[3].dictSort === this.penaltyStatusValue) {
                        this.$message.info("处分申请中");
                        return false;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
            } catch (error) {
                this.$message.error("处分状态获取失败");
                console.error("Error fetching disciplinary status:", error);
                return false;
            }
        },
        async fetchcjpm() {
            let loading = fullLoading(this);
            let res = await listOwnScoreClassRank().catch(error => {
                console.error("Error fetching score rank:", error);
                return { code: 500 };
            });
            loading.close();
            let data = res.data[0];
            if (res.code === 200 && data && data.stuMajorRank != null && data.majorCount != null) {

                let stuRank = Math.round(Math.round(data.stuMajorRank / data.majorCount * 10000) / 100);
                if (stuRank <= 30) {
                    return true;
                } else {
                    this.$message.info("您的学业成绩未达到专业前30%");
                    return false;
                }
            }
            this.$message.info("无法获取您的专业排名数据");
            return false;
        },
        /*         async fetchSportScoreData() {
                    const res = await listOwnSportScore()
                            if (res.code === 200 && res.data && res.data.length > 1) {
                                const sportScore = res.data[res.data.length - 1].sportScore;
                                if (sportScore >= 60) {
                                    this.applyV = true;
                                } else {
                                    this.applyV = false;
                                    this.$message.info("您的体能成绩不达标");
                                }
                            } else {
                                this.applyV = false;
                                this.$message.info("请先完成体能测试");
                            }
                },
                async fetchcfwjc() {
                    const response1 = await getDicts('rt_penalty_status');
                    const response2 = await listDisciplinaryApplication();
                    if (Array.isArray(response2.rows) && response2.rows.length === 1) {
                        this.penaltyStatusValue = response2.rows[0].penaltyStatus;
                        if (response1.data[0].dictSort === this.penaltyStatusValue) {
                            this.applyV = false;
                            this.$message.info("处分中");
                        } else if (response1.data[1].dictSort === this.penaltyStatusValue) {
                            this.applyV = true;
                        } else if (response1.data[2].dictSort === this.penaltyStatusValue) {
                            this.applyV = false;
                            this.$message.info("解除申请中");
                        } else if (response1.data[3].dictSort === this.penaltyStatusValue) {
                            this.applyV = false;
                            this.$message.info("处分申请中");
                        } else {
                            this.applyV = false;
                        }
                    } else {
                        this.applyV = true;
                    }
                },
                async fetchcjpm() {
                    let loading = fullLoading(this);
                    let res = await getOwnStuScoreMajorRank();
                    loading.close();
                    if (res.code == 200) {
                        let data = res.data;
                        let stuRank = Math.round(Math.round(data.majorRank / data.majorCount * 10000) / 100);
                        if (stuRank > 30) {
                            this.applyV = false;
                            this.$message.error("您的学业成绩未达到专业前30%");
                        } else { 
                            this.applyV = true;
                        }
                    }
                }, */
        lookVClick(row) {
            this.lookForm = {};
            this.lookForm = { ...row };
            this.lookV = true;
        },
        editVClick(row) {
            this.editForm = {};
            this.editForm = { ...row };
            this.editV = true;
        },
        async doEdit() {
            let sdata = { ...this.editForm };
            console.log(sdata);
            if (isEmpty(sdata.inTime)) {
                this.$message.info("请填写入学时间");
                return;
            }
            if (isEmpty(sdata.helpHis)) {
                this.$message.info("请填写曾获奖励,没有写无");
                return;
            }
            if (isEmpty(sdata.familyNum)) {
                this.$message.info("请填写家庭人口数");
                return;
            }
            if (isEmpty(sdata.monthMoney)) {
                this.$message.info("请填写月收入");
                return;
            }
            if (isEmpty(sdata.perMoney)) {
                this.$message.info("请填写人均收入");
                return;
            }
            if (isEmpty(sdata.moneySrc)) {
                this.$message.info("请填写收入来源");
                return;
            }
            if (isEmpty(sdata.majorRank)) {
                this.$message.info("请填写专业排名");
                return;
            }
            if (isEmpty(sdata.majorNum)) {
                this.$message.info("请填写专业人数");
                return;
            }
            if (isEmpty(sdata.bxk)) {
                this.$message.info("请填写必修课门数");
                return;
            }
            if (isEmpty(sdata.jg)) {
                this.$message.info("请填写及格门数");
                return;
            }


            if (isEmpty(sdata.hardFile)) {
                this.$message.info("请上传证明材料");
                return;
            }

            let loading = fullLoading(this);
            let res = await doEdit(sdata);
            loading.close();
            if (res.code == 200) {
                this.$message.success("修改成功");
                this.editV = false;
            }
        },
        doCancel(row) {
            let id = row.id;
            this.$confirm('确认取消申请吗？')
                .then(async () => {
                    let loading = fullLoading(this);
                    let res = await doCancel(id);
                    loading.close();
                    if (res.code == 200) {
                        this.$message.success("取消成功");
                        this.getList();
                    }
                });

        }
    }
}

</script>



<style scoped lang="scss">
.lookForm {
    .el-form-item {
        margin-bottom: 5px;
    }
}
</style>