<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="学号" prop="studentCode">
        <el-input v-model="queryParams.studentCode" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item v-if="xflag" label="班级" prop="classId">
        <el-select 
          v-model="queryParams.classId" 
          placeholder="请选择班级" 
          clearable 
          filterable 
          style="width: 300px;"
        >
          <el-option
            v-for="item in cascaderData"
            :key="item.classId"
            :label="item.className"
            :value="item.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-else label="班级" prop="deptId">
        <el-cascader ref="cas" v-model="queryParams.classId" style="width: 500px;" :options="cascaderData"
                     :props="{ checkStrictly: false }" clearable filterable @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['graduate:basedata:add']" type="warning" plain icon="el-icon-download" size="mini"
                   @click="importVClick"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['comprehensive:identifytexs:add']" type="primary" plain icon="el-icon-plus" size="mini"
                   @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['comprehensive:identifytexs:remove']" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['graduate:basedata:dayin']" type="success" plain icon="el-icon-printer" size="mini"
                   :disabled="multiple" @click="handleBatchPrint"
        >批量打印</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="identifytexsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="学号" align="center" prop="studentCode" />
      <el-table-column label="学院" align="center" prop="studentCollege" />
      <el-table-column label="所属班级" align="center" prop="studentClass" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['comprehensive:identifytexs:edit']" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button v-hasPermi="['comprehensive:identifytexs:remove']" size="mini" type="text" icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button v-hasPermi="['graduate:basedata:dayin']" size="mini" type="text" icon="el-icon-printer"
                     @click="takeEclData(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="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入姓名" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="学号" prop="studentCode">
          <el-input v-model="form.studentCode" placeholder="请输入学号" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input v-model="getSex" placeholder="请输入性别" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="学院" prop="studentCollege">
          <el-input v-model="getStudentCollege" placeholder="请输入学院" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="年级" prop="studentGrade">
          <el-input v-model="getStudentGrade" placeholder="请输入年级" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="所属班级" prop="studentClass">
          <el-input v-model="getStudentClass" placeholder="请输入所属班级" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="名族" prop="nation">
          <el-input v-model="getNation" placeholder="请输入名族" :readonly="redingData" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthData">
          <span v-if="form.birthData != null" class="readonly-label">{{ formatDate(form.birthData) }}</span>
          <el-date-picker v-else v-model="getBirthData" clearable type="date" value-format="yyyy-MM-dd"
                          placeholder="请选择出生日期"
          />
        </el-form-item>
        <!-- 第一学年信息 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <h3>第一学年</h3>
          </el-col>
          <el-form-item label="政治思想" prop="yearOne.politics">
            <el-input v-model="yearOneData.politics" placeholder="请输入政治思想" />
          </el-form-item>
          <el-form-item label="道德品质" prop="yearOne.moralCharacter">
            <el-input v-model="yearOneData.moralCharacter" placeholder="请输入道德品质" />
          </el-form-item>
          <el-form-item label="遵纪守法" prop="yearOne.observeDiscipline">
            <el-input v-model="yearOneData.observeDiscipline" placeholder="请输入遵纪守法" />
          </el-form-item>
          <el-form-item label="学习态度" prop="yearOne.attitude">
            <el-input v-model="yearOneData.attitude" placeholder="请输入学习态度" />
          </el-form-item>
          <el-form-item label="考勤情况" prop="yearOne.attendanceSituation">
            <el-input v-model="yearOneData.attendanceSituation" placeholder="请输入考勤情况" />
          </el-form-item>
          <el-form-item label="担任职务" prop="yearOne.positionHeld">
            <el-input v-model="yearOneData.positionHeld" placeholder="请输入担任职务" />
          </el-form-item>
          <el-form-item label="工作态度" prop="yearOne.workingAttitude">
            <el-input v-model="yearOneData.workingAttitude" placeholder="请输入工作态度" />
          </el-form-item>
          <el-form-item label="工作能力" prop="yearOne.workingAbility">
            <el-input v-model="yearOneData.workingAbility" placeholder="请输入工作能力" />
          </el-form-item>
          <el-form-item label="思想政治素质" prop="yearOne.ldeologicalPolitical">
            <el-input v-model="yearOneData.ldeologicalPolitical" placeholder="请输入思想政治素质" />
          </el-form-item>
          <el-form-item label="科学文化素质" prop="yearOne.scientificQuality">
            <el-input v-model="yearOneData.scientificQuality" placeholder="请输入科学文化素质" />
          </el-form-item>
          <el-form-item label="体能素质" prop="yearOne.physicalQuality">
            <el-input v-model="yearOneData.physicalQuality" placeholder="请输入体能素质" />
          </el-form-item>
          <el-form-item label="总分" prop="yearOne.totalPoints">
            <el-input v-model="yearOneData.totalPoints" type="number" placeholder="请输入总分" />
          </el-form-item>
          <el-form-item label="学年">
            <el-select v-if="mode === 'add' || yearOneData.stuYear == null" v-model="yearOneData.stuYear"
                       placeholder="请选择学年" @change="handleYearChange"
            >
              <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id" />
            </el-select>
            <span v-else class="readonly-label">{{ getYearNameById(form.yearOne.stuYear) }}</span>
          </el-form-item>
        </el-row>
        <!-- 第二学年信息 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <h3>第二学年</h3>
          </el-col>
          <el-form-item label="政治思想" prop="yearTwo.politics">
            <el-input v-model="yearTwoData.politics" placeholder="请输入政治思想" />
          </el-form-item>
          <el-form-item label="道德品质" prop="yearTwo.moralCharacter">
            <el-input v-model="yearTwoData.moralCharacter" placeholder="请输入道德品质" />
          </el-form-item>
          <el-form-item label="遵纪守法" prop="yearTwo.observeDiscipline">
            <el-input v-model="yearTwoData.observeDiscipline" placeholder="请输入遵纪守法" />
          </el-form-item>
          <el-form-item label="学习态度" prop="yearTwo.attitude">
            <el-input v-model="yearTwoData.attitude" placeholder="请输入学习态度" />
          </el-form-item>
          <el-form-item label="考勤情况" prop="yearTwo.attendanceSituation">
            <el-input v-model="yearTwoData.attendanceSituation" placeholder="请输入考勤情况" />
          </el-form-item>
          <el-form-item label="担任职务" prop="yearTwo.positionHeld">
            <el-input v-model="yearTwoData.positionHeld" placeholder="请输入担任职务" />
          </el-form-item>
          <el-form-item label="工作态度" prop="yearTwo.workingAttitude">
            <el-input v-model="yearTwoData.workingAttitude" placeholder="请输入工作态度" />
          </el-form-item>
          <el-form-item label="工作能力" prop="yearTwo.workingAbility">
            <el-input v-model="yearTwoData.workingAbility" placeholder="请输入工作能力" />
          </el-form-item>
          <el-form-item label="思想政治素质" prop="yearTwo.ldeologicalPolitical">
            <el-input v-model="yearTwoData.ldeologicalPolitical" placeholder="请输入思想政治素质" />
          </el-form-item>
          <el-form-item label="科学文化素质" prop="yearTwo.scientificQuality">
            <el-input v-model="yearTwoData.scientificQuality" placeholder="请输入科学文化素质" />
          </el-form-item>
          <el-form-item label="体能素质" prop="yearTwo.physicalQuality">
            <el-input v-model="yearTwoData.physicalQuality" placeholder="请输入体能素质" />
          </el-form-item>
          <el-form-item label="总分" prop="yearTwo.totalPoints">
            <el-input v-model="yearTwoData.totalPoints" type="number" placeholder="请输入总分" />
          </el-form-item>
          <el-form-item label="学年">
            <el-select v-if="mode === 'add' || yearTwoData.stuYear == null" v-model="yearTwoData.stuYear"
                       placeholder="请选择学年" @change="handleYearChange"
            >
              <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id" />
            </el-select>
            <span v-else class="readonly-label">{{ getYearNameById(form.yearTwo.stuYear) }}</span>
          </el-form-item>
        </el-row>
        <!-- 第三学年信息 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <h3>第三学年</h3>
          </el-col>
          <el-form-item label="政治思想" prop="yearThree.politics">
            <el-input v-model="yearThreeData.politics" placeholder="请输入政治思想" />
          </el-form-item>
          <el-form-item label="道德品质" prop="yearThree.moralCharacter">
            <el-input v-model="yearThreeData.moralCharacter" placeholder="请输入道德品质" />
          </el-form-item>
          <el-form-item label="遵纪守法" prop="yearThree.observeDiscipline">
            <el-input v-model="yearThreeData.observeDiscipline" placeholder="请输入遵纪守法" />
          </el-form-item>
          <el-form-item label="学习态度" prop="yearThree.attitude">
            <el-input v-model="form.yearThree.attitude" placeholder="请输入学习态度" />
          </el-form-item>
          <el-form-item label="考勤情况" prop="yearThree.attendanceSituation">
            <el-input v-model="yearThreeData.attendanceSituation" placeholder="请输入考勤情况" />
          </el-form-item>
          <el-form-item label="担任职务" prop="yearThree.positionHeld">
            <el-input v-model="yearThreeData.positionHeld" placeholder="请输入担任职务" />
          </el-form-item>
          <el-form-item label="工作态度" prop="yearThree.workingAttitude">
            <el-input v-model="yearThreeData.workingAttitude" placeholder="请输入工作态度" />
          </el-form-item>
          <el-form-item label="工作能力" prop="yearThree.workingAbility">
            <el-input v-model="yearThreeData.workingAbility" placeholder="请输入工作能力" />
          </el-form-item>
          <el-form-item label="思想政治素质" prop="yearThree.ldeologicalPolitical">
            <el-input v-model="yearThreeData.ldeologicalPolitical" placeholder="请输入思想政治素质" />
          </el-form-item>
          <el-form-item label="科学文化素质" prop="yearThree.scientificQuality">
            <el-input v-model="yearThreeData.scientificQuality" placeholder="请输入科学文化素质" />
          </el-form-item>
          <el-form-item label="体能素质" prop="yearThree.physicalQuality">
            <el-input v-model="yearThreeData.physicalQuality" placeholder="请输入体能素质" />
          </el-form-item>
          <el-form-item label="总分" prop="yearThree.totalPoints">
            <el-input v-model="yearThreeData.totalPoints" type="number" placeholder="请输入总分" />
          </el-form-item>
          <el-form-item label="学年">
            <el-select v-if="mode === 'add' || yearThreeData.stuYear == null" v-model="yearThreeData.stuYear"
                       placeholder="请选择学年" @change="handleYearChange"
            >
              <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id" />
            </el-select>
            <span v-else class="readonly-label">{{ getYearNameById(form.yearThree.stuYear) }}</span>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入模板对话框 -->
    <el-dialog title="导入模板" :visible.sync="importV" :before-close="handleClose" width="400px" center
               style="text-align: center;"
    >
      <el-row type="flex" class="row-bg" justify="space-around">
        <el-upload center class="upload-demo" drag :auto-upload="false" :limit="1" :on-exceed="handleExceed" action=""
                   :file-list="fileList" :on-change="fileChoose" :on-success="handleFileSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件(鉴定表) <el-link type="primary" size="mini"
                                                                              @click="downloadMode"
          >下载模板</el-link></div>
        </el-upload>
      </el-row>
      <br>
      <el-form>
        <el-form-item label="学年">
          <el-select v-model="stu_year_import" placeholder="请选择学年" @change="handleYearChanges">
            <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doImport()">导 入</el-button>
      </span>
    </el-dialog>

    <!-- 打印预览对话框 -->
    <el-dialog title="打印预览" :visible.sync="printDialogVisible" fullscreen>
      <div id="printContent" class="print-content">
        <!-- 双面打印提示 -->
        <div v-if="printDialogVisible" class="print-notice no-print">
          <el-alert title="打印提示" type="info" show-icon>
            <p>请确保打印机已设置为双面打印模式（短边翻转）</p>
            <p>评语表将打印在正面，鉴定表将打印在背面</p>
          </el-alert>
        </div>

        <!-- 使用 v-for 循环渲染每个待打印的学生信息 -->
        <div v-for="(student, index) in printList" :key="index" class="student-print-set">
          <!-- 学生评语表（正面） -->
          <div class="print-page">
            <div class="print-header">
              <h1>广西水利电力职业技术学院学生评语表</h1>
            </div>

            <table class="print-table comment-table">
              <tr>
                <th colspan="8">广西水利电力职业技术学院学生评语表</th>
              </tr>
              <tr>
                <td>学年</td>
                <td colspan="3">第一学年</td>
                <td colspan="3">第二学年</td>
                <td>第三学年</td>
              </tr>
              <tr>
                <td>辅导员评语</td>
                <td colspan="3" class="comment-cell">
                  {{ getYearData(student, 0, 'counselorComments') }}
                  <div class="signature">
                    <div>辅导员：{{ getYearData(student, 0, 'counselorName') }}</div>
                    <div>{{ formatDateForPrint(getYearData(student, 0, 'fillData')) }}</div>
                  </div>
                </td>
                <td colspan="3" class="comment-cell">
                  {{ getYearData(student, 1, 'counselorComments') }}
                  <div class="signature">
                    <div>辅导员：{{ getYearData(student, 1, 'counselorName') }}</div>
                    <div>{{ formatDateForPrint(getYearData(student, 1, 'fillData')) }}</div>
                  </div>
                </td>
                <td class="comment-cell">
                  {{ getYearData(student, 2, 'counselorComments') }}
                  <div class="signature">
                    <div>辅导员：{{ getYearData(student, 2, 'counselorName') }}</div>
                    <div>{{ formatDateForPrint(getYearData(student, 2, 'fillData')) }}</div>
                  </div>
                </td>
              </tr>
              <tr>
                <td>学院意见</td>
                <td colspan="3" class="comment-cell">
                  {{ getYearData(student, 0, 'collegeOpinion') || '无数据' }}
                  <div class="signature">
                    <div>{{ formatDateForPrint(getYearData(student, 0, 'fillData')) || '无数据' }}</div>
                  </div>
                </td>
                <td colspan="3" class="comment-cell">
                  {{ getYearData(student, 1, 'collegeOpinion') || '无数据' }}
                  <div class="signature">
                    <div>{{ formatDateForPrint(getYearData(student, 1, 'fillData')) || '无数据' }}</div>
                  </div>
                </td>
                <td class="comment-cell">
                  {{ getYearData(student, 2, 'collegeOpinion') || '无数据' }}
                  <div class="signature">
                    <div>{{ formatDateForPrint(getYearData(student, 2, 'fillData')) || '无数据' }}</div>
                  </div>
                </td>
              </tr>
            </table>

            <p class="print-note" style="text-align: center;">本表用钢笔或签字笔工整填写，由辅导员保管，学生离校时存入学生档案。</p>
            <p class="print-note" style="text-align: center;">广西水利电力职业技术学院 学生工作处印制</p>
          </div>

          <!-- 学生综合素质鉴定表（背面） -->
          <div class="print-page">
            <div class="print-header">
              <h1>广西水利电力职业技术学院学生综合素质鉴定表</h1>
            </div>

            <table class="print-table evaluation-table">
              <tr>
                <th colspan="5">学生基本信息</th>
              </tr>
              <tr>
                <td style="width: 120px;">姓名</td>
                <td>{{ student.studentName || '学生姓名' }}</td>
                <td style="width: 120px;">学号</td>
                <td colspan="2">{{ student.studentCode || '学生学号' }}</td>
              </tr>
              <tr>
                <td>学院</td>
                <td>{{ student.studentCollege || '所在学院' }}</td>
                <td>班级</td>
                <td colspan="2">{{ student.studentClass || '所属班级' }}</td>
              </tr>
              <tr>
                <td>性别</td>
                <td>{{ student.sex || '性别' }}</td>
                <td>民族</td>
                <td colspan="2">{{ student.nation || '民族' }}</td>
              </tr>
              <tr>
                <td>出生日期</td>
                <td colspan="4">{{ student.birth_data || '出生日期' }}</td>
              </tr>
            </table>

            <table class="print-table evaluation-table">
              <tr>
                <th rowspan="3">思想表现</th>
                <th>项目</th>
                <th>第一学年</th>
                <th>第二学年</th>
                <th>第三学年</th>
              </tr>
              <tr>
                <td>政治思想</td>
                <td>{{ getYearData(student, 0, 'politics') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'politics') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'politics') || '无数据' }}</td>
              </tr>
              <tr>
                <td>道德品质</td>
                <td>{{ getYearData(student, 0, 'moralCharacter') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'moralCharacter') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'moralCharacter') || '无数据' }}</td>
              </tr>
              <tr>
                <th rowspan="2">学习表现</th>
                <td>学习态度</td>
                <td>{{ getYearData(student, 0, 'attitude') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'attitude') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'attitude') || '无数据' }}</td>
              </tr>
              <tr>
                <td>考勤情况</td>
                <td>{{ getYearData(student, 0, 'attendanceSituation') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'attendanceSituation') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'attendanceSituation') || '无数据' }}</td>
              </tr>
              <tr>
                <th rowspan="3">工作表现</th>
                <td>担任职务</td>
                <td>{{ getYearData(student, 0, 'positionHeld') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'positionHeld') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'positionHeld') || '无数据' }}</td>
              </tr>
              <tr>
                <td>工作态度</td>
                <td>{{ getYearData(student, 0, 'workingAttitude') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'workingAttitude') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'workingAttitude') || '无数据' }}</td>
              </tr>
              <tr>
                <td>工作能力</td>
                <td>{{ getYearData(student, 0, 'workingAbility') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'workingAbility') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'workingAbility') || '无数据' }}</td>
              </tr>
              <tr>
                <th rowspan="4">综合成绩</th>
                <td>思想政治素质</td>
                <td>{{ getYearData(student, 0, 'ldeologicalPolitical') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'ldeologicalPolitical') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'ldeologicalPolitical') || '无数据' }}</td>
              </tr>
              <tr>
                <td>科学文化素质</td>
                <td>{{ getYearData(student, 0, 'scientificQuality') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'scientificQuality') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'scientificQuality') || '无数据' }}</td>
              </tr>
              <tr>
                <td>体能素质</td>
                <td>{{ getYearData(student, 0, 'physicalQuality') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'physicalQuality') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'physicalQuality') || '无数据' }}</td>
              </tr>
              <tr>
                <td>总分</td>
                <td>{{ getYearData(student, 0, 'totalPoints') || '无数据' }}</td>
                <td>{{ getYearData(student, 1, 'totalPoints') || '无数据' }}</td>
                <td>{{ getYearData(student, 2, 'totalPoints') || '无数据' }}</td>
              </tr>
            </table>

            <p class="print-note">
              备注：本表中的"思想表现"、"学习表现"、"工作表现"等项按优、良、中、及格、不及格等级填写；考勤情况按全勤，有迟到、旷课、早退、请假的按实际数填写；"担任职务"为班级、学院、学校学生干部名称；个人素质综合成绩参照《学生个人综合素质考评办法》中的要求进行填写。
            </p>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <div class="print-actions">
          <el-button v-print="printObj" type="primary" icon="el-icon-printer">双面打印全部</el-button>
          <el-button @click="printDialogVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listIdentifytexs, getIdentifytexs, delIdentifytexs, addIdentifytexs, updateIdentifytexs, deptDataList } from '@/api/comprehensive/identifytexs'
