<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="教师姓名" prop="teacherName">
        <el-input v-model="queryParams.teacherName" placeholder="请输入教师姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="获奖时间">
        <el-date-picker clearable
                        v-model="dateRange"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="获奖名称" prop="awardName">
        <el-input
          v-model="queryParams.awardName"
          placeholder="请输入获奖名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="荣誉级别" prop="honor">
        <el-select v-model="queryParams.honor" style="width: 100%" placeholder="请选择荣誉级别">
          <el-option v-for="dict in dict.type.honor" :key="dict.value" :label="dict.label" :value="dict.value"
                     @keyup.enter.native="handleQuery"></el-option>
        </el-select>
      </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 type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['teacher:teacherAward: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="['teacher:teacherAward: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="['teacher:teacherAward:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['teacher:teacherAward:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teacherAwardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="获奖图片" v-if="columns[0].visible" align="center" prop="picUrl">
        <template slot-scope="scope">
          <ListImage :image-url="scope.row.picUrl"></ListImage>
        </template>
      </el-table-column>
      <el-table-column label="教师名称" v-if="columns[1].visible" align="center" prop="teacherName"/>
      <el-table-column label="获奖时间" v-if="columns[2].visible" align="center" prop="awardTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.awardTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获奖名称" v-if="columns[3].visible" align="center" prop="awardName"/>
      <el-table-column label="荣誉级别" v-if="columns[4].visible" align="center" prop="honor">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.honor" :value="scope.row.honor"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" v-if="columns[5].visible" align="center" prop="remark"/>
      <el-table-column label="操作" v-if="columns[6].visible" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['teacher:teacherAward:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['teacher:teacherAward:remove']">删除
          </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"/>
    <TeacherSelect v-if="teacherSelectDialog" :openSelect.sync="teacherSelectDialog" :title="teacherSelect"
                   @getTeacherList="getTeacherList" @setTeacherInfo="setTeacherInfo"></TeacherSelect>

    <!-- 修改教师获奖情况对话框 -->
    <el-dialog :title="title" :visible.sync="dialogTeacherAward" width="800px">
      <el-form ref="form" :model="form" :rules="rules" style="width: 90%; margin: auto">
        <el-row type="flex" justify="center">
          <el-form-item prop="picUrl">
            <el-upload v-loading="uploadLoading" class="avatar-uploader" action="#" accept="image/*"
                       :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                       :http-request="uploadImage">
              <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div style="width: 150px; text-align: center; font-size: 20px">
              <span>获奖证书照片</span>
            </div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="教师名称" label-width="100px" prop="teacherName">
              <el-input v-model="form.teacherName" disabled placeholder="请输入教师名称"/>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="获奖时间" label-width="100px" prop="awardTime">
              <el-date-picker clearable v-model="form.awardTime" type="date" style="width: 100%"
                              value-format="yyyy-MM-dd" placeholder="请选择获奖时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="获奖名称" label-width="100px" prop="avardName">
              <el-input v-model="form.awardName" placeholder="请输入获奖名称"/>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="荣誉级别" label-width="100px" prop="honor">
              <el-select v-model="form.honor" style="width: 100%" placeholder="请选择荣誉级别">
                <el-option v-for="dict in dict.type.honor" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" label-width="100px" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAward">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导出对话框 -->
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>
  </div>
</template>

<script>
import {
  listTeacherAward,
  getTeacherAward,
  delTeacherAward,
  addTeacherAward,
  updateTeacherAward
} from '@/api/smartSchool/teacherManage/teacherAward'

import AvatarUploud from './avatarUploud'
// import {teacherInform} from "@/views/smartSchool/teacherManage/mixins/teacherInform.js";
import { listInform } from '@/api/smartSchool/teacherManage/teacherInformation'
import TeacherSelect from '@/views/components/moduleComponets/TeacherSelect/index.vue'
import { ExportType } from '@/enums/common'
import { uploadImage as commonUpload } from '@/api/common'

export default {
  name: 'TeacherAward',
  // mixins: [teacherInform],
  dicts: ['honor'],
  components: { TeacherSelect, AvatarUploud },
  data() {
    return {
      name: 'TeacherAward',
      teacherSelectDialog: false,
      teacherSelect: '教师信息',
      // 图片路径
      imageUrl: undefined,
      // 图片上传遮罩层
      uploadLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教师获奖情况表格数据
      teacherAwardList: [],
      // 弹出层标题
      titleInform: '教师信息',
      title: '',
      // 是否显示弹出层
      dialogTeacherInform: false,
      dialogTeacherAward: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teacherId: null,
        awardTime: null,
        honor: null,
        awardName: null,
        picUrl: null,
        teacherName: null
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: `图片路径`, visible: true },
        { key: 1, label: `教师名称`, visible: true },
        { key: 2, label: `获奖时间`, visible: true },
        { key: 3, label: `获奖名称`, visible: true },
        { key: 4, label: `荣誉级别`, visible: true },
        { key: 5, label: `备注`, visible: true },
        { key: 6, label: `操作`, visible: true }
      ],
      // 表单校验
      rules: {
        // teacherId: [
        //   {required: true, message: "教师id不能为空", trigger: "blur"}
        // ],
        // picUrl: [
        //   {required: true, message: "图片路径不能为空", trigger: "blur"}
        // ],
        awardTime: [{ required: true, message: '获奖时间不能为空', trigger: 'blur' }],
        awardName: [{ required: true, message: '获奖名称不能为空', trigger: 'blur' }],
        honor: [{ required: true, message: '荣誉级别不能为空', trigger: 'blur' }]

        // teacherName: [
        //   {required: true, message: "教师名称不能为空", trigger: "blur"}
        // ],
        // delFlag: [
        //   {required: true, message: "$comment不能为空", trigger: "blur"}
        // ]
      },
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      dateRange: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询教师获奖情况列表 */
    getList() {
      this.loading = true
      listTeacherAward(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.teacherAwardList = response.rows
        this.total = response.total
        this.loading = false
      })

      // this.loading = true;
      // listTeacherAward(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
      //   this.teacherAwardList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },
    // 取消按钮
    cancel() {
      this.dialogTeacherAward = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teacherId: null,
        awardTime: null,
        honor: null,
        awardName: null,
        remark: null,
        picUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        teacherName: null,
        delFlag: null
      }
      this.imageUrl = ''
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.teacherSelectDialog = true;
      this.title = '新增教师获奖情况';
    },
    // 新增操作
    setTeacherInfo(data) {
      this.teacherSelectDialog = false;
      this.reset();
      this.form.teacherName = data.teacherName;
      this.form.teacherId = data.id;
      this.dialogTeacherAward = true;
      this.title = '教师获奖情况';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      console.log('id', id)
      getTeacherAward(id).then(response => {
        this.form = response.data
        console.log('this.form=' + this.form)
        this.imageUrl = this.form.picUrl
        this.dialogTeacherAward = true
        this.title = '教师获奖情况!'
      })
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.url
      console.log(file)
      this.commonUpload(file)
    },
    // 上传前格式和图片大小限制
    beforeAvatarUpload(file) {
      const type = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!type) {
        this.$message.error('图片格式不正确!(只能包含jpg，png，webp，JPEG)')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return type && isLt2M
    },

    // 上传图片
    uploadImage(file) {
      const fileData = file.file
      const formData = new FormData()
      formData.append('file', fileData)
      this.uploadLoading = true
      commonUpload(formData)
        .then(response => {
          this.uploadLoading = false
          this.$modal.msgSuccess('上传成功')
          this.imageUrl = process.env.VUE_APP_BASE_API + response.url
          this.form.picUrl = process.env.VUE_APP_BASE_API + response.url
        })
        .catch(error => {
          this.uploadLoading = false
        })
    },

    // /** 提交按钮 */
    submitFormAward() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.form.id) {
            addTeacherAward(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.dialogTeacherAward = false
              this.getList()
            })
          } else {
            updateTeacherAward(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.dialogTeacherAward = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm(`是否确认删除选中的${ Object.hasOwnProperty.call(ids, 'length') ? ids.length : 1 }条数据？`)
        .then(() => {
          this.loading = true
          return delTeacherAward(ids)
        })
        .then(() => {
          this.getList()
          this.loading = false
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出选中，导出全部，根据查询条件导出
      this.exportOptions.open = true
      // this.$confirm(`是否确认导出${ !!this.ids.length ? this.ids.length + '条' : '所有' }数据？`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   if (this.ids.length) {
      //     console.log("this.ids", this.ids)
      //     this.download('/school/teacherAward/export/' + this.ids, {
      //       ...this.queryParams
      //       // }, `user_${new Date().getTime()}.xlsx`)
      //     }, `教师获奖信息.xlsx`)
      //   } else {
      //     this.download('/school/teacherAward/export', {
      //       ...this.queryParams
      //       // }, `user_${new Date().getTime()}.xlsx`)
      //     }, `教师获奖信息.xlsx`)
      //   }
      //   this.$message({
      //     type: 'success',
      //     message: '导出成功!'
      //   });
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   });
      // });
    },

    /** 导出 */
    exportFile(callback) {
      const ids = this.ids
      const options = [
        { type: ExportType.TOTAL, path: '/school/teacherAward/export', params: {} },
        { type: ExportType.SELECT, path: '/school/teacherAward/export/' + ids, params: {} },
        { type: ExportType.QUERY, path: '/school/teacherAward/export', params: this.queryParams }
      ]
      callback(options, `老师获奖信息${ new Date().getTime() }.xlsx`)
    },

    /** 获取教师信息列表 */
    getTeacherList(queryForm, callback) {
      listInform(queryForm)
        .then(response => {
          callback(response.rows, response.total)
        })
        .catch(error => {
          callback([], 0)
        })
    }
  }
}
</script>
