<template>
  <div class="collect-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="rewardGoods">
            <div
              class="form-sku"
              v-for="(sku, index) of form.rewardGoods"
              :key="`reward-sku-item-${index}`"
            >
              <Form-item
                :prop="`rewardGoods[${index}].goodsId`"
                :rules="formRules.skuGoodsId"
              >
                <Input
                  v-model="sku.goodsId"
                  placeholder="请输入商品编号"
                  @on-change="handleGoodsIdChange('rewardGoods', index)"
                />
              </Form-item>
              <Form-item
                :prop="`rewardGoods[${index}].skuId`"
                :rules="formRules.skuId"
              >
                <Select placeholder="请选择商品规格" v-model="sku.skuId">
                  <Option
                    v-for="item in sku.skuList"
                    :value="item.skuId"
                    :key="item.skuId"
                  >
                    {{ item.label }}
                  </Option>
                </Select>
              </Form-item>
              <Form-item
                :prop="`rewardGoods[${index}].num`"
                :rules="formRules.skuNum"
              >
                <Input
                  v-model="sku.num"
                  placeholder="请输入奖励数量"
                  type="number"
                  number
                />
              </Form-item>
              <Button type="error" @click="handleDelSku('rewardGoods', index)">
                删除
              </Button>
            </div>
            <Button
              v-if="form.rewardGoods.length < SKU_MAX_NUM"
              type="info"
              @click="handleAddSku('rewardGoods')"
            >
              新增奖励商品
            </Button>
          </Form-item>

          <Form-item label="条件商品：" prop="condGoods">
            <div
              class="form-sku"
              v-for="(sku, index) of form.condGoods"
              :key="`reward-sku-item-${index}`"
            >
              <Form-item
                :prop="`condGoods[${index}].goodsId`"
                :rules="formRules.skuGoodsId"
              >
                <Input
                  v-model="sku.goodsId"
                  placeholder="请输入商品编号"
                  @on-change="handleGoodsIdChange('condGoods', index)"
                />
              </Form-item>
              <Form-item
                :prop="`condGoods[${index}].skuId`"
                :rules="formRules.skuId"
              >
                <Select placeholder="请选择商品规格" v-model="sku.skuId">
                  <Option
                    v-for="item in sku.skuList"
                    :value="item.skuId"
                    :key="item.skuId"
                  >
                    {{ item.label }}
                  </Option>
                </Select>
              </Form-item>
              <Form-item
                :prop="`condGoods[${index}].num`"
                :rules="formRules.skuNum"
              >
                <Input
                  v-model="sku.num"
                  placeholder="请输入条件数量"
                  type="number"
                  number
                />
              </Form-item>
              <Button type="error" @click="handleDelSku('condGoods', index)">
                删除
              </Button>
            </div>
            <Button
              v-if="form.condGoods.length < SKU_MAX_NUM"
              type="info"
              @click="handleAddSku('condGoods')"
            >
              新增条件商品
            </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: "",

        rewardGoods: [
          { goodsId: "", skuId: "", skuList: [], num: "", type: 2 },
        ],
        condGoods: [{ goodsId: "", skuId: "", skuList: [], num: "", type: 1 }],

        eventDateTime: [],
        startDate: "",
        endDate: "",
        comm: "",
      },
      formRules: {
        name: [{ required: true, message: "不能为空！", trigger: "blur" }],
        rewardGoods: [
          {
            type: "array",
            required: true,
            message: "不能为空！",
            trigger: "change",
          },
        ],
        condGoods: [
          {
            type: "array",
            required: true,
            message: "不能为空！",
            trigger: "change",
          },
        ],
        skuGoodsId: [
          { required: true, message: "不能为空！", trigger: "blur" },
        ],
        skuId: [{ required: true, message: "不能为空！", trigger: "change" }],
        skuNum: [
          {
            type: "number",
            required: true,
            message: "不能为空！",
            trigger: "blur",
          },
        ],
        eventDateTime: [
          {
            type: "array",
            required: true,
            fields: {
              0: { type: "date", required: true, message: "请选择起止日期" },
              1: { type: "date", required: true, message: "请选择起止日期" },
            },
          },
        ],
      },
      SKU_MAX_NUM: 20,

      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: "getCollectEventList",
          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]);
            }
          },
        });
      }
    },
    requestSkuList(key) {
      const map = {
        rewardGoods: 2,
        condGoods: 1,
      };
      return new Promise((resolve, reject) => {
        this.api({
          apiName: "getCollectEventGoodsList",
          postdata: {
            activityId: this.activityId,
            type: map[key],
          },
          success: (res) => {
            this.form[key] = res.data.map(({ goodsId, skuId, num }) => {
              return {
                goodsId,
                skuId,
                num,
                type: map[key],
                skuList: [],
              };
            });
            let i = 0;
            res.data.forEach((sku) => {
              this.handleGoodsIdChange(key, i, sku.skuId);
              i++;
            });
          },
          complete: resolve,
        });
      });
    },
    handleCancel() {
      let route = this.$route;
      let toRouteName = "collect_event_list";
      this.closeTag({ route, toRouteName });
    },

    handleAddSku(key) {
      if (this.form[key].length >= this.SKU_MAX_NUM) {
        return;
      }
      this.$refs.addForm.validateField(key);
      this.form[key].push({
        goodsId: "",
        skuId: "",
        skuList: [],
        num: "",
        type: key == "condGoods" ? 1 : 2,
      });
    },
    handleDelSku(key, index) {
      this.$refs.addForm.validateField(key);
      this.form[key].splice(index, 1);
    },

    handleGoodsIdChange(k, index, skuId) {
      let sku = this.form[k][index];

      if (sku && sku.goodsId.length > 30) {
        this.api({
          apiName: "getGoodsSkuInfo",
          postdata: {
            goodId: sku.goodsId.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("-"),
                });
              }
            });
            sku.skuId = skuId ? skuId : "";
            sku.skuList = list;
          },
        });
      }
    },
    handleSubmit() {
      let title = "添加成功~";
      let apiName = "addCollectEvent";

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

      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 };
      let p1 = this.requestSkuList("rewardGoods");
      let p2 = this.requestSkuList("condGoods");
      Promise.all([p1, p2]).then(() => {
        this.loading = false;
      });
      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();
      for (let sku of this.form.rewardGoods) {
        console.log(sku);
        sku.goodsId = sku.goodsId.trim();
      }
      for (let sku of this.form.condGoods) {
        sku.goodsId = sku.goodsId.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">
.collect-add-event-con {
  height: 100%;
  min-width: 1000px;
  // position: relative;

  .loading-card {
    height: 100%;
  }
  .main_card {
    overflow: hidden;
    .main_info {
      float: left;
      width: 68%;
      .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;
        }
      }
    }

    .form-sku {
      display: flex;
      margin-bottom: 5px;
      > .ivu-form-item {
        flex: 1;
        margin-right: 5px;
        margin-bottom: 15px;
      }
      > button {
        height: 33px;
      }
    }
  }
}
</style>
