<template>
  <div class="purchase-gift-add-event-con">
    <Card v-if="loading" class="loading-card">
      <Spin fix size="large" />
    </Card>
    <Card v-else class="main_card">
      <div class="main_info">
        <div class="head">
          <Icon type="md-bookmark" color="#2d8cf0" :size="28" />
          <label>{{ title }}</label>
        </div>
        <Form ref="addForm" :model="form" :rules="formRules" :label-width="120">
          <Form-item label="活动名称：" prop="name">
            <Input v-model="form.name" placeholder="请输入活动名称" />
          </Form-item>
          <Form-item label="奖励商品：" prop="rewardGoodId">
            <Input
              v-model="form.rewardGoodId"
              placeholder="请输入商品编号"
              @on-change="handleGoodsIdChange('reward')"
            />
          </Form-item>
          <Form-item label="奖励规格：" prop="rewardSkuId">
            <Select placeholder="请选择商品规格" v-model="form.rewardSkuId">
              <Option
                v-for="item in rewardSkuList"
                :value="item.skuId"
                :key="item.skuId"
              >
                {{ item.label }}
              </Option>
            </Select>
          </Form-item>
          <!-- <Form-item label="奖励数量：" prop="rewardNum">
            <Input
              v-model="form.rewardNum"
              placeholder="请输入赠送数量"
              type="number"
              number
            />
          </Form-item> -->

          <Form-item label="条件商品：" prop="condGoodId">
            <Input
              v-model="form.condGoodId"
              placeholder="请输入商品编号"
              @on-change="handleGoodsIdChange('cond')"
            />
          </Form-item>
          <Form-item label="条件规格：" prop="condSkuId">
            <Select placeholder="请选择商品规格" v-model="form.condSkuId">
              <Option
                v-for="item in condSkuList"
                :value="item.skuId"
                :key="item.skuId"
              >
                {{ item.label }}
              </Option>
            </Select>
          </Form-item>
          <!-- <Form-item label="条件数量：" prop="condNum">
            <Input
              v-model="form.condNum"
              placeholder="请输入赠送数量"
              type="number"
              number
            />
          </Form-item> -->
          <!-- <Form-item label="集齐商品：" prop="num">
            <div class="sku-list-con">
              <Tag
                type="dot"
                color="primary"
                closable
                v-for="(item, index) of form.conSku"
                :key="`sku-item-${index}`"
              >
                {{item.name}}
              </Tag>
            </div>
            <Button type="primary" @click="handleSubmit">
              添加所需集齐的商品
            </Button>
          </Form-item> -->
          <Form-item label="起止时间：" prop="eventDateTime">
            <DatePicker
              v-model="form.eventDateTime"
              type="datetimerange"
              format="yyyy-MM-dd"
              placeholder="请选择开始时间与结束时间"
              separator=" 至 "
              transfer
              style="width: 100%"
              :options="dateOptions"
            />
          </Form-item>
          <Form-item label="备注：" prop="comm">
            <Input v-model="form.comm" placeholder="请输入备注信息" />
          </Form-item>
        </Form>

        <div class="footer-con">
          <Button type="default" @click="handleCancel"> 取消 </Button>
          <Button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </Button>
        </div>
      </div>
    </Card>
  </div>
</template>

