<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" :readonly="couponDeliveryId ? true : false" placeholder="请输入活动名称" />
          </Form-item>
          <Form-item label="编号：" prop="couponId">
            <Input v-model="form.couponId" placeholder="请输入优惠券编号编号" :readonly="couponDeliveryId ? true : false"/>
          </Form-item>
          <Form-item label="名称：">
            <Input v-model="couponName" readonly placeholder="优惠劵名称" />
          </Form-item>
          <Form-item label="数量：" prop="number">
            <Input v-model.number="form.number" :readonly="couponDeliveryId ? true : false" type="number"
              placeholder="请输入数量" />
          </Form-item>
          <Form-item label="数据：" prop="excelUrl">
            <div class="form-upload-data">
              <Upload ref="uploadFile" :action="uploadImgUrl" :headers="{
                token: $store.state.admin.token,
                adminId: $store.state.admin.uid,
              }" accept=".xlsx" :on-success="handleSuccess" :on-error="handleErr" :on-progress="handleOnProgress"
                :before-upload="beforeUpload">
                <Input :value="form.excelUrl" readonly placeholder="请选择数据文件">
                <span slot="append">上 传</span>
                </Input>
              </Upload>
              <Button type="text" class="down-excle" @click="downloadTemplate">下载模板</Button>
            </div>
          </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 { mapMutations } from "vuex";
import { apiVerify } from "@/api/apiVerify";
import { uploadImgUrl } from "@/api/apiConfig";
import { formatTime } from "@/libs/tools";
export default {
  name: "airdrop_add_airdrop",
  computed: {
    title() {
      return this.couponDeliveryId ? "补发优惠劵空投" : "新增优惠劵空投";
    },
  },
  data() {
    return {
      uploadImgUrl,
      couponDeliveryId: "",
      loading: false,
      submitLoading: false,
      form: {
        name: "",
        excelUrl: "",
        couponId: "",
        merchantId: "",
        number: null
      },
      formRules: {
        name: [
          { required: true, message: "活动名称不能为空！", trigger: "blur" },
        ],
        excelUrl: [
          { required: true, message: "数据文件不能为空！", trigger: "change" },
        ],
        couponId: [
          { required: true, message: "优惠劵编号不能为空！", trigger: "change" },
        ],
        number: [
          {
            type: "number",
            required: true,
            message: "数量不能为空！",
            trigger: "blur",
          },
        ],
      },
      SKU_MAX_NUM: 20,
      skuList: [],
      dateOptions: {
        disabledDate: (date) => {
          return date && date.valueOf() < Date.now();
        },
      },
      couponName:""
    };
  },
  watch:{
    'form.couponId':{
      handler(val){
        this.handlecouponIdChange()
      },
      deep:true
    }
  },
  mounted() {
    this.requestDetail();
  },
  methods: {
    ...mapMutations(["closeTag"]),
    handlecouponIdChange() {
      if (this.form.couponId) {
        this._geteCouponId();
      }else{
        this.couponName=''
      }
    },
    _geteCouponId() {
      this.api({
        apiName: "geteCouponId",
        postdata: this.form.couponId.trim(),
        success: (res) => {
          this.couponName = res.data.name
        },
        error:()=>{
          this.couponName=''
          this.$Notice.error({ title: "优惠劵编号错误！" });
        }
      });
    },
    downloadTemplate() {
      this.api({
        apiName: "AerialDeliveryExcel",
        success: (res) => {
          window.open(res.data, "_blank");
        },
      });
    },
    requestDetail() {
      this.couponDeliveryId = this.$route.query.couponDeliveryId;
      this.form.couponDeliveryId = this.couponDeliveryId;
      if (this.couponDeliveryId) {
        this.loading = true;
        this.api({
          apiName: "getCouponDeliveryList",
          postdata: {
            couponDeliveryId: this.couponDeliveryId,
            pageNum: 1,
            pageSize: 1
          },
          complete: () => {
            this.loading = false;
          },
          success: (res) => {
            let val = res.data && res.data.records
            if (val.length > 0) {
              this.form.name = val[0].name
              this.form.number = val[0].circulation
              this.form.couponId = val[0].couponId
              this.form.excelUrl = val[0].excelUrl
              this.form.couponName=val[0].couponName
              this.couponName=val[0].couponName
            }
          },
        });
      }
    },
    handleSubmit() {
      let title = "添加成功~";
      let apiName = "CouponDeliverySave";
      if (this.couponDeliveryId) {
        title = "补发成功~";
        apiName = "CouponDeliveryReissue";
      }
      this.form.couponName=this.couponName
      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;
            },
          });
        }
      });
    },
    genSubmitForm() {
      this.form.name = this.form.name.trim();
      this.form.couponId = this.form.couponId.trim();
    },
    handleCancel() {
      let route = this.$route;
      let toRouteName = "coupon-airdrop";
      this.closeTag({ route, toRouteName });
    },

    beforeUpload(file) {
      if (this.couponDeliveryId) {
        return false
      }
      this.$refs.uploadFile.clearFiles()
    },
    handleOnProgress(event, file) {
      console.log(event, file)
    },
    handleErr() {
      this.$Notice.error({ title: "上传失败，请稍后再试！" });
    },
    handleSuccess(res, file) {
      if (res.code === "00000") {
        this.form.excelUrl = res.data;
      } else {
        this.$Notice.error({ title: res.msg });
      }
    },
  },
};
</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-upload-data {
      display: flex;
      margin-bottom: 5px;

      >.ivu-form-item {
        flex: 1;
        margin-right: 5px;
        margin-bottom: 15px;
      }

      >button {
        height: 33px;
      }
    }
  }
}
</style>
