modal-create-coupon.vue 28 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
<template>
  <i-modal
    v-model="visiable"
    :loading="posting"
    :title="allreadonly ? '查看优惠券' : '创建/编辑优惠券'"
    @on-ok="onOk"
    width="600"
  >
    <i-spin v-if="loading"></i-spin>
    <i-form v-else ref="formCoupon" :rules="ruleValidate" :model="formData" :label-width="80">
      <i-form-item class="form-group" label="优惠券类型"></i-form-item>
      <i-form-item label="用户类型" prop="userType">
        <radio-group v-model="formData.userType" @on-change="changeUserType">
          <radio :label="1" :disabled="!!formData.id">买家</radio>
          <radio :label="2" :disabled="!!formData.id">卖家</radio>
      </radio-group>
      </i-form-item>
      <div :key="formData.userType">
      <i-form-item label="优惠券类型" prop="couponType">
        <i-select style="width: 100px;" v-model="formData.couponType" :disabled="readonly">
          <i-option :value="0">请选择</i-option>
          <i-option v-for="item in counponOptions" :value="item.value" :key="item.value">{{ item.label }}</i-option>
        </i-select>
      </i-form-item>
      <i-form-item class="form-group" label="基本信息"></i-form-item>
      <i-form-item label="Token" v-if="couponToken">{{couponToken}}</i-form-item>
      <i-form-item label="名称" prop="couponName">
        <i-input
          placeholder="名称建议30字以内"
          v-model="formData.couponName"
          :disabled="allreadonly"
          style="width: 200px"
        ></i-input>
      </i-form-item>
      <i-form-item label="数量" prop="couponNum">
        <i-input-number
          placeholder="数量"
          v-model="formData.couponNum"
          :disabled="allreadonly"
          style="width: 100px;"
        ></i-input-number>
      </i-form-item>
      <i-form-item label="使用次数" prop="useNum">
        <i-input placeholder="使用次数" v-model="formData.useNum" disabled style="width: 100px;"></i-input>
      </i-form-item>
      <i-form-item label="使用期限" prop="time">
        <i-date-picker
          type="datetimerange"
          v-model="formData.time"
          :disabled="allreadonly"
          placeholder="使用期限"
          format="yyyy-MM-dd HH:mm:ss"
          style="width: 250px"
        ></i-date-picker>
      </i-form-item>
      <i-form-item label="领券期限" prop="receiveTime">
        <i-date-picker
          type="datetimerange"
          v-model="formData.receiveTime"
          :disabled="readonly"
          placeholder="领券期限"
          format="yyyy-MM-dd HH:mm:ss"
          style="width: 250px"
        ></i-date-picker>
      </i-form-item>
      <i-form-item label="优惠券说明" prop="remark">
        <i-row>
          <i-col span="20">
            <i-input
              type="textarea"
              placeholder="优惠券使用条件简介"
              :disabled="allreadonly"
              v-model="formData.remark"
            ></i-input>
          </i-col>
        </i-row>
      </i-form-item>
      <i-form-item class="form-group" label="使用条件"></i-form-item>
      <i-form-item label="优惠条件" prop="useLimitType" style="display: inline-block; width: 100%">
        <i-select style="width: 100px" :disabled="readonly" v-model="formData.useLimitType">
          <i-option :value="0">无限制</i-option>
          <i-option :value="2">金额</i-option>
        </i-select>
        <div style="display: inline-block" v-if="formData.useLimitType === 2">
          &nbsp;
          金额满:
          <i-input-number
            style="width: 100px"
            :disabled="readonly"
            placeholder="限制金额"
            v-model="formData.useLimitValue"
          ></i-input-number>
        </div>
      </i-form-item>
      <i-form-item label="优惠金额" prop="couponAmount">
        <i-input-number
          placeholder="优惠金额"
          :disabled="readonly"
          v-model="formData.couponAmount"
          style="width: 100px"
        ></i-input-number>
      </i-form-item>

      <i-form-item label="适用范围" prop="productLimitType">
        <radio-group v-model="formData.productLimitType" @on-change="changeProductType">
          <radio v-for = "(val, key) in allowproductLimitTypeList" :key="formData.userType+key" :label="+key"  :disabled="readonly">{{val}}</radio>
      </radio-group>
      </i-form-item>

      <div :key="formData.productLimitType">
        <i-form-item prop="brandVal" v-if="formData.productLimitType === 4">
          <Select v-model="formData.brandVal" multiple style="width:300px">
          <Option v-for="item in brandList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        </i-form-item>
        <i-form-item :prop="cascaderData.prop"  v-else-if="formData.productLimitType === 5 || formData.productLimitType === 6">
            <i-row  v-for="item in cascaderData.formData.items" :key="item.index" class="add-item">
                <i-col span="16">
                <Cascader :data="cascaderData.data" v-model="item.value" :load-data="cascaderData.loadData"></Cascader>
                </i-col>
                <i-col span="4" offset="1" v-if="item.index > 1">
                    <i-button @click="handleRemove(cascaderData.formData, item.index)"  type="error" size="small" ghost icon="md-close" shape="circle"></i-button>
                </i-col>
            </i-row>

            <i-row>
                <i-col span="10">
                    <i-button type="dashed" long @click="handleAdd(cascaderData.formData)" icon="md-add">添加项</i-button>
                </i-col>
            </i-row>
        </i-form-item>

      <i-form-item
        :prop="uploadProp"
        :label="formData.productLimitType === 1 ? '' : '排除商品'"
      >
        <i-row>
          <i-col span="20">
            <i-input
              type="textarea"
              :key ="formData.productLimitType"
              :disabled="readonly"
              placeholder="填写商品编码,多个商品编码用英文逗号分隔"
              v-model="formData[uploadProp]"
            ></i-input>
          </i-col>
        </i-row>
        <i-poptip trigger="hover">
          <div slot="content">
            <p>1.上传文件必须是xlsx文件</p>
            <p>2.第一行标题栏:商品编码</p>
            <p>
              3.
              <a href="javascript:;" @click="onExample">下载样例</a>
            </p>
          </div>
          <i-upload action :format="['xlsx']" :max-size="1024" :before-upload="onBeforeUpload">
            <i-button type="success" size="small" :disabled="readonly">导入</i-button>
            <p>{{uploadTxt}}</p>
          </i-upload>
        </i-poptip>
      </i-form-item>
      </div>
      <!--<i-form-item label="禁用商品类型">
        <checkbox-group v-model="formData.skupForbidTypeLable" @on-change="getCheckBox">
          <checkbox label="现货" :disabled="readonly"></checkbox>
          <checkbox label="预售" :disabled="readonly"></checkbox>
          <checkbox label="二手" :disabled="readonly"></checkbox>
          <checkbox label="全新瑕疵" :disabled="readonly"></checkbox>
          <checkbox label="闪购" :disabled="readonly"></checkbox>
        </checkbox-group>
      </i-form-item>-->
      <i-form-item label="可用商品类型">
        <checkbox-group v-model="formData.skupAllowTypeLabel" @on-change="getCheckBox">
          <checkbox v-for = "(val, key) in allowTypeLabelList" :key="formData.userType+key" :label="key"  :disabled="readonly">{{val}}</checkbox>
        </checkbox-group>
      </i-form-item>

      <i-form-item label="购买渠道" prop="businessClientLabel">
        <checkbox-group v-model="formData.businessClientLabel" @on-change="getChannelCheckBox">
          <checkbox v-for = "(val, key) in businessClientLabelMap" :key="key" :label="key"  :disabled="readonly">{{val}}</checkbox>
        </checkbox-group>
      </i-form-item>
      <i-form-item label="需要校验" prop="checkRequired">
        <checkbox v-model="formData.isCheckRequired" :disabled="allreadonly" @on-change="getCheckRequired"></checkbox>
      </i-form-item>
      <i-form-item v-if="isShowDetail" label="展示在详情页" prop="isShowInDetail">
        <checkbox v-model="formData.isShowInDetail" :disabled="allreadonly" @on-change="setIsShowInDetail"></checkbox>
      </i-form-item>
      </div>
    </i-form>
  </i-modal>
