<template>
  <el-dialog
    title="图片选择器"
    :visible="isShow"
    class="piclibrary"
    :modal="modal"
    width="70%"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="tip-div">
      1、单次批量上传不能超过50张图片; 2、每张图片大小不能大于5M;
      3、单次选择图片不能超过
      <span style="font-weight: bold; color: #ff4040; font-size: 14px">
        {{ limit }}
      </span>
      张; 4.图片一旦删除，无法找回，对应商品图片无法展示;
    </div>
    <el-row>
      <el-col :span="5">
        <ul class="img-cate-ul">
          <li
            v-for="(item, index) in cate_list"
            :key="index"
            class="img-cate-li clearfix"
            :class="[category_id === item.id ? 'img-cate-on' : '']"
            @click="changeCate(item)"
          >
            <span v-if="!item.isEdit" class="float_left">{{ item.title }}</span>
            <el-input
              v-if="item.isEdit"
              v-model="item.title"
              size="mini"
              style="margin-top: 5px"
              placeholder="请输入内容"
            >
              <el-button
                slot="append"
                icon="el-icon-check"
                @click="editCateTit(item)"
              ></el-button>
            </el-input>
            <div v-if="item.id > 0" class="float_right">
              <span
                class="el-icon-delete"
                style="
                  display: inline-block;
                  padding-right: 5px;
                  color: #ff4040;
                "
                @click.stop="delMaterialCategory(item.id)"
              ></span>
              <span
                class="el-icon-edit"
                style="display: inline-block; color: #67c23a"
                @click.stop="item.isEdit = !item.isEdit"
              ></span>
            </div>
          </li>
          <li class="img-cate-li">
            <el-popover v-model="visible" placement="top" width="160">
              <div style="padding: 10px 0">
                <el-input
                  v-model="cate_name"
                  size="mini"
                  placeholder="分类名称"
                ></el-input>
              </div>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="visible = false">
                  取消
                </el-button>
                <el-button type="primary" size="mini" @click="addCate">
                  确定
                </el-button>
              </div>
              <el-button
                slot="reference"
                size="small"
                type="text"
                icon="el-icon-plus"
              >
                新建分类
              </el-button>
            </el-popover>
          </li>
        </ul>
      </el-col>
      <el-col
        :span="19"
        style="border-left: 1px solid #ddd; padding-left: 10px"
      >
        <div class="clearfix">
          <div class="float_left">
            <el-input
              v-model="img_key"
              size="small"
              style="width: 200px"
              placeholder="搜索图片名称"
              @keyup.enter.native="pageChange(1)"
            >
              <i
                slot="suffix"
                class="el-icon-search el-input__icon"
                @click="pageChange(1)"
              ></i>
            </el-input>
          </div>
          <div class="float_right up-btn-div">
            <!--            七牛-->
            <QiniuMultipleUp
              v-if="!isAliYun"
              style="display: inline-block"
              @uploadSuccess="uploadSuccessMultiple"
            >
              <el-button slot="upbtn" type="primary" size="small">
                批量上传
              </el-button>
            </QiniuMultipleUp>
            <!--            阿里云-->
            <OssUultipleUp
              v-else
              style="display: inline-block"
              @uploadSuccess="uploadSuccessMultiple"
            >
              <el-button slot="upbtn" type="primary" size="small">
                批量上传
              </el-button>
            </OssUultipleUp>
          </div>
        </div>
        <ul class="img-ul clearfix">
          <li
            v-for="(item, index) in img_list"
            :key="index"
            class="img-li"
            :class="[
              choose_data.find((itemF) => itemF.id === item.id) ? 'img-on' : '',
            ]"
            @click="selImg(item)"
          >
            <i
              v-if="choose_data.find((itemF) => itemF.id === item.id)"
              class="dui-icon el-icon-check"
            ></i>
            <img class="img-li-img" :src="item.content" alt="" />
            <p class="img-name">
              {{ item.name }}
            </p>
          </li>
        </ul>
        <FooterPage
          layout="prev,pager,next"
          :page-size="pre_page"
          :total-page.sync="total"
          :current-page.sync="page"
          @pageChange="pageChange"
          @sizeChange="sizeChange"
        ></FooterPage>
        <div
          class="clearfix"
          style="border-top: 1px solid #ddd; padding-top: 5px"
        >
          <div class="float_left">
            <el-dropdown trigger="click" @command="updateMaterialContent">
              <el-button size="small" type="primary">
                移动至
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="(item, index) in cate_list"
                  :key="index"
                  :command="item.id"
                >
                  {{ item.title }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              style="margin-left: 10px"
              type="danger"
              plain
              size="small"
              @click="delMaterialContent"
            >
              删除
            </el-button>
          </div>
          <div class="float_right">
            <el-button size="small" @click="cancel">取消</el-button>
            <el-button size="small" type="primary" @click="confirm">
              确定
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
  import QiniuMultipleUp from "./QiniuMultipleUp.vue";
  import OssUultipleUp from "./OssUultipleUp.vue";
  import { UploadDel } from "@/api/common";
  import { apiUrl } from "@/config/settings";
  import { getEnToken } from "@/utils/accessToken";
  import {
    updateMaterialCategory,
    getAllMaterialContent,
    getAllMaterialCategory,
    delMaterialCategory,
    addMaterialCategory,
    delMaterialContent,
    addMaterialContent,
    updateMaterialContent,
  } from "@/api/Material";
  import axios from "axios";
  import { aliUpSetting, isAliYun } from "@/config/settings.js";
  import OSS from "ali-oss";
  export default {
    name: "PicLibrary",
    components: {
      QiniuMultipleUp,
      OssUultipleUp,
    },
    props: {
      isShow: {
        type: Boolean,
        default: false,
      },
      limit: {
        type: Number,
        default: 1,
      },
      imgHeight: {
        type: Number,
        default: 750,
      },
      modal: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        del_url: apiUrl.INDEX_URL + "/Common/Upload/delete",
        img_key: "",
        up_show: false,
        visible: false,
        cate_name: "",
        pre_page: 30,
        page: 1,
        total: 0,
        choose_data: [],
        cate_list: [],
        img_list: [],
        category_id: 0,
        isAliYun: isAliYun,
      };
    },
    async created() {
      await this.getAllMaterialCategory();
      await this.getAllMaterialContent();
    },
    methods: {
      //  判断
      confirm() {
        if (this.choose_data.length > this.limit) {
          this.$message.warning(`抱歉，您最多可选择${this.limit}张图片`);
          return;
        }
        this.$emit("confirm", this.choose_data);
        this.cancel();
      },
      // 关闭弹窗
      cancel() {
        this.$emit("cancel");
      },
      // 改变页数
      pageChange(val) {
        this.page = val;
        this.getAllMaterialContent();
      },
      sizeChange(val) {
        this.pre_page = val;
        this.pageChange(1);
      },
      // 素材分类编辑
      async editCateTit(row) {
        const data = await updateMaterialCategory({
          title: row.title,
          id: row.id,
        });

        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.getAllMaterialCategory();
      },
      // 素材分类删除
      delMaterialCategory(id) {
        this.$confirm("确定删除选中的分类吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await delMaterialCategory(id);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
          if (this.category_id === id) {
            this.category_id = 0;
            this.getAllMaterialContent();
          }
          this.getAllMaterialCategory();
        });
      },
      // 素材内容删除
      delMaterialContent() {
        this.$confirm("确定删除选中的文件吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const id = this.choose_data.map((item) => {
            return item.id;
          });
          const data = await delMaterialContent({
            id: id,
          });
          this.choose_data.forEach((item) => {
            this.removePic(item);
          });
          this.choose_data = this.choose_data.filter((item) => {
            return !id.find((itemF) => itemF === item.id);
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });

          this.getAllMaterialContent();
        });
      },
      async removePic(item) {
        // axios
        //   .post(this.del_url, {
        //     bucket: apiUrl.QINIU_KEY,
        //     key: `${getEnToken()}/${name}`,
        //   })
        //   .then((res) => {});

        if (this.isAliYun) {
          this.aliDelete(item.name);
        } else {
          const key = item.content.replace(apiUrl.QINIU_URL + "/", "");
          const data = await UploadDel({
            bucket: apiUrl.QINIU_KEY,
            key: key,
          });
        }
      },
      // 阿里云删除
      async aliDelete(name) {
        let client = new OSS(aliUpSetting);
        try {
          let result = await client.delete(name);
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      },
      // 切换分类
      changeCate(obj) {
        this.category_id = obj.id;
        this.getAllMaterialContent();
      },
      // 素材内容分类移动
      updateMaterialContent(command) {
        this.$confirm("确定移动选中的文件吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const id = this.choose_data.map((item) => {
            return item.id;
          });
          const data = await updateMaterialContent({
            categoryId: command,
            id: id,
          });

          this.$message({
            type: "success",
            message: "移动成功!",
          });
          this.getAllMaterialContent();
        });
      },
      // 素材内容添加
      async addMaterialContent(name, content) {
        const data = await addMaterialContent({
          categoryId: this.category_id,
          name: name,
          content: content,
        });

        // this.$message.success('添加成功')
        this.pageChange(1);
      },
      // 新建分类
      async addCate() {
        const data = await addMaterialCategory({
          title: this.cate_name,
        });

        this.visible = false;
        this.$message.success("添加成功");
        this.getAllMaterialCategory();
      },
      // 多图上传成功
      uploadSuccessMultiple(name, url) {
        this.addMaterialContent(name, url);
      },
      // 素材分类列表
      async getAllMaterialCategory() {
        const { data } = await getAllMaterialCategory();

        this.cate_list = data.map((item) => {
          return {
            ...item,
            isEdit: false,
          };
        });
      },
      // 素材内容列表
      async getAllMaterialContent() {
        const { data, pageTotal } = await getAllMaterialContent({
          name: this.img_key,
          categoryId: this.category_id,
          page: this.page,
          pageSize: this.pre_page,
        });

        this.img_list = data;
        this.total = pageTotal;
      },
      selImg(obj) {
        const index = this.choose_data.findIndex((item) => item.id === obj.id);
        if (index > -1) {
          this.choose_data.splice(index, 1);
        } else {
          this.choose_data.push(obj);
        }
      },
    },
  };
