<template>
  <div style="width: 100%">
    <el-main>
      <div class="tou">家校社</div>
      <div class="pb_content_body">
        <div class="student_head">
          <div class="student_search">
            <div>条件筛选</div>
            <el-select
              v-model="subject"
              placeholder="请选择分类"
              style="margin-left: 5px; width: 110px"
              @change="find"
            >
              <el-option label="全部分类" value=""></el-option>
              <el-option label="家" value="0"></el-option>
              <el-option label="校" value="1"></el-option>
              <el-option label="社" value="2"></el-option>
            </el-select>
            <el-select
              v-model="school"
              placeholder="请选择学校"
              style="margin-left: 5px; width: 150px"
              @change="find"
            >
              <el-option label="全部学校" value=""></el-option>
              <el-option
                v-for="item in schoolArray"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-input
              v-model="sortTitle"
              placeholder="请输入标题"
              style="margin: 0 5px; width: 150px"
            />
            <el-button @click="find">查询</el-button>
          </div>
          <!-- <div class="add_task" @click="addTask">添加任务</div> -->
        </div>
        <div class="student_table">
          <el-table
            v-loading="isLoading"
            ref="table"
            :data="tableData"
            border
            stripe
            :height="tableHeight"
            :fit="true"
            style="width: 100%"
            :row-class-name="tableRowClassName"
            :header-cell-style="{ background: 'rgb(238,238,238)' }"
          >
            <el-table-column
              prop="course"
              label="关联课程"
              min-width="30"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="title"
              label="作业标题"
              min-width="20"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="sort"
              label="分类"
              min-width="20"
              align="center"
            >
              <template slot-scope="scope">
                {{
                  scope.row.sort == 0 ? "家" : scope.row.sort == 1 ? "校" : "社"
                }}
              </template></el-table-column
            >
            <el-table-column
              prop="schoolName"
              label="学校"
              min-width="20"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="老师"
              min-width="20"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="time"
              label="创建时间"
              min-width="20"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" min-width="30">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="
                    goTo(
                      '/home/homeDetail?id=' +
                        scope.row.id +
                        '&name=' +
                        scope.row.title +
                        '&type=' +
                        scope.row.sort
                    )
                  "
                  >查看作业</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  @click="updateTask(scope.row)"
                  >查看</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  style="background: #f74a4a; border: none"
                  @click="deleteTeacherWork(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-dialog
            title="添加任务"
            :visible.sync="dialogVisible"
            :append-to-body="true"
            width="750px"
            :before-close="handleClose"
            class="dialog_diy"
          >
            <el-form>
              <el-form-item label="标题" :label-width="formLabelWidth">
                <span>
                  {{ atitle }}
                  <!-- <el-input
                    placeholder="请输入标题"
                    clearable
                    v-model="atitle"
                    style="width: 85%"
                  ></el-input> -->
                </span>
              </el-form-item>
              <el-form-item label="分类" :label-width="formLabelWidth"
                ><span>
                  {{ asort == 0 ? "家" : asort == 1 ? "校" : "社" }}
                  <!-- <el-select v-model="asort" placeholder="选择分类">
                    <el-option label="家" value="0"></el-option>
                    <el-option label="校" value="1"></el-option>
                    <el-option
                      label="社"
                      value="2"
                    ></el-option> </el-select> -->
                </span></el-form-item
              >
              <el-form-item
                label="社团名称"
                :label-width="formLabelWidth"
                v-if="asort == 2"
              >
                <span>
                  {{ astitle }}
                </span>
              </el-form-item>
              <el-form-item
                label="联系人电话"
                :label-width="formLabelWidth"
                v-if="asort == 2"
              >
                <span>
                  {{ aphone }}
                </span>
              </el-form-item>
              <el-form-item label="关联课程" :label-width="formLabelWidth"
                ><span>
                  {{ checkList.title }}
                </span></el-form-item
              >
              <el-form-item label="标签" :label-width="formLabelWidth"
                ><span class="down_div">
                  <span>劳动能力</span>
                </span></el-form-item
              >
              <el-form-item label="内容详情" :label-width="formLabelWidth"
                ><span
                  ><el-input
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="atext"
                    readonly
                    rows="8"
                    resize="none"
                  ></el-input></span
              ></el-form-item>
              <el-form-item label="图片" :label-width="formLabelWidth"
                ><div
                  style="
                    width: 100%;
                    display: flex;
                    overflow: auto;
                    flex-wrap: nowrap;
                    flex-direction: row;
                  "
                >
                  <el-image
                    style="
                      min-width: 100px;
                      width: 100px;
                      height: 100px;
                      margin-left: 10px;
                      cursor: pointer;
                    "
                    @click="handlePictureCardPreview(item)"
                    v-for="item in imgList.fileList"
                    :key="item.url"
                    :src="item.url"
                    fit="cover"
                  ></el-image>
                  <!-- <el-upload
                    action="#"
                    list-type="picture"
                    v-loading="uploadLoading1"
                    :http-request="beforeUpload"
                    ref="upload1"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handle_remove1"
                    :show-file-list="true"
                    :file-list="imgList.fileList1"
                    accept="image/*"
                    :limit="10"
                    :on-exceed="onExceed"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-upload> -->
                </div></el-form-item
              >
              <!-- <el-form-item label="附件" :label-width="formLabelWidth"
                ><span
                  ><el-upload
                    action="#"
                    list-type="picture"
                    v-loading="uploadLoading1"
                    :http-request="beforeUpload1"
                    ref="upload"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handle_remove1"
                    :show-file-list="true"
                    :file-list="fileList1"
                    accept="image/*"
                    :limit="1"
                    :on-exceed="onExceed"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-upload></span
                ></el-form-item
              >-->
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" v-show="false">确认添加</el-button>
              <el-button type="primary" @click="dialogVisible = false"
                >关闭</el-button
              >
            </span>
          </el-dialog>
          <el-dialog :visible.sync="dialogVisible1" size="tiny">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </div>
        <div class="student_page" style="margin-top: 20px">
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="10"
            :total="total"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
    </el-main>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible1: false,
      dialogImageUrl: "",
      tableHeight: "500px",
      isLoading: false,
      formLabelWidth: "100px",
      subject: "",
      school: "",
      page: 1,
      total: 0,
      sort: [],
      sortTitle: "",
      tableData: [],
      dialogVisible: false,
      atitle: "",
      acoursesort: "",
      asort: "",
      atext: "",
      astitle: "",
      aphone: "",
      uploadLoading1: false,
      fileList1: [],
      checkList: [],
      schoolArray: [],
      imgList: { fileList: [], fileList1: [] },
    };
  },
  mounted() {
    this.$nextTick(function () {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
      // 监听窗口大小变化
      let self = this;
      window.onresize = function () {
        self.tableHeight =
          window.innerHeight - self.$refs.table.$el.offsetTop - 200;
        if (self.tableHeight <= 530) {
          self.tableHeight = 530;
        }
      };
    });
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible1 = true;
    },
    goTo(path) {
      this.$router.push(path);
    },
    //查询学校
    getOrg() {
      this.ajax
        .get(this.$store.state.api + "getAllOrg", "")
        .then((res) => {
          this.schoolArray = res.data[0];
          console.log(res.data[0]);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleClose(done) {
      done();
    },
    tableRowClassName({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return "even_row";
      } else {
        return "";
      }
    },
    addTask() {
      this.dialogVisible = true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible1 = true;
    },
    handle_remove1(file, fileList) {
      var _tmp = this.fileList1;
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if (_tmp[i].uid == file.uid) {
          _tmp.splice(i, 1);
          break;
        }
        this.fileList1 = _tmp;
      }
    },
    onExceed() {
      this.$message.error("图片仅支持上传十张，请删除后再进行上传");
    },
    beforeUpload(data) {
      var file = data.file;
      this.uploadLoading = true;
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域
      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function (err, data) {
            _this.uploadLoading = false;
            if (err) {
              var a = _this.$refs.upload.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              //上传成功处理
              _this.fileList.push({
                name: file.name,
                url: data.Location,
                uid: file.uid,
              });
              console.log(data.Location);
            }
          });
      }
    },
    beforeUpload1(data) {
      this.$refs.upload1.uploadFiles;
      this.uploadLoading1 = true;
      var file = data.file;
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function (err, data) {
            _this.uploadLoading1 = false;
            if (err) {
              var a = _this.$refs.upload1.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              //上传成功处理
              _this.fileList1.push({
                name: file.name,
                url: data.Location,
                uid: file.uid,
              });
              console.log(data.Location);
            }
          });
      }
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getDetail();
      console.log(`当前页: ${val}`);
    },
    find() {
      this.page = 1;
      this.getDetail();
    },
    getDetail() {
      this.isLoading = true;
      let params = {
        cp: this.subject,
        cn: this.sortTitle,
        oid: this.school,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "getAllHomeWork", params)
        .then((res) => {
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.tableData = res.data[0];
        })
        .catch((err) => {
          console.error(err);
        });
    },
    deleteTeacherWork(id) {
      let params = {
        id: id,
      };
      this.$confirm("确定删除此任务吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .get(this.$store.state.api + "deleteTeacherWork", params)
            .then((res) => {
              this.$message.success("删除成功");
              this.getDetail();
            })
            .catch((err) => {
              console.error(err);
            });
        })
        .catch(() => {});
    },
    updateTask(res) {
      this.updateId = res.id;
      this.atitle = res.title;
      this.asort = res.sort;
      this.astitle = res.typeName;
      this.aphone = res.phoneNumber;
      this.checkList = { title: res.course, courseId: res.courseId };
      this.groupid = res.classid;
      this.atext = res.content;
      var file = JSON.parse(res.file);
      var ps = file.photo.split(",");
      this.imgList.fileList = [];
      for (var i = 0; i < ps.length; i++) {
        this.imgList.fileList.push({
          name: ps[i].split("//")[1].split("/")[1].split(".")[0],
          url: ps[i],
        });
      }
      this.imgList.fileList1 = [];
      this.updateB = true;
      this.dialogVisible = true;
    },
  },
  created() {
    this.page = 1;
    this.getDetail();
    this.getOrg();
  },
};
</script>

