<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="素材名称" prop="materialName">
        <el-input
          placeholder="请输入素材名称"
          style="width: 240px"
          v-model="queryParams.materialName"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="md5" prop="signature">
        <el-input
          placeholder="请输入md5"
          style="width: 240px"
          v-model="queryParams.signature"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-document-add"
          size="mini"
          @click="addNew"
          >新增素材
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="showWordList"
          >违规词库
        </el-button>
      </el-col>
    </el-row>
    <el-tabs v-model="queryParams.materialStatus" @tab-click="handleClick">
      <el-tab-pane
        :label="item.label"
        :name="item.value"
        v-for="(item, index) in queryParamsList.tagList"
        :key="index"
      >
        <!-- <el-row>
          <el-col
            :span="6"
            v-for="(o, index) in typeList"
            :key="index"
            :offset="index > 0 ? 2 : 0"
          >
            <el-card :body-style="{ padding: '0px' }">
              <img :src="o.coverUrl" class="image" style="width:100%;height:auto"/>
              <div style="padding: 14px">
                <span>{{ o.materialName }}</span>
                <div class="bottom clearfix">
                  <time class="time">{{ o.materialText }}</time>
                  <el-button type="text" class="button">操作按钮</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row> -->
        <div class="home-card">
          <div class="home-item" v-for="(items, index) in typeList" :key="index">
            <div class="home-right">
              <span
                style="
                  color: #999;
                  fontsize: 14px;
                  padding-bottom: 10px;
                  display: inline-block;
                  width: 100%;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
                :title="items.materialName"
                >{{ items.materialName }}</span
              >
              <div
                style="
                  display: flex;
                  justify-content: center;
                  width: 100%;
                  height: 200px;
                  position: relative;
                "
              >
                <img
                  :src="items.coverUrl"
                  alt
                  style="height: 200px; max-width: 100%; position: absolute; z-index: 10"
                  @click="showMore(items)"
                />
              </div>
              <span>
                {{ items.userName }}
              </span>
              <div
                style="display: flex; margin-top: 15px; justify-content: space-between"
              >
                <span>{{ items.createTime.split(" ")[0] }}</span>
                <div style="display: flex">
                  <a
                    style="margin-right: 5px"
                    @click="editMaterialsStatus(items.id, '3')"
                    v-if="queryParams.materialStatus == '3'"
                    >验证通过</a
                  >
                  <a
                    style="margin-right: 5px"
                    @click="editMaterialsStatus(items.id, '2')"
                    v-if="queryParams.materialStatus == '2'"
                    >验证拒绝</a
                  >
                  <a @click="copyInfomation(items.materialUrl)">复制链接</a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
          :pageSizes="[12, 24, 36, 48]"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加直播 -->
    <el-dialog
      :title="'新增素材'"
      :visible.sync="openAllocation"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formBroadcast"
        :model="formBroadcast"
        :rules="rulesBroadcast"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="创建人" prop="userName" style="width: 100%">
          {{ $store.getters.name }}
        </el-form-item>
        <el-form-item label="上传素材" prop="url" style="width: 100%">
          <!-- v-loading="formBroadcast.urlList.length != md5Arr.length" -->
          <uploadFile
            uploadType="video"
            :multiple="true"
            :checkFile="checkFileOk"
            :value.sync="formBroadcast.urlList"
            :removeUpload="remove"
            ref="uploadFile"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFormBroadcast"
          :loading="confirmLoading"
          :disabled="formBroadcast.urlList.length == 0"
          >确 定
        </el-button>
        <el-button
          @click="
            confirmLoading = false;
            openAllocation = false;
            formBroadcast = { urlList: [] };
            $refs.uploadFile.fileList = [];
          "
          >取 消
        </el-button>
      </div>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog
      title="查看详情"
      :visible.sync="refuseVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div v-if="refuseInfo" style="width: 100%; display: flex">
        <div
          class="video-content"
          style="
            width: 50%;
            padding: 10px;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            border-right: 1px solid #f2f2f2;
          "
        >
          <video
            class="video"
            :src="refuseInfo.materialUrl"
            controls="controls"
            style="width: 70%"
            controlslist="nodownload"
          >
            您的浏览器不支持 video 标签。
          </video>
        </div>
        <div
          style="
            width: 50%;
            padding: 10px;
            box-sizing: border-box;
            justify-content: center;
            border-right: 1px solid #f2f2f2;
          "
        >
          <h4><span class="prefix"></span>配音</h4>
          <div
            v-if="refuseInfo.violatingText"
            v-html="
              brightenKeyword(
                refuseInfo.materialText,
                JSON.parse(refuseInfo.violatingText)
                  .map((c) => {
                    return c.keyWord;
                  })
                  .join(',')
              )
            "
          ></div>
          <div v-else>
            {{ refuseInfo.materialText }}
          </div>
          <!-- v-html="brightenKeyword(record.productName,oldSearchText)" -->
          <div v-if="refuseInfo.violatingText">
            <h4><span class="prefix"></span>违规词</h4>
            <div
              v-for="(item, index) in JSON.parse(refuseInfo.violatingText)"
              :key="index"
            >
              <span> {{ item.type }}：</span>
              <span style="color: darkgoldenrod">
                {{ item.keyWord }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 违规词库 -->
    <el-dialog
      title="违规词库"
      :visible.sync="wordListVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        :model="wordData"
        ref="wordData"
        size="small"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="类型" prop="type">
          <el-input placeholder="请输入类型" style="width: 240px" v-model="wordData.type">
          </el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="keyWord">
          <el-input
            placeholder="请输入关键词"
            style="width: 240px"
            v-model="wordData.keyWord"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        plain
        icon="el-icon-document-add"
        size="mini"
        style="float: right"
        @click="addWord"
        >新增违规词
      </el-button>

      <el-table v-loading="wordLoading" :data="wordList" ref="multipleTable">
        <el-table-column label="类型" align="center" prop="type" width="300">
        </el-table-column>
        <el-table-column label="关键词" align="center" prop="key_word"> </el-table-column>
      </el-table>
      <pagination
        v-show="wordTotal > 0"
        :total="wordTotal"
        :page.sync="wordParams.pageNum"
        :limit.sync="wordParams.pageSize"
        @pagination="getKeyWordList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { refreshCache } from "@/api/system/dict/type";
import {
  getMaterialList,
  fileCheck,
  addMaterials,
  editMaterialsStatus,
  getKeyWordList,
  insertKeyWord,
} from "@/api/jiaoyang/promoter";
import uploadFile from "./components/uploadFile.vue";
// import BMF from "browser-md5-file";
export default {
  name: "JyMaterialUpload",
  dicts: ["sys_normal_disable"],
  components: {
    uploadFile,
  },
  data() {
    return {
      mediaId: "2",
      byteDanceItemType: "2",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: null,
      idElse: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      //上传文件类型
      fileType: [".doc", ".xls", ".xlsx", ".ppt", ".pdf", ".csv"],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openFp: false,
      formFp: {},
      // 是否可编辑
      edit: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 日期范围
      dateRange: [],
      superiorList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        materialName: undefined,
        signature: undefined,
        materialStatus: "1",
      },
      wordParams: {
        pageNum: 1,
        pageSize: 10,
      },
      wordData: {
        type: null,
        keyWord: null,
      },
      //页面所有的下拉数据
      queryParamsList: {
        tagList: [
          { value: "1", label: "待处理" },
          { value: "2", label: "验证通过" },
          { value: "3", label: "验证拒绝" },
        ],
        categoryIdList: [],
        mediaList: [
          { value: 2, label: "快手" },
          { value: 1, label: "抖音" },
        ],
      },
      // 表单参数
      form: {},
      formBroadcast: {
        urlList: [],
      },

      formRuleEdit: {},
      options: [],
      regInfo: [],
      ruleInfo: [],
      //上传报表下拉数据
      formList: {},
      fileList: [],
      accept: "",
      //获取销售线索文件流
      dateFile: new FormData(),
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {},
      ruleEdit: {
        ruleId: {
          required: true,
          message: "结算规则必选",
          trigger: "change",
        },
      },
      rulesBroadcast: {},
      // 分配销售展示列表
      ksInfo: null,
      userId: null,
      refuseVisible: false,
      refuseLoading: false,
      refuseInfo: null,
      relateId: null,
      md5Arr: [],
      wordListVisible: false,
      wordList: [],
      wordTotal: 0,
      wordLoading: false,
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.getList();
  },
  filters: {
    activityItemStatusName(status) {
      const statusMap = {
        1: "待审核",
        2: "已上架",
        3: "审核失败（拒绝）",
        4: "活动结束",
        5: "失效",
      };
      return statusMap[status];
    },
  },
  watch: {
    "formBroadcast.partnerRecommendText": function (n, o) {
      // console.log(n.replace(/<p>|<\/?p>|&nbsp;/gim, ""));
    },
  },
  methods: {
    addWord() {
      if (this.wordData.type && this.wordData.keyWord) {
        insertKeyWord({
          type: this.wordData.type,
          keyWord: this.wordData.keyWord,
        }).then((res) => {
          if (res.code == 0) {
            this.wordParams.pageNum = 1;
            this.getKeyWordList();
            this.wordData.type = null;
            this.wordData.keyWord = null;
            this.$message.success("添加成功");
          }else{
            this.$message.error("添加失败");
          }
        });
      } else {
        this.$message.error("未填写，不可添加");
      }
    },
    showWordList() {
      this.wordListVisible = true;
      this.getKeyWordList();
    },
    getKeyWordList() {
      this.wordLoading = true;
      getKeyWordList(this.wordParams).then((res) => {
        if (res.list.length > 0) {
          this.wordList = res.list;
          this.wordTotal = res.total;
          this.wordLoading = false;
        }
      });
    },

    editMaterialsStatus(id, status) {
      this.$modal
        .confirm(`请确认是否${status == "2" ? "拒绝" : "通过"}该素材？`)
        .then(() => {
          var params = {};
          params.id = id;
          params.materialStatus = status == "2" ? 3 : 2;
          editMaterialsStatus(params)
            .then((res) => {
              this.getList();
              this.$modal.msgSuccess(res.msg);
            })
            .catch((err) => {});
        })
        .catch(() => {});
    },
    remove(fileList) {
      console.log(fileList);
    },
    checkFileOk(file) {
      var bmf = new BMF();
      var that = this;
      return new Promise(function (resolve, reject) {
        bmf.md5(file, (err, md5) => {
          if (that.md5Arr.findIndex((item) => item == md5) > -1) {
          } else {
            that.md5Arr.push(md5);
          }

          // that.ruleForm.urlList = []
          fileCheck({
            signature: md5,
          }).then((res) => {
            if (!res.data) {
              that.$message.error("素材" + file.name + "已经上传");

              reject();
            } else {
              resolve();
              //   reject()
            }
          });
        });
      });
    },
    getRedWords(contentText, keyword) {
      let keywordArray = keyword.split(",");
      let wordsArray = [];
      for (let key of keywordArray) {
        if (contentText.includes(key)) {
          wordsArray.push(key);
        }
      }
      return wordsArray;
    },
    brightenKeyword(contentText, keyword) {
      let wordsArray = this.getRedWords(contentText, keyword);
      let res = contentText; //res的初始值是不带任何红色格式的
      //遍历相同字数组，
      for (let word of wordsArray) {
        const Reg = new RegExp(word, "i");
        //替换每一个相同字
        res = res.replace(Reg, `<span style="color: darkgoldenrod;">${word}</span>`);
      }
      return res; //此时的res里已经将需要标红的字体带上了格式（<span style="color:red"></span>）
    },
    showMore(item) {
      this.refuseVisible = true;
      this.refuseInfo = item;
    },
    copyInfomation(value) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard
          .writeText(`${value}`)
          .then(() => {
            this.$message.success("复制成功");
          })
          .catch((err) => {
            this.$message.error("复制失败");
          });
      } else {
        // 创建text area
        const textArea = document.createElement("textarea");
        textArea.value = `${value}`;
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((resolve, reject) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? resolve() : reject(new Error("出错了"));
          textArea.remove();
        }).then(
          () => {
            this.$message.success("复制成功");
          },
          () => {
            this.$message.error("复制失败");
          }
        );
      }
    },
    handleNodeClick(val) {
      console.log(val);
      this.$set(this.formBroadcast, "postArea", val.id);
      this.$set(this.formBroadcast, "postAreaName", val.name);
      if (!val.children || val.children.length == 0) {
        this.$refs.selectReport.blur();
      }
    },
    handleClick() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;

      getMaterialList({ userId: this.userId, ...this.queryParams }).then((response) => {
        this.typeList = response.list;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("formBroadcast");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.mediaId = undefined;
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    addNew() {
      this.openAllocation = true;
      this.edit = false;
      this.ids = null;
      this.confirmLoading = false;
      this.formBroadcast = { urlList: [] };
    },
    /** 编辑地址 新增达人*/
    handleAddbroadcast(item) {},
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    },
    /** 修改/绑定结算规则 */
    submitFormRuleEdit() {
      this.$refs["formRuleEdit"].validate((valid) => {
        if (valid) {
        }
      });
    },
    /** 新增素材确定按钮 */
    submitFormBroadcast: function () {
      this.$refs["formBroadcast"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          var params = {};
          params.userId = this.userId;
          params.userName = this.$store.getters.name;
          params.materialList = this.formBroadcast.urlList.map((item) => {
            return {
              signature: item.signature,
              materialUrl: item.url,
              materialName: item.name,
            };
          });
          addMaterials(params).then((res) => {
            this.confirmLoading = false;
            if (res.code == 0) {
              this.$message.success(res.message);
              this.openAllocation = false;
              this.formBroadcast = { urlList: [] };
              this.$refs.uploadFile.fileList = [];
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          var fileList = this.$refs.fileUploadDialog.fileList;
          var dapanUrls = this.$refs.fileUpload.fileList;
          var portraitUrls = this.$refs.fileUploadFx.fileList;
          if (fileList.length == 0 && dapanUrls.length == 0 && portraitUrls.length == 0) {
            this.$message.error("直播数据,数据大盘,画像分析必须最少上传一项");
            return;
          } else {
            this.confirmLoading = true;
            let formData = new FormData();
            this.ids;
            formData.append("id", this.ids);
            formData.append("actualGmv", this.delcommafy(this.form.actualGmv));
            formData.append(
              "dapanUrls",
              JSON.stringify(
                dapanUrls.map((item) => {
                  return item.url;
                })
              )
            );
            formData.append(
              "portraitUrls",
              JSON.stringify(
                portraitUrls.map((item) => {
                  return item.url;
                })
              )
            );
            fileList.forEach((file) => formData.append("files", file.raw));
            dataUpload(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("上传成功");
                this.open = false;
                this.ids = null;
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          }
          console.log(fileList, dapanUrls, portraitUrls);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.prefix {
  display: inline-block;
  width: 3px;
  height: 15px;
  background: rgb(104, 163, 253);
  position: relative;
  top: 2px;
  margin-right: 5px;
}
.entire-line {
  width: 100%;

  ::v-deep .el-form-item__content {
    width: 60%;
  }
}

::v-deep .el-form-item__label {
  white-space: nowrap;
}
</style>
<style scoped lang="scss">
::v-deep a {
  color: #409eff;
  display: block;
  text-align: left;
}

.item-name-calss p {
  margin: 0;
  text-align: left;
}

.tableBox {
  width: 100%;
}

::v-deep .el-tabs__content {
  overflow: initial;
}
.home-card {
  width: 100%;
  overflow: hidden;
  padding: 10px 0px;
  display: flex;
  flex-wrap: wrap;
  margin-right: -10px;

  .home-right {
    width: 100%;
  }

  .bg:after {
    content: "";
    width: 110%;
    height: 110%;
    position: absolute;
    left: -5%;
    top: -5%;
    background: inherit;
    filter: blur(10px);
    z-index: 2;
  }
}
.home-item {
  overflow: hidden;
}

@media only screen and (min-width: 1200px) {
  .home-item {
    border-style: solid;
    border-width: 1px;
    border-color: #e4e4e4;
    width: calc(50% - 10px);
    padding: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    background: #fff;
    position: relative;
    z-index: 99;
  }
}

/*>=1024的设备*/

// @media (min-width: 1100px) {
//     .checkbox_item_container {
//         width:70%
//     }
// } /*>=1100的设备*/
@media only screen and (min-width: 1250px) {
  .home-item {
    border-style: solid;
    border-width: 1px;
    border-color: #e4e4e4;
    width: calc(25% - 10px);
    padding: 10px;
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    background: #fff;
    position: relative;
    z-index: 99;
  }
}
</style>
