<template>
  <!-- 衍生组-->
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="应用选择">
        <el-select
          v-model="materialList.appId"
          placeholder="应用选择"
          clearable
          filterable
          @change="pickInformation(value)"
        >
          <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.id"
            >
            </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="80" />
      <el-table-column prop="appName" label="应用" width="100" />
      <el-table-column prop="taskName" label="衍生组名称" />
      <el-table-column prop="status" label="任务进度">
        <template slot-scope="scope">
          <span>{{ scope.row.currentNum }} / {{ scope.row.totalNum }} </span>
        </template>
      </el-table-column>
      <el-table-column prop="executeTime" label="执行时间(s)" width="100" />
      <el-table-column prop="status" label="任务状态" width="100">
        <template slot-scope="scope">
          <!--          <el-button type="text" size="small">执行</el-button>-->
          <Tag type="info" v-if="scope.row.status == 0"> 未启用 </Tag>
          <Tag type="primary" v-if="scope.row.status == 1"> 等待执行 </Tag>
          <Tag type="warning" v-else-if="scope.row.status == 2"> 执行中 </Tag>
          <Tag type="success" v-else-if="scope.row.status == 3"> 已完成 </Tag>
        </template>
      </el-table-column>
      <el-table-column prop="tip" label="提示(tip)" />
      <el-table-column
        prop="createdAt"
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 0"
            icon="el-icon-check"
            type="primary"
            size="small"
            @click="APIopenDeriveTask(scope.row.id)"
            >开始合成</el-button
          >
          <el-button
            icon="el-icon-delete"
            type="warning"
            size="small"
            @click="alert('del')"
            >删除</el-button
          >
          <el-button
            icon="el-icon-circle-plus"
            type="primary"
            size="small"
            @click="alert(`clone: ${scope.row.id}`)"
            >克隆</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详情的弹窗 -->
    <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"
      width="70%"
      title="创建衍生任务"
      top="2vh"
      center
    >
      <el-form>
        <el-form-item label="衍生任务名称:">
          <el-input
            v-model="deriveTask.taskName"
            style="width: 200px"
          ></el-input>
        </el-form-item>

        <el-form-item label="选择应用:">
          <el-select
            v-model="deriveTask.appId"
            filterable
            clearable
            placeholder="请选择"
            @change="pickInformation(value)"
          >
            <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.id"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="视频声明文案:">
          <el-input v-model="deriveTask.tip" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>

      <h2 style="margin-top: 20px; margin-bottom: 10px">添加文案</h2>
      <div style="border: 1px solid blue; padding: 30px">
        <el-tag
          :key="tag"
          v-for="tag in textContainer"
          closable
          :disable-transitions="false"
          @close="handleClose2(tag)"
          @click="tagEdit(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          size="medium"
          v-if="inputVisible2"
          v-model="inputValue2"
          ref="saveTagInput2"
          @keyup.enter.native="handleInputConfirm2"
          @blur="handleInputConfirm2"
          style="width: 600px"
        >
        </el-input>
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          @click="showInput2"
        >
          + 添加
        </el-button>

        <!-- 选取文案子组件 -->
        <span class="outer-father">
          <!-- 子组件 选取文案列表 -->
          <select-text
            class="select-text"
            @selectData="receiveData"
            :appId="selectAppId"
          />
        </span>
      </div>

      <div>
        <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[5]"
                      />
                      <div>视频</div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </el-tab-pane>
        </el-tabs>
      </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
      :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
                v-if="item.resType === 2"
                :src="item.optionCovers[5]"
                class="Materiallist_img"
                fit="scale-down"
                @click="Preview(item)"
                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>
      <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>

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

.el-checkbox {
  display: flex;
}

.outer-father {
  display: inline-block;
}
</style>

<script>
import {
  getEnums,
  getSelectApps,
  getGrouplist,
  getBusinlist,
  getCreateOrUpdate,
  deriveTask,
  createDeriveTask,
  openDeriveTask,
} from "@/api/cloud";

import SelectText from "@/views/createDelivery/childComponents/SelectText";

