<template>
  <ContainerTit>
    <div slot="headr">
      <el-button
        :loading="loading"
        :disabled="vipCardId"
        @click="delPauseSave(1)"
      >
        清除暂存
      </el-button>
      <el-button :loading="loading" :disabled="vipCardId" @click="temData">
        暂存
      </el-button>
      <el-button type="primary" :loading="loading" @click="submitGoods">
        提交保存
      </el-button>
    </div>
    <div class="page-tip-div" style="margin-top: 0">
      1、添加会员卡之后，只有
      <i style="color: #f00">排序，状态，库存和使用须知</i>
      可以修改，其他选项不支持修改
      2、会员卡禁用请谨慎，一旦禁用用户将无法领取与使用此会员卡
    </div>
    <el-card class="box-card" shadow="never">
      <div slot="header">
        <span>基本信息</span>
      </div>
      <el-form
        ref="form"
        :rules="form_rule"
        :model="form"
        size="small"
        :label-width="'200px'"
      >
        <el-form-item label="会员卡名称" prop="name">
          <el-input
            v-model="form.name"
            :disabled="vipCardId"
            style="width: 300px"
            maxlength="5"
            placeholder="请填写五个字以内的会员卡名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="卡片样式" prop="styleId">
          <template>
            <div class="card">
              <div
                v-for="item in typeList"
                :key="item.id"
                class="card-item card-style-golden"
                :class="[item.title, form.styleId === item.id ? 'active' : '']"
                @click="chooseCard(item.id)"
              ></div>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :controls="false"
            style="width: 300px"
            placeholder="请填写排序"
          ></el-input-number>
          <div>
            <p class="el-icon-warning" style="font-size: 12px; color: #e6a23c">
              提示：数字越大排序越靠前，如果为空，默认排序方式为创建时间
            </p>
          </div>
        </el-form-item>
        <el-form-item label="会员卡模式" prop="mode">
          <el-radio-group v-model="form.mode">
            <el-radio
              v-for="item in vipType"
              :key="item.userTypeId"
              :disabled="vipCardId"
              :label="item.id"
            >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.mode === 4" prop="useShop">
          <el-button
            :disabled="vipCardId"
            type="primary"
            @click="goods_show = true"
          >
            选择商品
          </el-button>
          <div style="display: inline-block">
            <el-tag
              v-for="(item, index) in goodsName"
              :key="index"
              :closable="!vipCardId"
              @close="closeTag('delgood', item)"
            >
              {{ item }}
            </el-tag>
          </div>
        </el-form-item>
        <!--          <el-form-item-->
        <!--            label="折上折"-->
        <!--          >-->
        <!--            <el-switch-->
        <!--              v-model="form.doubleDiscount "-->
        <!--              active-color="#36B365"-->
        <!--              inactive-color="#ff4949"-->
        <!--              :active-value="5"-->
        <!--              :inactive-value="4"-->
        <!--              active-text="启用"-->
        <!--              inactive-text="禁用"-->
        <!--            >-->
        <!--            </el-switch>-->
        <!--            <el-tooltip-->
        <!--              effect="dark"-->
        <!--              content="启用后:会在会员等级折扣后再次折扣，即购买价格=会员折扣后的价格*会员卡折扣"-->
        <!--              placement="top-start"-->
        <!--            >-->
        <!--              <i class="el-icon-question"></i>-->
        <!--            </el-tooltip>-->
        <!--          </el-form-item>-->
        <el-form-item label="会员权益" prop="freeShipping">
          <el-radio-group v-model="form.freeShipping" :disabled="vipCardId">
            <el-radio :label="5">包邮</el-radio>
            <el-radio :label="4">不包邮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员特价" prop="memberSpecialPrice">
          <el-radio-group v-model="form.memberSpecialPrice">
            <el-radio :label="5">启用</el-radio>
            <el-radio :label="4">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="会员折扣" prop="discount">
          <el-radio-group v-model="form.vipDiscount" :disabled="vipCardId">
            <el-radio :label="5">折扣</el-radio>
            <el-radio :label="4">没有折扣</el-radio>
          </el-radio-group>
          <div v-if="form.vipDiscount === 5">
            <el-input-number
              v-model="form.discount"
              :disabled="vipCardId"
              :controls="false"
              style="width: 300px"
              :max="9.9"
              :min="0.1"
              placeholder="请填写会员折扣"
            ></el-input-number>
            折
            <div>
              <p
                class="el-icon-warning"
                style="font-size: 12px; color: #e6a23c"
              >
                提示：请填写整数或小数点后一位的数字，例如：9.9
              </p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="开卡赠送" prop="hasNewCardCoupon">
          <el-radio-group v-model="form.hasNewCardCoupon" :disabled="vipCardId">
            <el-radio :label="4">不赠送</el-radio>
            <el-radio :label="5">赠送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.hasNewCardCoupon === 5" prop="useShop">
          <el-button
            :disabled="vipCardId"
            type="primary"
            @click="coupon_show = true"
          >
            选择优惠券
          </el-button>
          <div style="display: inline-block">
            <el-tag
              v-for="(item, index) in hasNewCardName"
              :key="index"
              :closable="!vipCardId"
              @close="closeTag('NewCard', item)"
            >
              {{ item }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="每月领取" prop="hasMonthCoupon">
          <el-radio-group v-model="form.hasMonthCoupon" :disabled="vipCardId">
            <el-radio :label="4">不赠送</el-radio>
            <el-radio :label="5">赠送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.hasMonthCoupon === 5" prop="useShop">
          <el-button
            :disabled="vipCardId"
            type="primary"
            @click="coupon_month = true"
          >
            选择优惠券
          </el-button>
          <div style="display: inline-block">
            <el-tag
              v-for="(item, index) in hasMonthCouponName"
              :key="index"
              :closable="!vipCardId"
              @close="closeTag('month', item)"
            >
              {{ item }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card" shadow="never">
      <div slot="header">
        <span>领取设置</span>
      </div>
      <el-form :rules="form_rule" :label-width="'200px'" :model="form">
        <el-form-item label="有效期：" prop="effectiveDate">
          <el-radio-group v-model="form.effectiveDate" :disabled="vipCardId">
            <el-radio v-for="item in userDate" :key="item.id" :label="item.id">
              {{ item.title }}
            </el-radio>
          </el-radio-group>
          <el-input-number
            v-model="form.effectiveMonth"
            :disabled="vipCardId"
            :controls="false"
            style="width: 80px; margin-left: 10px"
            placeholder=""
          ></el-input-number>
          <i style="margin-left: 10px">个月</i>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :disabled="vipCardId"
            :controls="false"
            style="width: 300px"
            placeholder="请填写价格"
          ></el-input-number>
          <div>
            <p class="el-icon-warning" style="font-size: 12px; color: #e6a23c">
              提示：用户购买会员卡需要支付的金额，不填或填0用户将可以免费领取
            </p>
          </div>
        </el-form-item>
        <el-form-item label="库存" prop="totalNum">
          <el-input-number
            v-model="form.totalNum"
            :controls="false"
            style="width: 300px"
            placeholder="请填写库存"
          ></el-input-number>
          <div>
            <p class="el-icon-warning" style="font-size: 12px; color: #e6a23c">
              提示：会员卡剩余可以领取的数量
            </p>
          </div>
        </el-form-item>
        <el-form-item label="状态：" prop="enableStatus">
          <el-radio-group v-model="form.enableStatus">
            <el-radio v-for="item in eableList" :key="item.id" :label="item.id">
              {{ item.title }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用须知：" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            style="width: 400px"
            :rows="7"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <SaleGoodsList
      v-if="goods_show"
      :is-show="goods_show"
      @cancel="goods_show = false"
      @confirm="selGoods"
    ></SaleGoodsList>
    <CouponModel
      v-if="coupon_show"
      :is-show="coupon_show"
      :grant-type="50"
      :coupon-type="20"
      @cancel="coupon_show = false"
      @confirm="selCoupon"
    />
    <CouponModel
      v-if="coupon_month"
      :is-show="coupon_month"
      :coupon-type="20"
      @cancel="coupon_month = false"
      @confirm="selMonthCoupon"
    />
  </ContainerTit>
</template>

<script>
  import SaleGoodsList from "@/component/goods/SaleGoodsList";
  import CouponModel from "@/component/goods/CouponModel";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import { editVipCard, addVipCard, getVipCardInfo } from "@/api/Market";
  export default {
    name: "AddCard",
    components: {
      SaleGoodsList,
      CouponModel,
    },
    data() {
      const discountVali = (rule, value, callback) => {
        if (this.form.vipDiscount === 5 && this.form.discount === "") {
          callback(new Error("请输入会员折扣"));
        } else if (
          this.form.vipDiscount === 5 &&
          this.form.discount.toString().length > 3
        ) {
          callback(new Error("请输入正确的会员折扣"));
        } else {
          callback();
        }
      };
      const priceVali = (rule, value, callback) => {
        if (this.form.price < 0) {
          callback(new Error("请输入正确的价格"));
        } else {
          callback();
        }
      };
      return {
        vipCardId: "", // 编辑的id
        loading: false,
        goods_show: false,
        coupon_show: false, // 优惠券
        coupon_month: false,
        goodsName: [],
        hasMonthCouponName: [], // 月赠送优惠券名字
        hasNewCardName: [], // 开卡赠送优惠券
        form: {
          shopId: "",
          name: "",
          styleId: 1,
          sort: "",
          mode: 5,
          goodsIds: "",
          doubleDiscount: 5,
          freeShipping: 5,
          memberSpecialPrice: 5, //会员特价
          vipDiscount: 5,
          discount: "",
          hasNewCardCoupon: 4,
          newCardCouponIds: "",
          hasMonthCoupon: 4,
          monthCouponIds: "",
          enableStatus: 5,
          effectiveDate: 5,
          effectiveMonth: 1,
          price: "",
          totalNum: 1,
          remark:
            "1、持卡可以享受会员打折的尊贵服务，商城消费下单时请主动选择此卡。\n" +
            "2、此卡一经办理非店方原因，不找零、不提现、不退换。\n" +
            "3、此卡为实名制会员卡，仅限本人使用不可转借他人。\n" +
            "4、此卡的最终解释权归本商城所有。\n" +
            "5、本卡有效期请以开卡日期为准，从开卡日期起计算。",
        },
        chooseId: 1,
        pageName: "",
        typeList: [
          { id: 1, title: "card-style-golden" },
          { id: 2, title: "card-style-erythrine" },
          { id: 3, title: "card-style-gray" },
          { id: 4, title: "card-style-brown" },
          { id: 5, title: "card-style-blue" },
          { id: 6, title: "card-style-black" },
        ],
        form_rule: {
          remark: [
            { required: true, message: "请输入使用须知", trigger: "blur" },
          ],
          name: [
            { required: true, message: "请输入会员卡名称", trigger: "blur" },
          ],
          styleId: [
            { required: true, message: "请选择会员卡样式", trigger: "blur" },
          ],
          price: [{ required: true, validator: priceVali, trigger: "blur" }],
          discount: [
            { required: true, validator: discountVali, trigger: "blur" },
          ],
        },
        vipType: [
          { id: 5, name: "所有商品" },
          { id: 4, name: "部分商品" },
        ],
        eableList: [
          { id: 5, title: "启用" },
          { id: 4, title: "禁用" },
        ],
        userDate: [
          { id: 5, title: "永久有效" },
          { id: 4, title: "" },
        ],
      };
    },
    async created() {
      this.pageName = this.$route.name;
      this.vipCardId = this.$route.params.id;
      if (this.vipCardId) {
        await this.getVipCardInfo();
        this.getVipCardInfo();
      } else {
        await this.getTempVipData();
        this.getTempVipData();
      }
    },
    methods: {
      // 选择商品
      selGoods(val) {
        if (this.goodsName.length) {
          this.goodsName = this.$_common.unique(this.goodsName.concat(val), [
            "id",
          ]);
        } else {
          this.goodsName = val;
        }
        this.goodsName = val.map((item) => {
          return item.title;
        });
        this.form.goodsIds = val
          .map((item) => {
            return item.id;
          })
          .join(",");
      },
      // 选择优惠券   开卡赠送优惠券
      selCoupon(val) {
        if (this.hasNewCardName.length) {
          this.hasNewCardName = this.$_common.unique(
            this.hasNewCardName.concat(val),
            ["id"]
          );
        } else {
          this.hasNewCardName = val;
        }
        this.hasNewCardName = val.map((item) => {
          return item.name;
        });
        this.form.newCardCouponIds = val
          .map((item) => {
            return item.id;
          })
          .join(",");
      },
      selMonthCoupon(val) {
        if (this.hasMonthCouponName.length) {
          this.hasMonthCouponName = this.$_common.unique(
            this.hasMonthCouponName.concat(val),
            ["id"]
          );
        } else {
          this.hasMonthCouponName = val;
        }
        this.hasMonthCouponName = val.map((item) => {
          return item.name;
        });
        this.form.monthCouponIds = val
          .map((item) => {
            return item.id;
          })
          .join(",");
      },
      // 关闭标签
      closeTag(text, index) {
        if (text === "delgood") {
          this.goodsName.splice(index, 1);
          this.form.goodsIds = this.goodsName.map((item) => {
            return item.id;
          });
        } else if (text === "NewCard") {
          this.hasNewCardName.splice(index, 1);
          this.form.newCardCouponIds = val
            .map((item) => {
              return item.id;
            })
            .join(",");
        } else if (text === "month") {
          this.hasMonthCouponName.splice(index, 1);
          this.form.monthCouponIds = val
            .map((item) => {
              return item.id;
            })
            .join(",");
        }
      },
      // 暂存按钮
      async temData() {
        if (this.form.effectiveDate === 5) {
          this.form.effectiveMonth = 0;
        }
        const params = {
          ...this.form,
          newCardCouponNames: this.hasNewCardName,
          monthCouponNames: this.hasMonthCouponName,
          goodsName: this.goodsName,
        };

        this.loading = true;
        const data = await addPauseSave({
          key: this.pageName,
          data: params,
        });
        this.loading = false;

        this.$message({
          type: "success",
          message: "暂存成功",
        });
        this.$closeCurrentGoEdit("/Marketing/vip/membershipCard");
      },
      // 清除
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/Marketing/vip/AddCard");
        }
      },
      // 提交按钮
      async submitGoods(tempSave) {
        if (this.form.effectiveDate === 5) {
          this.form.effectiveMonth = 0;
        }
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            const params = {
              ...this.form,
              newCardCouponNames: this.hasNewCardName,
              monthCouponNames: this.hasMonthCouponName,
              goodsName: this.goodsName,
            };

            this.loading = true;
            let target = {};
            if (this.vipCardId) {
              target = await editVipCard(this.vipCardId, params);
            } else {
              target = await addVipCard(params);
            }
            const data = target;
            this.loading = false;

            this.$message({
              type: "success",
              message: "提交成功",
            });
            await this.delPauseSave();
            this.delPauseSave();
            this.$closeCurrentGoEdit("/Marketing/vip/membershipCard");
          }
        });
      },
      // 获取详情
      async getVipCardInfo() {
        const { data } = await getVipCardInfo(this.vipCardId);

        this.form = data;
        if (data.goodsName) {
          this.goodsName = data.goodsName.map((item) => {
            return item;
          });
        }
        //  开卡赠送优惠券
        if (data.newCardCouponNames) {
          this.hasNewCardName = data.newCardCouponNames.map((item) => {
            return item;
          });
        }
        //    每月领取
        if (data.monthCouponNames) {
          this.hasMonthCouponName = data.monthCouponNames.map((item) => {
            return item;
          });
        }
      },
      // 获取暂存数据
      async getTempVipData() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.form = data;
        this.goodsName = data.goodsName ? data.goodsName : [];
        //  开卡赠送优惠券
        this.hasNewCardName = data.newCardCouponNames
          ? data.newCardCouponNames
          : [];
        //    每月领取
        this.hasMonthCouponName = data.monthCouponNames
          ? data.monthCouponNames
          : [];
      },
      // 卡片样式
      chooseCard(val) {
        this.form.styleId = val;
      },
    },
  };
</script>

<style scoped>
  .card-item {
    display: inline-block;
    width: 100px;
    height: 60px;
    margin-right: 18px;
    border-radius: 4px;
  }
  .card-item.active {
    width: 100px;
    height: 60px;
    border: 2px solid #4aa3f7;
  }
  .card-style-golden {
    background: linear-gradient(to right, #c1a167, #e9d5aa);
  }
  .card-style-erythrine {
    background: linear-gradient(to right, #745757, #966d6d);
  }
  .card-style-gray {
    background: linear-gradient(to right, #434247, #7a7985);
  }
  .card-style-brown {
    background: linear-gradient(to right, #736e6c, #978c8c);
  }
  .card-style-blue {
    background: linear-gradient(to right, #576074, #6d7b96);
  }
  .card-style-black {
    background: linear-gradient(to right, #373737, #4a4a4a);
  }
</style>