import { treeStudent } from '@/api/stuCQS/basedata/student'
import { listQiyongYear as listYear } from '@/api/stuCQS/basedata/year'
import * as XLSX from 'xlsx'
import { excelDateToJSDate } from '@/utils/index'
import { isEmpty } from '@/api/helpFunc'
import { importGraduate, getStuInfo } from '@/api/graduate/index'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'Identifytexs',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生鉴定信息表格数据
      identifytexsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      cascaderData: null,
      stu_years: [],
      stu_year_import: null,
      fileList: [],
      importV: false,
      biaoJi: null,
      excelName: null,
      redingData: false,
      xflag: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentCode: null,
        studentClass: null,
        classId: null,
      },
      // 表单参数
      form: {
        id: null,
        studentName: null,
        studentCode: null,
        studentCollege: null,
        studentGrade: null,
        studentClass: null,
        sex: null,
        nation: null,
        birthData: null,
        yearOne: { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, biaoJit: null },
        yearTwo: { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, biaoJit: null },
        yearThree: { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, biaoJit: null },
      },
      // 表单校验
      rules: {
        studentName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
        studentCode: [{ required: true, message: '学生学号不能为空', trigger: 'blur' }],
        yearOne: [{ required: true, message: '第一学年信息不能为空', trigger: 'blur' }],
        yearTwo: [{ required: true, message: '第二学年信息不能为空', trigger: 'blur' }],
        yearThree: [{ required: true, message: '第三学年信息不能为空', trigger: 'blur' }]
      },
      mode: 'add',

      // 打印相关
      printDialogVisible: false,
      printList: [],
      printObj: {
        id: 'printContent',
        popTitle: '毕业生信息打印',
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        extraCss: 'https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/theme-chalk/index.css',
      },
    }
  },
  computed: {
    getStudentCollege: { get() { return this.form.studentCollege != null ? this.form.studentCollege : null }, set(val) { this.form.studentCollege = val } },
    getStudentGrade: { get() { return this.form.studentGrade != null ? this.form.studentGrade : null }, set(val) { this.form.studentGrade = val } },
    getStudentClass: { get() { return this.form.studentClass != null ? this.form.studentClass : null }, set(val) { this.form.studentClass = val } },
    getSex: { get() { return this.form.sex != null ? this.form.sex : null }, set(val) { this.form.sex = val } },
    getNation: { get() { return this.form.nation != null ? this.form.nation : null }, set(val) { this.form.nation = val } },
    getBirthData: { get() { return this.form.birthData != null ? this.form.birthData : null }, set(val) { this.form.birthData = val } },
    yearOneData() { return this.form.yearOne || { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, } },
    yearTwoData() { return this.form.yearTwo || { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, } },
    yearThreeData() { return this.form.yearThree || { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, } },
  },
  created() {
    this.getList()
    this.getCascaderData()
    this.listAllStuYear()
  },
  methods: {
    /** 查询学生鉴定信息列表 */
    getList() {
      this.loading = true
      listIdentifytexs(this.queryParams).then(response => {
        this.identifytexsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 级联选择处理
    handleChange(value) {
      this.queryParams = { ...this.queryParams, classId: value[2], }
    },
    // 获取级联数据
    async getCascaderData() {
      const res = await deptDataList()
      this.cascaderData = res.data
      if(this.cascaderData.length > 0) {
        this.xflag = true
        return
      }
      const ress = await treeStudent()
        this.cascaderData = ress.data
          this.cascaderData.forEach(dept => {
          dept.children.forEach(major => {
            major.children.forEach(c => { delete c.children })
          })
      })
      //console.log(this.cascaderData, "班级数据");
    },
    // 获取学年信息
    async listAllStuYear() {
      let res = await listYear()
      this.stu_years = [...res.data]
    },
    // 获取学年对应的下标数据
    handleYearChange(value) {
      const index = this.stu_years.findIndex(item => item.id === value)
      if (index !== -1) {
        if (index == 0) { this.form.yearThree.biaoJit = index + 1; return }
        if (index == 1) { this.form.yearTwo.biaoJit = index + 1; return }
        if (index == 2) { this.form.yearOne.biaoJit = index + 1; return }
        this.$alert('确定要选择此学年吗？', '提示', { confirmButtonText: '', showCancelButton: false, type: 'warning', center: true, callback: () => { } })
      }
    },
    //导入学年处理
    handleYearChanges(value) {
      const index = this.stu_years.findIndex(item => item.id === value)
      if (index !== -1) {
        this.biaoJi = index + 1
        return
      }
    },
    //出生日期格式处理
    formatDate(date) {
      return parseTime(date, 'yyyy-MM-dd')
    },
    // 导入毕业生信息
    async doImport() {
      if (isEmpty(this.stu_year_import)) { this.$message.info('请选择学年'); return }
      this.loading = true
      let sdata = []
      let temp = [...this.importData]
      temp.map(v => {
        if (true) {
          let temp1 = {}
          if (this.excelName == '鉴定表.xlsx') {
            temp1 = { studentCode: v.studentCode, studentName: v.studentName, politics: v.politics, moralCharacter: v.moralCharacter, observeDiscipline: v.observeDiscipline, attitude: v.attitude, attendanceSituation: v.attendanceSituation, positionHeld: v.positionHeld, workingAttitude: v.workingAttitude, workingAbility: v.workingAbility, stuYear: this.stu_year_import, biaoJit: this.biaoJi }
          } else { this.$message.info('只能上传鉴定表'); this.excelName = ''; return }
          sdata.push(temp1)
        }
      })
      this.excelName = ''
      let res = await importGraduate(sdata)
      this.loading = false
      this.$message(res.msg)
      this.getList()
      this.importV = false
      this.fileList = []
      this.stu_year_import = null
    },
    // 下载模板
    downloadMode() {
      this.download('/comprehensive/rankingModel/downloadAllTemplates', {}, 'allTemplates.zip')
    },
    // 导入模板弹窗
    importVClick() {
      this.importV = true
    },
    // 关闭导入弹窗
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => { this.excelData = []; this.fileList = []; this.tableData = []; done() }).catch(_ => { })
    },
    // 文件超出限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 文件选择处理
    async fileChoose(file, fileList) {
      this.loading = true
      this.excelName = file.name
      try {
        let data = await this.handleData(file)
        let daterank = []
        if (this.excelName == '鉴定表.xlsx') {
          daterank = data.map(item => ({ studentCode: item.学号, studentName: item.姓名, politics: item['思想表现-政治思想'], moralCharacter: item['思想表现-道德品质'], observeDiscipline: item['思想表现-遵纪守法'], attitude: item['学习表现-学习态度'], attendanceSituation: item['学习表现-考勤情况'], positionHeld: item['工作表现-担任职位'], workingAttitude: item['工作表现-工作态度'], workingAbility: item['工作表现-工作能力'], }))
        } else { this.$message.info('只能上传鉴定表'); return }
        this.importData = daterank
        this.importTotal = data.length
      } catch (error) { console.error('上传失败:', error) } finally { this.loading = false }
    },
    // 文件数据处理
    handleData(file) {
      let reader = new FileReader()
      reader.readAsArrayBuffer(file.raw)
      return new Promise((resolve, reject) => {
        reader.onload = (e) => {
          let data = e.target.result
          let workbook = XLSX.read(data, { type: 'binary' })
          let jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { defval: 'null' })
          resolve(jsonData)
        }
      })
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.tableData = []
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.redingData = false
    },
    // 表单重置
    reset() {
      this.form = {
        id: null, studentName: null, studentCode: null, studentCollege: null, studentGrade: null, studentClass: null, sex: null, nation: null, birthData: null,
        yearOne: { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, },
        yearTwo: { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, },
        yearThree: { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, },
      }
      this.mode = 'add'
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.classId = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加学生鉴定信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getIdentifytexs(id).then(response => {
        const data = response.data
        this.form = {
          ...data,
          studentCollege: data.studentCollege || null, studentGrade: data.studentGrade || null, studentClass: data.studentClass || null, sex: data.sex || null, nation: data.nation || null, birthData: data.birthData || null,
          yearOne: data.yearOne || { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, },
          yearTwo: data.yearTwo || { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, },
          yearThree: data.yearThree || { politics: null, moralCharacter: null, observeDiscipline: null, attitude: null, attendanceSituation: null, positionHeld: null, workingAttitude: null, workingAbility: null, ldeologicalPolitical: null, scientificQuality: null, physicalQuality: null, totalPoints: null, stuYear: null, }
        }
        this.mode = 'edit'
        this.open = true
        this.title = '修改学生鉴定信息'
        if (data.studentCollege != null && data.studentGrade != null) { this.redingData = true } else { this.redingData = false }
      })
    },
    /** 获取学年名称通过ID */
    getYearNameById(yearId) {
      const year = this.stu_years.find(item => item.id === yearId)
      return year ? year.stuYearName : ''
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const submitData = { ...this.form, ...this.form.yearOne, ...this.form.yearTwo, ...this.form.yearThree }
          if (this.form.id != null) {
            updateIdentifytexs(submitData).then(response => { this.$modal.msgSuccess('修改成功'); this.open = false; this.getList() })
          } else {
            if (this.form.yearOne.stuYear != null && this.form.yearTwo.stuYear != null && this.form.yearThree.stuYear != null) {
              addIdentifytexs(submitData).then(response => { this.$modal.msgSuccess('新增成功'); this.open = false; this.getList() })
            } else { this.$modal.msgSuccess('对应学生信息不能为空') }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除学生鉴定信息编号为"' + ids + '"的数据项？').then(function () { return delIdentifytexs(ids) }).then(() => { this.getList(); this.$modal.msgSuccess('删除成功') }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('comprehensive/identifytexs/export', { ...this.queryParams }, `identifytexs_${new Date().getTime()}.xlsx`)
    },
    // 单个打印按钮操作
    async takeEclData(row) {
      this.loading = true
      try {
        const response = await getStuInfo(row.id)
        if (response.code !== 200) { throw new Error(response.msg || '获取学生信息失败') }
        const processedData = this._processStudentData(row, response.data)
        this.printList = [processedData]
        this.printDialogVisible = true
      } catch (error) {
        console.error('打印操作失败:', error)
        this.$message.error(error.message || '获取打印数据失败')
      } finally {
        this.loading = false
      }
    },
    // 批量打印按钮操作
    async handleBatchPrint() {
      if (this.selection.length === 0) { this.$message.warning('请先选择要打印的学生'); return }
      this.loading = true
      try {
        const promises = this.selection.map(row => getStuInfo(row.id))
        const results = await Promise.all(promises)
        const processedList = results.map((response, index) => {
          if (response.code === 200) {
            const baseInfo = this.selection[index]
            return this._processStudentData(baseInfo, response.data)
          } else {
            this.$message.error(`获取学号 ${this.selection[index].studentCode} 的信息失败: ${response.msg}`)
            return null
          }
        }).filter(item => item !== null)

        if (processedList.length > 0) {
          this.printList = processedList
          this.printDialogVisible = true
        } else if (this.selection.length > 0) {
          this.$message.error('所有选中学生的数据都获取失败，无法打印')
        }
      } catch (error) {
        console.error('批量打印操作失败:', error)
        this.$message.error('批量获取打印数据时发生网络错误')
      } finally {
        this.loading = false
      }
    },
    // 内部函数：处理单个学生的数据，用于代码复用
    _processStudentData(baseInfo, detailInfo) {
      const yearDataMap = {}
      if (detailInfo.graduateVoList && detailInfo.graduateVoList.length > 0) {
        detailInfo.graduateVoList.forEach((item, index) => { yearDataMap[index] = item })
      }
      return {
        ...baseInfo, ...detailInfo, yearDataMap,
        birth_data: this.formatDateForPrint(detailInfo.birthData) || '无数据',
        studentCollege: detailInfo.studentCollege || baseInfo.studentCollege || '无数据',
        studentClass: detailInfo.studentClass || baseInfo.studentClass || '无数据',
        sex: detailInfo.sex || '无数据',
        nation: detailInfo.nation || '无数据',
        studentName: detailInfo.studentName || baseInfo.studentName || '无数据',
        studentCode: detailInfo.studentCode || baseInfo.studentCode || '无数据'
      }
    },
    // 修改 getYearData 以接收 student 对象
    getYearData(student, yearIndex, field) {
      if (!student || !student.yearDataMap) { return '无数据' }
      const yearData = student.yearDataMap[yearIndex]
      if (!yearData) { return '无数据' }
      const value = yearData[field]
      return value || '无数据'
    },
    // 专门为打印创建了一个日期格式化函数
    formatDateForPrint(dateInput) {
      if (!dateInput) return '无数据'
      if (typeof dateInput === 'string' && dateInput.includes('年') && dateInput.includes('月') && dateInput.includes('日')) { return dateInput }
      try {
        const date = new Date(dateInput)
        if (isNaN(date.getTime())) { return '无数据' }
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}年${month}月${day}日`
      } catch (e) { console.error('日期格式化错误:', e); return '无数据' }
    },
  }
}
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header h1 {
  color: #1e4e8c;
  font-size: 24px;
  font-weight: 500;
}

.school-logo {
  width: 60px;
  height: 60px;
  background: #1e4e8c;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
  text-align: center;
  line-height: 1.3;
}

.search-form {
  background: #f8f9fb;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.student-table {
  margin-bottom: 20px;
}

.action-button {
  margin-right: 10px;
}

.print-content {
  padding: 20px;
}

.print-page {
  margin-bottom: 30px;
  background: white;
  padding: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.print-header {
  text-align: center;
  border-bottom: 2px solid #1e4e8c;
}

.print-header h1 {
  color: #1e4e8c;
  font-size: 24px;
  margin-bottom: 5px;
}

.print-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-size: 14px;
}

.print-table th,
.print-table td {
  border: 1px solid #000;
  padding: 10px 8px;
  text-align: center;
}

.print-table th {
  background-color: #f2f2f2;
  font-weight: 600;
}

.print-note {
  font-size: 12px;
  color: #666;
  font-style: italic;
  margin-top: 10px;
}

.comment-cell {
  height: 150px;
  position: relative;
}

.signature {
  position: absolute;
  right: 10px;
  bottom: 10px;
  text-align: right;
}

.print-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
  justify-content: center;
}

@media print {
  body * {
    visibility: hidden;
  }

  .print-content,
  .print-content * {
    visibility: visible;
  }

  .print-content {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    padding: 0;
    margin: 0;
  }

  .no-print {
    display: none !important;
  }

  @page {
    size: A4 landscape;
    margin: 0;
  }

  .print-page {
    page-break-after: always;
    margin: 0;
    padding: 0;
    box-shadow: none;
    width: 100%;
    height: 100%;
  }

  .print-page:last-child {
    page-break-after: auto;
  }

  .student-print-set {
    page-break-after: always;
  }

  .student-print-set:last-child {
    page-break-after: auto;
  }

  .print-table {
    width: 100% !important;
    margin: 0 !important;
    font-size: 12px !important;
  }

  .comment-cell {
    height: 150px !important;
  }

  .signature {
    right: 5px !important;
    bottom: 5px !important;
  }
}

.readonly-label {
  display: inline-block;
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
}
</style>