<template>
  <div class="app-container">
    <div class="mb10">
      <el-input
        class="w260 mb10"
        clearable
        v-model="queryParams.videoName"
        placeholder="请输入直播标题名称"
      />
      <el-input
        class="w260 mb10"
        clearable
        v-model="queryParams.advisorName"
        placeholder="投顾主播名称"
      />
      <!-- <el-select class="mb10" clearable v-model="queryParams.comId" filterable placeholder="分公司">
          <el-option v-for="item in isOfColumnList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select> -->
      <el-select
        class="mb10"
        clearable
        v-model="queryParams.deptId"
        filterable
        placeholder="营业部"
      >
        <el-option
          v-for="item in deptList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select
        class="mb10"
        clearable
        v-model="queryParams.isOfColumn"
        filterable
        placeholder="是否为专栏直播"
      >
        <el-option
          v-for="item in isOfColumnList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-date-picker
        v-model="dateValue"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
      >
      </el-date-picker>
      <el-button type="primary" @click="searchList()">查询</el-button>
      <el-button type="success" :loading="downloadLoading" @click="toExport"
        >导出</el-button
      >
    </div>
    <div class="mb10">
      <el-table :data="data" v-loading="loading" border style="width: 100%">
        <el-table-column label="序号" type="index" fixed width="180">
        </el-table-column>
        <el-table-column prop="title" label="视频名称" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row)">{{
              scope.row.title
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="imgUrl" label="封面" width="100">
          <template #default="scope">
            <el-popover placement="right" :width="400" trigger="hover">
              <img :src="scope.row.imgUrl" width="375" height="300" />
              <template #reference>
                <img
                  :src="scope.row.imgUrl"
                  style="max-height: 60px; max-width: 60px"
                />
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.tagVOList.length > 0">
              <span v-for="item in scope.row.tagVOList" :key="index">{{
                item.name
              }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="投顾主播名称" width="180">
          <template slot-scope="scope">
            {{ scope.row.advisorName }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="createUserCmpName" label="所属分公司" width="180">
          <template slot-scope="scope">
            {{ scope.row.createUserCmpName }}
          </template>
        </el-table-column> -->
        <el-table-column prop="name" label="所属营业部" width="180">
          <template slot-scope="scope">
            {{ scope.row.deptName }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" label="播放类型" width="180">
            <template slot-scope="scope">
              {{ scope.row.playType ? '直播' : '录播' }}
            </template>
          </el-table-column> -->
        <el-table-column prop="columnId" label="是否为专栏直播" width="180">
          <template slot-scope="scope">
            {{ scope.row.columnId ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column prop="columnName" label="专栏名称" width="180">
          <template slot-scope="scope">
            {{ scope.row.columnName }}
          </template>
        </el-table-column>
        <el-table-column prop="riskLevel" label="风险等级" width="180">
          <template slot-scope="scope">
            {{ riskLevelList[scope.row.riskLevel] }}
          </template>
        </el-table-column>
        <el-table-column prop="realStartTime" label="直播开始时间" width="180">
        </el-table-column>
        <el-table-column prop="realEndTime" label="直播结束时间" width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" width="180">
        </el-table-column>
        <el-table-column
          prop="sensitiveWord"
          label="触发风控敏感词"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="triggerTime" label="触发时间" width="180">
        </el-table-column>
        <el-table-column
          prop="name"
          label="操作"
          fixed="right"
          align="center"
          width="400"
        >
          <template slot-scope="scope">
            <el-button
              v-if="[1].includes(scope.row.liveStatus)"
              @click="listing(scope.row)"
              type="text"
              >结束直播</el-button
            >
            <el-button v-if="[4].includes(scope.row.liveStatus)" type="text"
              >已结束</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="queryParams.current"
      :page-size="queryParams.size"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      title="带货产品清单"
      :visible.sync="dialogTableVisible"
      :modal-append-to-body="false"
    >
      <el-table :data="gridData">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column property="name" label="产品名称"></el-table-column>
        <el-table-column property="productType" label="产品类型">
          <template slot-scope="scope">
            {{ productTypeList[scope.row.productType] }}
          </template>
        </el-table-column>
        <el-table-column label="投顾名称">
          <template slot-scope="scope">
            {{ scope.row.advisorBasicVO.name }}
          </template>
        </el-table-column>
        <el-table-column
          property="clickCount"
          label="本场直播点击数"
        ></el-table-column>
        <el-table-column
          property="subCount"
          label="本场直播订阅数"
        ></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      title="推流"
      :visible.sync="dialogInputVisible"
      :modal-append-to-body="false"
    >
      <el-form ref="form" :model="dialogForm" label-width="80px">
        <el-form-item label="推流地址">
          {{ dialogForm.pushUrl }}
        </el-form-item>
        <el-form-item label="播流地址">
          {{ dialogForm.playUrl }}
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="带货产品清单"
      :visible.sync="dialogTableRecommend"
      :modal-append-to-body="false"
    >
      <el-form
        :model="recommendForm"
        :rules="rules"
        ref="recommendForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="视频名称">
          <el-input v-model="recommendForm.title" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="推荐权重" prop="name">
          <el-input-number
            v-model="recommendForm.weight"
            :min="0"
            :max="100"
            :step="1"
            :precision="0"
            label="权重值"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('recommendForm')"
            >确 定</el-button
          >
          <el-button @click="dialogTableRecommend = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  getInfoList,
  tagList,
  livePlayInfo,
  infoSubmit,
  cartList,
  uVideoControl,
  updateStatus,
  recommendSave,
  deptColumnList,
  riskList
} from "@/api/videoLive";
import Clipboard from "clipboard";
import dayjs from "dayjs";
export default {
  data() {
    return {
      queryParams: {
        current: 1,
        size: 10,
        deptId: null
      },
      dateValue: [],
      total: 1,
      loading: false,
      isOfColumnList: [{ value: 1, label: "是" }, { value: 2, label: "否" }],
      liveStatusList: [
        { value: 1, label: "未开始" },
        { value: 2, label: "直播中" },
        { value: 3, label: "已结束" },
        { value: 4, label: "暂停中" }
      ],
      statusList: [
        { value: 1, label: "待提交" },
        { value: 2, label: "待审核" },
        { value: 3, label: "已上架" },
        { value: 4, label: "已驳回" },
        { value: 5, label: "已下架" }
      ],
      statusListLabel: ["", "待提交", "待审核", "已上架", "已驳回", "已下架"],
      liveLabel: ["", "未开始", "直播中", "已结束", "暂停中"],
      limitTypeList: {
        1: "不限制",
        2: "手机号",
        3: "邀请码"
      },
      riskLevelList: {
        1: "低风险",
        2: "中低风险",
        3: "中风险",
        4: "中高风险",
        5: "高风险"
      },
      tagIdList: [],
      data: [],
      gridData: [],
      dialogTableVisible: false,
      dialogInputVisible: false,
      dialogTableRecommend: false,
      optionsTag: [],
      loadingTag: false,
      dialogForm: {
        pushUrl: "",
        playUrl: ""
      },
      recommendForm: {
        title: "",
        weight: "",
        option: 1,
        id: null
      },
      productTypeList: {
        3: "视频"
      },
      copyText: "",
      rules: {
        weight: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
        ]
      },
      deptList: [],
      downloadLoading: false
    };
  },
  computed: {},
  mounted() {
    this.queryList();
    this.getColumnList();
  },

  methods: {
    getColumnList() {
      deptColumnList({ type: 2 }).then(res => {
        if (res.code === 0) {
          this.deptList = res.data;
        }
      });
    },
    async toExport() {
      this.downloadLoading = true;

      const params = JSON.parse(JSON.stringify(this.queryParams));
      params.size = 9999;
      const { data, code, message } = await riskList(params);

      if (code === 0) {
        import("@/utils/export2Excel").then(excel => {
          const tHeader = [
            "视频名称",
            "封面",
            "标签",
            "投顾主播名称",
            // "所属分公司",
            "所属营业部",
            "是否为专栏直播",
            "专栏名称",
            "风险等级",
            "直播开始时间",
            "直播结束时间",
            "创建时间",
            "审核时间",
            "触发风控敏感词",
            "触发时间"
          ];
          const filterVal = [
            "title",
            "imgUrl",
            "tagVOList",
            "advisorName",
            // "createUserCmpName",
            "deptName",
            "columnId",
            "columnName",
            "riskLevel",
            "realStartTime",
            "realEndTime",
            "createTime",
            "auditTime",
            "sensitiveWord",
            "triggerTime"
          ];
          const excelData = this.formatJson(filterVal, data.list);
          excel.export_json_to_excel({
            header: tHeader,
            data: excelData,
            filename: "风控统计"
          });
          console.log("list=>", data.list);
        });
      } else {
        this.$message.error(message);
      }
      this.downloadLoading = false;
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "tagVOList") {
            return v[j].map(item => {
              return item.name;
            });
          } else if (j === "advisorBasic") {
            return v[j] ? v[j].name : "";
          } else if (j === "columnId") {
            return v[j] ? "是" : "否";
          } else if (j === "riskLevel") {
            return this.riskLevelList[v[j]];
          } else {
            return v[j];
          }
        })
      );
    },
    queryList() {
      this.loading = true;
      this.queryParams.userType = 2;
      riskList(this.queryParams).then(data => {
        this.data = data.data.list;
        this.total = data.data.total;
        this.loading = false;
      });
    },
    searchList() {
      this.queryParams.size = 10;
      this.queryParams.current = 1;
      this.queryParams.beginDate =
        this.dateValue && this.dateValue[0]
          ? dayjs(this.dateValue[0]).format("YYYY-MM-DD")
          : "";
      this.queryParams.endDate =
        this.dateValue && this.dateValue[1]
          ? dayjs(this.dateValue[1]).format("YYYY-MM-DD")
          : "";
      this.queryList();
    },
    handleSizeChange(val) {
      this.$set(this.queryParams, "size", val);
      this.$set(this.queryParams, "current", 1);
      this.queryList();
    },
    handleCurrentChange(val) {
      this.$set(this.queryParams, "current", val || 1);
      this.queryList();
    },
    openProduct(val) {
      this.$router.push(
        `/liveBroadcast/liveBroadcastDetail?id=${val.id}&type=2`
      );
    },
    toCreate(id, type) {
      // type = 2 查看
      if (id && type) {
        this.$router.push(
          `/liveBroadcast/liveBroadcastCreate?id=${id}&type=${type}&userType=3`
        );
      } else {
        this.$router.push("/liveBroadcast/liveBroadcastCreate?userType=3");
      }
    },
    remoteMethodTag(query) {
      this.loadingTag = true;
      const queryParams = {
        name: query,
        current: 1,
        size: 10,
        type: 3,
        status: 1
      };
      tagList(queryParams).then(data => {
        this.optionsTag = data.data.list;
        this.loadingTag = false;
      });
    },
    openPlayInfo(item) {
      livePlayInfo({ id: item.id }).then(res => {
        if (res.code === 0) {
          this.dialogForm.pushUrl = res.data.pushUrl;
          this.dialogForm.playUrl = res.data.playUrl;
          this.dialogInputVisible = true;
        }
      });
    },
    listing(item) {
      this.$confirm(`您确定结束直播?`, {
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          uVideoControl({ id: item.id, option: 2 }).then(res => {
            if (res.code === 0) {
              this.$message({
                type: "success",
                message: "结束直播成功!"
              });
              this.searchList();
            }
          });
        })
        .catch(() => {});
    },
    toProductList(item) {
      cartList({ id: item.id }).then(res => {
        if (res.code === 0) {
          this.gridData = res.data ? res.data.list : [];
          this.dialogTableVisible = true;
        } else {
          this.$message.error("获取带货产品失败!");
        }
      });
    },
    // 下载海报
    downloadByBlob(url, name) {
      let image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.src = url;
      image.onload = () => {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        canvas.toBlob(blob => {
          let url = URL.createObjectURL(blob);
          this.download(url, name);
          // 用完释放URL对象
          URL.revokeObjectURL(url);
        });
      };
    },
    download(href, name) {
      let eleLink = document.createElement("a");
      eleLink.download = name;
      eleLink.href = href;
      eleLink.click();
      eleLink.remove();
    },
    async copyUrl(item) {
      await livePlayInfo({ id: item.id }).then(res => {
        if (res.code === 0) {
          this.copyText = res.data.playUrl;
          let clipboard = new Clipboard(".tag", {
            text: function() {
              return res.data.playUrl;
            }
          });
          clipboard.on("success", e => {
            this.$message({
              message: "复制成功",
              showClose: true,
              type: "success"
            });
            // 释放内存
            clipboard.destroy();
          });
          clipboard.on("error", e => {
            this.$message({
              message: "复制失败,",
              showClose: true,
              type: "error"
            });
            clipboard.destroy();
          });
        }
      });
    },
    openRecommend(item, type) {
      if (type === 1) {
        this.dialogTableRecommend = true;
        this.recommendForm.option = type;
        this.recommendForm.title = item.title;
        this.recommendForm.weight = item.weight;
        this.recommendForm.id = item.id;
      } else {
        this.$confirm(`您确定取消推荐?`, {
          confirmButtonText: "提交",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            // 申请上架
            recommendSave({ id: item.id, option: 2 }).then(res => {
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: "取消推荐成功!"
                });
                this.searchList();
              }
            });
          })
          .catch(() => {});
      }
    },
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          recommendSave(this.recommendForm).then(res => {
            if (res.code === 0) {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.dialogTableRecommend = false;
              this.searchList();
            }
          });
        }
      });
    },
    toDetail(val) {
      this.$router.push(`/liveBroadcast/liveDetail?id=${val.id}&type=2`);
    }
  }
};
</script>

<style scoped lang="scss">
.mb10 {
  margin-bottom: 10px;
}

.flex-box {
  display: inline-flex;
  flex-direction: row;

  &_item {
    display: inline-flex;
    flex-direction: column;
    margin-right: 10px;
    cursor: pointer;
    background-color: rgb(255, 255, 255);
    align-self: center;

    div {
      padding: 5px 0;
      display: inline-flex;
      align-self: center;
    }
  }
}

.charts-box {
  padding: 20px;
  width: 60%;
}

.w260 {
  width: 260px;
}
</style>
