<template>
  <div class="app-container">
    <div class="head-container">
      <h3>{{ serial.name }}</h3>
      <p>
        <span>视频数量：</span><span>{{ serial.videoCount }}</span>
      </p>
      <el-button type="primary" @click="addTag()">添加视频</el-button>
    </div>

    <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="video.title" label="视频名称" width="180">
      </el-table-column>
      <el-table-column prop="video.coverImage" 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">
          {{
            serial.type === 2
              ? playTypeList[scope.row.video.playType]
              : "短视频"
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="video.status"
        label="状态"
        width="80"
        v-if="serial.type === 2"
      >
        <template slot-scope="scope">
          {{ statusList[scope.row.video.status] }}
        </template>
      </el-table-column>
      <el-table-column prop="video.riskLevelLabel" label="风险等级" width="100">
        <template slot-scope="scope">
          {{
            serial.type === 2
              ? scope.row.video.riskLevelLabel
              : riskLevelObj[scope.row.video.riskLevel]
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="video.playStyle"
        label="展示形式"
        width="100"
        v-if="serial.type === 2"
      >
        <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="100"
        v-if="serial.type === 2"
      >
        <template slot-scope="scope">
          {{ liveStatusList[scope.row.video.liveStatus] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="video.duration"
        label="直播/视频时长"
        width="120"
        v-if="serial.type === 2"
      >
        <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.readCount" 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
      :total="serialTotal"
      :current-page="formSerial.current"
      :page-size="formSerial.size"
      layout="total,  prev, pager, next, jumper"
      @current-change="serialCurrentChange"
    />

    <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-form inline size="small">
          <el-form-item>
            <el-input
              v-model="formVideo.title"
              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="videoList"
          height="500px"
          @select="handleSelectionChange"
          size="small"
          @select-all="handleSelectionAll"
        >
          <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="50" height="50" />
            </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-pagination
          :total="total"
          :current-page="formVideo.current"
          :page-size="formVideo.size"
          layout="total,  prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
        <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 { mapGetters } from "vuex";
// import { queryTagList, tagSave, tagUpdate, updateStatus } from "@/api/tag.js";
import { getToken } from "@/utils/auth";
import {
  getSerialContent,
  getSerialContentList,
  saveSerialContent
} from "@/api/serial.js";
import { getInfoList } from "@/api/videoLive.js";
import { queryShortVideoList } from "@/api/shortVideo";
import { timeFormatTwo } from "@/utils/index";
import { riskLevelObj } from "@/config/constant";

export default {
  name: "column",
  data() {
    return {
      dialog: false,
      dialogTitle: "",
      loading: false,
      delLoading: false,
      editLoading: false,
      newTag: "",
      serial: {},
      data: [],
      videoList: [],
      tag: {
        id: "",
        name: ""
      },
      liveStatusList: {
        1: "直播中",
        2: "未开始",
        3: "已暂停",
        4: "已结束"
      },
      playStyleList: {
        1: "竖屏",
        2: "横屏"
      },
      playTypeList: {
        1: "直播",
        2: "录播"
      },
      statusList: {
        1: "待提交",
        2: "待审核",
        3: "已上架",
        4: "已驳回",
        5: "已下架"
      },
      columnName: "",
      form: {
        contentId: 0,
        event: 0,
        isRecommend: 0,
        serialId: 0
      },
      multipleSelection: [],
      headers: {
        Authorization: "Bearer " + getToken(),

        "X-File-Size": 0
      },
      dialogWeight: false,
      riskLevelObj,
      formVideo: {
        title: "",
        current: 1,
        size: 10
      },
      total: 0,
      formSerial: {
        id: this.$route.params.id,
        current: 1,
        size: 10
      },
      serialTotal: 0
    };
  },
  computed: {
    ...mapGetters(["user"]),
    id() {
      return parseInt(this.$route.params.id);
    }
  },
  async mounted() {
    await this.getDetail();
    this.getLists();
  },

  methods: {
    timeFormatTwo,
    searchForm() {
      this.formVideo.current = 1;
      this.getVideoList();
    },
    handleSelectionChange(val, row) {
      let ids = this.multipleSelection.map(item => item.id);
      let idIndexOf = ids.indexOf(row.id);
      if (idIndexOf === -1) {
        this.multipleSelection.push(row);
      } else {
        this.multipleSelection.splice(idIndexOf, 1);
      }
    },
    handleSelectionAll(val) {
      let ids = this.multipleSelection.map(item => item.id);
      if (val.length) {
        val.forEach(item => {
          if (ids.indexOf(item.id) === -1) {
            this.multipleSelection.push(item);
          }
        });
      } else {
        let idIndexOf;
        this.videoList.forEach(item => {
          idIndexOf = ids.indexOf(item.id);
          if (idIndexOf !== -1) {
            this.multipleSelection.splice(idIndexOf);
          }
        });
      }
    },
    async getVideoList() {
      const { code, data } =
        this.serial.type === 1
          ? await queryShortVideoList(
              Object.assign(
                {
                  advisorId: this.serial.advisorId,
                  userType: this.user.user.userType,
                  excludeSerialId: this.id
                },
                this.formVideo
              )
            )
          : await getInfoList(
              Object.assign(
                {
                  advisorId: this.serial.advisorId,
                  userType: this.user.user.userType,
                  flag: 2,
                  serialId: this.id
                },
                this.formVideo
              )
            );
      if (code !== undefined && code === 0) {
        this.videoList = data.list;
        // this.originVideoList = data.list
        this.total = data.total;

        if (this.multipleSelection && this.multipleSelection.length) {
          this.$nextTick(() => {
            let list = [];
            //遍历表格的数据，再遍历需要在表格中反显的数据，两者的id一致
            this.multipleSelection.forEach(item => {
              for (var i = 0; i < this.videoList.length; i++) {
                if (item.id === this.videoList[i].id) {
                  // 把判断出来的默认表格数据push到创建的数组中
                  list.push(this.videoList[i]);
                  break;
                }
              }
            });
            if (list.length) {
              //再遍历数组，将数据放入方法中
              list.forEach(row => {
                this.$refs.tableRef.toggleRowSelection(row, true);
              });
            }
          });
        }
      }
    },
    handleCurrentChange(val) {
      this.formVideo.current = val;
      this.getVideoList();
    },
    async getDetail() {
      const { data } = await getSerialContent({ id: this.id });
      console.log(data);
      this.serial = data;
    },
    async getLists() {
      this.loading = true;
      const { code, data } = await getSerialContentList(this.formSerial);
      if (code !== undefined && code === 0) {
        this.data = (data.list || []).map(item => ({
          ...item,
          video:
            this.serial.type === 2 ? item.video || {} : item.shortVideo || {}
        }));
        console.log("this.data", this.data);
        this.serialTotal = data.total;
        if (this.formSerial.current > 1 && (data.list || []).length === 0) {
          this.serialCurrentChange(this.formSerial.current - 1);
        }
      }

      this.loading = false;
    },

    serialCurrentChange(val) {
      this.formSerial.current = val;
      this.getLists();
    },
    // 添加标签
    async addTag(val) {
      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.multipleSelection = [];
        this.handleCurrentChange(1);
        // const map = _.keyBy(this.data, 'contentId')

        // this.$nextTick(() => {
        //   this.videoList.forEach(video => {
        //     if (map[video.id]) {
        //       this.$refs.tableRef.toggleRowSelection(video, true)
        //       this.multipleSelection.push(video)
        //     }
        //   })
        // })
      }
    },
    cancel() {
      this.form = {
        advisorId: "",
        name: "",
        type: 1,
        remark: "",
        coverImage: "",
        authorityId: "",
        authority: "1",
        weight: null
      };
      this.dialog = false;
    },
    // 确定栏目按钮
    async submit() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择视频");
        return false;
      }
      const contentIds = this.multipleSelection.map(v => v.id);

      const data = await saveSerialContent({
        contentId: 0,
        contentIds,
        event: 4,
        serialId: this.id
      });
      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,
            serialId: item.serialId
          };
          const data = await saveSerialContent(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: [], event: 3 };
            const res = await saveSerialContent(data);
            if (res.code === 0) {
              this.$message.success("操作成功");
              this.getLists();
            }
          })
          .catch(() => {});
      } else {
        const data = { ...this.form, contentIds: [], event: 2 };
        const res = await saveSerialContent(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.serialId = val.serialId;
      this.dialogWeight = true;
    },
    // 分页器
    sizeChange(e) {
      this.page = 1;
      this.size = e;
      this.getLists();
    },
    pageChange(e) {
      this.page = e;
      this.getLists();
    },
    cancelWeight() {
      this.form = {
        contentId: "",
        serialId: "",
        event: 4,
        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>