</script>

<style scoped>
  .img-ul {
    font-size: 14px;
    color: #666;
    height: 380px;
    overflow-y: auto;
    padding-top: 10px;
  }
  .img-li {
    width: 112px;
    height: 132px;
    text-align: center;
    float: left;
    margin-right: 10px;
    border: 1px solid #eee;
    padding: 5px;
    margin-bottom: 10px;
    cursor: pointer;
    position: relative;
  }

  .img-li:hover {
    border-color: #67c23a;
  }
  .img-on {
    position: relative;
  }
  .img-on:after {
    content: "";
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .dui-icon {
    position: absolute;
    top: 50%;
    color: #fff;
    left: 50%;
    z-index: 9;
    font-weight: bold;
    font-size: 40px;
    transform: translate(-20px, -20px);
  }
  .img-li-img {
    width: 100px;
    height: 100px;
    object-fit: contain;
    display: block;
  }
  .img-name {
    line-height: 20px;
    font-size: 12px;
    white-space: nowrap;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
  }
  .img-cate-ul {
    height: 480px;
    overflow-y: auto;
  }
  .img-cate-li {
    font-size: 14px;
    cursor: pointer;
    padding: 0 10px;
  }
  .img-cate-on {
    background-color: rgba(28, 143, 239, 0.2);
    color: #409eff;
  }
  .tip-div {
    background-color: #f6ffed;
    border: 1px solid #b7eb8f;
    color: rgba(0, 0, 0, 0.85);
    font-size: 12px;
    line-height: 20px;
    padding: 5px;
    border-radius: 3px;
    margin-bottom: 10px;
  }
</style>
<style>
  .up-btn-div .el-upload-list {
    display: none;
  }
  .piclibrary .el-dialog__body {
    padding: 0 20px 30px;
  }
</style>
