<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="12vh"
    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
            :size="'mini'"
            :rules="rulesThis"
            label-width="80px"
          >
            <el-form-item label="预算单价" prop="budget_price">
              <digital-input
                :values="ruleForm.budget_price"
                :placeholder="'预算单价'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="budget_price_change"
              />
            </el-form-item>
            <el-form-item label="购买数量" prop="num">
              <digital-input
                :values="ruleForm.num"
                :placeholder="'购买数量'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="0"
                :size="'mini'"
                :controls="false"
                :append="''"
                @reschange="num_change"
              />
            </el-form-item>
            <el-form-item label="商品类型" prop="good_type">
              <el-select
                style="width: 100%"
                v-model="ruleForm.good_type"
                placeholder="商品类型"
                @change="good_type_change"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品分类" prop="cat_id">
              <good-class
                :value="ruleForm.cat_id"
                @handleChange="goods_class_change"
                :disabled="false"
                :size="'mini'"
                :isDetail="false"
                :placeholder="'商品分类'"
              />
            </el-form-item>
            <el-form-item label="商品名称" prop="good_name">
              <el-input
                placeholder="商品名称"
                v-model="ruleForm.good_name"
                maxlength="100"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="商品图片" prop="good_img">
              <div v-if="ruleForm.good_img" class="clearfix">
                <img
                  style="width: 50px; height: 50px"
                  :src="ruleForm.good_img"
                  class="avatar fl"
                />
                <el-link
                  :underline="false"
                  @click="deleteUrl()"
                  type="warning"
                  style="margin: 0 0 0 16px"
                  >删除</el-link
                >
              </div>

              <div class="activity-upload" v-else>
                <div class="btnupload" style="position: relative">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <file-upload
                    class="Upload"
                    :disabled="type === 'view' || type === 'editCoin'"
                    :accept="'.jpg,.png,.jpeg'"
                    :multiple="false"
                    :uploadcondition="beforeAvatarUpload"
                    @UploadErrorEvent="UploadErrorEventproof_url"
                    @UploadSuccessEvent="UploadSuccessEventproof_url"
                  ></file-upload>
                </div>
                <div class="txt-tips fl">
                  <p>建议大小：小于1MB</p>
                  <p>文件格式：.jpg,.png,.jpeg</p>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button :size="'small'" type="primary" @click="submitForm"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false" :size="'small'">{{
            "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/sellOut/project";
export default {
  name: "brand",
  props: ["showModel", "index", "sitem"],
  mixins: [resToken],
  data() {
    const validate_min_num = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("购买数量不能为空！"));
      } else if (value === "0") {
        callback(new Error("购买数量不能为零！"));
      } else {
        callback();
      }
    };
    const validate_sale_price = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("预算单价不能为空！"));
      } else if (
        value === "0" ||
        value === "0." ||
        value === "0.0" ||
        value === "0.00"
      ) {
        callback(new Error("预算单价不能为零！"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      title: "",
      options: [
        { value: "1", label: "竞品" },
        { value: "2", label: "竞聘" },
      ],
      showModelThis: this.showModel,
      ruleForm: {
        id: "",
        index: -1,
        good_type: "1",
        good_name: "",
        good_img: "",
        cat_id: [],
        budget_price: "",
        num: "",
      },
      rulesThis: this.rules,
      rules: {
        good_type: [
          { required: true, message: "请选择商品类型", trigger: "change" },
        ],
        good_name: [
          { required: false, message: "商品名称不能为空", trigger: "blur" },
        ],
        good_img: [
          { required: false, message: "商品图片不能为空", trigger: "change" },
        ],
        cat_id: [
          {
            type: "array",
            required: true,
            message: "请选择商品分类",
            trigger: "change",
          },
        ],
        budget_price: [
          { required: true, validator: validate_sale_price, trigger: "blur" },
        ],
        num: [{ required: true, validator: validate_min_num, 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;

      this.rulesThis = this.rules;
      console.log(this.index);
      if (this.index + "" === "-1") {
        this.title = "添加商品要求";
      } else {
        this.title = "修改商品要求";
      }
      await this.resetForm();
      this.loading = false;
    },
    //商品分类选择
    goods_class_change(e) {
      this.ruleForm.cat_id = e;
      this.$refs.ruleForm.validateField("cat_id");
    },
    deleteUrl() {
      this.ruleForm.good_img = "";
      this.$refs.ruleForm.validateField("good_img");
    },
    good_type_change() {
      const { good_type } = this.ruleForm;
      if (good_type === "1") {
        this.rulesThis.cat_id[0].required = true;
      } else {
        this.rulesThis.cat_id[0].required = false;
      }
    },
    //图片上传成功
    async UploadSuccessEventproof_url(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.good_img = url;
        this.$refs.ruleForm.validateField("good_img");
        this.$message.success("图片上传成功!");
      }
    },

    //图片上传失败
    UploadErrorEventproof_url(res) {
      if (res !== "break") {
        this.$refs.ruleForm.validatefield("good_img");
        this.$message.error("图片上传失败!");
      }
    },

    //判断图片规格
    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!");
      }
      return isJPG && isLt2M;
    },

    budget_price_change(e) {
      this.ruleForm.budget_price = e + "";
      this.$refs.ruleForm.validateField("budget_price");
    },
    num_change(e) {
      this.ruleForm.num = e + "";
      this.$refs.ruleForm.validateField("num");
    },
    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          await this.resetFormData();
        }
      });
    },
    async resetFormData() {
      const { id, cat_id, good_type, good_name, good_img, budget_price, num } =
        this.sitem;
      this.ruleForm = {
        id: id || "",
        index: this.index,
        good_type: good_type || "1",
        good_name: good_name || "",
        good_img: good_img || "",
        cat_id: cat_id ? [cat_id] : [],
        budget_price: budget_price || "0.00",
        num: num || "0",
      };
      this.good_type_change();
    },

    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));
          const { cat_id } = model;
          let cat_id_name = "";
          let length = cat_id.length;
          for (let i = 0; i < length; i++) {
            const { code, data, message } = await asyncRequest.catinfo({
              id: cat_id[i],
            });
            if (code === 0) {
              const { cat_name } = data;
              cat_id_name += i === 0 ? cat_name : `/${cat_name}`;
            } else if (code >= 100 && code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(message);
            }
          }
          model.cat_name = cat_id_name;
          this.showModelThis = false;
          this.$emit("refresh", model);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

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