<template>
  <div v-loading.fullscreen.lock="fullLoading" class="app-container">

    <el-form ref="queryForm" :model="queryParams" size="mini" :inline="true" label-width="68px">
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="queryParams.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生姓名" prop="stuName">
        <el-input v-model="queryParams.stuName" placeholder="请输入学生姓名" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="table_data">
      <el-table-column label="学生" prop="stuName" align="center" />
      <el-table-column label="学号" prop="stuNo" align="center" />
      <el-table-column label="班级" prop="className" align="center" />
      <el-table-column label="申请时间" prop="createTime" align="center">
        <template slot-scope="scope">
          {{ dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audius_detail_type" :value="scope.row.applyStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- 审核按钮：已提交审核状态(1)时显示 -->
          <el-button v-if="scope.row.applyStatus == 1 || scope.row.applyStatus == '1'" type="text" size="mini" icon="el-icon-view"
                     @click="auditVClick(scope.row)"
          >审核</el-button>
          <!-- 查看/修改按钮：其他所有状态都可以查看/修改 -->
          <el-button v-else type="text" size="mini" icon="el-icon-edit"
                     @click="auditVClick(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 title="申请" :visible.sync="auditV" fullscreen :append-to-body="true">
      <el-steps :active="getStep(auditForm)">
        <el-step title="学生提交申请" description="" />

        <el-step title="辅导员审核"
                 :status="isEmpty(auditForm.fdyCmt) ? 'wait' : getStepStatus(auditForm.fdyCmt)"
        >
          <template slot="description">
            <div>
              {{ isEmpty(auditForm.fdyNoName) ? '' : auditForm.fdyNoName }}
            </div>
            <div>
              {{ isEmpty(auditForm.fdyCmt) ? '' : auditForm.fdyCmt }}
            </div>
            <div>
              {{ isEmpty(auditForm.fdyTime) ? '' : auditForm.fdyTime }}
            </div>
          </template>
        </el-step>

        <el-step title="学院审核"
                 :status="isEmpty(auditForm.xwCmt) ? 'wait' : getStepStatus(auditForm.xwCmt)"
        >
          <template slot="description">
            <div>
              {{ isEmpty(auditForm.xwNoName) ? '' : auditForm.xwNoName }}
            </div>
            <div>
              {{ isEmpty(auditForm.xwCmt) ? '' : auditForm.xwCmt }}
            </div>
            <div>
              {{ isEmpty(auditForm.xwTime) ? '' : auditForm.xwTime }}
            </div>
          </template>
        </el-step>

        <el-step title="学工审核"
                 :status="isEmpty(auditForm.jwcCmt) ? 'wait' : getStepStatus(auditForm.jwcCmt)"
        >
          <template slot="description">
            <div>
              {{ isEmpty(auditForm.xgNoName) ? '' : auditForm.xgNoName }}
            </div>
            <div>
              {{ isEmpty(auditForm.jwcCmt) ? '' : auditForm.jwcCmt }}
            </div>
            <div>
              {{ isEmpty(auditForm.xgTime) ? '' : auditForm.xgTime }}
            </div>
          </template>
        </el-step>
      </el-steps>
      <hr>
      <el-form class="detail" label-width="160px">
        <el-row>
          <div style="display: flex;">
            <el-col :span="12" style="margin-right: 50px;">
              <el-form-item label="班级">
                <el-input v-model="auditForm.className" readonly size="mini"
                          class="auditForm-input"
                />
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="auditForm.stuName" readonly size="mini"
                          class="auditForm-input"
                />
              </el-form-item>

              <el-form-item label="政治面貌">
                <el-input v-model="auditForm.zzmm" readonly size="mini"
                          class="auditForm-input"
                />
              </el-form-item>

              <!-- <el-form-item label="青年大学习学习率">
                                <el-input readonly size="mini" class="auditForm-input"
                                    v-model="auditForm.youthStudy"></el-input>
                            </el-form-item> -->
              <el-form-item label="第二课堂学分认定">
                <el-input v-model="auditForm.classTwo" readonly size="mini"
                          class="auditForm-input"
                />
              </el-form-item>

              <el-form-item label="职务">
                <el-input v-model="auditForm.classPost" readonly size="mini"
                          class="auditForm-input"
                />
              </el-form-item>
              <el-form-item label="获奖情况">
                <el-input v-model="auditForm.goodHis" :readonly="!editMode" type="textarea"
                          :maxlength="1000" :autosize="{ minRows: 10, maxRows: 10 }"
                          class="auditForm-input"
                />
              </el-form-item>
              <el-form-item label="主要事迹">
                <el-input v-model="auditForm.mainHis" :readonly="!editMode" type="textarea"
                          :maxlength="1000" :autosize="{ minRows: 10, maxRows: 10 }"
                          class="auditForm-input"
                />
              </el-form-item>
              <el-form-item v-if="auditForm.applyStatus == 1 || auditForm.applyStatus == '1'" label="您的审核意见">
                <el-row>
                  <el-col :span="12">
                    <el-select v-model="doForm.applyStatus" placeholder="请选择审核意见"
                               style="width: 200px;" size="mini" @change="changeAuditStatus"
                    >
                      <el-option v-for="(v, i) in status_list" :key="i" :label="v.label"
                                 :value="v.value"
                      />
                    </el-select>
                  </el-col>
                  <!-- 根据audius_detail_type字典的按钮显示逻辑 -->
    
                  <el-col :span="12">
                    <!-- 非编辑模式下显示修改按钮 -->
                    <el-button v-if="!editMode" type="primary" size="mini" style="margin-right: 10px;" @click="toggleEditMode">修改申请</el-button>
                    <!-- 编辑模式下显示保存和取消按钮 -->
                    <template v-if="editMode">
                      <el-button type="primary" size="mini" style="margin-right: 10px;" @click="saveEdit">保存修改</el-button>
                      <el-button type="default" size="mini" style="margin-right: 10px;" @click="cancelEdit">取消编辑</el-button>
                    </template>
                    <el-button type="success" size="mini" @click="doAudit">提交审核</el-button>
                  </el-col>
                </el-row>
                <!-- 编辑模式下的输入框 -->
                <el-input v-if="editMode" v-model="doForm.fdyCmt" placeholder="请输入审核意见" type="textarea"
                          :maxlength="1000"
                          :autosize="{ minRows: 10, maxRows: 10 }"
                />
                <!-- 只读模式下的输入框 -->
                <el-input v-else v-model="doForm.fdyCmt" placeholder="请输入审核意见" type="textarea"
                          :maxlength="1000"
                          :autosize="{ minRows: 10, maxRows: 10 }" disabled
                />
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <div>
                <el-row>
                  <el-col :span="4">
                    <span style="font-weight: bolder;">该生申请奖项:</span>
                  </el-col>
                  <el-col :span="8">
                    <span style="color: red; font-weight: bolder;">
                      优秀毕业生
                    </span>
                  </el-col>
                  <el-col :span="6">
                    <el-button type="primary" size="mini"
                               @click="lookNeedV = true;"
                    >查看评优要求</el-button>
                  </el-col>
                </el-row>
              </div>


              <el-drawer :modal="false" size="50%" title="评优要求" :visible.sync="lookNeedV" direction="ltr"
                         :append-to-body="true"
              >
                <div class="sign">
                  <ol>
                    <li>
                      德、智、体、美、劳全面发展,在校期间未受纪律处分.
                    </li>
                    <li>
                      学习勤奋,成绩优异,第一学期至第五学期所有课程的平均学分绩专业排名前10%.
                    </li>
                    <li>
                      积极参加学校开展的第二课堂活动活动,第二课堂成绩单学分认定为优秀.身体健康,体能考核成绩达标.(每学年体测成绩60分以上)
                    </li>
                    <li>
                      获得过校级及以上"三好学生""优秀学生干部""优秀共青团员""优秀共青团干部"中的其中一项荣誉.
                    </li>
                    <li>
                      积极参与各级各类校园文化活动和社会实践活动;在各级各类活动(竞赛)中成绩突出;在就业创业方面作为优秀典型.
                    </li>
                    <!-- <li>
                                            积极参与各级各类校园文化活动和社会实践活动;在各级各类活动(竞赛)中成绩突出;六个学期青年大学习率达到98%以上;在就业创业方面作为优秀典型.
                                        </li> -->
                    <li>
                      同等条件下,获得国家奖学金或国家励志奖学金等国家级奖励的毕业生应优先推荐.
                    </li>
                    <li>
                      认定为校级优秀毕业生,才有资格推荐为上级优秀毕业生.
                    </li>
                  </ol>
                </div>
              </el-drawer>


              <el-table :data="rank_data">
                <el-table-column label="学业成绩专业排名" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.majorRank + "/" + scope.row.majorCount }}
                  </template>
                </el-table-column>
                <el-table-column label="专业排名百分比(四舍五入保留整数)" align="center">
                  <template slot-scope="scope">
                    {{ Math.round(Math.round(scope.row.majorRank / scope.row.majorCount * 10000) /
                      100)
                      + "%" }}
                  </template>
                </el-table-column>
              </el-table>
              <el-table :data="sport_data">
                <el-table-column label="学年" align="center" prop="stuYearName" />
                <el-table-column label="体测成绩" align="center" prop="sportScore" />
              </el-table>

            </el-col>
          </div>


        </el-row>
      </el-form>

    </el-dialog>

    <el-dialog :visible.sync="lookMoreV" :append-to-body="true">
      <MoreDetail />
    </el-dialog>


  </div>
