<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="140px" label-position="left">
      <el-form-item label="开启">
        <el-switch v-model.trim="form.status" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <template v-if="form.status">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            style="width: 500px"
            placeholder="例如：邀请1人可得，双方各得10元优惠券"
          ></el-input>
        </el-form-item>
        <el-form-item label="分享封面图" prop="shareImg">
          <single-image-upload
            style="width: 80px; height: 80px"
            v-model="form.shareImg"
          ></single-image-upload>
          <div class="tips u-m-l-14">建议尺寸：750*622</div>
        </el-form-item>
        <el-form-item label="邀请顶部图" prop="invitedImg">
          <single-image-upload
            style="width: 80px; height: 80px"
            v-model="form.invitedImg"
          ></single-image-upload>
          <div class="tips u-m-l-14">建议尺寸：750*622</div>
        </el-form-item>
        <el-form-item label="被邀顶部图" prop="beInvitedImg">
          <single-image-upload
            style="width: 80px; height: 80px"
            v-model="form.beInvitedImg"
          ></single-image-upload>
          <div class="tips u-m-l-14">建议尺寸：750*622</div>
        </el-form-item>
        <el-form-item label="活动日期" prop="startTime">
          <div>
            <el-date-picker
              style="width: 300px"
              v-model="createdAt"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="timeChange"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="新用户获得券" prop="newCouponList">
          <div>
            <el-button type="primary" @click="addRewardHandle('newCouponList')">添加券</el-button>
            <div class="tips">
              新用户的定义：没领过该活动券的都属于新用户，不管有没有下过单和是否第一次登录小程序。
            </div>
            <div>
              <el-table :data="form.newCouponList" border style="width: 600px">
                <el-table-column label="券ID" prop="id"></el-table-column>
                <el-table-column label="名称" prop="name"></el-table-column>
                <el-table-column label="数量" prop="num"></el-table-column>
                <el-table-column label="操作">
                  <template v-slot="scope">
                    <el-button
                      type="text"
                      @click="addRewardHandle('newCouponList', 2, scope.row, scope.$index)"
                    >
                      编辑
                    </el-button>
                    <el-button type="text" @click="form.newCouponList.splice(scope.$index, 1)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="奖励券" prop="invitedNum">
          <el-input
            v-model="form.invitedNum"
            style="width: 350px"
            @input="inputFilterInt($event, 'invitedNum')"
          >
            <template #prepend>用户每邀请</template>
            <template #append>人，可获得奖励券</template>
          </el-input>
          <el-button type="primary" @click="addRewardHandle('rewardCouponList')">添加券</el-button>
        </el-form-item>
        <el-form-item prop="rewardCouponList">
          <div>
            <div class="tips">奖励券不受优惠券发放数量影响</div>
            <el-table :data="form.rewardCouponList" border style="width: 600px">
              <el-table-column label="券ID" prop="id"></el-table-column>
              <el-table-column label="名称" prop="name"></el-table-column>
              <el-table-column label="数量" prop="num"></el-table-column>
              <el-table-column label="操作">
                <template v-slot="scope">
                  <el-button
                    type="text"
                    @click="addRewardHandle('rewardCouponList', 2, scope.row, scope.$index)"
                  >
                    编辑
                  </el-button>
                  <el-button type="text" @click="form.rewardCouponList.splice(scope.$index, 1)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="奖励获得方法">
          <el-radio-group v-model="form.getMethod">
            <el-radio label="get">新用户领取获得</el-radio>
            <el-radio label="use">仅新用户使用获得会员</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="onSubmitHandle">保存</el-button>
      </el-form-item>
    </el-form>
    <AddCoupon ref="AddCoupon" @success="addCouponSuccess" />
  </div>
</template>

