<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="5vh"
    width="600px"
    append-to-body
    :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"
            :size="'mini'"
            label-width="90px"
            class="demo-ruleForm"
          >
            <el-form-item label="支持品牌" prop="brand_id">
              <search-brand
                :value="ruleForm.brand_id"
                :size="'mini'"
                :disabled="type === 'view'"
                :isDetail="type !== 'add'"
                :names="brand_name"
                :placeholder="'商品品牌'"
                @searchChange="brandidsearchChange"
              />
            </el-form-item>
            <el-form-item label="授权类型" prop="long">
              <el-radio-group :disabled="type === 'view'" v-model="ruleForm.long">
                <el-radio :label="'0'">长期</el-radio>
                <el-radio :label="'1'">非长期</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="ruleForm.long === '1'" label="授权时间" style="margin: 0">
              <el-col :span="11">
                <el-form-item prop="starttime">
                  <el-date-picker
                    type="date"
                    :disabled="type === 'view'"
                    placeholder="开始日期"
                    v-model="ruleForm.starttime"
                    :picker-options="pickerOptions1"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    @change="timeChange"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line tc" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="endtime">
                  <el-date-picker
                    type="date"
                    :disabled="type === 'view'"
                    placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    v-model="ruleForm.endtime"
                    :picker-options="pickerOptions2"
                    style="width: 100%"
                    @change="timeChange"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-col :span="17">
              <el-form-item
                label="授权图片"
                prop="brand_book"
                :disabled="id == '007'"
                class="activity-upload"
              >
                <div class="btnupload" style="position: relative">
                  <img
                    v-if="ruleForm.brand_book"
                    :src="ruleForm.brand_book"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <file-upload
                    class="Upload"
                    :disabled="type === 'view'"
                    :accept="'.jpg,.png,.jpeg'"
                    :multiple="true"
                    :uploadcondition="beforeAvatarUpload"
                    @UploadErrorEvent="UploadErrorEvent"
                    @UploadSuccessEvent="UploadSuccessEvent"
                  ></file-upload>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="7" style="text-align: right; padding: 72px 0 0 0">
              <el-button
                v-if="type !== 'view'"
                :size="'small'"
                type="primary"
                @click="submitForm"
                >保 存
              </el-button>
              <el-button @click="showModelThis = false" :size="'small'">{{
                type === "view" ? "关 闭" : "取 消"
              }}</el-button>
            </el-col>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/serviceParam/supplierBrand";
import resToken from "@/mixins/resToken";
export default {
  name: "brand",
  props: ["showModel", "id", "type", "sitem"],
  mixins: [resToken],
  data() {
    return {
      loading: false,
      title: "添加支持品牌",
      showModelThis: this.showModel,
      brand_name: "",
      ruleForm: {},
      rulesThis: this.rules,
      pickerOptions1: {
        disabledDate: (time) => {
          if (this.ruleForm.endtime != null && this.ruleForm.endtime != "" && time) {
            return time.getTime() > new Date(this.ruleForm.endtime).valueOf();
          }
        },
      },
      pickerOptions2: {
        disabledDate: (time) => {
          if (this.ruleForm.starttime != null && this.ruleForm.starttime != "" && time) {
            return time.getTime() < new Date(this.ruleForm.starttime).valueOf();
          }
        },
      },
      rules: {
        gyscode: [
          {
            required: true,
            message: "供应商不能为空",
            trigger: "change",
          },
        ],

        brand_id: [
          {
            type: "array",
            required: true,
            message: "请选择支持品牌",
            trigger: "blur",
          },
        ],
        long: [{ required: false, message: "请选择授权类型", trigger: "change" }],
        starttime: [{ required: false, message: "请选择授权开始日期", trigger: "blur" }],
        brand_book: [{ required: false, message: "授权图片不能为空", trigger: "change" }],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.brand_name = "";
      this.resetFormData();
      if (this.type === "add") {
        this.rulesThis = this.rules;
        this.title = "添加支持品牌";
        await this.resetForm();
      } else if (this.type === "edit") {
        this.rulesThis = this.rules;
        this.title = "修改支持品牌";
        await this.resetForm();
        await this.initData();
      } else {
        this.rulesThis = {};
        this.title = "查看支持品牌";
        await this.resetForm();
        await this.initData();
      }
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.resetFormData();
        }
      });
    },
    timeChange() {
      if (
        this.ruleForm.starttime !== "" &&
        this.ruleForm.starttime !== null &&
        this.ruleForm.endtime !== "" &&
        this.ruleForm.endtime !== null
      ) {
        if (
          new Date(this.ruleForm.endtime).valueOf() <
          new Date(this.ruleForm.starttime).valueOf()
        ) {
          this.$message.warning("结束时间不大于开始时间！");
          this.ruleForm.endtime = "";
          this.ruleForm.starttime = "";
          this.$refs.ruleForm.validateField("starttime");
          this.$refs.ruleForm.validateField("endtime");
        } else {
          this.$refs.ruleForm.validateField("starttime");
          this.$refs.ruleForm.validateField("endtime");
        }
      } else {
        this.$refs.ruleForm.validateField("starttime");
        this.$refs.ruleForm.validateField("endtime");
      }
    },
    resetFormData() {
      this.ruleForm = {
        id: "",
        gyscode: this.sitem,
        brand_id: [],
        long: "1",
        starttime: "",
        endtime: "",
        brand_book: "",
      };
      console.log(this.sitem);
    },
    async initData() {
      this.loading = true;
      const { code, message, data } = await asyncRequest.detail({
        id: this.id,
      });
      this.loading = false;
      if (code === 0) {
        const {
          id,
          brand_book,
          brand_id,
          brand_name,
          long,
          starttime,
          endtime,
          gyscode,
        } = data;
        this.brand_name = brand_name;
        this.ruleForm = {
          id: id || "",
          gyscode: gyscode,
          brand_id: brand_id ? [brand_id] : [],
          long: long || "",
          starttime: starttime || "",
          endtime: endtime || "",
          brand_book: brand_book || "",
        };
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) return;
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          model.brand_id = model.brand_id.toString();
          // model.gyscode = model.gyscode.toString();

          let res = {};
          if (this.type === "add") {
            delete model["id"];
            res = await asyncRequest.add(model);
          } else {
            res = await asyncRequest.update(model);
          }
          this.loading = false;
          const { code, data, message } = res;
          if (code === 0) {
            const title = this.type === "add" ? "添加成功!" : "修改成功!";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh");
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //商品品牌选择
    brandidsearchChange(e) {
      const { id } = e;
      this.ruleForm.brand_id = id ? [id] : [];
      this.$refs.ruleForm.validateField("brand_id");
    },
    //判断图片规格
    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.brand_book = "";
        this.$refs.ruleForm.validateField("brand_book");
      }
    },
    //图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.brand_book = url;
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("brand_book");
      }
    },
  },
};
</script>

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