<template>
  <div>
    <BaseDialog
      width="800px"
      :isShow.sync="isShow"
      :title="goodsId ? '修改' : '新增'"
      @submit="submitForm"
      @close="close"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formData"
        label-width="100px"
        class="demo-ruleForm"
        ><el-form-item label="关联使用：" prop="useType">
          <el-select
            multiple
            clearable
            v-model="formData.useType"
            placeholder="请选择关联使用"
          >
            <el-option label="积分商城" :value="1"> </el-option
            ><el-option label="会员卡" :value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作商户：" prop="merId">
          <el-select
            @change="changeMerId"
            clearable
            v-model="formData.merId"
            placeholder="请选择合作商户"
          >
            <el-option
              v-for="(item, index) in merList"
              :key="index"
              :label="item.merName"
              :value="item.merId"
            >
            </el-option></el-select></el-form-item
        ><el-form-item label="商户店铺：" prop="storeId" v-if="formData.merId">
          <el-select
            @change="changeStoreId"
            clearable
            v-model="formData.storeId"
            placeholder="请选择商户店铺"
          >
            <el-option
              v-for="(item, index) in computerStore(storeList)"
              :key="index"
              :label="item.storeName"
              :value="item.storeId"
            >
            </el-option>
          </el-select> </el-form-item
        ><el-form-item
          label="商品分类："
          prop="categoryIds"
          v-if="formData.storeId"
        >
          <el-cascader
            clearable
            placeholder="请选择商品分类"
            v-model="formData.categoryIds"
            :options="computerTree(categorytreeList)"
            :show-all-levels="false"
            :props="{
              label: 'categoryName',
              value: 'categoryId',
              checkStrictly: true,
              emitPath: false,
            }"
          ></el-cascader> </el-form-item
        ><el-form-item label="商品名称：" prop="goodsName">
          <el-input
            clearable
            v-model="formData.goodsName"
            placeholder="输入商品名称"
          ></el-input> </el-form-item
        ><el-form-item label="商品主图：" prop="mainImg">
          <ul class="imgList">
            <li
              class="imgLi"
              v-for="(item, index) in formData.mainImg"
              :key="index"
            >
              <i class="el-icon-error del" @click="delImg(index)"></i>
              <el-image
                style="width: 90px; height: 90px"
                :src="$methodsTools.splitImgHost(item)"
                :preview-src-list="
                  formData.mainImg.map((i) => $methodsTools.splitImgHost(i))
                "
                :initial-index="index"
              >
              </el-image>
            </li>
            <li class="imgactive">
              <label for="file1" style="width: 100%; height: 100%">
                <i class="el-icon-plus" @click="uploadImg"></i
              ></label>
            </li>
            <input type="file" v-show="false" id="file1" @change="uploadImg" />
            <div style="clear: both"></div>
          </ul>
          <p style="color: #a4a4a4; margin: 0">
            建议尺寸：800*800像素；大小200K以下
          </p></el-form-item
        ><el-form-item label="商品原价:" prop="standPrice">
          <el-input-number
            :controls="false"
            v-model="formData.standPrice"
            placeholder="输入商品原价"
            :min="0"
            :precision="2"
          /> </el-form-item
        ><el-form-item label="会员优惠价:" prop="specialPrice">
          <el-input-number
            :controls="false"
            v-model="formData.specialPrice"
            placeholder="输入会员优惠价"
            :min="0"
            :precision="2"
          /> </el-form-item
        ><el-form-item label="可抵扣积分：" prop="integral">
          <el-input-number
            :disabled="true"
            :controls="false"
            v-model="formData.integral"
            placeholder="输入可抵扣积分"
            :min="0"
            :precision="0" /></el-form-item
        ><el-form-item label="是否上架：" prop="goodsStatus">
          <el-radio-group v-model="formData.goodsStatus">
            <el-radio :label="1">是</el-radio><el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品详情：">
          <editor
            v-model="formData.mobileDetailHtml"
            :min-height="300"
            :max-height="500"
            :uploadStatus="2"
          />
        </el-form-item>
      </el-form>
    </BaseDialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Editor from "@/components/Editor";
