<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="比赛类型" prop="competitionType">
        <el-select v-model="queryParams.competitionType" placeholder="请选择" clearable>
          <el-option v-for="(item, index) in dict.type.competition_type" :key="index" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="比赛项目名称" prop="competitionName">
        <el-input v-model="queryParams.competitionName" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</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="handleOption(0)">新增</el-button>
      </el-col>

    </el-row>
    <el-table border v-loading="loading" :data="competitionData" stripe>
      <el-table-column fixed="left" label="序号" type="index" width="55" align="center" />
      <el-table-column label="学年" align="center" prop="schoolYear" />
      <el-table-column label="参赛教师" align="center" prop="teacherName" />
      <el-table-column label="参赛课题" align="center" prop="entrySubject" />
      <el-table-column label="比赛项目名称" align="center" prop="competitionName" />
      <el-table-column align="center" prop="competitionType" label="比赛类型">
        <template slot-scope="{ row }">
          <div>{{ selectDictLabel(dict.type.competition_type, row.competitionType) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="比赛级别" align="center" prop="competitionLevel">
        <template slot-scope="{ row }">
          <div>{{ selectDictLabel(dict.type.competition_level, row.competitionLevel) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="证书照片" align="center">
        <template slot-scope="scope">
          <div>
            <el-image v-for="(accessory, index) in scope.row.schoolAccessoryList" :key="index"
              style="width: 100px; height: 100px" :src="accessory.accessoryUrl"
              :preview-src-list="[accessory.accessoryUrl]"></el-image>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="备注1" align="center" prop="remark1" />
      <el-table-column label="备注2" align="center" prop="remark2" />
      <el-table-column label="备注3" align="center" prop="remark3" />
      <el-table-column fixed="right" label="操作" align="center" prop="orgname" width="150">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click="handleOption(1, row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleOption(2, row)">查看</el-button>
          <el-button type="text" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination ref="pageBlock" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增、编辑、查看弹窗 -->
    <el-dialog title="详细信息" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" ref="form" size="small" label-width="108px" :disabled="isEdit" :rules="rules">
        <el-row>
          <el-col :span="10">
            <el-form-item label="学年" prop="schoolYear">
              <el-input v-model="form.schoolYear" placeholder="请输入" clearable
                :disabled="nowType == 2 ? true : false"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="参赛老师" prop="teacherId">
              <el-select v-model="form.teacherId" placeholder="请选择" clearable style="width: 100%;"
                :disabled="nowType == 2 ? true : false">
                <el-option v-for="(item, index) in teacherList" :key="index" :label="item.userName"
                  :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="参赛课题" prop="entrySubject">
              <el-input v-model="form.entrySubject" placeholder="请输入" clearable
                :disabled="nowType == 2 ? true : false"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="比赛项目名称" prop="competitionName">
              <el-input v-model="form.competitionName" placeholder="请输入" clearable
                :disabled="nowType == 2 ? true : false"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="比赛类型" prop="competitionType">
              <el-select v-model="form.competitionType" placeholder="请选择" clearable style="width: 100%;"
                :disabled="nowType == 2 ? true : false">
                <el-option v-for="dict in dict.type.competition_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="比赛级别" prop="competitionLevel">
              <el-select v-model="form.competitionLevel" placeholder="请选择" clearable style="width: 100%;"
                :disabled="nowType == 2 ? true : false">
                <el-option v-for="dict in dict.type.competition_level" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item prop="schoolAccessoryList" label="证书照片">
              <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-for="item in form.schoolAccessoryList" :key="item.accessoryUrl" :src="item.accessoryUrl"
                  class="avatar" />
                <i v-if="form.schoolAccessoryList.length === 0" class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

          </el-col>
          <el-col :span="10">
            <el-form-item label="备注1">
              <el-input v-model="form.remark1" placeholder="请输入" clearable
                :disabled="nowType == 2 ? true : false"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="备注2">
              <el-input v-model="form.remark2" placeholder="请输入" clearable
                :disabled="nowType == 2 ? true : false"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="备注3">
              <el-input v-model="form.remark3" placeholder="请输入" clearable
                :disabled="nowType == 2 ? true : false"></el-input>
            </el-form-item>
          </el-col>
        </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 ref="previewDialog" title="预览图片" :visible.sync="previewDialogVisible">
      <el-image style="width: 100%; max-height: 80vh; object-fit: contain" :src="previewImageUrl"
        fit="contain"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCompetition,
  updateCompetition,
  getCompetition,
  getCompetitionxq,
  deleteCompetition,
  getTeacher
} from '@/api/smartSchool/laboratoryManagement/laboratoryCompetition'
import ListImage from "@/components/ListImage";
import { uploadImage as commonUpload } from '@/api/common'
import picAvatar from '@/views/smartSchool/schoolManage/introduce/schoolInfo/profile/picAvatar'
export default {
  dicts: ['competition_type', 'competition_type',
    'competition_level'],
  components: { picAvatar },
  data() {
    return {
      //缩略图
      srcList: [],
      // 图片路径
      imageUrl: undefined,
      pev: process.env.VUE_APP_BASE_API,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      previewImageUrl: '',
      //获取子组件传来的信息
      pic: [],
      isEdit: false,
      nowType: 0, // 0新增、1修改、2查看
      uploadLoading: false,
      loading: false,
      total: 0,
      competitionData: [],
      isMultiple: false, // table是否有选择
      dialogTitle: '', //弹窗标题
      dialogVisible: false,
      nowOption: null,
      uploadedFiles: [],
      form: {
        schoolYear: '',
        teacherId: '',
        teacherName: '',
        entrySubject: '',
        competitionName: '',
        competitionType: '',
        competitionLevel: '',
        remark1: '',
        remark2: '',
        remark3: '',
        schoolAccessoryList: [],

      },
      rules: {
        schoolYear: [
          { required: true, message: "学年不能为空", trigger: "change" }
        ],
        teacherName: [
          { required: true, message: "教师名称不能为空", trigger: "change" }
        ],
        entrySubject: [
          { required: true, message: "参赛课题不能为空", trigger: "change" }
        ],
        competitionType: [
          { required: true, message: "比赛类型不能为空", trigger: "change" }
        ],
        competitionLevel: [
          { required: true, message: "比赛级别不能为空", trigger: "change" }
        ],
        // schoolAccessoryList: [
        //   { required: true, message: "证书照片不能为空", trigger: "change" }
        // ],
        competitionName: [
          { required: true, message: "比赛项目名称不能为空", trigger: "change" }
        ],
      },
      previewDialogVisible: false,
      teacherList: [],
      nowType: 0, // 0新增、1编辑、2查看
    }
  },
  watch: {
    pic: {
      handler(newValue, oldValue) {
        console.log('watch----oldValue', oldValue)
        console.log('watch----newValue', newValue)
        this.isUploadPic = newValue[3]
      }
    }
  },
  mounted() {
    this.getList();
    this.getTeacher();
  },
  methods: {
    handlePreview(url) {
      this.previewImageUrl = url;
      this.$refs.previewDialog.open();
    },
    //获取列表数据
    getList() {
      getCompetition(this.queryForm).then(response => {
        this.competitionData = response.rows;
        console.log('response', response);
        this.total = response.total;
        this.loading = false;
        this.competitionData.forEach(item => {
          if (item.schoolAccessoryList) {
            item.previewUrls = [item.schoolAccessoryList.map(accessory => accessory.accessoryUrl)];
            item.pictureUrl = item.schoolAccessoryList.map(accessory => accessory.accessoryUrl);
          } else {
            item.previewUrls = [];
            item.pictureUrl = [];
          }
        });


      });
    },

    //获取图片信息
    getSchoolInfoPic(val) {
      this.pic = val
    },
    // 移除图片
    handleRemove() {
      this.imageUrl = undefined
    },
    // 上传成功回调
    handleAvatarSuccess(response, file) {
      // 处理上传成功的逻辑
      console.log(response, 'response');
      console.log(file, 'file');
      const accessoryUrl = response.data.url; // 假设响应中包含了图片的访问URL
      const accessoryName = file.name; // 获取上传文件的名称

      this.form.schoolAccessoryList.push({
        accessoryUrl: accessoryUrl,
        accessoryName: accessoryName
      });
    },

    // 上传前格式和图片大小限制
    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
          // 添加以下代码将文件信息添加到 uploadedFiles 数组中
          this.uploadedFiles.push({
            accessoryUrl: process.env.VUE_APP_BASE_API + response.url,
            accessoryName: fileData.name
          })
        })
        .catch(error => {
          this.uploadLoading = false
        })
    },

    //重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        competitionType: "",
        competitionName: "",
      },
        this.getList();

    },


    //删除
    handleDelete(row) {
      this.$modal.confirm('是否确认删除选中数据？').then(() => {
        this.$modal.loading('正在处理数据，请稍等...');
        return deleteCompetition(row);

      }).then(response => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess("删除班级成功");
        this.getList();
      }).catch(error => {
        this.$modal.closeLoading();
      })
    },



    //编辑 0新增 1编辑 2查看
    handleOption(type, row) {
      this.imageUrl = '';
      this.form = {
        id: '',
        schoolYear: '',
        teacherId: '',
        teacherName: '',
        entrySubject: '',
        competitionName: '',
        competitionType: '',
        competitionLevel: '',
        remark1: '',
        remark2: '',
        remark3: '',
        schoolAccessoryList: [],
      }
      this.nowType = type;
      if (type != 0) {
        const id = row.id
        getCompetitionxq(id).then(response => {
          if (response.code == 200) {
            Object.keys(this.form).forEach(key => {
              if (response.data[key]) {
                this.$set(this.form, key, response.data[key]);
              }
              if (response.data.schoolAccessoryList && response.data.schoolAccessoryList.length > 0) {
                this.imageUrls = response.data.schoolAccessoryList.map(item => item.accessoryUrl); // 将所有证书照片的地址赋值给 imageUrls
              }
            })
          }
        })
      }
      this.dialogVisible = true;
    },

    //查询老师
    getTeacher() {
      getTeacher().then(response => {
        this.loading = false;
        this.teacherList = response.data;

      });
    },
    /** 提交按钮 */
    submitForm: function () {
      const teacherId = this.form.teacherId
      this.form.teacherName = teacherId == '' ? '' : this.teacherList.find(item => item.userId == teacherId).userName
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != "") {
            // 清空原有图片
            this.form.schoolAccessoryList.splice(0);
            for (let i = 0; i < this.uploadedFiles.length; i++) {
              const file = this.uploadedFiles[i];
              this.form.schoolAccessoryList.push({
                accessoryUrl: file.accessoryUrl,
                accessoryName: file.accessoryName
              });
            }

            updateCompetition(this.form).then(({ code }) => {
              if (code == 200) {
                this.$modal.msgSuccess('修改成功')
                this.dialogVisible = false
                this.getList()
              }
            }).catch(() => {
              this.$modal.msgError("修改失败");
            });
          } else {
            // 清空原有图片
            this.form.schoolAccessoryList = [];

            for (let i = 0; i < this.uploadedFiles.length; i++) {
              const file = this.uploadedFiles[i];
              this.form.schoolAccessoryList.push({
                accessoryUrl: file.accessoryUrl,
                accessoryName: file.accessoryName
              });
            }

            addCompetition(this.form).then(response => {
              console.log(this.form, 'this.form');
              this.$modal.msgSuccess('新增成功')
              this.dialogVisible = false
              this.getList()
            }).catch(() => {
              this.$modal.msgError("新增失败");
            });
          }
        }
      });
    },



    cancel() {
      this.dialogVisible = false;
    },


  },
}
</script>

<style lang="scss" scoped></style>
