<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 label="授权时间" style="margin: 0" required="true">
              <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" v-if="ruleForm.long === '1'">
                  <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>

                <p style="font-size:16px;font-weight:700" v-else>长期有效</p>
              </el-col>
            </el-form-item>
            <el-col :span="24">
              <el-form-item
                label="授权图片"
                prop="brand_book"
                :disabled="id == '007'"
                class="activity-upload"
              >
                <template v-if="ruleForm.brand_book && ruleForm.brand_book.length > 0">
                  <div
                    class="btnupload"
                    style="position: relative;"
                    v-for="(url,index) in ruleForm.brand_book"
                    :key="url"
                  >
                    <img :src="url" class="avatar" />
                    <i v-if="type !== 'view'" class="el-icon-close" @click="ruleForm.brand_book.splice(index,1)" />
                  </div>
                </template>

                <div class="btnupload" style="position: relative;"  v-if="type !== 'view'">
                  <i class="el-icon-plus avatar-uploader-icon" />
                  <file-upload
                    class="Upload"
                    :multiple="true"
                    :accept="'.jpg,.png,.jpeg'"
                    :disabled="type === 'view'"
                    @UploadErrorEvent="UploadErrorEvent"
                    :uploadcondition="beforeAvatarUpload"
                    @UploadSuccessEvent="UploadSuccessEvent"
                  ></file-upload>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input :disabled="type === 'view'" type="textarea" v-model="ruleForm.remark" placeholder="备注" />
              </el-form-item>
            </el-col>

            <el-col :span="24" style="text-align: right;">
              <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 { hasSpace } from "@/utils/validate";
import resToken from "@/mixins/resToken";
import dayjs from 'dayjs';
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: true, message: "请选择授权类型", trigger: "change" }
        ],
        starttime: [
          { required: true, message: "请选择授权开始日期", trigger: "blur" }
        ],
        endtime: [
          { required: true, message: "请选择授权结果日期", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // "ruleForm.long": function(val) {
    //   this.rulesThis.long[0].required = Number(val) !== 0;
    // },
    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: "",
        remark:"",
        gyscode: this.sitem,
        brand_id: [],
        long: "1",
        starttime: "",
        endtime: "",
        brand_book: []
      };
    },
    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,
          remark
        } = 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 ? brand_book.split(",") : [],
          remark: remark || ""
        };
      } 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.brand_book = model.brand_book.join(",");
          model.status = "1";

          if(model.starttime){
            model.starttime = dayjs(model.starttime).format("YYYY-MM-DD HH:mm:ss");
          }

          if(model.endtime){
            model.endtime = dayjs(model.endtime).format("YYYY-MM-DD HH:mm:ss");
          }

          if(String(model.long) === "0"){
            delete model.endtime
          }

          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 {
        console.log(this.ruleForm.brand_book);
        this.ruleForm.brand_book.push(url);
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("brand_book");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.btnupload {
  margin-left: 5px !important;
  margin-bottom: 5px !important;

  .el-icon-close {
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}
</style>