<style scoped>
.student_head {
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.student_search {
  display: flex;
  align-items: center;
}
.student_search > div:nth-child(1) {
  line-height: 35px;
  font-size: 14px;
}
/* .student_search >>> .el-input {
  width: 200px;
  margin-right: 5px;
}
.student_search >>> .el-input__inner {
  width: 190px;
  height: 35px;
  margin-left: 10px;
} */
.student_search >>> .el-button {
  background: #2268bd;
  color: #fff;
  height: 35px;
  line-height: 35px;
  text-align: center;
  width: 60px;
  padding: 0 !important;
  font-size: 12px;
}
.add_task {
  background: #007cff;
  color: #fff;
  font-size: 12px;
  width: 85px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  cursor: pointer;
}
.dialog_diy >>> .el-dialog {
  background: #fafafa;
}
.dialog_diy >>> .el-dialog__header {
  background: #eee !important;
  padding: 15px 20px;
}
.dialog_diy >>> .el-dialog__title {
  font-size: 15px;
}
.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
  display: none;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}
.student_head >>> .el-button--primary {
  background-color: #2268bc;
}
.dialog_diy >>> .el-rate__icon {
  font-size: 26px;
}
.dialog_diy >>> .el-rate {
  height: auto;
}
.dialog_diy >>> .el-dialog__body {
  background: #fff !important;
}
.dialog_diy >>> .el-textarea__inner {
  width: 85% !important;
}
.dialog_diy >>> .el-dialog__footer {
  padding: 10px 50px 20px !important;
}
.dialog-footer >>> .el-button--primary:nth-child(1) {
  width: 85px;
  height: 25px;
  background: #007aff;
  padding: 0;
  border-radius: 0;
  font-size: 12px;
  border: none;
}
.dialog-footer >>> .el-button--primary:nth-child(2) {
  width: 85px;
  height: 25px;
  background: #7e7e7e;
  padding: 0;
  border-radius: 0;
  font-size: 12px;
  border: none;
}
.down_div {
  display: flex;
  align-items: center;
  width: 550px;
  overflow: auto;
  white-space: nowrap;
}
.down_div > div {
  color: #b9b9b9;
  border: 1px solid #b9b9b9;
  padding: 0 10px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 20px;
  font-size: 14px;
  margin-right: 10px;
  cursor: pointer;
}
.Tactive {
  background: rgb(102, 177, 255) !important;
  color: #fff !important;
}
</style>
