<template>
  <div class="container">
    <div class="title">活动设置</div>
    <van-cell-group class="all">
      <van-cell :required="true" title="活动标题" style="font-size:14px;">
        <template slot="default">
          <van-field v-model="title" placeholder="请输入活动标题" class="right" style="font-size:14px;" />
        </template>
      </van-cell>
      <van-cell :required="true" title="活动开始时间" style="font-size:14px;">
        <template slot="default">
          <div class="nobr">
            <van-field
              class="right"
              v-model="startTime1"
              placeholder="请选择开始时间"
              readonly="readonly"
              @click="startShow = true"
            />
            <van-popup v-model="startShow" position="bottom" :overlay="true">
              <van-datetime-picker
                v-model="startTime"
                type="datetime"
                :min-date="minStartDate"
                @cancel="startShow = false"
                @confirm="handleStartTime"
                @change="startTimeChange"
              />
            </van-popup>
          </div>
        </template>
      </van-cell>
      <van-cell :required="true" title="活动结束时间" style="font-size:14px;">
        <template slot="default">
          <div class="jpsl">
            <van-field
              class="right"
              v-model="endTime1"
              placeholder="请选择结束时间"
              readonly="readonly"
              @click="endShow = true"
            />
            <van-popup v-model="endShow" position="bottom" :overlay="true">
              <van-datetime-picker
                v-model="endTime"
                type="datetime"
                :min-date="minEndDate"
                @cancel="endShow = false"
                @confirm="handleEndTime"
                @change="endTimeChange"
              />
            </van-popup>
          </div>
        </template>
      </van-cell>
      <van-cell title="背景图片" style="font-size: 14px">
        <van-uploader v-model="bg_imgs" :max-count="1" :after-read="afterBGRead" />
      </van-cell>
      <van-cell :required="true" title="活动Logo" style="font-size: 14px">
        <van-uploader :max-count="1" v-model="logo_imgs" :after-read="afterLogoRead"></van-uploader>
      </van-cell>
      <van-cell :required="true" title="单日最大发放数量">
        <template slot="default">
          <div class="jpsl">
            <van-field
              class="right noborder"
              readonly
              clickable
              :value="maxNumber"
              placeholder="请输入限制次数"
              @touchstart.native.stop="maxNumber_show = true"
            />
            <van-number-keyboard
              v-model="maxNumber"
              :show="maxNumber_show"
              :maxlength="6"
              @blur="maxNumber_show = false"
            />
          </div>
        </template>
      </van-cell>
      <van-cell :required="true" title="总发放数量">
        <template slot="default">
          <div class="jpsl">
            <van-field
              class="right noborder"
              readonly
              clickable
              :value="totalLimit"
              placeholder="请输入限制次数"
              @touchstart.native.stop="totalLimit_show = true"
            />
            <van-number-keyboard
              v-model="totalLimit"
              :show="totalLimit_show"
              :maxlength="6"
              @blur="totalLimit_show = false"
            />
          </div>
        </template>
      </van-cell>
      <van-cell
        :required="true"
        title="选择优惠券"
        :value="checked_coupon.name"
        is-link
        @click="showCoupon = true"
        center
      />
    </van-cell-group>
    <!-- 活动描述 -->
    <van-cell :required="true" class="detail">
      <div class="border">
        <div class="des">活动描述</div>
        <van-field
          class="area"
          v-model="message"
          rows="2"
          autosize
          type="textarea"
          placeholder="请输入描述"
          show-word-limit
        />
      </div>
    </van-cell>
    <!-- 活动图片 -->
    <div class="detail" style="margin-top:0;">
      <div class="des">活动图片</div>
      <van-uploader v-model="fileList_show" multiple :max-count="9" :after-read="afterImgRead" />
    </div>
    <div class="creat" @click="handleCreate">创建活动</div>
    <van-action-sheet v-model="showCoupon" :actions="coupons" cancel-text="取消" @select="onSelect" />
  </div>
</template>

