<template>
  <a-modal
    :width="800"
    v-model="visible"
    @cancel="visible = false"
    class="dec-imgModal"
  >
    <template slot="title">
      <div class="dec-flex-row" v-if="!add">
        <a-button
          type="primary"
          key="search"
          :value="searchTxt"
          @click="addIcon"
          >点击新增</a-button
        >
        <a-input-search
          placeholder="输入文件名"
          @search="searchGoods"
          class="m-search"
        >
          <a-button slot="enterButton">搜索</a-button>
        </a-input-search>
      </div>
      <div class="dec-flex-row" v-else>
        <a-button type="primary" key="search" @click="addIcon">返回</a-button>
      </div>
    </template>
    <a-spin :spinning="spinning">
      <div class="img-list" v-if="!add">
        <div class="left-nav">
          <div class="nav-item">
            <a-icon
              type="pushpin"
              style="margin-right: 5px; font-size: 16px"
            />建议选择及上传的图片尺寸为：80 * 80
          </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.miniPath, 'img-list.png')"
                alt
                draggable="false"
              />
            </div>
            <div class="dec-truncate pic-name">{{ item.remark }}</div>
          </div>
        </div>
      </div>
      <div v-else class="dec-img-upload">
        <div class="size-tip">
          <a-icon
            type="pushpin"
            style="margin-right: 5px; font-size: 16px"
          />建议选择及上传的图片尺寸为：80 * 80
        </div>
        <a-form-model
          ref="ruleForm"
          :model="model"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :rules="rules"
        >
          <a-form-model-item has-feedback label="未选图标" prop="miniPath">
            <a-upload
              name="file"
              :show-upload-list="false"
              :data="dealUpLoadData"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="model.miniPath"
                class="uploadImg"
                :src="decAxios.decImgDomain(model.miniPath, 'img-list.png')"
              />
              <div v-else class="upload">
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传图标</div>
              </div>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item has-feedback label="选中图标" prop="miniPath">
            <a-upload
              name="file"
              :show-upload-list="false"
              :data="dealUpLoadData1"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="model.miniPath"
                class="uploadImg"
                :src="decAxios.decImgDomain(model.publicPath, 'img-list.png')"
              />
              <div v-else class="upload">
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传图标</div>
              </div>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item has-feedback label="名称" prop="remark">
            <a-input v-model="model.remark" />
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-spin>
    <template slot="footer">
      <div class="dec-flex-between" v-if="!add">
        <a-pagination
          size="small"
          :total="total"
          :pageSize="pageSize"
          :current="current"
          :showSizeChanger="false"
          @change="pageChange"
          show-size-changer
          show-quick-jumper
        />
        <div v-if="iNum !== -1">
          <a-button class="btn-right" type="primary" ghost @click="upteData"
            >修改</a-button
          >
          <a-button class="btn-right" @click="deteteData" type="danger" ghost
            >删除</a-button
          >
          <a-button
            class="btn-right"
            key="submit"
            type="primary"
            @click="handleOk"
            >确定</a-button
          >
        </div>
      </div>
      <div v-if="add">
        <a-button class="btn-right" key="submit" type="primary" @click="save"
          >保存</a-button
        >
      </div>
    </template>
  </a-modal>
</template>

<script>
import { imgSourceSizeLimit, imgSourceFomatLimit } from "../util/setting.js";
export default {
  props: ["imgArg"],
  inject: ["decAxios"],
  data() {
    return {
      labelCol: {
        span: 3,
      },
      wrapperCol: {
        span: 14,
      },
      rules: {
        miniPath: [
          {
            required: true,
            message: "请上传未选图标",
            trigger: "blur",
          },
        ],
        publicPath: [
          {
            required: true,
            message: "请上传选中图标",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入上传名称",
            trigger: "change",
          },
        ],
      },
      visible: false, //弹窗控制参数
      iNum: -1, // 选中参数
      searchTxt: "",
      pictureShow: [],
      isSearch: false,
      spinning: false,
      pageSize: 10,
      total: 0,
      current: 1,
      add: false,
      loading: false,
      model: {},
    };
  },
  watch: {
    visible: function (curVal, oldVal) {
      if (curVal === oldVal) return;
      if (curVal) {
        // 设置要获取的图片类型，获取图片数据，设置上传图片的路径
        this.searchTxt = "";
        this.isSearch = false;
        this.getPicture();
      }
    },
  },
  methods: {
    // 获取图片数据
    getPicture() {
      this.iNum = -1;
      this.spinning = true;
      let params = {
        pageNo: this.current,
        pageSize: this.pageSize,
        fileCate: this.imgArg,
      };
      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;
        }
      });
    },
    // 弹出
    show() {
      this.visible = true;
      this.iNum = -1;
    },
    addIcon() {
      this.model = {};
      this.add = !this.add;
    },
    upteData() {
      if (this.iNum != -1) {
        this.add = true;
        var obj = this.pictureShow[this.iNum];
        this.model = obj;
      }
    },
    // 传递选择图片数据
    handleOk() {
      if (this.iNum != -1) {
        var obj = this.pictureShow[this.iNum];
        this.$emit("choose", obj);
        this.visible = false;
      } else {
        this.$message.warning("请选择对应图片");
      }
    },
    dealUpLoadData(result, type) {
      let fileName = result.name.split(".");

      const that = this;
      function successCallback(imgurl) {
        that.$set(that.model, "miniPath", imgurl);
      }
      function failCallback(mes) {
        mes && that.$message.error(mes);
      }
      let fileInfo = {
        fileTyle: fileName.length > 1 ? fileName[fileName.length - 1] : "",
        fileName: fileName[0],
        biz: "temp",
        file: result,
      };
      this.decAxios
        .uploadSource(fileInfo, successCallback, failCallback, false)
        .then((res) => {
          if (res.code === 200) {
            !res.message && successCallback(res.url);
          } else {
            failCallback(res.message);
          }
        });
    },
    dealUpLoadData1(result, type) {
      let fileName = result.name.split(".");
      const that = this;
      function successCallback(imgurl) {
        that.$set(that.model, "publicPath", imgurl);
      }
      function failCallback(mes) {
        mes && that.$message.error(mes);
      }
      let fileInfo = {
        fileTyle: fileName.length > 1 ? fileName[fileName.length - 1] : "",
        fileName: fileName[0],
        biz: "temp",
        file: result,
      };

      this.decAxios
        .uploadSource(fileInfo, successCallback, failCallback, false)
        .then((res) => {
          if (res.code === 200) {
            !res.message && successCallback(res.url);
          } else {
            failCallback(res.message);
          }
        });
    },
    save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let api = "";
          if (this.model.id) {
            //修改
            api = this.decAxios.editPageNavIcon;
          } else {
            //保存
            api = this.decAxios.savePageNavIcon;
          }
          api(this.model).then((res) => {
            if (res.success && res.message) {
              this.$message.success(res.message);
              this.add = false;
              this.getPicture();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    //删除
    deteteData() {
      if (this.iNum != -1) {
        var obj = this.pictureShow[this.iNum];
        this.decAxios.deletePageNavIcon(obj).then((res) => {
          if (res.success && res.message) {
            this.$message.success(res.message);
            this.getPicture();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    // 搜索商品图片
    searchGoods(e) {
      this.isSearch = true;
      this.searchTxt = e;
      this.getPicture();
    },
    beforeAvatarUpload(file, type) {
      // 控制上传数据
      const extension = imgSourceFomatLimit.includes(file.name.split(".")[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) {
      obj && (this.current = obj) && this.getPicture();
    },
  },
};
</script>
