<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="aerialDeliveryId?true:false" placeholder="请输入活动名称" />
          </Form-item>

          <Form-item label="商品编号：" prop="goodsId">
            <Input
              v-model="form.goodsId"
              placeholder="请输入商品编号"
							:readonly="aerialDeliveryId?true:false"
              @on-change="handleGoodsIdChange"
            />
          </Form-item>

          <Form-item label="规格：" prop="skuId" v-if="form.salesType!==4">
            <Select placeholder="请选择商品规格" v-model="form.skuId">
              <Option
                v-for="item in skuList"
                :value="item.skuId"
								:readonly="aerialDeliveryId?true:false"
                :key="item.skuId"
              >
                {{ item.label }}
              </Option>
            </Select>
          </Form-item>

          <Form-item label="数量：" prop="number">
            <Input
              v-model.number="form.number"
							:readonly="aerialDeliveryId?true:false"
              type="number"
              placeholder="请输入数量"
            />
          </Form-item>
          <!-- <Form-item label="备注：" prop="comm">
            <Input v-model="form.comm" 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.aerialDeliveryId ? "补发空投活动" : "新增空投活动";
    },
  },
  data() {
    return {
      uploadImgUrl,
      aerialDeliveryId: "",
      loading: false,
      submitLoading: false,
      form: {
        name: "",
        excelUrl: "",
        goodsId: "",
        merchantId: "",
        number: null,
        skuId: "",
      },
      formRules: {
        name: [
          { required: true, message: "活动名称不能为空！", trigger: "blur" },
        ],
        skuId: [
          { required: true, message: "规格不能为空！", trigger: "change" },
        ],
        excelUrl: [
          { required: true, message: "数据文件不能为空！", trigger: "change" },
        ],
        goodsId: [
          { 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();
        },
      },
    };
  },
  mounted() {
    this.requestDetail();
  },
  methods: {
    ...mapMutations(["closeTag"]),
    handleGoodsIdChange() {
      if (this.form.goodsId && this.form.goodsId.length > 30) {
        this._getGoodsSkuInfo();
      }
    },
    _getGoodsSkuInfo(type,skuId) {
      this.api({
        apiName: "getGoodDetail",
        postdata: {
          id: this.form.goodsId.trim(),
        },
        success: (res) => {
          let list = [];
          let arr=res.data.skus || []
            arr.forEach((item)=>{
            let propertyList=item.propertyList || []
              list.push({
                skuId:item.skuId,
                label: propertyList.map((p) => `${p.propKey}: ${p.propVal}`)
                  .join("-"),
              });
          })
          this.form.salesType=res.data.salesType
          this.skuList = list;
					if(type==='reissue'){
						this.form.skuId = skuId;
					}else{
						this.form.skuId = "";
					}
          if(res.data.salesType===4){
            this.form.skuId=""
            this.form.number=1
          }
        },
      });
    },
    downloadTemplate() {
      this.api({
        apiName: "AerialDeliveryExcel",
        success: (res) => {
          window.open(res.data, "_blank");
        },
      });
    },
    requestDetail() {
      this.aerialDeliveryId = this.$route.query.aerialDeliveryId;
      this.form.aerialDeliveryId = this.aerialDeliveryId;
      this.form.id = this.$route.query.id;
      if (this.aerialDeliveryId) {
        this.loading = true;
        this.api({
          apiName: "getAerialDeliveryId",
          postdata: {
            aerialDeliveryId: this.aerialDeliveryId,
          },
          complete: () => {
            this.loading = false;
          },
          success: (res) => {
            if (res.data) {
              this.form.name=res.data.name
							this.form.number=res.data.circulation
							this.form.goodsId=res.data.goodsId
							this.form.excelUrl=res.data.excelUrl
							this._getGoodsSkuInfo("reissue",res.data.skuId)
            }
          },
        });
      }
    },
    handleSubmit() {
			let title = "添加成功~";
      let apiName = "AerialDeliverySave";
      if (this.aerialDeliveryId) {
        title = "补发成功~";
        apiName = "AerialDeliveryReissue";
      }
      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.goodsId = this.form.goodsId.trim();
    },
    handleCancel() {
      let route = this.$route;
      let toRouteName = "airdrop_activity";
      this.closeTag({ route, toRouteName });
    },

    beforeUpload(file) {
			if(this.aerialDeliveryId){
				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>