</template>

<script>
import Api from "api/api";
import dayjs from "dayjs";
import XLSX from "xlsx";

const api = new Api();
const forbidenTypeMap = {
  现货: 1,
  预售: 4,
  二手: 6,
  全新瑕疵: 5,
  闪购: 3
};
const forbidenLabelMap = {
  1: "现货",
  4: "预售",
  6: "二手",
  5: "全新瑕疵",
  3: "闪购"
};
const userCouponType = {
  buyer: [{
              value: 100,
              label: '活动券'
          },
          {
              value: 110,
              label: '运费券'
          }],
  seller: [{
              value: 100,
              label: '活动券'
          }]
}

const sellerAllowLabel = {
  "1-N": "现货发货",
  "4": "预售",
  "5": "瑕疵",
  "6": "二手",
};
const allowproductLimitTypeList = {
  1: "指定商品",
  2: "全部商品",
  // 3: "排除商品",
  4: "特定品牌",
  5: "特定品类",
  6: "特定系列"
}

const allowLabelMap = {
  // '2': '线下店订单',
  "9-N": "极速发货",
  "9-Y": "极速寄存",
  "4": "预售",
  "5": "瑕疵",
  "6": "二手",
  // '8': '鉴定',
  "17": "海外直邮",
  "1-N": "现货发货",
  "1-Y": "现货寄存",
  "3-N": "闪购发货",
  "3-Y": "闪购寄存"
};

