<template>
  <div>
    <el-dialog
      :visible.sync="dialogFormVideo"
      close-on-click-modal
      title="创建素材组"
      top="2vh"
      width="70%"
      center
      @close="closeDialog"
    >
      <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>添加素材</h2>
      <el-button type="primary" size="small" @click="selectMaterial"
        >+ 选取素材</el-button
      >
      <div v-if="items && items.length !== 0" class="outer-border">
        <div
          v-for="(stated, index) in items"
          :key="index"
          class="sourceMaterial"
        >
          <div class="sourceMaterial" style="border: 1px solid gainsboro">
            <i
              class="el-icon-circle-close"
              @click="deleteMaterial(stated.id)"
            ></i>
            <div class="sourceMaterial_con">
              <img v-if="stated.resType === 1" :src="stated.url" alt="" />
              <!-- <video
                      v-if="stated.resType === 2"
                      :src="stated.url"
                    ></video> -->
              <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>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVideo = false">取 消</el-button>
        <el-button type="primary" @click="createMaterial">确定</el-button>
      </span>
    </el-dialog>

    <!-- 选取素材弹框 -->
    <el-dialog title="素材分类" :visible.sync="dialogVisible" width="65%">
      <el-tabs
        v-model="tabOptions"
        type="border-card"
        @tab-click="handleTabClick"
      >
        <el-tab-pane
          v-for="(item, index) in tabOptionsArr"
          :key="index"
          :label="item.label"
          :name="item.value"
        >
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="checkedMaterial"
            @change="handleCheckedMaterialChange"
          >
            <el-checkbox
              v-for="(item, index) in materialList"
              :label="item"
              :key="index"
              class="MateriaCheck"
              id="MateriaCheck"
            >
              <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]"
                    fit="scale-down"
                    lazy
                  ></el-image>
                </div>
                <div>{{ item.updatedAt }}</div>
                <div>{{ item.materialName }}</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>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ensure">确 定</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>
  </div>
</template>