<script>
import axios from "axios";
import * as API_Active from "@/api/active";
export default {
  data() {
    return {
      minStartDate: null,
      minEndDate: null,
      checked_coupon: {},
      logo_imgs: [],
      bg_imgs: [],
      title: "",
      title2: "",
      coupon: "",
      newCustomer: "",
      condition: "",
      type: "",
      show: false,
      show2: false,
      cashCoupon: "",
      limit: "",
      startTime: new Date(),
      startTime1: "",
      endTime: new Date(),
      endTime1: "",
      startShow: false,
      endShow: false,
      message: "",
      fileList: [],
      fileList_show: [],
      showCoupon: false,
      coupons: [],
      maxNumber: "",
      maxNumber_show: false,
      totalLimit: "",
      totalLimit_show: false
    };
  },
  created() {
    this.minStartDate = new Date();
    this.minEndDate = new Date((new Date()/1000+86400)*1000);
  },
  methods: {
    getTemplateDate(id) {
      API_Active.getTemplateData(id).then(res => {
        this.title = res.data.activityInfo.activityName;
        let time1 = res.data.activityInfo.startTime;
        this.startTime1 =
          `${time1.substring(0, 4)}-${time1.substring(4, 6)}-${time1.substring(
            6,
            8
          )}` + time1.substring(8);
        let time2 = res.data.activityInfo.endTime;
        this.endTime1 =
          `${time2.substring(0, 4)}-${time2.substring(4, 6)}-${time2.substring(
            6,
            8
          )}` + time2.substring(8);
        this.bg_imgs[0] = { url: res.data.activityInfo.backImage };
        this.logo_imgs[0] = { url: res.data.activityInfo.logo };
        this.maxNumber = res.data.activityInfo.joinLimit?.toString();
        this.totalLimit = res.data.activityInfo.totalLimit?.toString();
        this.checked_coupon = JSON.parse(res.data.activityInfo.coupon);
        this.checked_coupon.couponId = res.data.activityInfo.couponId;
        this.message = res.activityInfo.des;
        let imgs = JSON.parse(res.data.activityInfo.image);
        let img_list = [];
        imgs.forEach(i => {
          let item = {};
          item.url = i;
          img_list.push(item);
        });
        this.fileList = img_list;
      });
    },
    onSelect(val) {
      this.checked_coupon = val;
      this.showCoupon = false;
    },
    afterImgRead(file) {
      if (file.length) {
        file.forEach(e => {
          let params = new FormData();
          params.append("file", e.file);
          let url = "http://139.155.48.151:8084/admin/auth/util/saveImg";
          axios.post(url, params).then(res => {
            let img_url = JSON.parse(JSON.stringify(res.data.data.imgPath));
            this.fileList.push(img_url);
          });
        });
      } else {
        let params = new FormData();
        params.append("file", file.file);
        let url = "http://139.155.48.151:8084/admin/auth/util/saveImg";
        axios.post(url, params).then(res => {
          this.fileList.push(JSON.parse(JSON.stringify(res.data.data.imgPath)));
        });
      }
    },
    getCoupons() {
      console.log('获取优惠券');
      let id = sessionStorage.getItem("oyStallCode") || 1;
      API_Active.getAllCouponsByOyStallCode(id).then(res => {
        if (res.data.length === 0 || !res.data.length) {
          this.$toast('您所在店铺没有优惠券,请先去创建');
          setTimeout(()=>{
            this.$router.push('/');
          }, 500);
        } else {
          this.coupons = res.data;
        }
      });
    },
    async afterLogoRead(file) {
      let logo_img = await this.getImgUrl(file.file);
      let item = {
        url: logo_img,
        status: "done",
        message: "上传成功"
      };
      this.logo_imgs[0] = item;
    },
    async afterBGRead(file) {
      let bg_img = await this.getImgUrl(file.file);
      let item = {
        url: bg_img,
        status: "done",
        message: "上传成功"
      };
      this.bg_imgs[0] = item;
    },
    // 上传图片
    async getImgUrl(file) {
      let params = new FormData();
      params.append("file", file);
      let url = "http://139.155.48.151:8084/admin/auth/util/saveImg";
      const img = await axios.post(url, params);
      let urls = img.data.data.imgPath;
      return urls;
    },
    handleCreate() {
      if (
        this.title === '' ||
        this.startTime1 == '' ||
        this.endTime1 == '' ||
        this.logo_imgs.length == 0 ||
        this.maxNumber == '' ||
        this.totalLimit == '' || 
        this.checked_coupon == {} ||
        this.message == ''
      ) {
        this.$toast('请完整填写活动表单!');
        return;
      }
      if (new Date(this.startTime1) >= new Date(this.endTime1)) {
        this.$toast("活动开始时间应小于活动开始时间");
        return;
      }

      let params = {
        activityInfo: {
          id: 0,
          activityName: this.title,
          activityType: "coupon",
          startTime: this.startTime1,
          endTime: this.endTime1,
          backImage: this.bg_imgs[0] ? this.bg_imgs[0].url : "",
          logo: this.logo_imgs[0] ? this.logo_imgs[0].url : "",
          // 单日最大发放数量
          joinLimit: Number(this.maxNumber),
          // 总发放数量
          totalLimit: Number(this.totalLimit),
          coupon: JSON.stringify(this.checked_coupon),
          couponId: this.checked_coupon.id,

          des: this.message,
          image: JSON.stringify(this.fileList)
        }
      };
      console.log("params", params);
      API_Active.createActive(params).then(res => {
        if (res.result === "fail") {
          this.$toast(res.errorMsg);
          return;
        }
        this.$toast.success("创建成功");
        setTimeout(() => {
          this.$router.push({
            name: "createSuccess",
            params: {
              id: 0,
              activityId: res.data.activityInfo.id,
              activityType: "coupon",
              logo: this.logo_imgs[0].url,
              des: this.message
            }
          });
        }, 200);
      });
    },
    timeFormat(time) {
      let year = 1900 + time.getYear();
      let month = "0" + (time.getMonth() + 1);
      let date = "0" + time.getDate();
      let hour = "0" + time.getHours();
      let minute = "0" + time.getMinutes();
      return (
        year +
        "-" +
        month.substring(month.length - 2, month.length) +
        "-" +
        date.substring(date.length - 2, date.length) +
        " " +
        hour.substring(hour.length - 2, hour.length) +
        ":" +
        minute.substring(minute.length - 2, minute.length) +
        ":00"
      );
    },
    startTimeChange(e) {
      let startTimeArr = e.getValues();
      this.startTime1 = `${startTimeArr[0]}-${startTimeArr[1]}-${startTimeArr[2]}`;
    },
    handleStartTime(value) {
      this.startTime1 = this.timeFormat(value);
      this.startShow = false;
    },
    handleEndTime(value) {
      this.endTime1 = this.timeFormat(value);
      this.endShow = false;
    },
    endTimeChange(e) {
      let endTimeArr = e.getValues();
      this.endTime1 = `${endTimeArr[0]}-${endTimeArr[1]}-${endTimeArr[2]}`;
    }
  },
  mounted() {
    if (this.$route.query.activityId) {
      console.log("有模板数据");
      let template_id = this.$route.query.templateId;
      this.getTemplateDate(template_id);
    }
    this.getCoupons();
  }
};
</script>
<style></style>

<style scoped>
.condition {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.phone {
  margin-right: 10px;
}
.all >>> input {
  text-align: right;
}
.noborder >>> .van-cell:not(:last-child)::after {
  display: none !important;
}
.npbr .van-cell:not(:last-child)::after {
  display: none !important;
}
.creat {
  margin-top: 80px;
  width: 96%;
  height: 40px;
  background: rgba(117, 178, 253, 1);
  border-radius: 10px;
  text-align: center;
  line-height: 40px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  margin-left: 2%;
  margin-bottom: 16px;
}
.container {
  height: auto;
  display: flex;
  flex-direction: column;
  background: rgba(248, 248, 248, 1);
  min-height: 100%;
}
.area >>> .van-field__control {
  background: #f8f8f8;
  padding: 12px;
}
.des {
  padding: 5px 18px 0px;
  font-size: 14px;
  color: #2d476a;
}

.title {
  background-color: #f8f8f8;
  height: 36px;
  line-height: 36px;
  font-size: 12px;
  padding-left: 16px;
  color: #2d476a;
}
[data-v-08d4afe1] .van-cell {
  height: 100%;
  font-size: 14px;
}
.right {
  padding: 0;
}
.van-cell__title {
  color: #2d476a !important;
}
</style>