<template>
  <div class="studentEvaluation">
    <div class="form-header h4">
      <div>基本信息</div>
    </div>
    <el-form :model="form" ref="form" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="form.studentName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="注册序号" prop="schoolNo">
            <el-input v-model="form.schoolNo" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="form-header h4">
      <div>测评记录</div>
    </div>
    <!-- 操作按钮 -->
    <el-row>
      <el-button type="primary" size="mini" plain icon="el-icon-plus"
                 @click="addEvaluation"
      >
        新增
      </el-button>
      <el-button type="info" size="mini" plain icon="el-icon-document"
                 @click="evaluationDetail" :disabled="isDetail"
      >
        详情
      </el-button>
      <el-button type="success" size="mini" plain icon="el-icon-edit"
                 @click="editEvaluation" :disabled="isEdit"
      >
        修改
      </el-button>
      <el-button type="danger" size="mini" plain icon="el-icon-delete"
                 @click="detleEvaluation" :disabled="isDetele"
      >
        删除
      </el-button>
      <el-button type="primary" size="mini" plain icon="el-icon-upload"
                 @click="uploadEvaluation" :disabled="isUpload"
      >
        导出
      </el-button>
      <el-button type="info" size="mini" plain icon="el-icon-close"
                 @click="closeEvaluation"
      >
        关闭
      </el-button>
    </el-row>

    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      border
      v-loading="loading"
      tooltip-effect="dark"
      style="width: 100%; margin-top: 10px"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center"></el-table-column>
      <!-- <el-table-column prop="studentName" label="学生姓名" align="center"></el-table-column> -->
      <el-table-column prop="evaluate" label="班主任寄语" align="center"></el-table-column>
      <el-table-column prop="academicEvaluation" label="学业测评" align="center"></el-table-column>
      <el-table-column prop="dailyComments" label="日常点评" align="center"></el-table-column>
      <el-table-column prop="physiqueEvaluation" label="体质测评" align="center"></el-table-column>
      <el-table-column prop="score" label="分值" align="center"></el-table-column>
    </el-table>

    <!-- 分页 -->
    <ExPagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getEvaluateList"/>

    <!-- 新增弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="addVisible"
      width="45%"
      center
      @close="cancelSubmit"
    >
      <el-form :model="dialogForm" :rules="rules" ref="form" label-width="100px"
               class="demo-ruleForm" :disabled="isShowForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input v-model="dialogForm.studentName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分值" prop="score">
              <el-input
                ref="score"
                placeholder="请输入分值"
                class="custom-input__number"
                clearable
                v-model="dialogForm.score"
                @keydown.native="handleScore"
                @input="handleScoreSplice"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="班主任寄语" prop="evaluate">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="dialogForm.evaluate"
            maxlength="2000"
            :autosize="{ minRows: 5, maxRows: 20}"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="学业测评" prop="academicEvaluation">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="dialogForm.academicEvaluation"
            maxlength="2000"
            :autosize="{ minRows: 5, maxRows: 20}"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="日常点评" prop="dailyComments">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="dialogForm.dailyComments"
            maxlength="2000"
            :autosize="{ minRows: 5, maxRows: 20}"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="体质测评" prop="physiqueEvaluation">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="dialogForm.physiqueEvaluation"
            maxlength="2000"
            :autosize="{ minRows: 5, maxRows: 20}"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="自我测评" prop="studentComment">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="dialogForm.studentComment"
            maxlength="2000"
            :autosize="{ minRows: 5, maxRows: 20}"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEvaluation">确 定</el-button>
        <el-button @click="cancelSubmit">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  studentEvaluateList,
  addStudentEvaluation,
  editStudentEvaluation,
  deleteEvaluation
} from '@/api/smartSchool/studentManage/comprehensiveEvaluation'