<script>
import {
  getSelectApps,
  getEnums,
  getBusinlist,
  getCreateOrUpdate,
} from "@/api/cloud";
export default {
  props: {
    dialogFormVideo: {
      type: Boolean,
      default: "false",
    },

    /* 获取父组件中传过来的Id */
    // selectedAllList: {
    //   type: Array,
    //   default() {
    //     return [];
    //   },
    // },

    /* 获取父组件传过来的需要添加到素材组的素材 */
    items: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      materialGroupName: "", // 素材组名称
      selectApps: [], // 选择应用
      pkg: "",
      dialogVisible: false, // 控制选取素材弹框
      tabOptions: "", // 素材分类value
      tabOptionsArr: [], // 素材分类列表
      /* 请求素材所需参数 */
      material: {
        source: null,
        page: 1,
        size: 10,
        materialCategory: "verticalVideo",
        appCategory: "",
        total: null,
      },
      materialList: [], // 素材列表
      checkedMaterial: [], // 被选中的素材
      dialogFormImage: false, // 控制选取封面弹窗
      selectPicture: [], // 选择图片
      isShow: -1,
      singleChoice: [],
      coverUrl: "",
      isIndeterminate: false,
      checkAll: false,
    };
  },
  created() {
    this.APIgetSelectApps(); // 获取创意素材组列表
    this.APIGetEnums();
  },
  methods: {
    /* 数据获取 */

    // 创意素材组获取列表
    APIgetSelectApps() {
      const params = {
        platformId: 4,
        menuCode: "putin.apps",
        isGroup: "group",
      };
      getSelectApps(params).then((res) => {
        // console.log("创意素材组下的下拉列表", res);
        this.selectApps = res.result.data;
      });
    },

    /* 这里我是为了得到 素材的分类 */
    APIGetEnums() {
      getEnums().then((res) => {
        // console.log("enums", res);
        this.tabOptionsArr = res.result.data.materialType;
        this.tabOptions = this.tabOptionsArr[0].value;
      });
    },

    // 从素材库选取素材
    APIgetBusinlist() {
      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) => {
        console.log("从素材库获取的素材", res);
        this.materialList = res.result.data.content;
        this.material.total = res.result.data.total;
        console.log("获取的素材列表", this.materialList);
      });
    },

    /***********************/

    /* 取消创建素材组按钮 */
    closeDialog() {
      this.$emit("closeDialog");
    },

    /* 去除选中的素材 */
    deleteMaterial(id) {
      this.items.forEach((item, index) => {
        if (item.id === id) {
          this.$emit("deleteMaterial", index);
        }
      });
    },

    /* 选取素材弹窗 */
    selectMaterial() {
      if (this.pkg) {
        this.dialogVisible = true; // 打开素材选取弹窗
        /* 获取素材 */
        this.APIgetBusinlist();
        this.checkedMaterial = []; // 让之前选取的值为空
      } else {
        this.$message.error("请选择应用！");
      }
      this.checkAll = false; // 进入弹窗关闭掉全选按钮
    },

    /* 选取素材时 分页重新请求数据 */
    handleCurrentChange(val) {
      console.log(`这是${val}页`);
      this.material.page = val;
      this.APIgetBusinlist();
      this.checkAll = false;
    },

    /* 当每页有多少条改变时 重新请求数据 */
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.material.size = val;
      this.APIgetBusinlist();
      this.checkAll = false;
    },

    /* 当切换tab 时重新请求数据 */
    handleTabClick(tab) {
      console.log("tab", tab);
      this.material.materialCategory = tab.name;
      this.APIgetBusinlist();
    },

    /* 当素材被选中时 */
    handleCheckedMaterialChange(value) {
      console.log("被选中", value);
      console.log("被选中", this.checkedMaterial);
    },

    /* 将选中的值传给父组件 让父组件的items拼接上在传过来 */
    ensure() {
      this.dialogVisible = false;
      console.log("zzzzzz", this.checkedMaterial);
      this.$emit("ensureMaterial", this.checkedMaterial);
    },

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

    /* 图片点击选取封面 */
    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;
      console.log("cover", this.coverUrl);
      this.isShow = index;
    },

    /* 选取封面的确定按钮 */
    coverSelection() {
      console.log(1111111, this.items);
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].id === this.stated.id) {
          this.items[i].coverUrl = this.coverUrl;
        }
      }
      this.dialogFormImage = false;
    },

    /* 确定创建素材组 */
    createMaterial() {
      let paramsItem = [];
      this.items.forEach((i) => {
        let coverUrl = i.resType === 2 ? i.coverUrl || i.optionCovers[4] : "";
        let obj = {
          coverUrl: coverUrl,
          materialId: i.id,
          resType: i.resType,
        };
        if (obj.coverUrl) paramsItem.push(obj);
      });

      console.log("paramsItem", paramsItem);
      /* 发送请求 */
      let params = {
        pkg: this.pkg,
        materialGroupName: this.materialGroupName,
        items: paramsItem,
      };
      getCreateOrUpdate({
        ...params,
      })
        .then((res) => {
          if (res.status === 200) {
            this.closeDialog();
            this.$message.success("提交成功！");
            // this.APIgetgrouplist();
          } else {
            this.$message.error("请填写素材组名并选择应用！");
          }
        })
        .catch((err) => {
          this.$message.error("网络错误，提交失败...");

          console.log(err);
        });
    },

    // 全选按钮
    handleCheckAllChange(val) {
      if (this.checkAll) {
        this.checkedMaterial = [];
        this.checkedMaterial = this.materialList;
      } else {
        this.checkedMaterial = [];
      }
    },
  },
};
</script>

<style scoped>
.outer-border {
  width: 650px;
  margin-top: 15px;
  border: 1px solid #dddddd;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);
}

.sourceMaterial {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  position: relative;
}

.sourceMaterial_con {
  border: 1px solid gainsboro;
  padding: 15px 5px;
  margin: 0 5px;
}

.sourceMaterial img,
.sourceMaterial video {
  width: 110px;
}

.el-icon-circle-close {
  position: absolute;
  font-size: 18px;
  z-index: 999;
  right: -10px;
  top: -10px;
}

.el-icon-circle-close:hover {
  cursor: pointer;
  color: skyblue;
}

.MateriaCheck {
  margin: 20px;
}

#MateriaCheck .el-checkbox__input {
  position: absolute;
  right: 10%;
  top: 5%;
}

#MateriaCheck .el-checkbox__label {
  padding-left: 0;
}

.Materiallist {
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #eeeeee;
  color: #606266;
}

.Materiallist .Materiallist_img {
  width: 200px;
  height: 100px;
  text-align: center;
}

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

.active {
  border: 2px solid red;
}
</style>