const businessClientLabelMap = {
  ufo: "UFO",
  "h5/xianyu": "闲鱼"
};
const initFormData = {
        id: 0,
        couponName: "",
        couponNum: 0,
        couponType: 0,
        useNum: 1,
        couponAmount: 0,
        useLimitType: 0,
        remark: "",
        productLimitValue: "",
        productLimitType: 2,
        brandVal: [],
        category: {
          index: 1,
          items: [{
            index: 1,
            value: []
          }]
        },
        series: {
          index: 1,
          items: [{
            index: 1,
            value: []
          }]
        },
        excludeProductIds: "",
        useLimitValue: 0,
        time: ["", ""],
        receiveTime: ["", ""],
        skupAllowTypeLabel: [],
        businessClientLabel: [],
        checkRequired: 0,
        isCheckRequired: false,
        // 是否展示在详情页
        isShowInDetail: false,
        //        skupForbidTypeLable:[],
        //        skupForbidType: ''
    };

export default {
  components: {},
  name: "ModalCreateCoupon",
  data() {
    return {
      readonly: false,
      allreadonly: false,
      visiable: false,
      loading: false,
      posting: true,
      uploadTxt: "",
      couponToken: "",
      formData: {
        userType: 1,
        ...initFormData
      },
      buyerFormDataCache: {
        userType: 1,
        ...initFormData
      },
      sellerFormDataCache: {
        userType: 2,
        ...initFormData
      },
      lastSelectType: 2,
      excludeValCache: {
        2: "",
        3: "",
        4: "",
        5: "",
        6: ""
      },
      allowproductLimitTypeList,
      businessClientLabelMap,
      brandList: [],
      categoryList: [],
      seriesList: [],
      ruleValidate: {
        couponType: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === 0 || value === "0") {
              callback(new Error("请选择优惠券类型"));
            } else {
              callback();
            }
          }
        },
        couponName: { required: true, max: 30, message: "请输入名称" },
        couponNum: {
          type: "number",
          required: true,
          min: 1,
          message: "请输入数量"
        },
        couponAmount: {
          type: "number",
          required: true,
          min: 1,
          message: "请输入优惠金额"
        },
        time: {
          required: true,
          validator: (rule, value, callback) => {
            if (value.some(v => !v)) {
              callback(new Error("请选择使用期限"));
            } else {
              callback();
            }
          }
        },
        receiveTime: {
          required: true,
          validator: (rule, value, callback) => {
            if (value.some(v => !v)) {
              callback(new Error("请选择领券期限"));
            } else {
              let endTime = this.formData.time[1]
                ? dayjs(this.formData.time[1]).unix()
                : void 0;
              let receiveEndTime = value[1] ? dayjs(value[1]).unix() : void 0;
              // console.log('====/'+endTime+"///===/"+receiveEndTime)
              if (endTime < receiveEndTime) {
                callback(new Error("请选择领券结束时间小于使用结束时间"));
              } else {
                callback();
              }
            }
          }
        },
        remark: { required: true, message: "请输入优惠券说明" },
        useLimitType: {
          required: true,
          validator: (rule, value, callback) => {
            if (value >= 0) {
              if (value === 2) {
                if (parseInt(this.formData.useLimitValue) > 0) {
                  callback();
                } else {
                  callback(new Error("请输入限制金额"));
                }
              } else {
                callback();
              }
            } else {
              callback(new Error("请选择优惠条件"));
            }
          }
        },
        productLimitValue: {
          required: true,
          validator: (rule, value, callback) => {
            const ids = (value || "").split(",");

            if (!value || !ids.length) {
              callback(new Error("请输入适用范围"));
            } else if (ids.some(id => (id ? !parseInt(id) : false))) {
              callback(new Error("适用范围格式错误"));
            } else {
              callback();
            }
          }
        },
        excludeProductIds: {
          required: false,
          validator: (rule, value, callback) => {
            const ids = (value || "").split(",");

            if (ids.some(id => (id ? !parseInt(id) : false))) {
              callback(new Error("适用范围格式错误"));
            } else {
              callback();
            }
          }
        },
        brandVal: {
          required: true,
          validator: (rule, value, callback) => {
            if (value.length > 0) {
              callback();
            } else {
              callback(new Error("请选择品牌"));
            }
          }
        },
        category: {
          required: true,
          validator: (rule, value, callback) => {
          if(value.items.length >0 && value.items[0].value.length > 0) { //保证至少有一组值
              callback();
            } else {
              callback(new Error("请选择品类"));
            }
          }
        },
        series: {
          required: true,
          validator: (rule, value, callback) => {
          if(value.items.length >0 && value.items[0].value.length > 0) { //保证至少有一组值
              callback();
            } else {
              callback(new Error("请选择系列"));
            }
          }
        },
        productLimitType: {
          required: true,
          validator: (rule, value, callback) => {
            if (value > 0) {
              callback();
            } else {
              callback(new Error("请选择类型"));
            }
          }
        },
        businessClientLabel: {
          required: true,
          validator: (rule, value, callback) => {
            if (value.length > 0) {
              callback();
            } else {
              callback(new Error("请选择购买渠道"));
            }
          }
        }
      }
    };
  },
  computed: {
    allowTypeLabelList: function() {
      return this.formData.userType === 1 ? allowLabelMap : sellerAllowLabel
    },
    counponOptions: function() { 
      return  this.formData.userType === 1 ? userCouponType.buyer : userCouponType.seller
    },
    isShowDetail: function() {
      return  this.formData.userType === 1 ? true : false
    },
    uploadProp: function() {
      return  this.formData.productLimitType === 1 ? 'productLimitValue' : 'excludeProductIds'
    },
    cascaderData: function() {
      let cascaderObj = {}
      if (this.formData.productLimitType === 5) {
        cascaderObj.prop = "category"
        cascaderObj.formData = this.formData.category
        cascaderObj.data = this.categoryList
        cascaderObj.loadData = this.loadCategoryData
      }else if(this.formData.productLimitType === 6) {
        cascaderObj.prop = "series"
        cascaderObj.formData = this.formData.series
        cascaderObj.data = this.seriesList
        cascaderObj.loadData = this.loadSeriesData
      }
      return cascaderObj
    } 
  },
  methods: {
    async show(id, readonly, allreadonly) {
      // console.log(id)
      this.readonly = readonly;
      this.allreadonly = allreadonly;
      this.posting = this.visiable = true;
      this.$refs.formCoupon.resetFields();
      for (let key in this.excludeValCache) {
        this.excludeValCache[key] = ""
      }
      this.couponToken = "";
      let initData = initFormData
      initData.userType = 1
      if (id) {
        this.loading = true;
        const result = await api._get("/ufoPlatform/coupon/getCouponInfo", {
          id
        });

        // console.log(result);

        this.loading = false;

        if (result.code === 200) {
          const coupon = result.data.coupon;
          console.log(result.data)
          const productLimits = result.data.productLimits;

          this.couponToken = coupon.couponToken;
          let isCheckRequired = coupon.checkRequired === 1
          console.log('=====:'+isCheckRequired)
          initData = {
            ...initFormData,
            id,
            userType: coupon.userType,
            couponName: coupon.couponName,
            couponNum: coupon.couponNum,
            couponType: coupon.couponType || 0,
            useNum: coupon.useNum,
            couponAmount: coupon.couponAmount,
            useLimitType: coupon.useLimitType,
            remark: coupon.remark,
            productLimitType: coupon.productLimitType,
            excludeProductIds: result.data.excludeProductIds,
            useLimitValue: coupon.useLimitValue,
            time: [
              dayjs.unix(coupon.startTime).format("YYYY-MM-DD HH:mm:ss"),
              dayjs.unix(coupon.endTime).format("YYYY-MM-DD HH:mm:ss")
            ],
            receiveTime: [
              dayjs.unix(coupon.receiveStartTime).format("YYYY-MM-DD HH:mm:ss"),
              dayjs.unix(coupon.receiveEndTime).format("YYYY-MM-DD HH:mm:ss")
            ],
            skupAllowTypeLabel: coupon.skupAllowType.split(","),
            businessClientLabel: coupon.businessClient.split(","), //购买渠道
            checkRequired: coupon.checkRequired,
            isCheckRequired,
            isShowInDetail: result.data.showInPrdDetail === 'Y'
          };
          this.setSelectItems(coupon.productLimitType,coupon.productLimitValue)
        } else {
          result.message && this.$Message.warning(result.message);
        }
      }
      this.formData = initData;
    },
    async setSelectItems(type,val) {
      await this.getSelectItems(type)
      this.setValToSelect(type,val)
      this.lastSelectType = type
    },
    setValToSelect(type,val) {
      switch (type) {
        case 1:
          this.formData.productLimitValue = val
          break
        case 4:
          this.formData.brandVal = val.split(",").map(item => parseInt(item))
          break
        case 5:
          this.formData.category = this.getFormSelectedVal(val)
          break
        case 6:
          this.formData.series = this.getFormSelectedVal(val)
      }
    },
    getFormSelectedVal(val) {
      let selectedVal = {}
          let valArr = val.split(",")
          selectedVal.index = valArr.length
          let itemsArr = []
          for(let i = 0; i < valArr.length; i++) {
            let item = {}
            item.index = i+1
            item.value = valArr[i].split("-").map(item => parseInt(item))
            itemsArr.push(item)
          }
          selectedVal.items = itemsArr
          return selectedVal
    },
    async getSelectItems(type) {
      let typeData = {
        4: { url: "/ufoPlatform/brand/getBrandName",name: "brandList"},
        5: { url: "/ufoPlatform/productSort/getLevel1SortIdAndName", name: "categoryList"},
        6: { url: "/ufoPlatform/brand/getBrandName", name: "seriesList"}
      };
      if(!typeData[type]) {
        return
      }
      let dataListName = typeData[type].name
      if(this[dataListName].length > 0) {
        return this[dataListName]
      }
      const result = await api._get(typeData[type].url)
      let dataList = result.data
        dataList.map((item) => {
        item.label = item.text
        item.value = item.id
        delete item.text
        delete item.id
        if(+type === 6 || +type == 5) {
          item.children = []
          item.loading = false
        }
        return item
      })

      this[dataListName] = dataList
    },
    loadSeriesData (item, callback) {
      this.loadData("seires", item, callback)
    },
    loadCategoryData (item, callback) {
      this.loadData("category", item, callback)
    },
    async loadData (name, item, callback) {
      let loadRequest = {
        "seires": {url: "/ufoPlatform/brandSeries/querySeriesByBrandId", params: {brandId: item.value}},
        "category": {url: "/ufoPlatform/productSort/getLevel2SortBySortId", params: {sortId: item.value}}
      }
      item.loading = true;
      const result = await api._get(loadRequest[name].url, loadRequest[name].params)
      let childrenList = result.data

      childrenList.map((item) => {
      item.label = item.text
      item.value = item.id
      delete item.text
      delete item.id
      return item
      })
      item.children = childrenList
      item.loading = false;
      callback();
    },
    handleAdd (cascaderData) {
      cascaderData.index++;
      cascaderData.items.push({index: cascaderData.index,value:[]});
    },
    handleRemove (cascaderData, index) {
      let totalItem = cascaderData.index
      cascaderData.index--;
      
      if(index < totalItem) { // 删除中间项时 后面index重置
      cascaderData.items.splice(index-1,1);
      let newData = cascaderData.items
        for(let i = index-1; i < cascaderData.index; i++) {
          newData[i].index--
        }
        cascaderData.items = newData
      } else {
        cascaderData.items.pop();
      }
    },
    onOk() {
      this.$refs.formCoupon.validate(valid => {
        if (!valid) {
          this.posting = false;
          this.$nextTick(() => {
            this.posting = true;
          });
        } else {
          this.saveData(this.formData);
        }
      });
    },
    getCheckRequired(checked) {
      if(checked) {
        this.formData.checkRequired = 1
      }else {
        this.formData.checkRequired = 0
      }
      

    },
    setIsShowInDetail(checked) {
      this.formData.isShowInDetail = checked
    },
    changeUserType(val) {
      if(val === 2) {
        this.buyerFormDataCache = {...this.formData, userType: 1}
        this.formData = this.sellerFormDataCache
      } else {
        this.sellerFormDataCache = {...this.formData, userType: 2}
        this.formData = this.buyerFormDataCache
      }
    },

    changeProductType(val) {
      // 排除商品缓存设置
      this.excludeValCache[this.lastSelectType] = this.formData.excludeProductIds
      this.formData.excludeProductIds = this.excludeValCache[val]
      this.lastSelectType = val
      this.getSelectItems(val)
      
    },

    getLimitVal(propName) {
        let processData = this.formData[propName].items
        let idsArr = []
        for(let i = 0; i < processData.length; i++) {
          if(processData[i].value.length > 0) {
            let lastId = processData[i].value.pop()
            idsArr.push(lastId)
          }
        }
        return idsArr.join(",")
    },
    processProductLimitValue(type) {
      let valueType = {
        1: this.formData.productLimitValue,
        2: "",
        3: "",
        4: this.formData.brandVal.join(","),
        5: this.getLimitVal('category'),
        6: this.getLimitVal('series')
      }
      return valueType[type]
    },
    async saveData(params) {
      console.log('post params')
      console.log(params)
      let that = this
      if (this.allreadonly) {
        this.visiable = false;
        return;
      }

      const result = await api._post("/ufoPlatform/coupon/saveOrUpdateCoupon", {
        id: params.id || void 0,
        userType: params.userType,
        couponName: params.couponName,
        couponAmount: params.couponAmount,
        couponNum: params.couponNum,
        couponType: params.couponType,
        useNum: params.useNum,
        useLimitValue: params.useLimitValue,
        productLimitType: params.productLimitType,
        productLimitValue: this.processProductLimitValue(params.productLimitType),
        excludeProductIds: params.excludeProductIds,
        remark: params.remark,
        useLimitType:
          parseInt(params.useLimitType) >= 0 ? params.useLimitType : void 0,
        startTime: params.time[0] ? dayjs(params.time[0]).unix() : void 0,
        endTime: params.time[1] ? dayjs(params.time[1]).unix() : void 0,
        skupAllowType: params.skupAllowTypeLabel.join(","),
        businessClient: params.businessClientLabel.join(","),
        receiveStartTime: params.receiveTime[0]
          ? dayjs(params.receiveTime[0]).unix()
          : void 0,
        receiveEndTime: params.receiveTime[1]
          ? dayjs(params.receiveTime[1]).unix()
          : void 0,
          checkRequired:params.checkRequired,
        showInPrdDetail: params.isShowInDetail ? 'Y' : 'N'

      });

      // console.log('result=', result);

      if (result.code === 200) {
        this.$Message.success("保存成功");
        this.visiable = false;
        this.$emit("on-created");
      } else {
        result.message && this.$Message.warning(result.message);
        this.posting = false;
        this.$nextTick(() => {
          this.posting = true;
        });
      }
    },
    onBeforeUpload(file) {
      const fileExt = file.name
        .split(".")
        .pop()
        .toLocaleLowerCase();
      // console.log(fileExt)
      if (fileExt !== "xlsx") {
        this.$Message.warning("文件格式错误");
        return false;
      }
      if (file.size > 1024 * 1024) {
        this.$Message.warning("文件大小超过1M");
        return false;
      }
      const reader = new FileReader();

      reader.readAsArrayBuffer(file);
      reader.onloadstart = () => {
        this.uploadTxt = "开始读取";
      };
      reader.onprogress = e => {
        this.uploadTxt = `进度:${Math.round((e.loaded / e.total) * 100)}...`;
      };
      reader.onerror = () => {
        this.uploadTxt = "文件读取出错";
      };
      reader.onload = e => {
        this.uploadTxt = "";
        try {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const results = XLSX.utils.sheet_to_json(worksheet);

          this.formData[this.uploadProp] = results
          
            .map(r => r["商品编码"])
            .filter(r => r)
            .join(",");
        } catch (error) {
          this.uploadTxt = "文件解析失败,请按照格式上传";
        }
      };
      return false;
    },
    onExample() {
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet([
        {
          商品编码: "123456"
        }
      ]);
      XLSX.utils.book_append_sheet(wb, ws, "优惠券适用范围示例");
      XLSX.writeFile(wb, "优惠券适用范围示例.xlsx");
    }
  }
};
</script>

<style lang="scss">
.ivu-form-item .ivu-form-item-label {
  width: 102px !important;
}
</style>

<style lang="scss" scoped>
.form-group {
  width: 100%;
  height: 30px;
  background-color: #f5f7f9;
}
.add-item {
  margin-bottom: 10px;
}
</style>