<template>
  <!-- 素材组-->
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="应用选择">
        <el-select
          v-model="materialList.pkg"
          placeholder="应用选择"
          clearable
          filterable
        >
          <el-option-group
            v-for="(group, index) in selectApps"
            :key="index"
            :label="group.value"
          >
            <el-option
              v-for="item in group"
              :key="item.index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="APIgetgrouplist">查询</el-button>
      <el-button type="primary" @click="createFrom">创建素材组</el-button>
    </el-form>

    <!-- 内容-->
    <el-table :data="newGetList" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="pkg" label="pkg" />
      <el-table-column prop="materialGroupName" label="素材组名称" />
      <el-table-column prop="countDesc" label="描述" />

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="primary"
            @click="handleDetails(scope.row)"
          >
            编辑
          </el-button>
          <el-button size="medium" type="danger"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 素材组分页底栏 -->
    <el-pagination
      @size-change="materialGroupSizeChange"
      @current-change="materialGroupCurPageChange"
      :current-page="materialList.page"
      :page-sizes="[10, 20, 50, 80]"
      :page-size="materialList.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="materialList.total"
      style="text-align: center"
    >
    </el-pagination>

    <!-- 查看详情的弹窗 -->
    <el-dialog center :visible.sync="is_checkDetails">
      <template v-for="item of videoList">
        <div
          style="border-bottom: 1px solid #666; margin-bottom: 30px"
          :key="item.id"
        >
          <video :src="item.url" autoplay loop></video>
          <div>
            <template v-for="(items, indexs) of item.optionCovers">
              <el-image
                style="width: 80px; height: 80px"
                :src="items"
                fit="contain"
                :key="indexs"
              />
            </template>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 创建素材组弹框 -->
    <el-dialog
      :visible.sync="dialogFormVideo"
      :close-on-click-modal="false"
      title="创建素材组"
      top="2vh"
      width="70%"
      center
    >
      <el-form>
        <el-form-item label="素材组名称">
          <el-input v-model="materialGroupName" style="width: 200px"></el-input>
        </el-form-item>

        <el-form-item label="选择应用">
          <el-select v-model="pkg" clearable filterable placeholder="请选择">
            <el-option-group
              v-for="(group, index) in selectApps"
              :key="index"
              :label="group.label"
            >
              <el-option
                v-for="item in group"
                :key="item.index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </el-form>

      <h2 style="margin: 20px 0 10px">添加素材</h2>
      <el-tabs v-model="message" type="border-card" @tab-click="handleClick">
        <el-tab-pane
          v-for="(item, index) in options2"
          :key="index"
          :label="item.label"
          :name="item.value"
        >
          <div>
            <el-button
              size="small"
              style="margin-bottom: 20px"
              type="primary"
              @click="materialGrab(2)"
              >选取素材</el-button
            >
          </div>

          <div
            v-if="options2List.length !== 0"
            style="
              width: 100%;
              height: 400px;
              overflow-y: scroll;
              border: 1px dashed #409eff;
              padding: 20px 0;
            "
          >
            <template v-for="(stated, index) in options2List">
              <div
                style="
                  display: flex;
                  float: left;
                  position: relative;
                  margin: 0 15px 10px 15px;
                "
                :key="index"
              >
                <i
                  class="el-icon-circle-close"
                  @click="deleteMaterial(stated)"
                ></i>
                <div style="border: 1px solid #dddddd" class="sourceMaterial">
                  <div class="sourceMaterial_con">
                    <img v-if="stated.resType === 1" :src="stated.url" alt="" />
                    <img
                      v-if="stated.resType === 2"
                      :src="stated.optionCovers[4]"
                    />
                    <div v-if="stated.resType === 1">图片</div>
                    <div v-if="stated.resType === 2">视频</div>
                  </div>

                  <div v-if="stated.resType === 2" class="sourceMaterial_con">
                    <img
                      :src="stated.coverUrl || stated.optionCovers[5]"
                      @click="SelectPhotos(stated)"
                    />
                    <div>封面</div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogFormVideo = false;
            options2List = [];
          "
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="createMaterial"
          :disabled="submitBtnState"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <!-- 素材库选取素材 -->
    <el-dialog
      :visible.sync="dialogFormInformation"
      center
      :close-on-click-modal="false"
      width="90%"
      top="2vh"
      title="素材库列表"
    >
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        >全选</el-checkbox
      >
      <el-checkbox-group
        v-model="checkedCities"
        @change="handleCheckedCitiesChange"
        v-if="cities.length !== 0"
      >
        <el-checkbox v-for="item in cities" :label="item" :key="item.id">
          <div class="Materiallist">
            <div>
              <el-image
                v-if="item.resType === 1"
                class="Materiallist_img"
                :src="item.url"
                fit="scale-down"
                lazy
              />
              <el-image
                class="Materiallist_img"
                v-if="item.resType === 2"
                :src="item.optionCovers[5]"
                @click="Preview(item)"
                fit="scale-down"
                lazy
              ></el-image>
            </div>
            <div>{{ item.updatedAt }}</div>
            <div>{{ item.materialName }}</div>
            <div v-if="item.score != null" class="triangle"></div>
            <div v-if="item.score != null" class="triangle-text">推荐</div>
          </div>
        </el-checkbox>
      </el-checkbox-group>

      <el-pagination
        :total="material.total"
        :page-size="material.size"
        :current-page="material.page"
        style="text-align: center; margin-top: 20px"
        layout="total, prev, pager, next, sizes"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelList">取 消</el-button>
        <el-button type="primary" @click="pickList"> 确定 </el-button>
      </span>
    </el-dialog>

    <!-- 封面选取 -->
    <el-dialog :visible.sync="dialogFormImage" title="选取封面">
      <div
        v-for="(item, index) in selectPicture"
        :key="index"
        class="selectionImg"
        :class="{ active: index == isShow }"
        @click="selectcover(item, index)"
      >
        <img :src="item" style="max-width: 100%; height: auto" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormImage = false">取 消</el-button>
        <el-button type="primary" @click="coverSelection">确定</el-button>
      </span>
    </el-dialog>

    <!-- 视频弹窗 -->
    <el-dialog
      :visible.sync="dialogVideoVisible"
      @opened="openVideo"
      @close="closeVideoDialog"
      top="2vh"
      title="查看视频"
      center
    >
      <video
        :src="VideoUrl"
        ref="videoRef"
        controls
        preload
        width="600px"
        height="600px"
        autoplay
      ></video>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEnums,
  getSelectApps,
  getGrouplist,
  getBusinlist,
  getCreateOrUpdate,
  getShowParams, // 根据id 回显素材组数据
} from "@/api/cloud";
export default {
  data() {
    return {
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: false,
      dialogVideoVisible: false, //查看素材视频弹窗是否可视
      VideoUrl: "", //视频链接
      submitBtnState: false, //提交按钮状态

      // +++++++++++++++++++++++++++++++++++++++=
      stated: {}, // 给某个素材选封面
      videoList: [], // 查看详情的视频数组
      is_checkDetails: false, // 控制查看弹窗的显示隐藏
      checkDetailsItem: {}, // 查看某条数据详情
      materialGroupName: "",
      pkg: "",

      newGetList: [],
      options2: [],
      options2List: [],
      value: "",
      dialogFormVideo: false,
      selectApps: [],
      message: "",
      uploadUrl: process.env.PUTIN_API + "/v1/global/upload",
      fileList: [],
      itemForm: {
        resType: "image",
        file: "",
      },
      uploadMaterialurl: "",
      materialList: {
        pkg: "",
        page: 1,
        size: 10,
        total: 0,
      },

      // 从素材选取素材的弹框参数
      checkAll: false,
      dialogFormInformation: false,
      material: {
        source: null,
        page: 1,
        size: 50,
        materialCategory: "verticalVideo",
        appCategory: "",
        total: null,
      },
      singleChoice: [],
      dialogFormImage: false,
      selectPicture: [],
      isShow: -1,
      // 创建素材组的参数
      establish: {},
      coverUrl: "",
      editId: "", // 编辑回显id
    };
  },

  created() {
    this.APIGetEnums();
    this.APIgetSelectApps();
    this.APIgetgrouplist();
  },

  methods: {
    /* 点击预览视频 */
    Preview(item) {
      if (item.resType === 2) {
        this.VideoUrl = item.url;
        this.dialogVideoVisible = true;
      } else {
        this.$message.error("播放源不是视频！");
      }
    },
    //打开视频
    openVideo() {
      if (("openVideo", this.$refs.videoRef.paused)) {
        this.$refs.videoRef.play();
      }
    },
    //关闭视频
    closeVideoDialog() {
      this.$refs.videoRef.pause();
    },

    /* 修改获取素材组的大小size */
    materialGroupSizeChange(val) {
      this.materialList.size = val;
      this.APIgetgrouplist();
    },

    /* 修改获取素材组的页数 */
    materialGroupCurPageChange(val) {
      this.materialList.page = val;
      this.APIgetgrouplist();
    },

    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : [];
      this.isIndeterminate = false;
    },

    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },

    // 素材库确认按钮
    pickList() {
      this.dialogFormInformation = false;
      this.checkAll = false;

      for (let i = 0; i < this.options2.length; i++) {
        if (this.message === this.options2[i].value) {
          this.options2[i].list = this.options2[i].list.concat(
            this.checkedCities
          );
          this.options2List = this.options2List.concat(this.checkedCities);
        }
      }
    },

    // 选择类别
    handleClick(tab) {
      this.material.materialCategory = tab.name;

      for (let i = 0; i < this.options2.length; i++) {
        if (tab.name == this.options2[i].value) {
          this.options2List = this.options2[i].list;
        }
      }
    },

    // 弹框素材库取消
    cancelList() {
      this.dialogFormInformation = false;
      this.checkAll = false;
    },

    // 详情按钮
    handleDetails: function (item) {
      this.dialogFormVideo = true;
      this.editId = item.id;

      // 根据 id 请求  回显素材
      getShowParams({ groupId: item.id }).then((res) => {
        // 回显
        this.options2List = res.result.data.content[0].items;
        this.pkg = res.result.data.content[0].pkg;
        this.materialGroupName = res.result.data.content[0].materialGroupName;
        this.options2.map((item, index) => {
          if (item.value == this.message) {
            this.options2[index].list = res.result.data.content[0].items;
          }
        });
      });
    },

    // 创建素材
    createFrom() {
      this.materialGroupName = "";
      this.pkg = "";
      this.dialogFormVideo = true;
      this.options2List = [];
    },

    // 创意素材组获取列表
    APIgetSelectApps() {
      const params = {
        platformId: 5,
        menuCode: "game.Overview,android",
        isGroup: "group",
      };
      getSelectApps(params).then((res) => {
        this.selectApps = res.result.data;
      });
    },

    // 获取创意素材组列表
    APIgetgrouplist() {
      const params = {
        pkg: this.materialList.pkg,
        page: this.materialList.page,
        size: this.materialList.size,
      };
      getGrouplist(params)
        .then((res) => {
          if (res.status == 200) {
            this.newGetList = res.result.data.content;
            this.materialList.total = res.result.data.total;
          } else {
            this.$message.error(`请求失败，错误代码：${res.status}`);
          }
        })
        .catch((err) => {
          this.$message.error(err);
          console.log(err);
        });
    },

    // 上传文件返回的url
    uploadSuccess(response, file) {
      this.establish.coverUrl = response.result.data.url;
    },

    //  上传图片 视频传递的参数
    beforeUpload(file) {
      // console.log(file, file.name);
      this.itemForm.file = file.name;
    },

    // 从素材库选取文件
    materialGrab(source) {
      if (this.pkg === "") {
        this.$message.warning("请选择应用");
        return;
      }
      this.checkedCities = []; // 清空
      this.dialogFormInformation = true;
      this.APIgetBusinlis();
    },

    // 从素材库选取
    APIgetBusinlis() {
      let params = {
        page: this.material.page,
        size: this.material.size,
        pkg: this.pkg,
        materialCategory: this.material.materialCategory,
        appCategory: this.material.appCategory,
        source: this.material.source,
      };
      getBusinlist(params).then((res) => {
        this.cities = res.result.data.content;
        this.material.total = res.result.data.total;
      });
    },

    // 分页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`, this.val);
      this.material.page = val;
      this.APIgetBusinlis();
      this.checkAll = false;
    },

    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.material.size = val;
      this.APIgetBusinlis();
      this.checkAll = false;
    },

    // 获取默认的全局信息
    APIGetEnums() {
      getEnums().then((res) => {
        this.options2 = res.result.data.materialType;
        this.message = this.options2[0].value;

        for (let i = 0; i < this.options2.length; i++) {
          this.options2[i].list = [];
        }
      });
    },

    // 更换封面
    SelectPhotos(stated) {
      this.isShow = -1;
      this.stated = stated;
      this.selectPicture = stated.optionCovers;
      this.dialogFormImage = true;
      console.log("state", stated);
    },

    // 删除
    deleteMaterial(item) {
      for (let i = 0; i < this.options2.length; i++) {
        for (let j = 0; j < this.options2[i].list.length; j++) {
          if (this.options2[i].list[j].id === item.id) {
            this.options2[i].list.splice(j, 1);
            this.options2List = this.options2[i].list;
          }
        }
      }
    },

    // 图片点击选取封面
    selectcover(item, index) {
      for (let i = 0; i < this.singleChoice.length; i++) {
        if (this.singleChoice[i].id === this.stated.id) {
          this.singleChoice[i].coverUrl = item;
        }
      }

      this.coverUrl = item;
      this.isShow = index;
    },

    coverSelection() {
      for (let i = 0; i < this.options2List.length; i++) {
        if (this.options2List[i].id === this.stated.id) {
          this.options2List[i].coverUrl = this.coverUrl;
        }
      }

      this.dialogFormImage = false;
    },

    // 提交
    createMaterial() {
      let items = [];
      this.submitBtnState = true; //提交后不能再次提交

      this.options2.map((item) => {
        if (item.list.length > 0) {
          item.list.map((option) => {
            let obj = {
              coverUrl:
                option.resType === 2
                  ? option.coverUrl || option.optionCovers[0]
                  : "",
              materialId: option.id,
              resType: option.resType,
            };
            items.push(obj);
          });
        }
      });

      let params = {
        pkg: this.pkg,
        materialGroupName: this.materialGroupName,
        items: items,
      };

      if (this.editId && this.editId != "") {
        params.id = this.editId;
      }

      getCreateOrUpdate({
        ...params,
      })
        .then((res) => {
          if (res.status === 200) {
            this.dialogFormVideo = false;
            this.$message.success("提交成功！");
            this.APIgetgrouplist();
          } else {
            this.$message.error("请填写素材组名并选择应用！");
          }
          this.submitBtnState = false;
          this.editId = ""; // 将id标识给清空
        })
        .catch((err) => {
          this.$message.error("网络错误，提交失败...");
          console.log(err);
          this.submitBtnState = false;
          this.editId = ""; // 将id标识给清空
        });
    },
  },
};
</script>

