<template>
  <div class="listPage H100">
    <div class="search-container">
      <el-form :inline="true" :model="form" class="search-form" onsubmit="return false;">
        <el-form-item label="">
          <el-input
            placeholder="请输入视频名称"
            v-model="form.nameOrCode"
            @keyup.enter.native="Search"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="">
            <el-select
              placeholder="请选择视频版权方"
              @focus="getAssetCopyrightData"
              v-model="form.videoContentCopyrightOwnerId"
              clearable
            >
              <el-option
                v-for="item in copyrightOwner"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select
              placeholder="请选择预设视频分类"
              @focus="getAssetTypeData"
              v-model="form.videoContentCatId"
              clearable
            >
              <el-option
                v-for="item in videoContentCat"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        <el-form-item>
          <div class="btn-group">
            <el-button size="mini" type="primary" class="btn_form_search" @click="Search">查询</el-button>
            <el-button size="mini" class="btn_form_search" @click="Reset">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div class="page-tip">
        <span class="page-tip-title">页面说明:</span>
        <span class="page-tips">可使用版权方、视频分类、视频名称模糊搜索对需要汇出的视频进行快速检索，下载至本地。</span>
      </div>
    </div>
    <div class="table-content">
      <div class="btn-group">
        <el-button type="primary" @click="downloadCipher()">导出加密秘钥</el-button>
        <el-button type="primary" @click="multipleRemitGet()">汇出</el-button>
        <!-- <el-button type="primary" @click="multipleRemit()">汇出</el-button> -->
      </div>
      <div class="party-table">
        <el-table
          border
          style="width: 100%;height:100%"
          height="100%"
          ref="multipleTable"
          :data="tableData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
           <el-table-column type="index" width="120" label="序号">
            <template slot-scope="scope">
              <span>{{ (page.currentPage - 1) * 10 + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="视频名称" prop="fileName"></el-table-column>
          <el-table-column label="版权方" prop="videoContentCopyrightOwnerName"></el-table-column>
          <el-table-column label="视频类别" prop="videoContentCatName"></el-table-column>
        </el-table>
      </div>
      <div class="partyt-pagination">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-size="page.pageSize"
          layout="prev, pager, next, jumper"
          :total="page.total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    var checkIsNull = (rule, value, callback) => {
      if (value) {
        if (value.trim() == "") {
          callback(new Error("不允许只输入空格"));
        } else {
          callback();
        }
      }
    };
    return {
      nowDate: "", // 当前日期
      fullscreenLoading: false,
      copyrightOwner:[],
      videoContentCat:[],
      type: true,
      value1: "",
      page: { currentPage: 1, pageSize: 10, total: 0 },
      tableData: [],
      FormVisible: false,
      FormVisible1: false,
      formLabelWidth: "100px",
      form: {
        nameOrCode: ""
      },
      editform: {
        menuName: "",
        menuUrl: "",
        parentId: "",
        sort: "",
        id: ""
      },
      classForm: {
        menuName: "",
        menuUrl: "",
        parentId: "",
        sort: ""
      },
      typeList: [],
      rules: {
        sort: [
          { required: true, message: "请输入顺序值", trigger: "change" },
          { pattern: /^(\d{1,5})?$/, message: "排序值为低于5位数的纯数字" }
        ],
        menuName: [
          { required: true, message: "请输入菜单名称", trigger: "change" },
          { max: 20, message: "不能超过20个字符", trigger: "change" },
          { validator: checkIsNull, trigger: "blur" }
        ],
        menuUrl: [
          { required: true, message: "请输入菜单地址", trigger: "change" },
          { validator: checkIsNull, trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "请输入父级菜单", trigger: "change" }
        ]
      },
      value: "",
      name: ""
    };
  },
  computed: {},
  mounted() {
    this.onSearch();
    // this.getPermis();
  },
  components: {},
  methods: {
    formatDate() {
      let date = new Date();
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      let week = date.getDay(); // 星期
      let weekArr = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ];
      let hour = date.getHours(); // 时
      hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
      let minute = date.getMinutes(); // 分
      minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
      let second = date.getSeconds(); // 秒
      second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
      this.nowDate = `${year}${month}${day}}`;
    },
       // 获取展板分类列表
    getAssetCopyrightData(){
       let vm = this;
      vm.$https({
        url: "copyrightOwner/getList",
        method: "get",
        authType: this.backToken
      },
      {copyrightOwnerType:'VIDEO_CONTENT'})
        .then(res => {
          let data = res.data.data;
          this.copyrightOwner = data;
        })
        .catch(function(err) {
          console.log(err);
        });
    },
    // 获取视频分类列表
    getAssetTypeData() {
      let vm = this;
      vm.$https({
        url: "videoContentCat/getList",
        method: "get",
        authType: this.backToken
      })
        .then(res => {
          let data = res.data.data;
          this.videoContentCat = data;
        })
        .catch(function(err) {
          console.log(err);
        });
    },
    // 渲染父级权限
    getPermis() {
      let vm = this;
      vm.$https({
        method: "get",
        url: "menu/getRoleMenu?roleId=" + sessionStorage.getItem("roleId"),
        authType: this.backToken
      }).then(
        res => {
          let data = res.data;
          vm.typeList = data.map((e, i) => {
            return {
              id: e.id,
              name:
                e.menuName.indexOf("-") == -1
                  ? e.menuName
                  : e.menuName.split("-")[1]
            };
          });
        },
        error => {
          console.log(error);
        }
      );
    },
    // 获得数据接口
    getTableData(param) {
      let vm = this;
      vm.$https(
        {
          url: "asset/getPageList",
          method: "post",
          authType: this.backToken
        },
        vm.$qs.stringify(param)
        // param
      )
        .then(res => {
          let data = res.data.data;
          vm.page.pageSize = data.size;
          vm.page.total = data.total;
          vm.tableData = data.records;
        })
        .catch(function(err) {
          console.log(err);
        });
    },
    // 分页
    handleCurrentChange(val) {
      let _this = this;
      _this.page.currentPage = val;
      _this.onSearch();
    },
    onSearch() {
      let _this = this;
      let param = _this.getSearchQuery();
      _this.getTableData(param);
    },
    // 重置
    Reset(){
      this.form = {}
      this.Search()
    },
    Search() {
      let _this = this;
      _this.page.currentPage = 1;
      let searchObj = {
        _index: 1,
        _size: _this.page.pageSize,
        nameOrCode: _this.form.nameOrCode,
        videoContentCatId:_this.form.videoContentCatId,
        videoContentCopyrightOwnerId:_this.form.videoContentCopyrightOwnerId
      };
      this.getTableData(searchObj);
    },
    // // 获取当前查询参数
    getSearchQuery() {
      let _this = this;
      let searchObj = {
        _index: _this.page.currentPage,
        _size: _this.page.pageSize
      };
      for (let key in _this.form) {
        if (_this.form[key]) {
          searchObj[key] = _this.form[key];
        }
      }
      return searchObj;
    },

    // 批量操作
    handleSelectionChange(selection) {
      let _this = this;
      _this.selection = selection;
    },
    getMultipleSelect() {
      let _this = this;
      let arr = [];
      let str = "";
      if (_this.selection) {
        _this.selection.forEach(function(e) {
          arr.push(e.id);
        });
        str = arr.join(",");
        // str = arr;
      } else {
        str = "";
        // str = [];
      }
      return str;
    },
    // 汇出
    multipleRemit() {
      let _this = this;
      let str = _this.getMultipleSelect();
      //   console.log(str)
      if (str.length > 0) {
        console.log(str);
        _this.$https({
            url: "asset/download",
            method: "post",
            authType: this.backToken
          },
          // {idList:str}
          _this.$qs.stringify({idList:str})
          )
          .then(
            res => {
                const blob = new Blob([res.data], {
            type:
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'"
          })
          const downloadElement = document.createElement('a')
          const contentDisposition = res.headers['content-disposition']
          const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
          const result = patt.exec(contentDisposition)
          const filename = decodeURI(result[1])
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = filename // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放blob对象 
            },
            error => {}
          );
      } else {
        this.$message({
          type: "info",
          message: "请至少选择一个选项！"
        });
      }
    },
    openFullScreen2() {
      this.formatDate()
        const loading = this.$loading({
          lock: true,
          text: '下载中，请稍候。。。',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // setTimeout(() => {
        //   loading.close();
        // }, 2000);
      },
      // 导出机顶盒文件加密秘钥
      downloadCipher(){
          const loading = this.$loading({
          lock: true,
          text: '下载中，请稍候。。。',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        
         axios({
        method: "get",
        url: 'http://111.203.232.175:8088/mall/asset/downloadCipher',
        params: {
         
          // idList:str
        },
        headers: {
            "Authorization":  localStorage.getItem("backToken") || "",
        },
        responseType: "blob",
    }).then(res => {
        console.log(res)
        loading.close();
        let blobUrl = window.URL.createObjectURL(res.data);
        const aElement = document.createElement("a");
        aElement.href = blobUrl; 
        // aElement.download = res.data.fileName;
        aElement.download =  '密钥.zip';
        aElement.click();
        window.URL.revokeObjectURL(blobUrl);
       
    })
      },
    // get测试
       multipleRemitGet() {
        
          let _this = this;
        let str = _this.getMultipleSelect();
        if(str){
          const loading = this.$loading({
          lock: true,
          text: '下载中，请稍候。。。',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        
         axios({
        method: "get",
        url: 'http://111.203.232.175:8088/mall/asset/download',
        params: {
          // idList: "1382697227765313538"
          idList:str
        },
        headers: {
            "Authorization":  localStorage.getItem("backToken") || "",
        },
        responseType: "blob",
    }).then(res => {
        console.log(res)
        loading.close();
        let blobUrl = window.URL.createObjectURL(res.data);
        const aElement = document.createElement("a");
        aElement.href = blobUrl; 
        // aElement.download = res.data.fileName;
        aElement.download = _this.nowDate + '视频集.zip';
        aElement.click();
        window.URL.revokeObjectURL(blobUrl);
       
    })
        }else{
          this.$message({
          type: "info",
          message: "请至少选择一个选项！"
        });
        }
         
      // let _this = this;
      // let str = _this.getMultipleSelect();

      //   console.log(str);
      //   _this.$https({
      //       url: "asset/download",
      //       method: "get",
      //       authType: this.backToken,
      //   //      dataType: 'json',
      //   // responseType: 'arraybuffer' // 该条件是重点
      //       responseType: 'blob'
      //     },
      //     {idList:'1382697227765313538'}
      
      //     )
      //     .then(
      //       res => {
      //         let blobUrl = window.URL.createObjectURL(res.data);
      //   const aElement = document.createElement("a");
      //   aElement.href = blobUrl; 
      //   aElement.download = 'aaaa.zip';
      //   aElement.click();
      //   window.URL.revokeObjectURL(blobUrl);


        // const content = res
        // const blob = new Blob([content])
        // const fileName = 'electron-mat.zip'
        // if ('download' in document.createElement('a')) { // 非IE下载
        //   const elink = document.createElement('a')
        //   elink.download = fileName
        //   elink.style.display = 'none'
        //   elink.href = URL.createObjectURL(blob)
        //   document.body.appendChild(elink)
        //   elink.click()
        //   URL.revokeObjectURL(elink.href) // 释放URL 对象
        //   document.body.removeChild(elink)
        // } else { // IE10+下载
        //   // navigator.msSaveBlob(blob, fileName)
        // }

        //   const blob = new Blob([res.data], { type: 'application/zip' })
        // const url = window.URL.createObjectURL(blob)
        // window.location.href = url



        // if(typeof(res.data) == 'string'){
        //     var blob = new Blob([res.data], { type: 'application/zip' })
        //     if (window.navigator.msSaveOrOpenBlob) {//msSaveOrOpenBlob方法返回bool值
        //       navigator.msSaveBlob(blob, 'fileName');//本地保存
        //     } else {
        //       var link = document.createElement('a');//a标签下载
        //       link.href = window.URL.createObjectURL(blob);
        //       link.download = 'fileName';
        //       link.click();
        //       window.URL.revokeObjectURL(link.href);
        //     }
        //   }else{
        //   }

      //   console.log(res)
      //   const blob = new Blob([res.data], { type: 'application/zip' })
      // const url = window.URL.createObjectURL(blob)
      // const link = document.createElement('a') // 创建a标签
      // link.href = url
      // // link.download = data.fileName // 设置下载的文件名
      // document.body.appendChild(link)
      // link.click() //执行下载
      // document.body.removeChild(link) //释放标签

          // const downloadElement = document.createElement('a')
          // const contentDisposition = res.headers['content-disposition']
          // const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
          // const result = patt.exec(contentDisposition)
          // const filename = decodeURI(result[1])
          // const href = window.URL.createObjectURL(blob) // 创建下载的链接
          // downloadElement.href = href
          // downloadElement.download = filename // 下载后文件名
          // document.body.appendChild(downloadElement)
          // downloadElement.click() // 点击下载
          // document.body.removeChild(downloadElement) // 下载完成移除元素
          // window.URL.revokeObjectURL(href) // 释放blob对象 
          //   },
          //   error => {}
          // );
      // } else {
      //   this.$message({
      //     type: "info",
      //     message: "请至少选择一个选项！"
      //   });
      // }

      //   if (str) {
      //     this.$confirm("此操作将删除选中菜单, 是否继续?", "提示", {
      //       confirmButtonText: "确定",
      //       cancelButtonText: "取消",
      //       type: "warning"
      //     }).then(() => {
      //       _this
      //         .$https({
      //           url: "menu/batchDel?menuIds=" + str,
      //           method: "DELETE",
      //           authType: this.backToken
      //         })
      //         .then(
      //           res => {
      //             if (res.data.status == 201 || res.data.status == 200) {
      //               this.$message({
      //                 type: "success",
      //                 message: "删除成功!"
      //               });
      //             }
      //             //重新查询数据
      //             _this.onSearch();
      //           },
      //           error => {}
      //         );
      //     });
      //   } else {
      //     this.$message({
      //       type: "info",
      //       message: "请至少选择一个选项！"
      //     });
      //   }
    }
  }
};
</script>

<style lang="less">
// @import "../../../../style/common";
// @import "../../style/list";
@import "../../../../style/dialog.less";
@import "../../../../style/table.less";
@import "../../../../style/pagination.less";
</style>