export default {
  data() {
    return {
      selectAppId: "", // 传递给子组件的appid
      deriveTask: {
        taskName: "",
        appId: "",
        tip: "",
      },
      textContainer: [],
      videoContainer: [],
      inputVisible2: false,
      inputValue2: "",

      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: false,
      dialogVideoVisible: false, //查看素材视频弹窗是否可视
      VideoUrl: "", //视频链接

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

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

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

  components: {
    SelectText,
  },

  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();
    },

    showInput2() {
      this.inputVisible2 = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput2.$refs.input.focus();
      });
    },
    handleInputConfirm2() {
      let inputValue2 = this.inputValue2;
      if (inputValue2) {
        this.textContainer.push(inputValue2);
      }
      this.inputVisible2 = false;
      this.inputValue2 = "";
      console.log("衍生文案列表：", this.textContainer);
    },
    handleClose2(tag) {
      this.textContainer.splice(this.textContainer.indexOf(tag), 1);
    },
    APIopenDeriveTask(id) {
      openDeriveTask({ deriveTaskId: id }).then((resp) => {
        this.$Message.success(`开启[${id}]成功`);
        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;

      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);
        }
      }

      console.log(22222, this.options2List);
    },

    // 选择类别
    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;
    },

    checkDetails: function (item) {
      return;
      // this.is_checkDetails = true;
      // this.videoList = item.items;
      // console.log(JSON.stringify(item, null, 2));
    },

    // 创建素材
    createFrom() {
      this.dialogFormVideo = true;
    },

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

    // 获取创意素材组列表
    APIgetgrouplist() {
      console.log("衍生任务列表");
      const params = {
        appId: this.materialList.appId,
        page: this.materialList.page,
        size: this.materialList.size,
      };
      deriveTask(params).then((res) => {
        console.log("衍生任务列表：", res.result.data);
        this.newGetList = res.result.data;
      });
    },

    // 获取素材的列表
    pickInformation(value) {
      console.log("选取应用：", value);
      console.log(this.formLabelAlign.value);
      this.establish.pkg = this.formLabelAlign.value;
      console.log(this.establish.pkg);

      this.selectAppId = this.deriveTask.appId + ""; // 传递给子组件的appid
    },

    materialName() {
      console.log(this.formLabelAlign.name);
      this.establish.materialName = this.formLabelAlign.name;
    },

    // 上传文件返回的url
    uploadSuccess(response, file) {
      console.log("本地上传返回的URL" + response.result.data.url);
      this.establish.coverUrl = response.result.data.url;
      console.log(this.establish.coverUrl);
    },

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

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

    // 从素材库选取
    APIgetBusinlis() {
      let params = {
        page: this.material.page,
        size: this.material.size,
        appId: this.deriveTask.appId,
        materialCategory: this.material.materialCategory,
        appCategory: this.material.appCategory,
        excludeSource: 3,
      };
      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();
    },

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

    // 获取默认的全局信息
    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;
    },

    // 删除
    deleteMaterial(item) {
      console.log(item, this.options2);

      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.splice(j, 1);
          }
        }
      }

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

    // 图片点击选取封面
    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: function () {
      let items = [];

      console.log(11114444, this.options2);
      for (let i = 0; i < this.options2.length; i++) {
        for (let j = 0; j < this.options2[i].list.length; j++) {
          let obj = {
            type: 2,
            materialCategory: this.options2[i].list[j].materialCategory,
            mbId: this.options2[i].list[j].id,
            url: this.options2[i].list[j].url,
            // resType: this.options2[i].list[j].resType
          };
          items.push(obj);
        }
      }

      let texts = this.textContainer;
      let textItems = texts.map((t) => {
        return { type: 1, text: t };
      });
      items.push.apply(items, textItems);

      let params = {
        ...this.deriveTask,
        items: items,
      };

      console.log(JSON.stringify(params, null, 4));
      createDeriveTask({
        ...params,
      }).then((res) => {
        if (res.status === 200) {
          this.dialogFormVideo = false;
          this.APIgetgrouplist();

          // deriveTask: {
          //   taskName: "",
          //     appId: '',
          //     tip: '',
          // },
          // textContainer: [],
          //   videoContainer: [],
          this.deriveTask.taskName = "";
          this.deriveTask.appId = "";
          this.deriveTask.tip = "";
          this.textContainer = [];
          this.videoContainer = [];
        }
      });
    },

    /* 接收子组件传递过来的文案数据 */
    receiveData(textData) {
      textData.forEach((item) => {
        if (this.textContainer.indexOf(item) === -1) {
          this.textContainer.push(item);
        }
      });
    },

    /* tag标签实现编辑功能 */
    tagEdit(value) {
      // 他的逻辑就是表单回弹
      this.inputVisible2 = true;
      this.handleClose2(value);
      this.inputValue2 = value;
      this.$nextTick((_) => {
        this.$refs.saveTagInput2.$refs.input.focus();
      });
    },
  },
};
</script>

<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 .sourceMaterial_con {
  flex: 1;
  overflow: hidden;
  position: relative;
  border: 1px solid #dddddd;
}
.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;
}

.input-new-tag {
  width: 90px;
  margin-right: 10px;
  vertical-align: bottom;
}
</style>

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