<style scoped>
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  overflow-y: scroll;
  height: 65vh;
}

.el-checkbox {
  display: flex;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.Materia {
  overflow: hidden;
}

.Materiallist {
  position: relative;
  overflow: hidden;
  width: 200px;
  border: 1px solid rgb(201, 201, 201);
  padding: 6px 5px;
  box-sizing: border-box;
  display: inline-block;
  margin: 0 18px 20px 18px;
  color: #606266;
}

.Materiallist .Materiallist_img {
  width: 200px;
  height: 100px;
  text-align: center;
}
.Materiallist .Materiallist_text {
  font-size: 14px;
  line-height: 20px;
  text-align: left;
}
.MateriallistApplication {
  display: flex;
  justify-items: center;
  align-items: center;
}
.MateriallistApplication .MateriallistApplication_img {
  width: 40px;
  height: 40px;
  margin-right: 6px;
}

.font_overflow {
  overflow: hidden;
  text-overflow: ellipsis; // 超出显示
  display: -webkit-box; // 将元素作为弹性伸缩盒子模型显示 。
  -webkit-line-clamp: 1; // 用来限制在一个块元素显示的文本的行数
  -webkit-box-orient: vertical; // 设置或检索伸缩盒对象的子元素的排列方式
}
.sourceMaterial {
  padding: 10px;
  display: flex;
  flex: 1;
  overflow: hidden;
  position: relative;
  border: 1px solid #dddddd;
}

.sourceMaterial_con {
  border: 1px solid gainsboro;
  padding: 5px;
  margin: 0 5px;
}
.sourceMaterial img,
.sourceMaterial video {
  width: 110px;
}
.sourceMaterial_title {
  position: absolute;
  text-align: center;
  top: 27px;
  left: 50%;
  margin-left: -28px;
  z-index: 999;
  color: #000000;
}
.el-icon-circle-close {
  position: absolute;
  font-size: 18px;
  z-index: 999;
  right: -6px;
  top: -6px;
}

.selectionImg {
  width: 100px;
  float: left;
  margin: 10px;
  display: block;
  border: 2px solid #cccccc;
  border-radius: 4px;
  overflow: hidden;
}
.active {
  border: 2px solid red;
}

.triangle {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  border-left: 50px solid rgba(64, 158, 255, 1);
  border-bottom: 50px solid transparent;
  z-index: 0;
}
.triangle-text {
  position: absolute;
  left: 0;
  top: 3px;
  color: #fff;
}
</style>

<style>
.el-dialog .el-dialog__body {
  display: inline-block;
}
</style>
