<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="form" :model="studentInfo" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="学生姓名" prop="name">
            <el-input v-model="studentInfo.name" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证号">
            <el-input v-model="studentInfo.idCard" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册序号">
            <el-input v-model="studentInfo.schoolNo" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:education:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:education:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:education:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭
        </el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="educationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
      <el-table-column label="事件描述" align="center" prop="eventDescription" show-overflow-tooltip />
      <el-table-column label="奖惩" align="center" prop="isReward" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.isReward == "1" ? "奖" : "惩" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分值" align="center" prop="score">

      </el-table-column>
      <el-table-column label="日期" align="center" prop="day">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.day, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="级别" align="center" prop="level" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.level === '1' ? "班级" : "级部" }}</span>
        </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="openForAdd" width="500px">
      <el-form ref="form" :model="form" label-width="98px" :rules="rules" style="text-align: center">
        <el-form-item label="事件描述：" prop="eventDescription">
          <el-input v-model="form.eventDescription"></el-input>
        </el-form-item>
        <el-form-item label="奖/惩：" prop="isReward">
          <el-select v-model="form.isReward" style="width: 100%">
            <el-option v-for="item in rewardOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分值：" prop="score">
          <el-input-number v-model="form.score" :precision="2" :step="1" :max="10" :min="0" controls-position="right"
            style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="日期：" prop="day">
          <el-date-picker :picker-options="pickerOptions" v-model="form.day" type="date" value-format="yyyy-MM-dd"
            placeholder="选择日期" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="级别：" prop="level">
          <el-select v-model="leveltype" disabled style="width: 100%">
            <el-option v-for="item in levelOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="openForAdd = false">取 消</el-button>
      </el-row>
    </el-dialog>

    <!-- 导出 -->
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>

  </div>
</template>

<script>
import {
  listEducation,
  getEducation,
  delEducation,
  addEducation,
  updateEducation
} from "@/api/smartSchool/studentManage/educationCheck.js";
import { ExportType } from "@/enums/common";
import SelectUser from "./components/selectUser.vue";
import {
  Path_Destination,
  jumpTo,
} from "@/utils/utilLibrary/routerBatch/routerBatch.js";

export default {
  name: "Education",
  components: { SelectUser },
  data() {
    this.educationDetail = (id) =>
      new this.Path_Destination(`/studentmanage/score/${id}`);
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生德育检查表格数据
      educationList: [],
      // 弹出层标题
      title: "",
      // 添加学生德育检查对话框
      openForAdd: false,
      // 修改学生德育检查对话框
      openForEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        day: '',
        level: this.leveltype,
        studentId: '',
        isReward: null,
        term: this.deTerm,
        schoolYear: undefined,
        score: ''
      },
      // 修改德育表单参数
      form: {
        isReward: ''
      },
      // 表单校验
      rules: {
        eventDescription: [{ required: true, message: '事件描述不能为空', trigger: 'blur' }],
        isReward: [{ required: true, message: '奖惩不能为空', trigger: 'blur' }],
        score: [{ required: true, message: '奖惩不能为空', trigger: 'blur' }],
        day: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
      },
      // 学生信息
      studentInfo: {},
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      // 限制选择日期不能超过今天
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      // 奖惩选项
      rewardOption: [
        {
          value: '0',
          label: '惩'
        },
        {
          value: '1',
          label: '奖'
        },
      ],
      // // 奖惩默认值
      // valuetype: '0',
      // 级别选项
      levelOption: [
        {
          value: '0',
          label: '级部'
        },
        {
          value: '1',
          label: '班级'
        },
      ],
      // 级别默认值
      leveltype: '0',
      // 学期选项
      termOption: [
        {
          value: '0',
          label: '上学期'
        },
        {
          value: '1',
          label: '下学期'
        }
      ],
      deTerm: '0'
    }
  },
  computed: {
    resolveClassName() {
      return info => {
        const { gradeName, className, yearValue } = info;
        return yearValue + '-' + gradeName + '-' + className;
      }
    }

  },
  created() {
    const { name, idCard, schoolNo, id, } = this.$route?.query;
    this.studentInfo = { name, idCard, schoolNo, id };
    this.queryParams.studentId = id;
    this.queryParams.schoolYear = this.$route?.query?.schoolYear;

    this.getList();
  },
  activated() {
    const { name, idCard, schoolNo, id } = this.$route?.query;
    this.studentInfo = { name, idCard, schoolNo, id };
    this.queryParams.studentId = id;
    this.getList();
  },
  methods: {
    // 路由工具库模块
    Path_Destination,
    jumpTo,
    /** 查询学生德育检查列表 */
    getList() {
      this.loading = true;
      listEducation(this.queryParams).then(response => {
        console.log(response);
        this.educationList = response.rows;
        console.log('this.educationList', this.educationList);
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        studentId: this.studentInfo.id,
        score: null,
        day: null,
        isReward: null,
        term: this.deTerm,
        level: this.leveltype,
        inspectorId: null,
        createBy: null,
        createTime: null,
      };
      this.resetForm("form");
    },
    //
    selectable(row, index) {
      if (row.level == '0') {
        return true
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        studentId: this.studentInfo.id,
        day: undefined,
        score: null,
        isReward: null,
        term: this.deTerm,
        level: this.leveltype,
        inspectorId: null,
        createBy: null,
        createTime: null,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 打开选择检查员对话框
    selectUser() {
      this.$refs.selectUser.open();
    },
    // 确认选择的检查员
    confirmUser({ userName, userId }) {
      this.$set(this.form, 'userName', userName);
      this.$set(this.form, 'inspectorId', userId);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openForAdd = true;
      this.title = "添加学生德育检查";
      this.$set(this.form, 'isReward', '0')
    },
    // 新增学生德育检查确认按钮
    submitFormAdd() {
      addEducation(this.form).then(response => {
        this.openForAdd = false;
        this.getList();
      })

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.$modal.loading('正在加载数据，请稍等...');
      getEducation(id).then(response => {
        this.$modal.closeLoading();
        this.form = response.data;
        this.openForAdd = true;
        this.title = "修改学生德育检查";
      }).catch(error => {
        this.$modal.closeLoading();
      })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEducation(this.form).then(response => {
              console.log('this.form', this.form);
              this.$modal.msgSuccess("修改成功");
              this.openForAdd = false;
              this.getList();
            });
          } else {
            addEducation(this.form).then(response => {
              console.log('this.form', this.form);
              this.$modal.msgSuccess("新增成功");
              this.openForAdd = false;
              this.getList();
            }).catch(() => {
              this.$modal.msgError("新增失败");
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      // this.$modal.confirm('是否确认删除学生德育检查编号为"' + ids + '"的数据项？').then(function () {
      this.$modal.confirm('是否确认删除选中的数据项？').then(function () {
        return delEducation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.exportOptions.open = true;
      this.download('/integral/export/' + this.queryParams.studentId, { schoolYear: this.queryParams.schoolYear }, `学生积分${Date.now()}.xlsx`)
    },
    /** 关闭 */
    // handleClose() {
    //   this.$tab.closeOpenPage({ path: '/studentmanage/manage' });
    // },
    /** 导出 */
    exportFile(callback) {
      const ids = this.ids;
      const options = [
        { type: ExportType.TOTAL, path: '/school/education/export', params: {} },
        { type: ExportType.SELECT, path: '/school/education/export/' + ids, params: {} },
        { type: ExportType.QUERY, path: '/school/education/export', params: this.queryParams },
      ]
      callback(options, `学生信息${new Date().getTime()}.xlsx`);
    },
  }
};
</script>
