<template>
  <div calss="app-container">
    <div class="content">
      <el-form :inline="true">
        <el-form-item label="应用类型">
          <el-select
            v-model="condition.appCategory"
            clearable
            filterable
            placeholder="应用类型"
          >
            <el-option-group
              v-for="group in options1"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.children"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="抓取应用">
          <el-select
            v-model="condition.appId"
            placeholder="抓取应用"
            clearable
            filterable
          >
            <el-option
              v-for="(item1, index) in options"
              :key="index"
              :label="item1.label"
              :value="item1.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName1">
        <el-tab-pane label="创意素材" name="firsts"></el-tab-pane>
        <el-tab-pane label="创意文案" name="seconds"></el-tab-pane>
      </el-tabs>
      <!-- 创意素材 -->
      <div v-if="activeName1 == 'firsts'">
        <el-form :inline="true">
          <el-form-item label="素材分类">
            <el-select
              v-model="FormGetList.materialCategory"
              clearable
              placeholder="请选择"
              @change="getPictureSizeLsit(FormGetList.materialCategory)"
            >
              <el-option
                v-for="(item, index) in options2"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="尺寸筛选">
            <el-select
              v-model="FormGetList.materialSize"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in pictureSizeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="清洗状态">
            <el-select
              v-model="FormGetList.ifClean"
              clearable
              placeholder="素材状态"
            >
              <el-option
                v-for="(item, index) in CleaningState"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fosno" label="日期">
            <el-date-picker
              format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              :picker-options="pickerOptions2"
              v-model="FormGetList.time"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="startTime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData()">查询</el-button>
          </el-form-item>
          <el-checkbox
            :indeterminate="isIndeterminated"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选所有筛选项</el-checkbox
          >
          <el-button type="danger" @click="Delete">删除</el-button>

          <el-popconfirm
            confirmButtonText="好的"
            cancelButtonText="不用了"
            icon="el-icon-info"
            iconColor="red"
            @onConfirm="cleaning"
            title="素材清洗目前仅支持图片类型，确定清洗吗？"
          >
            <el-button slot="reference" style="margin: 0 20px">清洗</el-button>
          </el-popconfirm>

          <el-button
            type="primary"
            @click="addMaterial"
            style="margin-bottom: 20px"
            >添加到素材库</el-button
          >
        </el-form>

        <el-dialog :visible.sync="dialogFormVisible">
          <el-form>
            <el-form-item label="选择应用">
              <el-select
                v-model="appId"
                filterable
                clearable
                placeholder="请选择"
                style="width: 200px"
              >
                <el-option
                  v-for="item in pkgList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="getoriginedit">确 定</el-button>
          </div>
        </el-dialog>

        <el-checkbox-group
          v-loading="loading"
          v-model="selectedAllList"
          class="Materia"
        >
          <el-checkbox
            v-for="(item, index) in newGetList"
            id="MateriaCheck"
            :key="index"
            style="margin-bottom: 20px; margin-right: 0"
            :label="item.id"
            @change="handleCheckedCitiesChange(item)"
          >
            <div class="Materiallist">
              <p class="Subscript">
                {{
                  item.ifClean == 0
                    ? "未清洗"
                    : item.ifClean == "1"
                    ? "已清洗"
                    : ""
                }}
              </p>
              <div
                style="height: 141px; display: flex"
                @click.stop="Preview(item)"
              >
                <img
                  v-if="item.resType == 1"
                  class="Materiallist_img"
                  :src="item.washedUrl"
                  alt=""
                />
                <video
                  v-if="item.resType == 2"
                  :src="item.url"
                  class="Materiallist_img"
                ></video>
                <i v-if="item.resType == 2" class="el-icon-video-play"></i>
              </div>
              <p class="Materiallist_text font_spacing">
                {{ item.findDate }} - {{ item.lastDate }}
              </p>

              <p class="Materiallist_title font_spacing">
                {{ item.materialName }}
              </p>

              <div class="MateriallistApplication">
                <img
                  :src="item.logo"
                  alt=""
                  class="MateriallistApplication_img"
                />
                <p class="Materiallist_text font_overflow">
                  {{ item.appName }}
                </p>
              </div>
            </div>
          </el-checkbox>
        </el-checkbox-group>

        <!-- 分页 -->
        <div>
          <el-pagination
            background
            style="text-align: right; margin-top: 20px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="pageSizes"
            :page-size="size"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 创意文案-->
      <div v-if="activeName1 == 'seconds'">
        <el-row style="margin-bottom: 20px">
          <!--<el-input v-model="textKeyWord" placeholder="关键词过滤"></el-input>-->
          <el-button type="primary" @click="addCopywriting" style="float: right"
            >添加至文案</el-button
          >
          <el-button type="danger" style="float: right" @click="deleCopy"
            >删除</el-button
          >
          <el-checkbox
            style="float: right; line-height: 43px"
            v-model="copyCheckAll"
            @change="entireCopy"
            >全选当前筛选项</el-checkbox
          >
        </el-row>
        <el-checkbox-group v-model="checkedCities">
          <el-checkbox
            v-for="(inText, index) in newGetText"
            style="margin-bottom: 20px; width: 100%"
            :key="index"
            :label="inText.id"
            @change="selectedCopy(inText, index)"
          >
            <el-input
              ref="saveTagInput"
              placeholder="请输入内容"
              style="width: 500px"
              v-model="inText.text"
            ></el-input>
          </el-checkbox>
        </el-checkbox-group>

        <div>
          <el-pagination
            background
            style="text-align: right; margin-top: 20px"
            @size-change="nextpage"
            @current-change="numberpage"
            :current-page="copyWriting.page"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="copyWriting.size"
            layout="total, prev, pager, next, sizes, jumper"
            :total="copyWriting.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 弹窗-->
    <el-dialog :visible.sync="dialogFormImage" class="spacing">
      <el-tag type="primary" v-if="washImg !== null">清洗素材</el-tag>
      <el-image
        :preview-src-list="srcWashImage"
        v-if="washImg !== null"
        :src="washImg"
      ></el-image>
      <el-divider><i class="el-icon-mobile-phone"></i></el-divider>
      <el-tag type="danger">原始素材</el-tag>
      <el-image :preview-src-list="srcImage" :src="previewImg"></el-image>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVideo"
      class="spacing"
      @opened="openVideo"
      @close="closeDialog"
    >
      <video
        :src="Video"
        ref="videoRef"
        controls
        preload
        width="600"
        height="600"
        autoplay
      ></video>
    </el-dialog>

    <!-- 子组件 添加至文案库弹窗 -->
    <add-material
      v-if="checkedCities && checkedCities.length > 0"
      :childDialog="childDialog"
      :ids="checkedCities"
      @cancelDialog="cancelDialog"
      @successAdd="successAdd"
    />
  </div>