export default {
  components: { Editor },
  name: "",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    goodsId: {
      type: Number,
      default: 0,
    },
    getRules: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      formData: {
        useType: [],
        merId: "",
        storeId: "",
        categoryIds: "",
        mainImg: [],
        status: 1,
        goodsStatus: 1,
      },
      rules: {
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        standPrice: [
          { required: true, message: "请输入商品原价", trigger: "blur" },
        ],
        specialPrice: [
          { required: true, message: "请输入会员优惠价", trigger: "blur" },
        ],
        useType: [
          { required: true, message: "请选择关联使用", trigger: "change" },
        ],
        merId: [
          { required: true, message: "请选择合作商户", trigger: "change" },
        ],
        mainImg: [
          { required: true, message: "请上传商品主图", trigger: "change" },
        ],
        storeId: [
          { required: true, message: "请选择商户店铺", trigger: "change" },
        ],
        categoryIds: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        goodsStatus: [
          { required: true, message: "请选择是否上架", trigger: "change" },
        ],
        status: [
          { required: true, message: "请选择商品状态", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    "formData.standPrice"(newVal) {
      if ((newVal || 0) && this.formData.specialPrice) {
        var integral =
          parseInt(
            parseFloat(newVal) - parseFloat(this.formData.specialPrice)
          ) * this.getRules;
        this.$set(this.formData, "integral", integral);
      } else {
        this.$set(this.formData, "integral", 0);
      }
    },
    "formData.specialPrice"(newVal) {
      if ((newVal || newVal == 0) && this.formData.standPrice) {
        var integral =
          parseInt(parseFloat(this.formData.standPrice) - parseFloat(newVal)) *
          this.getRules;
        this.$set(this.formData, "integral", integral);
      } else {
        this.$set(this.formData, "integral", 0);
      }
    },
  },
  methods: {
    delImg(index) {
      this.formData.mainImg.splice(index, 1);
      this.$refs["formData"].validateField("mainImg");
    },
    changeMerId(e) {
      this.$set(this.formData, "storeId", null);
    },
    changeStoreId(e) {
      this.$set(this.formData, "categoryIds", null);
    },
    uploadImg(e) {
      var self = this;
      var file = e.target.files[0];
      if (file.size > 0.2 * 1024 * 1024) {
        self.$message.error("图片不得大于200kb");
        return;
      }
      var type = e.target.value.toLowerCase().split(".").splice(-1);
      if (type[0] != "jpg" && type[0] != "png" && type[0] != "jpeg") {
        self.$message.error("上传格式需为：.jpg/.png/.jpeg");
        return;
      }
      this.$upload
        .upload(file, 0)
        .then((res) => {
          self.formData.mainImg.push(res);
          this.$refs["formData"].validateField("mainImg");
        })
        .finally(() => {
          e.target.value = "";
        });
    },
    init() {
      if (this.goodsId) {
        this.$api.obtainGoods(this.goodsId).then((res) => {
          res.data.mainImg = res.data.mainImg?.split(",") || [];
          res.data.useType = res.data.useType?.split(",").map(Number) || [];
          res.data.categoryIds = parseInt(res.data.categoryIds);
          this.formData = res.data;
        });
      } else {
        this.formData = {
          useType: [],
          merId: "",
          storeId: "",
          categoryIds: "",
          mainImg: [],
          status: 1,
          goodsStatus: 1,
        };
      }
    },
    close() {
      this.$refs["formData"].resetFields();
    },
    submitForm() {
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          var data = JSON.parse(JSON.stringify(this.formData));
          data.mainImg = data.mainImg.toString();
          data.useType = data.useType.toString();
          this.$api[
            this.formData.goodsId ? "editgoodspoints" : "addgoodspoints"
          ](data).then((res) => {
            this.$message.success("操作成功");
            this.isShow = false;
            this.$emit("search");
          });
        } else {
          return false;
        }
      });
    },
  },
  computed: {
    ...mapGetters(["merList", "storeList", "categorytreeList"]),
    computerStore: function () {
      return function (rows) {
        var array = [];
        if (rows?.length > 0) {
          array = rows.filter((i) => i.merId == this.formData.merId) || [];
        }
        return array;
      };
    },
    computerTree: function () {
      return function (rows) {
        var array = [];
        if (rows?.length > 0) {
          array = rows.filter((i) => i.storeId === this.formData.storeId);
        }
        return array;
      };
    },
    isShow: {
      get() {
        if (this.dialogVisible) {
          this.init();
        }
        return this.dialogVisible;
      },
      set(val) {
        this.$emit("update:dialogVisible", false);
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.imgList {
  margin-bottom: 0;
  li {
    margin-right: 10px;
    margin-bottom: 10px;
    float: left;
    user-select: none;
    cursor: pointer;
    width: 98px;
    height: 98px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    position: relative;
  }
  .imgLi {
    border: 1px solid #666;
    &:hover {
      box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.2);
      transform: scale(1.02);
    }
  }
  .imgactive {
    border: 1px dotted #666;
    label {
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    i {
      font-size: 20px;
    }
    &:hover {
      box-shadow: 0px 0px 6px 1px rgba(0, 0, 0, 0.2);
    }
  }
}
.el-input {
  width: 220px;
  margin-right: 10px;
}
.el-select {
  width: 220px;
  margin-right: 10px;
}
.del {
  color: red;
  position: absolute;
  top: 0;
  right: 0;
  font-size: 20px;
  z-index: 2;
  background-color: #fff;
  border-radius: 50%;
  overflow: hidden;
}
</style>
