<template>
  <div class="app-container">
    <div class="head-container">
      <h3>{{ course.name }}</h3>
      <p>
        <span>内容数：</span><span>{{ course.contentCount }}</span>
      </p>
      <el-button type="primary" @click="addTag()">添加课程内容</el-button>
    </div>

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane name="1" label="合集">
        <el-table
          v-loading="loading"
          :data="data"
          size="small"
          style="width: 100%;"
        >
          <el-table-column label="序号" align="center" type="index" fixed />
          <el-table-column prop="createTime" label="收录时间" width="180">
          </el-table-column>
          <el-table-column prop="serial.name" label="合集名称">
          </el-table-column>
          <el-table-column prop="serial.coverImage" label="封面图" width="100">
            <template #default="scope">
              <el-popover placement="right" :width="400" trigger="hover">
                <img
                  :src="scope.row.serial.coverImage"
                  width="375"
                  height="300"
                />
                <template #reference>
                  <img
                    :src="scope.row.serial.coverImage"
                    style="max-height: 60px; max-width: 60px"
                  />
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="serial.type" label="类型" width="100">
            <template slot-scope="scope">
              {{ serialTypeList[scope.row.serial.type] }}
            </template>
          </el-table-column>
          <el-table-column prop="serial.status" label="状态" width="80">
            <template slot-scope="scope">
              {{ statusList[scope.row.serial.status] }}
            </template>
          </el-table-column>
          <el-table-column
            prop="serial.videoCount"
            label="包含视频数量"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="serial.createTime"
            label="创建时间"
            width="180"
          >
          </el-table-column>
          <el-table-column
            prop="serial.updateTime"
            label="最近更新时间"
            width="180"
          >
          </el-table-column>
          <el-table-column prop="isRecommend" label="是否推荐" width="80">
            <template slot-scope="scope">
              {{ scope.row.isRecommend ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="isRecommend" label="权重" width="80">
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="250"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.isRecommend"
                type="text"
                size="mini"
                @click="update(scope.row, 3)"
                >取消推荐</el-button
              >
              <el-button
                v-else
                type="text"
                size="mini"
                @click="recommendation(scope.row)"
                >推荐</el-button
              >
              <el-button type="text" size="mini" @click="update(scope.row, 5)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 50px;"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="sizeChange"
          @current-change="pageChange"
        />
      </el-tab-pane>
      <el-tab-pane name="2" label="直播课">
        <el-table
          v-loading="loading"
          :data="data2"
          size="small"
          style="width: 100%;"
        >
          <el-table-column label="序号" align="center" type="index" fixed />
          <el-table-column prop="createTime" label="视频收录时间" width="180">
          </el-table-column>
          <el-table-column prop="video.title" label="视频名称">
          </el-table-column>
          <el-table-column prop="video.imgUrl" label="封面图" width="100">
            <template #default="scope">
              <el-popover placement="right" :width="400" trigger="hover">
                <img :src="scope.row.video.imgUrl" width="375" height="300" />
                <template #reference>
                  <img
                    :src="scope.row.video.imgUrl"
                    style="max-height: 60px; max-width: 60px"
                  />
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="video.playType" label="视频类型" width="100">
            <template slot-scope="scope">
              {{ playTypeList[scope.row.video.playType] }}
            </template>
          </el-table-column>
          <el-table-column prop="video.status" label="状态" width="80">
            <template slot-scope="scope">
              {{ statusList[scope.row.video.status] }}
            </template>
          </el-table-column>
          <el-table-column
            prop="video.riskLevelLabel"
            label="风险等级"
            width="100"
          >
          </el-table-column>
          <el-table-column prop="video.playStyle" label="展示形式" width="100">
            <template slot-scope="scope">
              {{ playStyleList[scope.row.video.playStyle] }}
            </template>
          </el-table-column>
          <el-table-column prop="video.createTime" label="创建时间" width="180">
          </el-table-column>
          <el-table-column prop="video.liveStatus" label="直播状态" width="80">
            <template slot-scope="scope">
              {{ liveStatusList[scope.row.video.liveStatus] }}
            </template>
          </el-table-column>
          <el-table-column
            prop="video.duration"
            label="直播/视频时长"
            width="120"
          >
            <template slot-scope="scope">
              {{
                scope.row.video.duration
                  ? timeFormatTwo(scope.row.video.duration)
                  : scope.row.video.duration
              }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="video.favorUserCount" label="点赞数" width="80">
          </el-table-column>
          <el-table-column prop="video.readUserCount" label="播放量" width="80">
          </el-table-column>
          <el-table-column prop="video.joinUserCount" label="互动数" width="80">
          </el-table-column> -->
          <el-table-column prop="video.isCart" label="视频是否带货" width="100">
            <template slot-scope="scope">
              {{ scope.row.video.isCart === 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="isRecommend" label="是否推荐" width="80">
            <template slot-scope="scope">
              {{ scope.row.isRecommend ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="isRecommend" label="权重" width="80">
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="250"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.isRecommend"
                type="text"
                size="mini"
                @click="update(scope.row, 3)"
                >取消推荐</el-button
              >
              <el-button
                v-else
                type="text"
                size="mini"
                @click="recommendation(scope.row)"
                >推荐</el-button
              >
              <el-button type="text" size="mini" @click="update(scope.row, 5)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 50px;"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="sizeChange"
          @current-change="pageChange"
        />
      </el-tab-pane>
    </el-tabs>

    <div style="display: inline-block">
      <el-dialog
        v-model="form"
        :visible.sync="dialog"
        :close-on-click-modal="false"
        :title="dialogTitle"
        append-to-body
        width="800px"
      >
        <el-tabs v-model="form.type">
          <el-tab-pane label="合集" name="1">
            <el-form inline>
              <el-form-item>
                <el-input
                  v-model="form.name1"
                  placeholder="请输入合集名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchForm">查询</el-button>
              </el-form-item>
            </el-form>
            <el-table
              ref="tableRef"
              :data="serialList"
              height="400px"
              row-key="id"
              @selection-change="handleSelectionChange1"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="coverImage" label="封面图">
                <template #default="scope">
                  <img :src="scope.row.coverImage" width="100" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="合集名称"></el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template slot-scope="scope">
                  {{ statusList[scope.row.status] }}
                </template>
              </el-table-column>
              <el-table-column
                prop="auditTime"
                label="上架时间"
              ></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="直播课" name="2">
            <el-form inline>
              <el-form-item>
                <el-input
                  v-model="form.name2"
                  placeholder="请输入视频名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchForm">查询</el-button>
              </el-form-item>
            </el-form>
            <el-table
              ref="tableRef2"
              :data="videoList"
              height="400px"
              row-key="id"
              @selection-change="handleSelectionChange2"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="imgUrl" label="封面图">
                <template #default="scope">
                  <img :src="scope.row.imgUrl" width="100" />
                </template>
              </el-table-column>
              <el-table-column prop="title" label="视频名称"></el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template slot-scope="scope">
                  {{ statusList[scope.row.status] }}
                </template>
              </el-table-column>
              <el-table-column
                prop="auditTime"
                label="上架时间"
              ></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="cancel()">取消</el-button>
          <el-button
            size="mini"
            :loading="editLoading"
            type="primary"
            @click="submit()"
            >确认</el-button
          >
        </div>
      </el-dialog>
    </div>
    <div style="display: inline-block">
      <el-dialog
        :visible.sync="dialogWeight"
        :close-on-click-modal="false"
        title="推荐"
        append-to-body
      >
        <el-form>
          <el-form-item label="课程权重：">
            <el-input-number
              v-model="form.isRecommend"
              :min="1"
              :max="100"
              label="请输入权重"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="editWeight()"
            >提交</el-button
          >
          <el-button size="mini" @click="cancelWeight()">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import { mapGetters } from "vuex";
// import { queryTagList, tagSave, tagUpdate, updateStatus } from "@/api/tag.js";
import { getToken } from "@/utils/auth";
import {
  getCourseContent,
  getCourseContentList,
  saveCourseContent
} from "@/api/course.js";
import { getSerialList } from "@/api/serial.js";
import { getInfoList } from "@/api/videoLive.js";
import { timeFormatTwo } from "@/utils/index";

export default {
  name: "column",
  data() {
    return {
      activeName: "1",
      page: 1,
      size: 10,
      total: 0,
      dialog: false,
      dialogTitle: "",
      loading: false,
      delLoading: false,
      editLoading: false,
      newTag: "",
      course: {},
      data: [],
      data2: [],
      videoList: [],
      originVideoList: [],
      serialList: [],
      originSerialList: [],
      tag: {
        id: "",
        name: ""
      },
      liveStatusList: {
        1: "直播中",
        2: "未开始",
        3: "已暂停",
        4: "已结束"
      },
      playStyleList: {
        1: "竖屏",
        2: "横屏"
      },
      serialTypeList: {
        1: "短视频",
        2: "直播/录播"
      },
      playTypeList: {
        1: "直播",
        2: "录播"
      },
      statusList: {
        1: "待提交",
        2: "待审核",
        3: "已上架",
        4: "已驳回",
        5: "已下架"
      },
      columnName: "",
      form: {
        type: "1",
        contentId: 0,
        event: 0,
        isRecommend: 0,
        courseId: 0
      },
      multipleSelection1: [],
      multipleSelection2: [],
      headers: {
        Authorization: "Bearer " + getToken(),
        "X-File-Size": 0
      },
      dialogWeight: false
    };
  },
  computed: {
    ...mapGetters(["user"]),
    id() {
      return parseInt(this.$route.params.id);
    }
  },
  mounted() {
    this.getDetail().then(() => {
      this.getSerialList();
      this.getVideoList();
    });
    this.getLists();
  },
  methods: {
    timeFormatTwo,
    searchForm() {
      if (+this.form.type === 1) {
        this.serialList = this.form.name1
          ? this.originSerialList.filter(item =>
              item.name.includes(this.form.name1)
            )
          : this.originSerialList;
      } else {
        this.videoList = this.form.name2
          ? this.originVideoList.filter(item =>
              item.title.includes(this.form.name2)
            )
          : this.originVideoList;
      }
    },
    handleClick(tab, event) {
      this.form.type = tab.name;
      // reset pagination
      this.page = 1;
      this.getLists();

      this.$nextTick(() => {
        if (+this.activeName === 1) {
          const map = _.keyBy(this.data, "contentId");
          this.serialList.forEach(video => {
            if (map[video.id]) {
              setTimeout(() => {
                this.$refs.tableRef.toggleRowSelection(video, true);
              }, 100);
            }
          });
        } else {
          const map = _.keyBy(this.data2, "contentId");
          this.videoList.forEach(video => {
            if (map[video.id]) {
              setTimeout(() => {
                this.$refs.tableRef2.toggleRowSelection(video, true);
              }, 100);
            }
          });
        }
      });
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val;
    },
    async getSerialList() {
      const { data } = await getSerialList({
        current: 1,
        size: 9999,
        status: undefined,
        userType: this.user.user.userType === 1 ? 1 : 2,
        excludeCourseId: this.id
      });
      this.serialList = data.list.filter(
        v => v.advisorId === this.course.advisorId
      );
      this.originSerialList = data.list.filter(
        v => v.advisorId === this.course.advisorId
      );
    },
    async getVideoList() {
      const { data } = await getInfoList({
        deptId: this.user.user.deptId,
        userType: this.user.user.userType,
        status: undefined,
        size: 99999,
        courseId: this.id,
        current: 1,
        flag: 2
      });

      this.videoList = data.list.filter(
        v => (v.teacherId || v.advisorBasic.id) === this.course.advisorId
      );
      this.originVideoList = data.list.filter(
        v => (v.teacherId || v.advisorBasic.id) === this.course.advisorId
      );
    },
    async getDetail() {
      const { data } = await getCourseContent({ id: this.id });

      this.course = data;
    },
    async getLists(type = +this.activeName) {
      this.loading = true;
      const { data } = await getCourseContentList({
        courseId: this.id,
        current: this.page,
        size: this.size,
        type
      });

      if (type === 1) {
        this.data = data.list.map(item => ({
          ...item,
          serial: item.serial || {}
        }));
      } else {
        this.data2 = data.list.map(item => ({
          ...item,
          video: item.video || {},
          shortVideo: item.shortVideo || {}
        }));
      }
      this.total = data.total;
      this.loading = false;
    },
    // 添加标签
    async addTag(val) {
      this.getSerialList();
      this.getVideoList();
      this.cancel();
      if (val) {
        this.form.name = JSON.parse(JSON.stringify(val.name));
        this.form.coverImage = JSON.parse(JSON.stringify(val.coverImage));
        this.form.introduce = JSON.parse(JSON.stringify(val.introduce));
        this.dialogTitle = "审核课程";
        this.dialog = true;
      } else {
        this.dialog = true;
        this.dialogTitle = "添加视频";
        this.multipleSelection1 = [];
        this.multipleSelection2 = [];
      }
    },
    cancel() {
      this.form = {
        advisorId: "",
        name: "",
        type: this.form.type || "1",
        remark: "",
        coverImage: "",
        authorityId: "",
        authority: "1",
        weight: null
      };
      this.dialog = false;
    },
    // 确定栏目按钮
    async submit() {
      const multipleSelection =
        +this.form.type === 1
          ? this.multipleSelection1
          : this.multipleSelection2;

      if (multipleSelection.length === 0) {
        this.$message.error("请选择");
        return false;
      }
      const {
        data: { list }
      } = await getCourseContentList({
        courseId: this.id,
        current: 1,
        size: 9999,
        type: this.form.type
      });
      const contentList = list;
      const contentIds = multipleSelection
        .map(v => v.id)
        .concat(contentList.map(v => v.contentId));
      const data = await saveCourseContent({
        contentId: 0,
        contentIds,
        event: 1,
        courseId: this.id,
        type: +this.form.type
      });
      if (data.code === 0) {
        this.$message.success("修改成功");
        this.cancel();
        this.getDetail();
        this.getLists();
      } else {
        // this.$message.error(data.message)
        this.$message.error("修改失败");
      }
    },
    // 删除标签
    async update(item, event) {
      console.log(item, event);
      const eventMap = {
        1: "保存",
        2: "推荐",
        3: "取消推荐",
        4: "添加",
        5: "删除"
      };
      this.$confirm(`您确定进行${eventMap[event]}${item.title || ""}?`, {
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const params = {
            contentId: item.contentId,
            contentIds: [item.contentId],
            event,
            courseId: item.courseId,
            type: +this.activeName
          };
          const data = await saveCourseContent(params);
          // console.log(data)
          if (data.code === 0) {
            this.$message.success("操作成功");
            if (this.data.length === 1 && this.page !== 1) {
              this.page -= 1;
            }
            this.getDetail();
            this.getLists();
          } else {
            this.$message.error(data.message);
          }
        })
        .catch(() => {});
    },
    async editWeight(val) {
      if (val) {
        this.$confirm(`您确定取消推荐?`, {
          confirmButtonText: "提交",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            const data = {
              ...this.form,
              contentIds: [this.form.contentId],
              event: 3,
              type: +this.activeName
            };
            const res = await saveCourseContent(data);
            if (res.code === 0) {
              this.$message.success("操作成功");
              this.getLists();
            }
          })
          .catch(() => {});
      } else {
        const data = {
          ...this.form,
          contentIds: [this.form.contentId],
          event: 2,
          type: +this.activeName
        };
        const res = await saveCourseContent(data);
        if (res.code === 0) {
          this.$message.success("操作成功");
          this.cancelWeight();
          this.getLists();
        }
      }
    },
    recommendation(val) {
      this.form.isRecommend = val.isRecommend;
      this.form.contentId = val.contentId;
      this.form.courseId = val.courseId;
      this.dialogWeight = true;
    },
    // 分页器
    sizeChange(e) {
      this.page = 1;
      this.size = e;
      this.getLists();
    },
    pageChange(e) {
      this.page = e;
      this.getLists();
    },
    cancelWeight() {
      this.form = {
        contentId: "",
        courseId: "",
        event: 3,
        isRecommend: 0
      };
      this.dialogWeight = false;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-pagination {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.head-container {
  h3 {
    font-size: 20px;
  }
  p {
    font-size: 16px;
    line-height: 32px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