<script>
import shopShareApi from "@/api/account/shopShare";
import AddCoupon from "./addCoupon.vue";
import { ElMessage } from "element-plus";
export default {
  components: { AddCoupon },
  data() {
    const imgValidate1 = (rule, value, callback) => {
      if (!this.form.shareImg) {
        callback(new Error("请上传分享封面图"));
      } else {
        callback();
      }
    };
    const imgValidate2 = (rule, value, callback) => {
      if (!this.form.invitedImg) {
        callback(new Error("请上传邀请顶部图"));
      } else {
        callback();
      }
    };
    const imgValidate3 = (rule, value, callback) => {
      if (!this.form.beInvitedImg) {
        callback(new Error("请上传被邀顶部图"));
      } else {
        callback();
      }
    };
    const startTimeValidate = (rule, value, callback) => {
      if (!this.form.startTime) {
        callback(new Error("请选择活动日期"));
      } else {
        callback();
      }
    };
    const newCouponListValidate = (rule, value, callback) => {
      if (!this.form.newCouponList.length) {
        callback(new Error("请添加新用户获得券"));
      } else {
        callback();
      }
    };
    const rewardCouponListValidate = (rule, value, callback) => {
      if (!this.form.rewardCouponList.length) {
        callback(new Error("请添加奖励券"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      createdAt: [],
      formImgKey: "",
      couponKey: "",
      tableType: "1", // 1添加 2编辑
      tableEditorIndex: 0, // 编辑时的index
      form: {
        status: 1,
        title: "",
        shareImg: "",
        invitedImg: "",
        beInvitedImg: "",
        startTime: "",
        endTime: "",
        newCouponList: [],
        invitedNum: "1",
        rewardCouponList: [],
        getMethod: "get",
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur",
          },
        ],
        shareImg: [
          {
            required: true,
            validator: imgValidate1,
            trigger: "change",
          },
        ],
        invitedImg: [
          {
            required: true,
            validator: imgValidate2,
            trigger: "change",
          },
        ],
        beInvitedImg: [
          {
            required: true,
            validator: imgValidate3,
            trigger: "change",
          },
        ],
        startTime: [
          {
            required: true,
            validator: startTimeValidate,
            trigger: "change",
          },
        ],
        newCouponList: [
          {
            required: true,
            validator: newCouponListValidate,
            trigger: "change",
          },
        ],
        invitedNum: [
          {
            required: true,
            message: "请输入邀请人数",
            trigger: "blur",
          },
        ],
        rewardCouponList: [
          {
            required: true,
            validator: rewardCouponListValidate,
            trigger: "change",
          },
        ],
      },
      urlList: [],
    };
  },
  mounted() {
    this.byShopId();
  },
  methods: {
    // 添加完成优惠券
    addCouponSuccess(e) {
      console.log(this.form);
      console.log(this.form.newCouponList);
      console.log(this.couponKey);
      if (this.tableType == 1) {
        this.form[this.couponKey].push({ ...e });
      } else {
        this.form[this.couponKey][this.tableEditorIndex] = { ...e };
      }
    },
    // 添加奖励券
    addRewardHandle(key, type = 1, row = {}, index = 0) {
      this.tableEditorIndex = index;
      this.tableType = type;
      this.couponKey = key;
      if (key == "rewardCouponList" && !this.form.invitedNum) {
        this.$refs.form.validateField("invitedNum");
        return;
      }
      this.$refs.AddCoupon.show(row);
    },
    // 日期回调
    timeChange(e) {
      this.form.startTime = e[0];
      this.form.endTime = e[1];
    },
    // 过滤input只能输入整数
    inputFilterInt(e, key) {
      if (!e) return;
      setTimeout(() => {
        this.form[key] = e.replace(/[^\d]/g, "");
      }, 50);
    },
    // 提交
    onSubmitHandle() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            this.form.shopId = localStorage.getItem("shopId");
            await shopShareApi.update(this.form);
            this.loading = false;
            ElMessage({
              title: "成功",
              message: `保存成功`,
              type: "success",
            });
          } catch (error) {
            this.loading = false;
            console.log(error);
          }
        }
      });
    },
    // 获取店铺设置
    async byShopId() {
      try {
        const res = await shopShareApi.get();
        if (res.id) {
          this.form = res;
          this.form.newCouponList = res.newCouponList || [];
          this.form.rewardCouponList = res.rewardCouponList || [];
          this.createdAt = [res.startTime, res.endTime];
          this.urlList = [res.shareImg, res.invitedImg, res.beInvitedImg];
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.img_list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

  .item {
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    position: relative;
    overflow: hidden;

    &.upload {
      border: 1px dashed #ddd;
    }

    &:hover {
      cursor: pointer;

      .del {
        transform: translateY(0);
      }
    }

    .del {
      width: 100%;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      left: 0;
      bottom: 0;
      background-color: rgba(255, 0, 0, 0.6);
      backdrop-filter: blur(3px);
      color: #fff;
      font-size: 12px;
      transform: translateY(100%);
      transition: all 0.2s ease-in-out;
    }

    .img {
      width: 100%;
      height: 100%;
      display: block;
    }

    .icon {
      font-size: 20px;
      color: #ddd;
    }
  }
}
</style>