<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    width="500px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            v-loading="loading"
            :model="ruleForm"
            status-icon
            size="small"
            :rules="rulesThis"
            label-width="55px"
            class="supplierAdd"
          >
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                style="width: 100%"
                :disabled="isDetail"
                placeholder="活动名称"
              />
            </el-form-item>
            <el-form-item label="图片" prop="act_img">
              <div class="activity-upload" style="margin-left: 0">
                <div
                  class="btnupload"
                  v-for="(item, index) in ruleForm.act_img"
                  :key="index"
                >
                  <img
                    :src="ruleForm.act_img[index]"
                    class="avatar"
                    v-viewer
                    style="cursor: pointer"
                  />
                  <i class="el-icon-close" @click="closeImg(index, 'act_img')"></i>
                </div>
                <div v-if="ruleForm.act_img.length < 10" class="btnupload">
                  <i
                    class="el-icon-plus avatar-uploader-icon"
                    style="position: relative; width: 50px; height: 50px"
                  >
                    <file-upload
                      class="Upload"
                      :accept="'.jpg,.png,.jpeg'"
                      :multiple="true"
                      :uploadcondition="beforeAvatarUpload"
                      @UploadErrorEvent="imgUploadError"
                      @UploadSuccessEvent="UploadSuccessEvent"
                    ></file-upload>
                  </i>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="链接" prop="act_url">
              <el-input
                v-model="ruleForm.act_url"
                style="width: 100%"
                :disabled="isDetail"
                placeholder="活动链接"
              />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" class="bottom-btn tr">
          <el-button v-if="!isDetail" type="primary" @click="submitForm" :size="'mini'"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false" :size="'mini'">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/operate/shopTrim/activity";
import { formItem, rules } from "./columns";
export default {
  name: "shop",
  props: ["showModel", "id", "isDetail", "sitem", "store_id"],
  data() {
    return {
      loading: false,
      visible1: false,
      toponym: "",
      storeTypeOptions: [],
      supplierOptions: [],
      title: "添加曾办活动",
      showModelThis: this.showModel,
      ruleForm: {},
      rules,
      rulesThis: this.rules,
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  mounted() {
    this.ruleForm = {
      ...formItem,
    };
  },
  methods: {
    async initForm() {
      this.loading = true;
      if (this.id === "add") {
        this.title = "添加曾办活动";
        this.rulesThis = this.rules;
      } else {
        if (this.isDetail) {
          this.title = "曾办活动详情";
          this.rulesThis = {};
        } else {
          this.title = "修改曾办活动";
          this.rulesThis = this.rules;
        }
      }
      await this.resetForm();
      this.loading = false;
    },

    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          if (this.sitem && this.sitem.id) {
            const { id, name, act_img, act_url } = this.sitem;
            this.ruleForm = {
              id: id || "",
              name: name || "",
              act_url: act_url || "",
              act_img: act_img ? act_img.split(",") : [] || [],
            };
          } else {
            this.ruleForm = {
              ...formItem,
              act_img: [],
            };
          }
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            let model = JSON.parse(JSON.stringify(this.ruleForm));
            model.store_id = this.store_id;
            model.act_img = model.act_img.toString();
            let res = {};
            if (this.id === "add") {
              delete model["id"];
              res = await asyncRequest.add(model);
            } else {
              res = await asyncRequest.update(model);
            }
            this.loading = false;
            if (res && res.code === 1) {
              const title = this.id === "add" ? "添加成功" : "修改成功";
              this.$notify.success({
                title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //图片上传成功
    async UploadSuccessEvent(data) {
      // if (this.ruleForm.act_img.length > 10) {
      //   this.$message.warning("上传图片最多不能超过10张");
      //   return;
      // }
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.act_img.push(url);
        this.$refs.ruleForm.validateField("act_img");
        console.log(this.ruleForm.act_img.length);
      }
    },

    //图片上传失败
    imgUploadError(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField("act_img");
      }
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false;
      if (
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/jpeg"
      ) {
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("图片格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 1MB!");
      }
      if (this.ruleForm.act_img.length >= 10) {
        return false;
      } else {
        return isJPG && isLt2M;
      }
    },
    //图片悬浮删除
    closeImg(index, key) {
      this.ruleForm[key].splice(index, 1);
      this.$refs.ruleForm.validateField(key);
    },
  },
};
</script>

<style lang="scss" scoped>
.btnupload {
  position: relative;

  border-radius: 5px;
  overflow: hidden;
  margin: 0 5px 5px 0;
  border: 1px dashed #e6ebf5;
  background-color: #edf2fc;
}
i.el-icon-close {
  position: absolute;
  z-index: 2;
  top: 0;
  right: 0;
  color: #6954f0;
  font-weight: bold;
  cursor: pointer;
}
// .btnupload {
//   width: 86px;
//   height: 86px;
//   line-height: 86px;
// }
// .avatar-uploader-icon {
//   width: 86px;
//   height: 86px;
//   line-height: 86px;
// }
// .img-find {
//   position: relative;
//   width: 86px;
//   height: 86px;
//   line-height: 86px;
//   &:hover {
//     .img-close {
//       color: #409eff;
//     }
//   }
// }
// .img-close {
//   position: absolute;
//   top: 0;
//   right: 0;
//   font-size: 18px;
//   font-weight: lighter;
//   z-index: 999999;
//   &:hover {
//     cursor: pointer;
//   }
// }
</style>