export default {
  name: 'Evaluation',
  data() {
    // 分值校验规则
    const validateScore = (rule, value, callback) => {
      const IntReg = new RegExp(/^[0-9]*$/);
      if (Number(value) < 0) {
        callback(new Error('分值不能小于0'));
      } else if (Number(value) > 100) {
        callback(new Error('分值不能大于100'));
      } else if (value == null || value === '') {
        callback(new Error('分值不能为空'));
      } else if (value != 0 && !Number(value)) {
        callback(new Error('分值应为数字'));
      } else {
        callback();
      }
    };

    // var validateScore = (rule, value, callback) => {
    //   const num= /^[0-9]*$/
    //   if (!num.test(value)) {
    //     callback(new Error('请输入数字'))
    //   }else{
    //     if(value < 0){
    //       return callback(new Error('分值不能小于0'));
    //     } else if(value > 100){
    //       return callback(new Error('分值不能大于100'));
    //     } else {
    //       return callback()
    //     }
    //   }
    // }

    return {
      // 学生信息
      form: {},
      // 弹框标题
      title: '',
      selectId: [],
      isDetail: true,
      isEdit: true,
      isDetele: true,
      isUpload: true,
      isShowForm: false,
      // 表格数据
      tableData: [],
      // 弹框数据
      dialogForm: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      // 表格数据条数
      total: 0,
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        studentName: '',
        studentId: undefined
      },
      // 是否展示新增弹框
      addVisible: false,
      loading: false,
      // 校验规则
      rules: {
        score: [
          { required: true, validator: validateScore, trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {
    stuId() {
      return this.$route.query.stuId
    },
  },
  watch: {
    stuId() {
      if (this.stuId !== undefined) {
        this.getEvaluateList()
      }
    }
  },
  mounted() {
    this.getEvaluateList()
  },
  created() {
    const { stuId, studentName, schoolNo } = this.$route.query;
    this.form = { stuId, studentName, schoolNo };
    this.queryForm.studentId = stuId;
    this.getEvaluateList();
  },
  methods: {
    async getEvaluateList() {
      this.loading = true
      const data = await studentEvaluateList({ studentId: this.stuId })
      this.loading = false
      this.tableData = data.rows
      this.total = data.total
    },

    //  查询按钮
    handleQuery() {
      this.throttle(() => {
        this.queryForm.pageNum = 1;
        this.getEvaluateList();
      })
    },
    // 【新增】按钮
    addEvaluation() {
      this.reset();
      this.addVisible = true;
      this.isShowForm = false;
      this.dialogForm = {};
      this.dialogForm.studentName = this.form.studentName;
      this.title = '新增测评';
    },

    // 详情
    evaluationDetail() {
      this.addVisible = true
      this.isShowForm = true
      this.title = '测评详情'
      let arr = this.tableData.filter(item => {
        return item.id == this.selectId[0]
      })
      console.log(arr, 'arr');
      this.dialogForm = arr[0]
    },

    // 修改
    editEvaluation() {
      this.reset();
      this.addVisible = true;
      this.isShowForm = false;
      this.title = '修改测评';
      let arr = this.tableData.filter(item => {
        return item.id == this.selectId[0];
      })
      this.dialogForm = JSON.parse(JSON.stringify(arr[0]));
    },

    // 删除
    detleEvaluation() {
      this.$confirm('确定删除该测评信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteEvaluation(this.selectId)
        this.$message.success('删除成功!');
        this.getEvaluateList()
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 提交
    submitEvaluation() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.dialogForm.id) {
            // 修改提交
            this.$message.success('修改成功');
            this.dialogForm.studentId = this.stuId;
            await editStudentEvaluation(this.dialogForm);
            this.cancelSubmit();
            this.getEvaluateList();
          } else {
            // 新增提交
            this.$message.success('新增成功');
            this.addVisible = false;
            this.dialogForm.studentId = this.stuId;
            await addStudentEvaluation(this.dialogForm);
            this.cancelSubmit();
            this.getEvaluateList();
          }
        }
      })
    },
    // 取消
    cancelSubmit() {
      this.reset();
      this.addVisible = false;
    },

    // 导出
    uploadEvaluation() {
    },

    // 关闭
    closeEvaluation() {
      this.$tab.closeOpenPage({ path: '/class/classinfo' });
    },

    // 表格中的选中数据
    handleSelectionChange(selection) {
      this.selectId = []
      selection.forEach(item => {
        this.selectId.push(item.id);
      });
      this.isEdit = this.selectId.length == 1 ? false : true
      this.isDetail = this.selectId.length == 1 ? false : true
      this.isDetele = this.selectId.length > 0 ? false : true
      this.isUpload = this.selectId.length > 0 ? false : true
    },
    /** 重置 */
    reset() {
      this.dialogForm = {
        studentId: null,
        studentName: null,
        evaluate: null,
        academicEvaluation: null,
        dailyComments: null,
        physiqueEvaluation: null,
        studentComment: null,
        score: null,
        semester: null
      };
      this.resetForm('form');
    },
    /** 处理特殊字符： e, '.' */
    handleScore(value) {
      const disabledChar = ['e', 'E', '.'];
      console.log(value);
      if (disabledChar.indexOf(value.key) > -1) {
        value.returnValue = false;
        return false;
      }
      return true;
    },
    /** 限制输入长度 */
    handleScoreSplice(value) {
      if (value && value.toString().length > 3) {
        const result = this.dialogForm.score.toString().slice(0, 3);
        this.$set(this.dialogForm, 'score', Number(result));
      }
    }
  },
}
</script>

<style lang='scss' scoped>
.studentEvaluation {
  padding: 20px;
}
</style>
