<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="18vh"
    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: -20px 0 0 0">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="品牌名称" prop="brand_name">
              <el-input
                v-model="ruleForm.brand_name"
                :disabled="id == '007'"
                placeholder="品牌名称"
                maxlength="20"
              />
            </el-form-item>
            <el-form-item
              label="LOGO"
              prop="logo_url"
              :disabled="id == '007'"
              class="activity-upload"
            >
              <div class="btnupload" style="position: relative">
                <img
                  v-if="ruleForm.logo_url"
                  :src="ruleForm.logo_url"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <file-upload
                  class="Upload"
                  :disabled="id == '007'"
                  :accept="'.jpg,.png,.jpeg'"
                  :multiple="true"
                  :uploadcondition="beforeAvatarUpload"
                  @UploadErrorEvent="UploadErrorEvent"
                  @UploadSuccessEvent="UploadSuccessEvent"
                ></file-upload>
              </div>
              <div class="txt-tips fl">
                <p>大小：小于1M</p>
                <p>尺寸：100*100</p>
                <p>类型：jpg.png.jpeg</p>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button v-if="id !== '007'" type="primary" @click="submitForm"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            id == "007" ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/goodStore/brand";
import resToken from "@/mixins/resToken";
import { isChinese } from "@/utils/validate";
export default {
  name: "brand",
  props: ["showModel", "id", "sitem"],
  mixins: [resToken],
  data() {
    const validateusername = (rule, value, callback) => {
      let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (value === "") {
        callback(new Error("品牌名称不能为空！"));
      } else if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("品牌名称必须包含汉字！"));
      }
    };
    return {
      loading: false,
      title: "添加品牌",
      showModelThis: this.showModel,
      select: "1",
      activeOptions: [],
      actionList: [],
      ruleForm: {
        id: "",
        brand_name: "",
        logo_url: "",
      },
      rulesThis: this.rules,
      rules: {
        brand_name: [
          { required: true, validator: validateusername, trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      if (this.id === "003") {
        this.title = "添加品牌";
        this.rulesThis = this.rules;
      } else if (this.id === "005") {
        this.title = "修改品牌";
        this.rulesThis = this.rules;
      } else {
        this.title = "品牌详情";
        this.rulesThis = {};
      }
      await this.resetForm();
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { id, brand_name, logo_url } = this.sitem;
          this.ruleForm = {
            id: id || "",
            brand_name: brand_name || "",
            logo_url: logo_url || "",
          };
        }
      });
    },
    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));
            let res = {};
            if (this.id === "003") {
              delete model["id"];
              res = await asyncRequest.add(model);
            } else {
              res = await asyncRequest.update(model);
            }
            this.loading = false;
            if (res && res.code === 0) {
              const title = this.id === "add" ? "添加成功!" : "修改成功!";
              this.$notify.success({
                title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            } else if (res && res.code >= 100 && res.code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(res.message);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false,
        isLt2M = false;
      if (file) {
        if (
          file.type === "image/jpg" ||
          file.type === "image/png" ||
          file.type === "image/jpeg"
        ) {
          isJPG = true;
        }
        isLt2M = file.size / 1024 / 1024 < 1;
        if (!isJPG) {
          this.$message.error("图片格式不正确！");
        }
        if (!isLt2M) {
          this.$message.error("图片大小不能超过 1MB!");
        }
      }

      return isJPG && isLt2M;
    },
    //图片上传失败
    UploadErrorEvent(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.ruleForm.logo_url = "";
        this.$refs.ruleForm.validateField("logo_url");
      }
    },
    //图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.logo_url = url;
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("logo_url");
      }
    },
  },
};
</script>

   <style lang="scss" scoped>
.brand {
}
</style>