<script>
import Tables from "_c/tables";
import { mapMutations } from "vuex";
import { formatTime } from "@/libs/tools";
export default {
  name: "add-coupon",
  components: {
    Tables,
  },
  computed: {
    title() {
      return this.activityId ? "编辑购赠活动" : "新增购赠活动";
    },
  },
  data() {
    let dateNow = new Date().setHours(0, 0, 0, 0);
    return {
      activityId: "",
      loading: false,
      submitLoading: false,
      form: {
        id: "",
        activityId: "",
        name: "",

        rewardGoodId: "",
        rewardSkuId: "",
        rewardNum: "",

        condGoodId: "",
        condSkuId: "",
        condNum: "",

        eventDateTime: [],
        startDate: "",
        endDate: "",
        comm: "",
      },
      formRules: {
        name: [{ required: true, message: "不能为空！", trigger: "blur" }],
        rewardGoodId: [
          { required: true, message: "不能为空！", trigger: "blur" },
        ],
        rewardSkuId: [
          { required: true, message: "不能为空！", trigger: "change" },
        ],
        // rewardNum: [
        //   {
        //     required: true,
        //     type: "number",
        //     message: "不能为空！",
        //     trigger: "blur",
        //   },
        // ],
        condGoodId: [
          { required: true, message: "不能为空！", trigger: "blur" },
        ],
        condSkuId: [
          { required: true, message: "不能为空！", trigger: "change" },
        ],
        // condNum: [
        //   {
        //     required: true,
        //     type: "number",
        //     message: "不能为空！",
        //     trigger: "blur",
        //   },
        // ],
        eventDateTime: [
          {
            type: "array",
            required: true,
            fields: {
              0: { type: "date", required: true, message: "请选择起止日期" },
              1: { type: "date", required: true, message: "请选择起止日期" },
            },
          },
        ],
      },
      rewardSkuLoading: false,
      rewardSkuList: [],
      condSkuLoading: false,
      condSkuList: [],

      dateOptions: {
        disabledDate: (date) => {
          return date && date.valueOf() < dateNow;
        },
      },
    };
  },
  mounted() {
    this.requestDetail();
  },
  methods: {
    ...mapMutations(["closeTag"]),
    requestDetail() {
      this.activityId = this.$route.query.activityId;
      this.form.activityId = this.activityId;
      this.form.id = this.$route.query.id;
      if (this.activityId) {
        this.loading = true;
        this.api({
          apiName: "purchaseGiftEventList",
          postdata: {
            activityId: this.activityId,
            activityName: "",
            status: 0,
            pageIndex: 1,
            pageSize: 10,
          },
          complete: () => {
            this.loading = false;
          },
          success: (res) => {
            if (res.data.records && res.data.records[0]) {
              this.initForm(res.data.records[0]);
            }
          },
        });
      }
    },
    handleCancel() {
      let route = this.$route;
      let toRouteName = "purchase_gift_event_list";
      this.closeTag({ route, toRouteName });
    },
    handleGoodsIdChange(k, skuId) {
      const map = {
        reward: {
          goodsIdKey: "rewardGoodId",
          skuIdKey: "rewardSkuId",
          skuLoadingKey: "rewardSkuLoading",
          skuListKey: "rewardSkuList",
        },
        cond: {
          goodsIdKey: "condGoodId",
          skuIdKey: "condSkuId",
          skuLoadingKey: "condSkuLoading",
          skuListKey: "condSkuList",
        },
      };
      let key = map[k];

      if (this.form[key.goodsIdKey] && this.form[key.goodsIdKey].length > 30) {
        this.api({
          apiName: "getGoodsSkuInfo",
          postdata: {
            goodId: this.form[key.goodsIdKey].trim(),
          },
          success: (res) => {
            let list = [];
            res.data.forEach((item) => {
              for (let skuId in item) {
                list.push({
                  skuId,
                  propList: item[skuId],
                  label: item[skuId]
                    .map((p) => `${p.propKey}: ${p.propVal}`)
                    .join("-"),
                });
              }
            });
            this.form[key.skuIdKey] = skuId ? skuId : "";
            this[key.skuListKey] = list;
          },
        });
      }
    },
    handleSubmit() {
      let title = "添加成功~";
      let apiName = "addPurchaseGiftEvent";

      if (this.activityId) {
        title = "编辑成功~";
        apiName = "updatePurchaseGiftEvent";
      }

      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.genSubmitForm();

          this.api({
            apiName,
            postdata: this.form,
            success: () => {
              this.handleCancel();
              this.$Notice.success({ title });
            },
            complete: () => {
              this.submitLoading = false;
            },
          });
        }
      });
    },
    initForm(data) {
      this.form = { ...this.form, ...data };
      this.handleGoodsIdChange("reward", data.rewardSkuId);
      this.handleGoodsIdChange("cond", data.condSkuId);
      this.form.eventDateTime = [
        new Date(data.startDate),
        new Date(data.endDate - 24 * 60 * 60 * 1000 + 1000),
      ];
    },
    genSubmitForm() {
      this.form.name = this.form.name.trim();
      this.form.comm = this.form.comm.trim();
      this.form.condGoodId = this.form.condGoodId.trim();
      this.form.rewardGoodId = this.form.rewardGoodId.trim();
      this.form.startDate = +new Date(this.form.eventDateTime[0]);
      this.form.endDate =
        +new Date(this.form.eventDateTime[1]) + 24 * 60 * 60 * 1000 - 1000;
    },
  },
};
</script>

<style scoped lang="less">
.purchase-gift-add-event-con {
  height: 100%;
  min-width: 1000px;
  // position: relative;

  .loading-card {
    height: 100%;
  }
  .main_card {
    overflow: hidden;
    .main_info {
      float: left;
      width: 50%;
      .head {
        color: #17233d;
        font-size: 18px;
        font-weight: bold;
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        i {
          margin-right: 10px;
        }
      }
      .time {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .footer-con {
        display: flex;
        padding: 20px;
        justify-content: center;
        > button:first-of-type {
          margin-right: 20px;
        }
      }
    }
  }
}
</style>