</template>

<script>
import {
  getOlist,
  getEnums,
  getoriginedit,
  getCleanService,
  getTextlist,
  getTextedit,
  getSelectApps,
  getBusinTextAdd,
} from "@/api/cloud";
import { menuSelectApps, getPictureSizeLsit } from "@/api/report";

import AddMaterial from "./AddMaterial";

export default {
  data() {
    return {
      loading: true,
      pictureSizeList: [], //图片尺寸列表
      childDialog: false, // 添加文案弹窗控制
      appId: "",
      pkgList: [],
      dialogFormVisible: false,
      newGetList: [],
      /* 分页 */
      total: null,
      page: 1,
      size: 10,
      pageSizes: [10, 20, 30, 50],
      /* 提取任务 */
      condition: {
        appCategory: "",
        appId: "",
      },
      options: [],
      options1: [],
      options2: [],
      CleaningState: [
        { name: "已清洗", value: 1 },
        { name: "未清洗", value: 0 },
      ],
      activeName1: "firsts",
      dialogFormVideo: false,
      dialogFormImage: false,
      previewImg: "",
      washImg: "",
      srcImage: [
        "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
      ],
      srcWashImage: [],
      Video: "",
      checkAll: false,
      FormGetList: {
        ifClean: "",
        materialCategory: "",
        time: "",
        startDate: "",
        endDate: "",
        materialSize: "",
      },
      isIndeterminated: false,
      selectedAllList: [],
      selectedAll: false,

      /* 文案库的参数 */
      newGetText: [],
      textKeyWord: "",
      copyCheckAll: false,
      checkedCities: [],
      copyWriting: {
        page: 1,
        size: 10,
        total: null,
      },
      addForm: {
        appId: "",
        text: "",
      },
      selectApps: [],
      putInStorarg: [], // 需要保存的文案信息

      pickerOptions2: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const start = new Date();
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, start]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  components: {
    AddMaterial,
  },
  created() {
    this._menuSelectApps(); // 获取App名称配置列表
    this.APIGetEnums();
    this.APIGetList();
    this.APIGetTextlist();
  },
  mounted() {},

  methods: {
    // 获取App名称配置列表
    _menuSelectApps: function () {
      menuSelectApps({
        platformId: 4,
        menuCode: "materialContent",
      }).then((res) => {
        this.pkgList = res.result.data;
      });
    },

    closeDialog() {
      console.log(this.$refs.videoRef.paused);
      this.$refs.videoRef.pause();
    },
    openVideo() {
      if (("openVideo", this.$refs.videoRef.paused)) {
        this.$refs.videoRef.play();
      }
    },

    //获取图片尺寸列 数据
    getPictureSizeLsit(val) {
      let params = {
        materialCategory: val,
      };
      getPictureSizeLsit(params)
        .then((res) => {
          if (res.status == 200) {
            this.pictureSizeList = res.result.data;
          } else {
            this.$message.error("获取图片尺寸列请求错误。");
          }
        })
        .catch((err) => {
          this.$message.error("获取图片尺寸列失败！");
          console.log(err);
        });
    },
    /* 添加文案库 */
    addCopywriting() {
      if (this.checkedCities && this.checkedCities.length > 0) {
        this.childDialog = true; // 控制子组件弹窗显示
      }

      let params = {
        ids: this.checkedCities.toString(),
        status: 2,
      };
      getTextedit(params).then((res) => {
        if (res.status == 200) {
          this.$message({
            message: "添加至文案库",
            type: "success",
          });
          this.APIGetTextlist();
        }
        console.log(res);
      });
    },

    /* 删除 */
    deleCopy() {
      let params = {
        ids: this.checkedCities.toString(),
        status: 2,
      };
      getTextedit(params).then((res) => {
        if (res.status == 200) {
          this.$confirm("是否删除?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.APIGetTextlist();
              this.checkedCities = [];
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        } else {
          this.$message({
            message: "请选择要删除的文案",
            type: "warning",
          });
        }
        console.log(res);
      });
    },
    /* 选择当前文案 */
    selectedCopy(inText, index) {
      console.log("选择当前文案", inText);
      // this.checkedCities.push(inText)
      console.log("文案数据", this.checkedCities);
    },

    /* 全选按钮 */
    entireCopy(val) {
      console.log("全选数据", val);
      if (this.copyCheckAll) {
        this.newGetText.forEach((inText) => {
          this.checkedCities.push(inText.id);
        });
      } else {
        this.checkedCities = [];
      }
    },
    /* 分页*/
    numberpage(val) {
      console.log(val);
      this.copyWriting.page = val;
      this.APIGetTextlist();
    },
    nextpage(val) {
      this.copyWriting.size = val;
      this.APIGetTextlist();
    },

    /* 获取原始文案 */
    APIGetTextlist() {
      let params = {
        appId: this.condition.appId,
        appCategory: this.condition.appCategory,
        // keyword: this.textKeyWord,
        page: this.copyWriting.page,
        size: this.copyWriting.size,
      };
      getTextlist(params).then((res) => {
        console.log("原始文案", res);
        this.newGetText = res.result.data.content;
        console.log("newGetText", this.newGetText);
        this.copyWriting.total = res.result.data.total;
      });
    },

    /* 获取公共参数*/
    APIGetEnums() {
      getEnums().then((res) => {
        console.log(res);
        this.options = res.result.data.fetchApps;
        this.options1 = res.result.data.categorys;
        this.options2 = res.result.data.materialType;
      });
    },

    /* 获取原始素材列表*/
    APIGetList() {
      this.loading = true;
      let params = {
        appCategory: this.condition.appCategory,
        appId: this.condition.appId,
        endDate: this.FormGetList.endDate,
        startDate: this.FormGetList.startDate,
        ifClean: this.FormGetList.ifClean,
        materialCategory: this.FormGetList.materialCategory,
        materialSize: this.FormGetList.materialSize,
        resType: "",
        page: this.page,
        size: this.size,
      };
      getOlist(params).then((res) => {
        /* 对一页全部数据选择做处理 */
        if (this.pageSizes[this.pageSizes.length - 1] != 50) {
          this.pageSizes.pop();
        }
        this.loading = false;
        console.log(res);
        this.newGetList = res.result.data.content;
        this.total = res.result.data.total;
        this.pageSizes.push(this.total);
      });
    },

    /* 点击预览 */
    Preview(item) {
      console.log(0);
      if (item.resType === 1) {
        this.srcImage = [];
        console.log(item.url);
        this.previewImg = item.url;
        this.washImg = item.washedUrl;
        this.dialogFormImage = true;
        this.srcImage.push(item.url);
        this.srcWashImage.push(item.washedUrl);
      } else if (item.resType === 2) {
        console.log(item.url);
        this.dialogFormVideo = true;
        this.Video = item.url;
      }
    },

    /* 分页 */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.removeCheck();
      this.APIGetList();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.removeCheck();
      this.APIGetList();
    },

    /* 全选框 */
    handleCheckAllChange(val) {
      if (this.checkAll) {
        this.newGetList.forEach((item) => {
          this.selectedAllList.push(item.id);
          console.log(this.selectedAllList);
        });
      } else {
        this.selectedAllList = [];
      }
    },

    /* 移除选中的素材 */
    removeCheck() {
      this.checkAll = false;
      this.selectedAllList = [];
    },

    /* 单选框 */
    handleCheckedCitiesChange(item) {
      console.log("素材选取：", item.id);
      console.log("所选素材集合：", this.selectedAllList);
    },

    /* 查询 */
    fetchData() {
      this.page = 1;
      this.size = 10;

      if (this.activeName1 === "firsts") {
        this.APIGetList();
      } else {
        this.APIGetTextlist();
      }
    },

    /* 删除 */
    Delete() {
      let params = {
        ids: this.selectedAllList.toString(),
        status: 1,
      };
      getoriginedit(params).then((res) => {
        console.log(res);
        if (res.status == 200) {
          this.$confirm("是否删除?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.APIGetList();
              this.checkedCities = [];
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        } else {
          this.$message({
            message: "请选择要删除的文案",
            type: "warning",
          });
        }
      });
    },

    /* 清洗 */
    cleaning() {
      if (this.selectedAllList.length === 0) {
        this.$message({
          message: "请选择需要添加的素材",
          type: "warning",
        });
        return;
      }
      let params = {
        ids: this.selectedAllList.toString(),
        status: 1,
      };
      getCleanService(params).then((res) => {
        console.log(res);
        if (res.status === 200) {
          this.$message({
            message: "已经加入清洗队列中，请稍后1-2分钟",
            type: "success",
          });
          this.APIGetList();
        }
      });
    },

    /* 添加到素材库 */
    addMaterial() {
      if (this.selectedAllList.length === 0) {
        this.$message({
          message: "请选择需要添加的素材",
          type: "warning",
        });
        return;
      }
      this.dialogFormVisible = true;
    },

    getoriginedit: function () {
      let params = {
        ids: this.selectedAllList.toString(),
        status: 2,
        appId: this.appId,
      };
      getoriginedit(params).then((res) => {
        console.log(res);
        this.dialogFormVisible = false;
        if (res.status === 200) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.APIGetList();
        }
      });
    },

    /* 日期 */
    startTime() {
      console.log(this.FormGetList.item);
      this.startDate();
      this.endDate();
      console.log("开始日期" + this.startDate(), "结束日期" + this.endDate());
      this.FormGetList.startDate = this.startDate();
      this.FormGetList.endDate = this.endDate();
    },

    /* 开始日期 */
    startDate() {
      let createTime = this.FormGetList.time[0];
      var date = new Date(createTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      const startDate = y + "-" + m + "-" + d;
      return startDate;
    },

    /* 结束日期 */
    endDate() {
      let endTime = this.FormGetList.time[1];
      var date = new Date(endTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      const endDate = y + "-" + m + "-" + d;
      return endDate;
    },

    /* 接收子组件发射过来的事件 */
    /* 取消 让弹窗消失 */
    cancelDialog() {
      this.childDialog = false;
    },

    /* 添加成功时 取消选中状态 即让复选框绑定的值为空 */
    successAdd() {
      this.checkedCities = [];
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.Materia {
  overflow: hidden;
}

.Materiallist {
  position: relative;
  overflow: hidden;
  width: 264px;
  border: 1px solid rgb(201, 201, 201);
  padding: 6px 3px;
  box-sizing: border-box;
  //display: inline-table;
  float: left;
  margin: 0 30px 20px 30px;
  color: #606266;
}

.Materiallist .Materiallist_img {
  width: 254px;
  //height: 141px;
  display: inline-block;
  height: auto;
  max-width: 100%;
  object-fit: contain;
}
.Materiallist .Materiallist_title {
  font-size: 14px;
  color: #edba1c;
  line-height: 20px;
  text-align: left;
}

.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: 2; // 用来限制在一个块元素显示的文本的行数
  -webkit-box-orient: vertical; // 设置或检索伸缩盒对象的子元素的排列方式
}
.Subscript {
  position: absolute;
  z-index: 999;
  font-size: 14px;
  background: #ccc;
  border-radius: 10px;
  padding: 2px 10px;
  left: 0;
  top: 0;
}
.el-icon-video-play {
  font-size: 50px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -25px;
  margin-top: -50px;
  color: #ffffff;
}
</style>

<style>
#MateriaCheck .el-checkbox__input {
  position: absolute;
  right: 10%;
  top: 5%;
}
#MateriaCheck .el-checkbox__label {
  padding-left: 0;
}
.spacing .el-dialog {
  width: 37%;
}
</style>
