<template>
  <a-modal
    centered
    :width="780"
    v-model="visible"
    @cancel="handleCancel"
    class="dec-imgModal"
  >
    <template slot="title">
      <div class="dec-flex-row">
        <a-upload
          class="upload-demo"
          :show-upload-list="false"
          :customRequest="dealUpLoadData"
          :before-upload="beforeAvatarUpload"
        >
          <a-button type="primary" key="search">点击上传</a-button>
        </a-upload>
        <a-input-search
          placeholder="输入文件名"
          :value="searchTxt"
          @search="searchGoods"
          class="m-search"
        >
          <a-button slot="enterButton">搜索</a-button>
        </a-input-search>
      </div>
    </template>
    <a-spin :spinning="spinning">
      <div class="img-list">
        <div class="left-nav">
          <div class="nav-item">
            <a-icon
              type="pushpin"
              style="margin-right: 5px; font-size: 16px"
            />建议选择及上传的图片尺寸为：{{ imgSize || "无限制" }}
          </div>
        </div>
        <div class="right-pic">
          <div
            class="img-box"
            v-for="(item, index) in pictureShow"
            @click="iNum = index"
            :class="{ selected: index === iNum }"
            :key="index"
          >
            <div class="top-img">
              <div class="icon-wrap">
                <a-icon type="check" />
              </div>
              <img
                :src="decAxios.decImgDomain(item.fileUrl)"
                alt
                draggable="false"
              />
            </div>
            <div class="dec-truncate pic-name">{{ item.fileName }}</div>
          </div>
        </div>
      </div>
    </a-spin>
    <template slot="footer">
      <div class="dec-flex-between">
        <a-pagination
          size="small"
          :total="total"
          :pageSize="pageSize"
          :current="current"
          :showSizeChanger="false"
          @change="pageChange"
          show-size-changer
          show-quick-jumper
        />
        <a-button
          class="btn-right"
          key="submit"
          type="primary"
          @click="handleOk"
          >确定</a-button
        >
      </div>
    </template>
  </a-modal>
</template>

<script>
import { imgSourceSizeLimit, imgSourceFomatLimit } from "../util/setting.js";
export default {
  inject: ["decAxios"],
  data() {
    return {
      visible: false, // 弹窗控制参数
      iNum: -1, // 选中参数
      searchTxt: "",
      isSearch: false,
      pictureShow: [],
      spinning: false,
      pageSize: 21,
      total: 0,
      current: 1,
      newName: "",
      imgArg: "1",
      imgSize: "140x140",
    };
  },
  methods: {
    // 弹出
    show(imgArg, imgSize) {
      this.imgArg = imgArg || "1";
      this.imgSize = imgSize || "160*160";
      this.iNum = -1;
      this.visible = true;
      if (this.visible) {
        // 设置要获取的图片类型，获取图片数据，设置上传图片的路径
        this.currentPage = 1;
        this.searchTxt = "";
        this.isSearch = false;
        this.getPicture();
      }
    },
    // 获取图片数据
    getPicture() {
      this.iNum = -1;
      this.spinning = true;
      const params = {
        pageNo: this.current,
        pageSize: this.pageSize,
        fileCate: this.imgArg,
        imgSize: this.imgSize,
      };
      if (this.isSearch) params.fileName = this.searchTxt;
      this.decAxios.getSource(params).then((res) => {
        this.spinning = false;
        if (res.code === 200) {
          this.pictureShow = res.result.records;
          this.total = res.result.total;
        } else {
          this.pictureShow = [];
          this.total = 0;
        }
      });
    },
    // 传递选择图片数据
    handleOk() {
      if (this.iNum !== -1) {
        const obj = this.pictureShow[this.iNum];
        this.$emit("promise", { success: true, ...obj });
        this.visible = false;
      } else {
        this.$message.warning("请选择对应图片");
      }
    },
    handleCancel() {
      this.visible = false;
      this.$emit("promise", { success: false });
    },
    dealUpLoadData(result) {
      const { file } = result;
      const fileName = file.name.split(".");

      let fileInfo = {
        fileCate: this.imgArg,
        fileTyle: fileName.length > 1 ? fileName[fileName.length - 1] : "",
        fileName: "",
        biz: "temp",
        file: file,
      };
      const that = this;
      function successCallback() {
        that.getPicture();
      }
      function failCallback(mes) {
        mes && that.$message.error(mes);
      }

      // 新增一个名称输入框
      const uploadHandle = (name) => {
        fileInfo.fileName = name;
        this.decAxios
          .uploadSource(fileInfo, successCallback, failCallback)
          .then((res) => {
            if (res.code === 200) {
              !res.message && successCallback();
            } else {
              failCallback(res.message);
            }
          });
      };

      this.newName = fileName[0];
      this.$confirm({
        title: "确认上传文件？",
        content: (h) => {
          return h("div", [
            h("span", "文件重命名:"),
            h("a-input", {
              style: { marginLeft: "10px", width: "230px" },
              props: {
                placeholder: "重命名文件便于查询",
                value: that.newName,
              },
              on: {
                input: (e) => {
                  this.newName = e.target.value;
                },
              },
            }),
          ]);
        },
        okText: "确定",
        cancelText: "取消",
        onOk() {
          uploadHandle(that.newName);
        },
      });
    },
    // 搜索商品图片
    searchGoods(value) {
      this.isSearch = true;
      this.searchTxt = value;
      this.getPicture();
    },
    beforeAvatarUpload(file) {
      // 控制上传数据
      console.log(file);
      let dotIndex = file.name.lastIndexOf(".");
      let { name } = file;
      let extension = name.substr(dotIndex + 1);
      const isLt2M =
        file.size / Math.pow(1024, imgSourceSizeLimit) < imgSourceSizeLimit;
      if (!extension) {
        this.$message.warning(
          `仅能上传${imgSourceFomatLimit.join("、")}格式的文件!`
        );
      }
      if (!isLt2M) {
        this.$message.warning(`文件大小不能超过${imgSourceSizeLimit}MB!`);
      }
      return extension && isLt2M;
    },
    pageChange(obj) {
      if (obj) {
        this.current = obj;
        this.getPicture();
      }
    },
  },
};
</script>