</template>
<script>
import { listAllYear as listYear } from '@/api/stuCQS/basedata/year'
import { listOwnClass } from '@/api/stuCQS/info-fill/stu_eva_task'
import { listSelect } from '@/api/stuCQS/lake/type'

import {
    fdyAudit, getStuScoreMajorRank,
    listFdy,
    listStuSportScore,
    listStuSportScoreByTag,
    updateBiyeapply
} from '@/api/comprehensive/biyeapply'

import {
    applyStatus
} from '@/api/stuCQS/good/audit'

import { isEmpty } from '@/api/helpFunc'
import MoreDetail from '@/views/stuCQS/lake/MoreDetail.vue'
import dayjs from 'dayjs'


export default {
    name: 'Lakefdy',
    dicts: ['audius_detail_type'],
    components: {
        MoreDetail
    },
    data() {
        return {
            dayjs,
            applyStatus,
            search_type_list: [],

            isEmpty,

            fullLoading: false,

            loading: false,
            table_data: [],
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                code: null,
                status: null,
                stuNo: '',
                stuName: ''
            },

            auditV: false,
            auditForm: {},

            myScoreV: false,


            doForm: {
                id: null,
                applyStatus: null,
                fdyCmt: '同意申请'
            },

            class_list: [],
            year_list: [],

            lookNeedV: false,
            lookMoreV: false,

            status_list: [
                {
                    label: '通过',
                    value: 2
                },
                {
                    label: '驳回(学生可以重新提交)',
                    value: 10
                },
                {
                    label: '拒绝(学生不可以再提交)',
                    value: 11
                }
            ],

            rank_data: [],
            sport_data: [],
            
            // 修改功能相关变量
            editMode: false,
            originalGoodHis: '',
            originalMainHis: ''

        }
    },
    created() {
        this.listSelect()
        this.listOwnClass()
        this.listAllStuYear()
        this.getList()
    },
    methods: {
        getStepStatus(data) {
            if ((data.includes('同意') && !data.includes('不同意')) || data.includes('通过') || (data.includes('符合') && !data.includes('不符合'))) {
                return 'success'
            } else {
                return 'error'
            }
        },
        getStep(data) {
            if (!isEmpty(data.jwcCmt)) {
                return 4
            } else if (!isEmpty(data.xwCmt)) {
                return 3
            } else if (!isEmpty(data.fdyCmt)) {
                return 2
            } else {
                return 1
            }
        },
        changeAuditStatus(v) {
            switch (v) {
                case 2:
                    this.doForm.fdyCmt = '同意申请.'
                    break
                case 10:
                    this.doForm.fdyCmt = '填写有误,请重新提交.'
                    break
                case 11:
                    this.doForm.fdyCmt = '拒绝申请.'
                    break
                default:
                    this.doForm.fdyCmt = '同意申请.'
                    break
            }
        },
        async listSelect() {
            let res = await listSelect()
            if (res.code == 200) {
                this.search_type_list = [...res.data]
            }
        },
        lookMore() {
            this.lookMoreV = true
            window.open('http://zhxg.gxsdxy.cn/file/jhzx2023.pdf')
        },
        async listAllStuYear() {
            let res = await listYear()
            if (res.code == 200) {
                this.year_list = [...res.data]
            }
        },
        async listOwnClass() {
            let res = await listOwnClass()
            if (res.code == 200) {
                this.class_list = [...res.data]
            }
        },
        async getList() {
            this.loading = true
            let res = await listFdy(this.queryParams)
            this.loading = false
            if (res.code == 200) {
                this.table_data = [...res.rows]
                this.total = res.total
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        async auditVClick(v) {
            this.auditForm = { ...v }
            this.auditV = true
            this.editMode = false
            
            // 调试信息
            console.log('auditVClick - v:', v)
            console.log('auditVClick - auditForm.applyStatus:', this.auditForm.applyStatus)
            console.log('auditVClick - editMode:', this.editMode)
            
            // 如果已有审核意见，则显示在doForm中
            if (!isEmpty(v.fdyCmt)) {
                this.doForm.fdyCmt = v.fdyCmt
            } else {
                this.doForm.fdyCmt = '同意申请'
            }
            
            this.getStuScoreMajorRank(v.stuNo)
            this.listStuSportScore(v.stuNo)
        },
        async getStuScoreMajorRank(stuNo) {
            let res = await getStuScoreMajorRank(stuNo)
            if (res.code == 200) {
                this.rank_data = [res.data]
            }
        },
        async listStuSportScore(stuNo) {
            /* let res = await listStuSportScore(stuNo) */
            /*当前功能是获取'优秀毕业生---YXBY'标签对应学年的体测成绩。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        ---尽量避免学年标签字典的更改!!!! */
            const yearTag = 'YXBY'
            let res = await listStuSportScoreByTag(stuNo,yearTag)
            if (res.code == 200) {
                this.sport_data = [...res.data.filter(x => x.sportScore != 0)]
            }
        },

        async doAudit() {
            let sdata = { ...this.doForm }
            if (isEmpty(sdata.applyStatus)) {
                this.$message.info('请选择是否通过')
                return
            }
            if (isEmpty(sdata.fdyCmt)) {
                this.$message.info('请填写审核意见')
                return
            }
            sdata.id = parseInt(this.auditForm.id)
            this.fullLoading = true
            let res = await fdyAudit(sdata)
            this.fullLoading = false
            if (res.code == 200) {
                this.getList()
                this.auditForm = {}
                this.doForm = {
                    id: null,
                    applyStatus: null,
                    fdyCmt: '同意申请'
                }
                this.auditV = false
                this.$message.success(res.msg)
            }
        },

        // 修改功能相关方法
        toggleEditMode() {
            this.editMode = true
            this.originalGoodHis = this.auditForm.goodHis
            this.originalMainHis = this.auditForm.mainHis
        },

        cancelEdit() {
            this.editMode = false
            this.auditForm.goodHis = this.originalGoodHis
            this.auditForm.mainHis = this.originalMainHis
        },

        async saveEdit() {
            if (isEmpty(this.auditForm.goodHis) && isEmpty(this.auditForm.mainHis)) {
                this.$message.info('请填写获奖情况或主要事迹')
                return
            }

            let updateData = {
                id: parseInt(this.auditForm.id),
                goodHis: this.auditForm.goodHis,
                mainHis: this.auditForm.mainHis
            }

            this.fullLoading = true
            try {
                let res = await updateBiyeapply(updateData)
                this.fullLoading = false
                if (res.code == 200) {
                    this.editMode = false
                    this.getList()
                    this.$message.success('修改成功')
                } else {
                    this.$message.error(res.msg || '修改失败')
                }
            } catch (error) {
                this.fullLoading = false
                this.$message.error('修改失败')
            }
        },


    }
}
</script>
<style lang="scss" scoped>
.addForm-input {
    width: 400px;
}

.detail {
    .el-form-item {
        margin-bottom: 0px;
    }
}

.sign {
    width: 100%;
    border: 1px solid rgb(163, 211, 255);
    font-size: small;
    margin-bottom: 10px;
    border-radius: 2px;
}
</style>