<template>
  <div style="width: 100%">
    <el-main>
      <div class="tou">首页管理</div>
      <div>
        <div>
          <div class="home_titleHead">
            <div class="ban">Banner管理</div>
            <el-button size="small" type="primary" @click="dialogVisible = true"
              >添加图片</el-button
            >
            <!-- -->
          </div>
          <el-table
            :data="tableData"
            stripe
            border
            :header-cell-style="{
              background: '#f1f1f1',
              'text-align': 'center',
            }"
            :cell-style="{ 'text-align': 'center' }"
            style="width: 100%"
          >
            <el-table-column label="图片" min-width="33">
              <template slot-scope="scope">
                <el-image
                  style="width: 200px; height: 100px; cursor: pointer"
                  :src="scope.row.poster"
                  fit="cover"
                  @click="handlePictureCardPreviewA(scope.row.poster)"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="链接课程" min-width="33">
            </el-table-column>
            <el-table-column label="操作" min-width="33">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  style="删除"
                  type="primary"
                  @click="deleteBanner(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div>
          <el-button
            size="small"
            type="primary"
            style="margin: 20px 0 0"
            @click="dialogVisible4 = true"
            >添加首页课程专区</el-button
          >
        </div>
        <div v-for="(item, index) in zoneList" :key="item.id">
          <div class="home_titleHead">
            <div class="ban">
              <el-popover placement="right" trigger="hover">
                <p>位置移动</p>
                <div slot="reference">
                  <span class="up" @click="up(index)"></span>
                  <span class="down" @click="down(index)"></span>
                </div>
              </el-popover>
              <span>{{ item.name }}</span>
            </div>
            <div>
              <el-button size="small" type="primary" @click="addPop(item.id)"
                >添加课程</el-button
              >
              <el-button
                size="small"
                type="primary"
                @click="getZoneNum(item.id)"
                >删除课程专区</el-button
              >
            </div>
          </div>
          <el-table
            :data="zoneClass[item.id]"
            stripe
            border
            :header-cell-style="{
              background: '#f1f1f1',
              'text-align': 'center',
            }"
            height="500"
            :cell-style="{ 'text-align': 'center' }"
            style="width: 100%"
            v-loading="loading[item.id]"
          >
            <el-table-column prop="title" label="课程名称" min-width="25">
            </el-table-column>
            <el-table-column prop="brief" label="课程简介" min-width="25">
              <template slot-scope="scope">
                <div
                  v-html="snippet(scope.row.brief)"
                  class="DivOverflow"
                ></div>
                <div></div>
              </template>
            </el-table-column>
            <el-table-column prop="vcount" label="浏览量" min-width="25">
            </el-table-column>
            <el-table-column label="操作" min-width="25">
              <template slot-scope="scope">
                <!-- <el-button
                  size="mini"
                  type="primary"
                  @click="goTo('/course?index=2&id=' + scope.row.courseId)"
                  >查看</el-button
                > -->
                <el-button
                  size="mini"
                  style="删除"
                  type="primary"
                  @click="deleteZoneCourse(scope.row.id, item.id)"
                  >删除</el-button
                >
              </template>

              >
            </el-table-column>
          </el-table>
          <div class="student_page" style="margin: 15px 0 0">
            <el-pagination
              background
              layout="prev, pager, next"
              :page-size="10"
              :total="total[item.id]"
              v-if="!isListAjax && page[item.id]"
              @current-change="(val) => handleCurrentChange(val, item.id)"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </el-main>
    <el-dialog
      title="添加图片"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
      class="dialog_diy"
      center
    >
      <div>
        <div class="dialogBox">
          <span>添加图片</span>

          <el-upload
            :class="{ disUoloadSty: noneBtnImg }"
            action="#"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            v-loading="uploadLoading"
            :http-request="beforeUpload"
            ref="upload"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
        <div class="dialogBox" style="color: #bebebe; margin: 10px 0 0 0">
          注:适宜上传banner尺寸为1218×300
        </div>
        <div class="dialogBox" style="margin: 10px 0 0 0">
          <span>Banner课程链接</span>
          <span style="max-width: 160px">{{ bannerCourse.title }}</span>
          <el-button type="primary" size="medium" @click="addBannerUrlPop"
            >选择课程</el-button
          >
          <!-- <el-input
            v-model="linkInput"
            style="width: 200px; margin: 15px 0px"
            placeholder=""
          ></el-input> -->
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBanner">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="imgVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-dialog
      title="添加课程"
      :visible.sync="dialogVisible1"
      width="500px"
      :before-close="handleClose"
      class="dialog_diy"
      style="text-align: center"
      center
    >
      <div>
        <el-card class="box-card">
          <div slot="header" class="cardHead">
            <el-input
              v-model="searchClassName"
              placeholder="请输入需要添加的课程"
              @keypress.native.enter="Search"
            ></el-input>
            <el-button type="text" style="margin: 0 0 0 20px" @click="Search"
              >搜索</el-button
            >
          </div>
          <div class="cardList">
            <el-checkbox-group v-model="checkList" v-if="courseList.length > 0">
              <div v-for="item in courseList" :key="item.courseId">
                <el-popover placement="top-start" trigger="hover">
                  <p style="max-width: 380px">课程名称: {{ item.title }}</p>
                  <p style="max-width: 380px">
                    简介: {{ snippet(item.brief) }}
                  </p>
                  <el-checkbox :label="item.courseId" slot="reference"
                    ><span>课程名称：</span
                    ><span>{{ item.title }}</span></el-checkbox
                  >
                </el-popover>
              </div>
            </el-checkbox-group>
            <div v-else>暂无数据</div>
          </div>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="getZoneClassRepeat">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加课程专区"
      :visible.sync="dialogVisible4"
      width="500px"
      :before-close="handleClose"
      class="dialog_diy"
      style="text-align: center"
      center
    >
      <div class="dialogBox">
        <span>课程专区</span>
        <el-input
          v-model="zoneName"
          style="width: 250px; margin: 15px 0px"
          placeholder="请输入课程专区名称"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible4 = false">取 消</el-button>
        <el-button type="primary" @click="addZone">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加链接"
      :visible.sync="dialogVisible5"
      width="500px"
      :before-close="handleClose"
      class="dialog_diy"
      style="text-align: center"
      center
    >
      <div>
        <el-card class="box-card">
          <div slot="header" class="cardHead">
            <el-input
              v-model="searchClassName"
              placeholder="请输入需要添加的课程"
              @keypress.native.enter="Search"
            ></el-input>
            <el-button type="text" style="margin: 0 0 0 20px" @click="Search"
              >搜索</el-button
            >
          </div>
          <div class="cardList">
            <!-- <el-checkbox-group v-model="checkList" v-if="courseList.length > 0"> -->
            <div v-for="item in courseList" :key="item.courseId">
              <el-popover placement="top-start" trigger="hover">
                <p style="max-width: 380px">课程名称: {{ item.title }}</p>
                <p style="max-width: 380px">简介: {{ item.brief }}</p>
                <el-radio
                  :label="item"
                  slot="reference"
                  v-model="checkBannerCourse"
                  ><span>课程名称：</span
                  ><span>{{ item.title }}</span></el-radio
                >
              </el-popover>
            </div>
            <!-- </el-checkbox-group> -->
            <div v-if="courseList.length == 0">暂无数据</div>
          </div>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible5 = false">取 消</el-button>
        <el-button type="primary" @click="setBannerUrl">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import "../../common/aws-sdk-2.235.1.min";
import $ from "jquery";

export default {
  data() {
    return {
      uploadLoading: false,
      fileList: [],
      now: "",
      noneBtnImg: false,
      zoneName: "",
      searchClassName: "",
      dialogVisible1: false,
      dialogVisible4: false,
      dialogVisible5: false,
      dialogImageUrl: "",
      imgVisible: false,
      dialogVisible: false,
      disabled: false,
      linkInput: "",
      checkList: [],
      courseList: [],
      tableData: [],
      zoneList: [],
      zoneClass: {},
      loading: {},
      page: {},
      total: {},
      pid: "",
      checkBannerCourse: "",
      bannerCourse: "",
      isListAjax: false,
    };
  },
  methods: {
    //在method里面写方法
    snippet(value) {
      return value.replace(/<[^>]*>/g, "");
    },
    time() {
      if (!this.now) {
        this.now = new Date().getTime();
        return true;
      } else {
        let time = new Date().getTime();
        if (time - this.now > 3000) {
          this.now = time;
          return true;
        } else {
          return false;
        }
      }
    },
    init() {
      this.zoneName = "";
      this.searchClassName = "";
      this.checkList = [];
      this.courseList = [];
      this.pid = "";
      this.fileList = [];
      this.linkInput = "";
      this.$refs.upload ? (this.$refs.upload.uploadFiles.length = 0) : "";
      this.noneBtnImg = false;
      this.dialogImageUrl = "";
      this.bannerCourse = "";
      this.checkBannerCourse = "";
    },
    handleClose(done) {
      done();
    },
    imgChange(file, fileList) {
      var _tmp = this.fileList;
      this.noneBtnImg = _tmp.length >= 1;
    },
    handleRemove(file) {
      var _tmp = this.fileList;
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if (_tmp[i].uid == file.uid) {
          _tmp.splice(i, 1);
          break;
        }
        this.fileList = _tmp;
      }
      this.noneBtnImg = _tmp.length >= 1;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.fileList[0].url;
      this.imgVisible = true;
    },
    handlePictureCardPreviewA(url) {
      this.dialogImageUrl = url;
      this.imgVisible = true;
    },
    // handleDownload(file) {
    //   console.log(file);
    // },
    handleCurrentChange(val, zid) {
      this.page[zid] = val;
      this.getZoneClass(zid);
    },
    beforeUpload(data) {
      this.$refs.upload.uploadFiles;
      this.uploadLoading = 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.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);
              _this.imgChange();
            }
          });
      }
    },
    //获取专区
    getZone() {
      this.ajax
        .get(this.$store.state.api + "getZone", "")
        .then((res) => {
          console.log(res.data[0]);
          this.zoneList = res.data[0];
          this.zoneList.filter((element) => {
            this.page[element.id] = 1;
            this.loading[element.id] = true;
            this.getZoneClass(element.id);
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //获取专区下的课程
    getZoneClass(zid) {
      this.loading[zid] = true;
      let params = { bid: zid,oid:this.$store.state.userInfo.organizeid, page: this.page[zid] };
      this.ajax
        .get(this.$store.state.api + "getZoneClass", params)
        .then((res) => {
          this.loading[zid] = false;
          this.isListAjax = false;
          // this.zoneClass[zid] = res.data[0];
          this.$set(this.zoneClass, zid, res.data[0]);
          this.total[zid] = res.data[0].length ? res.data[0][0].num : 0;
          if (res.data[0].length == 0 && this.page[zid] != 1) {
            this.page[zid] = this.page[zid] - 1;
            this.getZoneClass(zid);
          }
          console.log(this.zoneClass);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //添加课程专区
    addZone() {
      if (this.zoneName === "") {
        this.$message.error("请填写添加课程专区名称");
        return;
      }
      if (this.time()) {
        let params = [
          { n: this.zoneName, cuid: this.$store.state.userInfo.uid },
        ];
        this.ajax
          .post(this.$store.state.api + "addZone", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.zoneName = "";
            this.dialogVisible4 = false;
            this.init();
            this.getZone();
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    //获取专区下的课程数量
    getZoneNum(zid) {
      let params = { bid: zid };
      this.ajax
        .get(this.$store.state.api + "getZoneClassNum", params)
        .then((res) => {
          if (res.data[0][0].num > 0) {
            this.$message.error("请把专区底下的课程全部删除才可以删除专区");
          } else {
            this.deleteZone(zid);
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //删除课程专区
    deleteZone(zid) {
      let params = [{ id: zid }];
      this.$confirm("确定删除此专区吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteZone", params)
            .then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getZone();
            })
            .catch((err) => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    //打开添加弹窗
    addPop(zid) {
      this.init();
      this.dialogVisible1 = true;
      this.pid = zid;
      this.Search();
    },
    //打开添加弹窗
    addBannerUrlPop() {
      // this.init()
      this.dialogVisible5 = true;
      this.searchClassName = "";
      this.Search();
    },
    //搜索获取课程
    Search() {
      this.checkList = [];
      let params = { t: this.searchClassName };
      this.ajax
        .get(this.$store.state.api + "getSearchCourse", params)
        .then((res) => {
          this.courseList = res.data[0];
          console.log(this.courseList);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    getZoneClassRepeat() {
      var list = this.checkList;
      if (list.length == 0) {
        this.$message.error("请选择需要添加的课程");
        return;
      }

      for (var i = 0; i < list.length; i++) {
        let _i = i;
        let _is = 0;
        let params = { pid: this.pid, cid: list[i] };
        var _this = this;
        $.ajax({
          url: this.$store.state.api + "getZoneClassRepeat", //url路径
          type: "GET", //GET
          async: false, //或false,是否异步
          data: params,
          timeout: 5000, //超时时间
          dataType: "json", //返回的数据格式：
          beforeSend: function (xhr) {},
          success: function (res, textStatus, jqXHR) {
            if (res[0][0].num > 0) {
              _this.$message.error(
                "您添加的课程在此专区有重复添加,请去掉后再重新提交"
              );
              _is = 1;
              return;
            }
            if (_i == list.length - 1) {
              _this.addCourse();
            }
          },
          error: function (xhr, textStatus) {
            console.log(textStatus);
          },
          complete: function () {},
        });
        if (_is != 0) {
          break;
        }
      }
    },
    //把课程添加进专区
    addCourse() {
      var list = this.checkList;

      if (this.time()) {
        for (var i = 0; i < list.length; i++) {
          let params = [{ pid: this.pid,oid:this.$store.state.userInfo.organizeid, uid: "0", cid: list[i] }];
          this.ajax
            .post(this.$store.state.api + "addZoneCourse", params)
            .then((res) => {
              this.$message({
                message: "添加成功",
                type: "success",
              });
            })
            .catch((err) => {
              this.$message.error("添加失败");
              console.error(err);
            });
          if (i == list.length - 1) {
            this.isListAjax = true;
            this.page[this.pid] = 1;
            this.getZoneClass(this.pid);
            this.init();
            this.dialogVisible1 = false;
          }
        }
      }
    },
    goTo(path) {
      this.$router.push(path);
    },
    //删除课程专区
    deleteZoneCourse(id, zid) {
      let params = [{ id: id }];
      this.$confirm("确定把此课程从次专区删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteZoneCourse", params)
            .then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getZoneClass(zid);
            })
            .catch((err) => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    //把课程添加进专区
    addBanner() {
      var list = this.fileList;
      if (list.length == 0) {
        this.$message.error("请上传需要添加的banner");
        return;
      } else if (this.bannerCourse === "") {
        this.$message.error("请填写选择banner的链接");
        return;
      }
      if (this.time()) {
        let params = [
          //this.bannerCourse.courseId
          {
            p: list[0].url,
            url: this.bannerCourse.courseId,
            uid: this.$store.state.userInfo.uid,
          },
        ];
        this.ajax
          .post(this.$store.state.api + "addBanner", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.init();
            this.getBanner();
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    //获取banner
    getBanner() {
      this.ajax
        .get(this.$store.state.api + "getBanner", "")
        .then((res) => {
          this.tableData = res.data[0];
          console.log(this.tableData);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //删除banner
    deleteBanner(id) {
      let params = [{ id: id }];
      this.$confirm("确定删除此banner吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteBanner", params)
            .then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getBanner();
            })
            .catch((err) => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
    up(index) {
      if (index == 0) {
        this.$message.error("已经是最上面的一个,不可以再上移了");
        return;
      }
      let params = [
        { aid: this.zoneList[index].id, bid: this.zoneList[index - 1].id },
      ];
      this.ajax
        .post(this.$store.state.api + "zoneRank", params)
        .then((res) => {
          this.$message({
            message: "上移成功",
            type: "success",
          });
          this.getZone();
        })
        .catch((err) => {
          this.$message.error("上移失败");
          console.error(err);
        });
    },
    down(index) {
      if (index == this.zoneList.length - 1) {
        this.$message.error("已经是最下面的一个,不可以再下移了");
        return;
      }
      let params = [
        { aid: this.zoneList[index].id, bid: this.zoneList[index + 1].id },
      ];
      this.ajax
        .post(this.$store.state.api + "zoneRank", params)
        .then((res) => {
          this.$message({
            message: "下移成功",
            type: "success",
          });
          this.getZone();
        })
        .catch((err) => {
          this.$message.error("下移失败");
          console.error(err);
        });
    },
    //设置banner链接
    setBannerUrl() {
      if (this.checkBannerCourse == "") {
        this.$message.error("请选择作为banner链接的课程");
        return;
      }
      this.bannerCourse = this.checkBannerCourse;
      this.dialogVisible5 = false;
    },
  },
  created() {
    this.getBanner();
    this.getZone();
  },
};
</script>

<style>
.el-popover {
  min-width: 80px;
  text-align: center;
}
</style>

<style scoped>
.disUoloadSty >>> .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}

.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
}
.home_titleHead {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.ban {
  margin: 20px 0px;
  font-size: 20px;
  display: flex;
  align-items: center;
}
.ban div {
  display: flex;
  flex-direction: column;
  margin-right: 10px;
  align-items: center;
  justify-content: center;
}

.ban .up {
  background: url("../../assets/up.png");
  width: 20px;
  background-size: 100% 100%;
  height: 12px;
  margin-bottom: 5px;
  cursor: pointer;
}

.ban .down {
  background: url("../../assets/up.png");
  width: 20px;
  background-size: 100% 100%;
  height: 12px;
  transform: rotate(180deg);
  cursor: pointer;
}

.head {
  text-align: center;
  background-color: #c9c9c9;
}
.dialogBox {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dialogBox span {
  margin: 0 20px;
}
.dialog_diy >>> .el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}
.dialog_diy >>> .el-dialog__title {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}

.cardList {
  font-size: 14px;
  height: 360px;
  overflow: auto;
}
.cardList div {
  margin-bottom: 18px;
}
.cardList div:last-child {
  margin-bottom: 0;
}
.cardHead {
  display: flex;
}
.box-card {
  /* width: 480px; */
}
.DivOverflow {
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
