buyFreeCoupon.js 66.7 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 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
// pack-activity/pack/buyFreeCoupon.js
import util from '../../utils/util';
import App from '../../utils/api';
// import {monidata} from './aa';
Page({
    /**
     * 页面的初始数据
     */
    data: {
        options: {},
        available: '1', //输入金额够优惠券最低消费1  不够0
        couponArr: [], //所有券列表
        finalList: [], //勾选的券列表
        dataStr: Date.now() * 1 / 1000,
        discountPrice: '', //优惠价格
        actualPrice: '', //实付价格
        inputValue: '', //输入的金额
        canSolt: {}, //当前时间是哪个餐段、节假日
        totalPrice: '', //送券的总金额
        couponSwitch: false, //本单使用优惠券开关
        consumeSwitch: false, //本单使用消费金开关
        purePhoneNumber: '', //手机号
        coexist: '0', //1可以同时使用券和消费金 0不可同时使用
        ratio: '', //消费金支付占实际消费金额的百分比
        consumeDiscount: '0.00', //消费金抵扣金额
        consumePrice: '', //个人消费金余额
        remainingConsume: '', //抵扣后剩余消费金余额
        totalConsumePrice: 0, //赠送的消费金金额
        noConfiguration: '', //配置消费金 0未配置 1已配置
        returnData: '', //赠送消费金配置
        isReturn: '', //赠送消费金的开关
        giveConsumePrice: '', //新老用户赠送消费金额
        isNewUser: '',//新用户1 老用户2
        recharge_data: [], //所有满赠充值活动
        payType: '2', //1余额支付  2微信支付
        multiple: '', //充值几倍当餐免费
        rechargeList:{},
        myBalance: '', //店铺总余额
        balancePay: '', //余额支付金额
        soothPrice: '', //实付价格-余额的价格
        countDown: '5', //5秒后自动关闭弹框
        timer: null,
    },
    sid: '', //扫码进入带的参数商家id
    couponModal: '',
    giveCouponModal: '',
    consumeModal: '',
    giveConsume: '',
    myToast:'',
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('options----', options);
        this.couponModal = this.selectComponent("#couponModal");
        this.giveCouponModal = this.selectComponent("#giveCouponModal");
        this.consumeModal = this.selectComponent("#consumeModal");
        this.giveConsume = this.selectComponent("#giveConsume");
        if (options.sid) {
            this.sid = options.sid
            this.getSellerDetailFun(options.sid)
            this.getRechargeDetail(options.sid)
        }
    },
    // 检测用户是否绑定手机号
    getCheckUserHavePhone() {
        App.Wechat.CheckUserHavePhone({
            openid: getApp().openid,
        }).then((json) => {
            if (json.ret == 200) {
                let data = json.data;
                if (data) {
                    this.setData({
                        purePhoneNumber: data.phone,
                    })
                    this.getUserInfo()
                    this.getUserRechargeInfo(data.phone, '0')
                } else {
                    this.getUserInfo()
                    this.setData({
                        purePhoneNumber: '',
                    })
                }
            }
        })
    },
    // 切换支付方式
    checkPay(e) {
        let type = e.currentTarget.dataset['type'];
        let actualPrice = this.data.actualPrice;
        if (type == '1') {
            let myBalance = this.data.myBalance * 1;
            if (actualPrice && actualPrice > 0) {
                let balancePay = actualPrice > myBalance ? myBalance : actualPrice;
                let soothPrice = (actualPrice - balancePay).toFixed(2)
                this.setData({
                    balancePay,
                    soothPrice,
                })
            }
        } else {
            this.setData({
                balancePay: '0.00',
                soothPrice: actualPrice,
            })
        }
        this.setData({
            payType: type,
        })
    },
    // 根据充值ID获取充值详情
    getRechargeDetail(sellerid) {
        App.Activity.GetNewRechargeList({
            sellerid,
        }).then(res => {
            if (res.data) {
                let arr = []
                res.data.forEach(i => {
                    if (i.status != '1') {
                        arr.push(i)
                    }
                })
                let recharge_data = arr;
                recharge_data.forEach(item => {
                    item.recharge_list = item.recharge_list ? JSON.parse(item.recharge_list) : '';
                    let recharge_list = item.recharge_list;
                    item.timeStr = util.unixtoTime(item.stime, 'YYYY-MM-DD') + ' - ' + util.unixtoTime(item.etime, 'YYYY-MM-DD')
                })
                // 筛选出 未过期的 && 开启状态的充值活动
                recharge_data = recharge_data.filter(item => {
                    return (this.data.dataStr < (item.etime * 1) || !item.etime) && item.is_open == '1'
                })
                console.log('所有充值活动--------------', recharge_data);
                this.setData({
                    recharge_data,
                })
            } else {
                this.setData({
                    recharge_data: [],
                })
            }
        })
    },
    // 获取用户在商家的账户余额
    getUserRechargeInfo(phone, type) {
        App.Activity.GetRechargeBalanceByOpenid({
            openid: getApp().openid,
            phone,
            sellerid: this.sid,
        }).then((json) => {
            if (json.ret == 200) {
                let data = json.data;
                if (data) {
                    console.log('获取用户在商家的余额----', data.recharge_balance);
                    this.setData({
                        myBalance: data.recharge_balance ? (data.recharge_balance * 1).toFixed(2) : '0.00',
                    })
                } else {
                    if (type == '1') this.createInfoFun(phone)
                    console.log('用户在商家没有账号');
                    this.setData({
                        myBalance: null,
                    })
                }
            }
        })
    },
    // 用户绑定手机号
    bindUserPhoneFun(phone) {
        console.log('用户绑定手机号');
        let params = {
            phone,
            openid: getApp().openid,
        }
        App.Wechat.BindUserPhone(params).then(res => {
            if (res.ret == 200) {
                console.log(res, '用户绑定手机号');
            }
        })
    },
    // 如果该用户不存在账户  新增用户在商家的账户信息
    createInfoFun(phone) {
        let params = {
            openid: getApp().openid,
            sellerid: this.data.seller.sid,
            phone
        }
        App.Activity.CreateCustomerConsumeSeller(params).then(res => {
            if (res.ret == 200) {
                console.log('新增用户在商家的账户信息----', res);
            }
        })
    },
    // 获取用户在商家&所有消费金
    getUserInfo() {
        App.Activity.GetConsumeBySeller({
            openid: getApp().openid,
            sellerid: this.sid,
        }).then((json) => {
            if (json.ret == 200) {
                let data = json.data;
                if (data && data.length > 0) {
                    let obj = data[0]
                    console.log('获取用户在商家的消费金----', obj);
                    this.setData({
                        consumePrice: obj.balance ? (obj.balance * 1).toFixed(2) : '0.00',
                        remainingConsume: obj.balance ? (obj.balance * 1).toFixed(2) : '0.00',
                        consumeDiscount: '0.00', //消费金抵扣金额
                    })
                } else {
                    this.setData({
                        consumePrice: '0.00',
                        remainingConsume: '0.00',
                        consumeDiscount: '0.00', //消费金抵扣金额
                    })
                }
                this.getIdentityFun()
            }
        })
    },
    // 获取当餐免费的配置信息
    getFreeMealConfigFun() {
        App.Activity.GetFreeMealConfigBySeller({
            sellerid: this.sid,
        }).then(res => {
            if (res && res.data && res.data.length > 0 && res.data[0].is_open == '1') {
                let data = res.data[0];
                let list = data.recharge_list ? JSON.parse(data.recharge_list) : {}
                list.priceInfo = '';
                list.scoreInfo = '';
                list.certificate = '';
                if (list.is_price == '1') list.priceInfo = '赠' + list.price + '元余额';
                if (list.is_score == '1') list.scoreInfo = '赠' + list.score + '积分';
                if (list.is_coupons == '1' && list.coupons_names.length > 0) list.certificate = '赠' + list.coupons_names.join('、') + '券';;
                this.setData({
                    multiple: data.multiple,
                    rechargeList: list
                })
            } else {
                this.setData({
                    multiple: '',
                    rechargeList: {}
                })
            }
        })
    },
    // 获取用户在当前商家身份及是否领取过消费金
    getIdentityFun(){
        App.Activity.GetIdentityBySeller({
            sellerid: this.sid,
            openid: getApp().openid,
            phone: this.data.purePhoneNumber,
        }).then(res => {
            let is_get_consume = '1'
            if (res && res.data) {
                is_get_consume = res.data.is_get_consume
                this.setData({
                    isNewUser:res.data.identity,
                })
            }
            this.getConsumeConfigFun(is_get_consume)
        })
    },
    // 获取商家消费金规则
    getConsumeConfigFun(isConsume) {
        App.Activity.GetConsumeConfig({
            sellerid: this.sid,
        }).then(res => {
            if (res && res.data) {
                let data = res.data;
                let together = util.determine(data.together_json);
                let returnData = util.determine(data.return_json);
                let beforePay = util.determine(data.before_pay_json);
                if(beforePay && beforePay.new) beforePay.new = util.determine(beforePay.new);
                if(beforePay && beforePay.old) beforePay.old = util.determine(beforePay.old);
                console.log('returnData---',returnData);
                if(returnData && returnData.ladder_data) returnData.ladder_data = util.determine(returnData.ladder_data);
                console.log('111配置---',together);
                console.log('222顾客支付后返消费金---',returnData);
                console.log('3333新老用户领取消费金---',beforePay);
                let time = Math.floor(Date.now() / 1000)
                let giveConsumePrice = '';
                if(beforePay){
                    // 新用户 && 没有领取过 && 开启新用户领取
                    if(this.data.isNewUser == 'new' && isConsume == '0' && beforePay.new && beforePay.is_new == '1'){
                        let newData = beforePay.new;
                        if((time > newData.stime) && (time < newData.etime)){
                            giveConsumePrice = newData.is_fix == '1'?newData.fix_price :this.getRandomInt(newData.random_min, newData.random_max);
                        }
                    }
                    // 老用户 && 个人消费金大于0 && 开启老用户领取
                    if(this.data.isNewUser == 'old' && this.data.consumePrice == '0.00'  && beforePay.old && beforePay.is_old == '1'){
                        let oldData = beforePay.old;
                        if((time > oldData.stime) && (time < oldData.etime)){
                            giveConsumePrice = oldData.is_fix == '1'?oldData.fix_price :this.getRandomInt(oldData.random_min, oldData.random_max);
                        }
                    }
                    console.log('giveConsumePrice-------',giveConsumePrice);
                }
                this.setData({
                    noConfiguration: '1', //配置为1 未配置为0
                    coexist: together?together.is_coexist:'',
                    ratio: together && together.ratio_data ? together.ratio_data : '100',
                    couponSwitch: true,
                    consumeSwitch: together && together.is_coexist == '1' ? true : false,
                    returnData,
                    isReturn: data.is_return,
                    giveConsumePrice,
                })
            } else {
                this.setData({
                    noConfiguration: '0', //配置为1 未配置为0
                    couponSwitch: true,
                    consumeSwitch: false,
                    returnData: null,
                    isReturn: '0',
                    giveConsumePrice:'',
                })
            }
        })
    },
    // 使用券或者消费金的开关
    switchChange(event) {
        let type = event.currentTarget.dataset.type;
        if (type == '1') {
            this.setData({
                couponSwitch: event.detail.value,
            })
            if (this.data.coexist == '0' && event.detail.value) {
                this.setData({
                    consumeSwitch: false,
                })
            }
        }
        if (type == '2') {
            this.setData({
                consumeSwitch: event.detail.value,
            })
            if (this.data.coexist == '0' && event.detail.value) {
                this.setData({
                    couponSwitch: false,
                })
            }
        }
        // 开或者关闭使用优惠券
        if (this.data.couponSwitch) {
            this.colationData()
        }
        if (!this.data.couponSwitch) {
            this.getCoupon()
            let val = parseFloat(this.data.inputValue);
            if (!val) return
            let discountPrice = 0;
            let actualPrice = (val - this.data.consumeDiscount - discountPrice).toFixed(2)
            console.log('actualPrice----', actualPrice);
            let myBalance = this.data.myBalance * 1;
            let balancePay = (this.data.payType == '1' && actualPrice > myBalance) ? myBalance : actualPrice;
            let soothPrice = this.data.payType == '1' ? (actualPrice - balancePay).toFixed(2) : actualPrice;
            this.setData({
                discountPrice: 0,
                actualPrice,
                balancePay,
                soothPrice,
            })
        }
        // 开或者关闭使用消费金
        if (this.data.consumeSwitch) {
            let val = parseFloat(this.data.inputValue);
            if (!val) return
            let consumeDiscount = this.calculateConsumeGold(val);
            let discountPrice = this.data.couponSwitch ? this.data.discountPrice : 0
            let actualPrice = (val - consumeDiscount - discountPrice).toFixed(2)
            let remainingConsume = (this.data.consumePrice * 1 - consumeDiscount).toFixed(2)
            let myBalance = this.data.myBalance * 1;
            let balancePay = (this.data.payType == '1' && actualPrice > myBalance) ? myBalance : actualPrice;
            let soothPrice = this.data.payType == '1' ? (actualPrice - balancePay).toFixed(2) : actualPrice;
            this.setData({
                consumeDiscount,
                actualPrice,
                remainingConsume: remainingConsume,
                balancePay,
                soothPrice,
            })
        }
        if (!this.data.consumeSwitch) {
            let val = parseFloat(this.data.inputValue);
            if (!val) return
            let discountPrice = this.data.couponSwitch ? this.data.discountPrice : 0
            let consumeDiscount = this.data.consumeSwitch ? this.data.consumeDiscount : 0
            let actualPrice = (val - consumeDiscount - discountPrice).toFixed(2)
            let myBalance = this.data.myBalance * 1;
            let balancePay = (this.data.payType == '1' && actualPrice > myBalance) ? myBalance : actualPrice;
            let soothPrice = this.data.payType == '1' ? (actualPrice - balancePay).toFixed(2) : actualPrice;
            this.setData({
                consumeDiscount: '0.00',
                actualPrice,
                remainingConsume: this.data.consumePrice,
                balancePay,
                soothPrice,
            })
        }
    },
    // 按比例计算出的最大可用消费金
    calculateConsumeGold(val) {
        let ratio = this.data.ratio;
        let consumePrice = parseFloat(this.data.consumePrice);
        const maxByRatio = val * (ratio / 100).toFixed(2);
        let availableConsumeGold = Math.min(val, maxByRatio).toFixed(2) * 1;
        if (availableConsumeGold > consumePrice) availableConsumeGold = consumePrice
        return availableConsumeGold;
    },
    // 打开优惠券弹框
    showCouponModal() {
        this.couponModal.showModal()
    },
    // 关闭优惠券弹框
    closeCouponModal() {
        this.couponModal.closeModal()
    },
    // 打开送券送消费金弹框
    showgiveCouponModal() {
        this.giveCouponModal.showModal()
    },
    // 打开消费金弹框
    showConsumeModal() {
        this.consumeModal.showModal()
    },
    // 关闭消费金弹框
    closeConsumeModal() {
        this.consumeModal.closeModal()
    },
    // 打开赠送消费金弹框
    showGiveConsumeModal() {
        let num = this.data.giveConsumePrice;
        this.setData({
            giveConsumePrice: num
        })
        this.giveConsume.showModal()
        this.setData({
            countDown: 5,
        })
        if (this.data.timer) {
            clearInterval(this.data.timer);
        }
        this.startCountDown();
        console.log('送消费金----',num);
    },
    // 开始倒计时
    startCountDown() {
        let that = this;
        const timer = setInterval(() => {
            if (that.data.countDown <= 1) {
                that.closeGiveConsumeModal()
                clearInterval(timer);
                that.setData({
                    timer: null
                });
            } else {
                that.setData({
                    countDown: that.data.countDown - 1
                });
            }
        }, 1000);
        this.setData({
            timer
        });
    },
    // 关闭消费金弹框
    closeGiveConsumeModal() {
        this.giveConsume.closeModal()
        this.getConsumeFun(this.data.giveConsumePrice,'1')
    },
    // 选择充值活动
    checkRechargeData(e) {
        let id = e.currentTarget.dataset['id'];
        console.log('id', id);
        if (!id) {
            let price = this.data.actualPrice * 1 * this.data.multiple
            if (!price) return false
            let str = this.data.finalList.map(item => item.activity_id).join(',');
            console.log('核销所勾选的券传参', str);
            let params = {
                type: '2',
                types: '4', // 1邀请函  2提前点餐  3商家端app分享 4支付页充值 5我的页面余额充值
                sid: this.sid,
                totalize: price.toFixed(2), //充值几倍金额
                name: this.data.seller.sellername,
                isFree: '1',
                multiple: this.data.multiple,
                inputValue: this.data.inputValue, //订单实际应该支付金额(扣除消费金、券之前)
            }
            // 消费金开关开启 && 消费金抵扣金额大于0
            if (this.data.consumeDiscount * 1 > 0 && this.data.consumeSwitch) {
                params.consume = this.data.consumeDiscount;
            }
            if (str) {
                params.activity_id = str;
            }
            if (this.data.givePrice) {
                params.givePrice = this.data.givePrice; //当餐免费送的余额
            }
            let url = util.http_build_query({
                ...params
            }, '/pack-activity/pack/vipRecharge')
            return wx.navigateTo({
                url
            })
        }
        wx.navigateTo({
            url: util.http_build_query({
                id,
                name: this.data.seller.sellername,
                sid: this.sid,
                types: '4',
                isFree: '0',
            }, '/pack-activity/pack/vipRecharge')
        })
    },
    // 关闭优惠券弹框
    closegiveCouponModal() {
        this.giveCouponModal.closeModal()
        this.getUserInfo()
    },
    // 获取code、手机号
    getPhoneNumberFun(e) {
        console.log('eeeeeeeeee', e.detail);
        if (e.detail && e.detail.code) {
            App.Wechat.GetUserPhoneNumber({
                code: e.detail.code,
            }).then(res => {
                console.log('resresres----', res);
                if (res.ret == 200 && res.data && res.data.phone_info && res.data.phone_info.purePhoneNumber) {
                    this.setData({
                        purePhoneNumber: res.data.phone_info.purePhoneNumber,
                    })
                    this.getUserInfo()
                    this.bindUserPhoneFun(res.data.phone_info.purePhoneNumber)
                    this.getUserRechargeInfo(res.data.phone_info.purePhoneNumber, '1')
                } else {
                    this.getUserInfo()
                    util.toast('手机号获取失败!', 'none')
                }
            })
        }
    },
    // 获取店铺名称
    getSellerDetailFun(sid) {
        App.Customer.GetSellerDetail({
            sid
        }).then(res => {
            let data = res.data;
            this.setData({
                seller: {
                    seller_image: data.seller_image,
                    sellername: data.sellername,
                    sid: data.id
                }
            })
            // 判断当前时间餐段、节假日
            this.getSellerDailyFun(data.daily)
        })
    },
    // 赠送券
    giftCouponsFun(priceSum,orderid) {
        App.Activity.GetActivityConfig({
            sellerid: this.data.seller.sid,
        }).then(res => {
            if (res.ret == 200) {
                let data = res.data;
                priceSum = parseFloat(priceSum)
                // 满减
                if (data.full_reduction && data.full_reduction == '1') {
                    let fullData = data.full_reduction_data ? util.determine(data.full_reduction_data) : ''
                    let coupons = fullData.coupons ? util.determine(fullData.coupons) : '';
                    const now = Math.floor(Date.now() / 1000);
                    console.log('满减---',{...fullData},{...coupons},now);
                    // 在送券活动开始的有效期之内
                    if (now >= parseInt(fullData.stime) && now <= parseInt(fullData.etime)) {
                        // rule 1每满门槛均发放(满50送一张券,金额是100送2张)  
                        // rule 0仅发放一次(每次满足金额一个券只发一张)
                        const price = parseFloat(fullData.price)
                        const amount = parseInt(priceSum / price)
                        if (fullData.rule == '1') {
                            if (coupons.length > 0 && amount > 0) this.getCouponFun(coupons, '1', amount,orderid)
                        } else {
                            if (coupons.length > 0 && amount > 0) this.getCouponFun(coupons, '1', 1,orderid)
                        }
                    }
                }
                // 阶梯
                if (data.stairs && data.stairs == '1') {
                    let stairsData = data.stairs_data ? util.determine(data.stairs_data) : ''
                    let ladder_data = stairsData.ladder_data ? util.determine(stairsData.ladder_data) : '';
                    const now = Math.floor(Date.now() / 1000);
                    console.log('阶梯---',{...stairsData},{...ladder_data},now);
                    // 在送券活动开始的有效期之内
                    if (now >= parseInt(stairsData.stime) && now <= parseInt(stairsData.etime)) {
                        let obj = this.findObjectByNum(ladder_data, priceSum)
                        console.log('在送券活动开始的有效期之内',{...obj});
                        if (obj && obj.coupons) {
                            let coupons = obj.coupons ? util.determine(obj.coupons) : '';
                            this.getCouponFun(coupons, '2', '1',orderid)
                        }
                    }
                }
            }
        })
    },
    getCouponFun(coupons, type, amount,orderid) {
        console.log('送的券coupons---', coupons, type, amount,orderid);
        let str = coupons.map(item => item.id).join(',');
        App.Activity.GetActivityById({
            id: str,
        }).then(res => {
            if (res.ret == 200) {
                let list = res.data;
                let couponArr = [];
                list.forEach(item => {
                    item.aexpiration = item.aexpiration ? util.determine(item.aexpiration) : '';
                    // 如果送券的数量大于剩余券的数量,设置送券的数量=剩余券的数量
                    if (type == '1' && amount > item.grant_last && item.grant_last > 0) {
                        item.amountA = item.grant_last
                    } else {
                        item.amountA = amount
                    }
                    console.log('券信息---',{...item});
                    // 只留下开启状态 && 在券的有效期内 && 可领取数量大于0的
                    if (item.is_open == '1' && (this.data.dataStr < item.etime * 1 || item.aexpiration.valid_forever == '1') && ((type == '1' && item.grant_last >= item.amountA) || (type == '2' && item.grant_last > 0))) {
                        console.log('可领取的券', item.aname, {
                            ...item
                        });
                        couponArr.push({
                            ...item
                        })
                    }
                })
                if (couponArr.length > 0) {
                    let result = [];
                    let ids = '';
                    let totalPrice = 0;
                    if (amount) {
                        couponArr.forEach(item => {
                            for (let i = 0; i < item.amountA; i++) {
                                result.push(item.id);
                            }
                        });
                        ids = result.join(",")
                    } else {
                        ids = coupons.map(item => item.id).join(',')
                    }
                    totalPrice = couponArr.reduce((sum, item) => sum + item.price * item.amountA, 0);
                    this.setData({
                        totalPrice,
                    })
                    this.setcouponFun(ids,orderid)
                }
            }
        })
    },
    setcouponFun(str,orderid) {
        console.log('领取券方法ids---', str,orderid);
        App.Activity.SetActivityAsReserve({
            aid: str,
            orderid,
        }).then((json) => {
            if (json.ret != 200) {
                wx.showToast({
                    title: res.msg,
                    duration: 2000,
                    mask: true
                })
            }
        })
    },
    // 获取所有优惠券列表
    getCoupon() {
        App.Activity.ActivityListByOpenid({
            sellerid: this.sid
        }).then(res => {
            if (res.ret == 200 && res.data && res.data.length > 0) {
                let list = res.data
                list.forEach(detail => {
                    detail.exp_date = detail.exp_date ? util.determine(detail.exp_date) : '';
                    detail.arule = detail.arule ? util.determine(detail.arule) : '';
                    detail.expiration_date = detail.expiration_date ? util.determine(detail.expiration_date) : '';
                    detail.aexpiration = detail.aexpiration ? util.determine(detail.aexpiration) : '';
                    if (detail.arule) {
                        detail.accumulationShow = detail.arule.is_accumulation
                    }
                    if (detail.exp_date && detail.exp_date.week_data) {
                        let mor = this.hasConsecutiveSelect(detail.exp_date.week_data, '1').rArr.join('、')
                        let noon = this.hasConsecutiveSelect(detail.exp_date.week_data, '2').rArr.join('、')
                        let nig = this.hasConsecutiveSelect(detail.exp_date.week_data, '3').rArr.join('、')
                        if (mor) mor = '早餐:' + mor
                        if (noon) noon = '午餐:' + noon
                        if (nig) nig = '晚餐:' + nig
                        detail.morText = mor;
                        detail.noonText = noon;
                        detail.nigText = nig;
                    }
                    detail.checked = false;
                    detail.showCpupon = '0';
                    // 获取使用券的有效期
                    detail.cdate = detail.cdate * 1;
                    detail.useStime = '';
                    detail.useEtime = '';
                    let condition = detail.aexpiration
                    if (condition.valid_forever === '0' && condition.stime && condition.etime) {
                        detail.useStime = condition.stime;
                        detail.useEtime = condition.etime;
                    }
                    if (condition.valid_forever === '1') {
                        detail.foreverText = '永久有效';
                    }
                    if (condition.valid_forever === '0' && condition.today) {
                        let obj = this.setTimeRange(detail.cdate, 0, parseInt(condition.today) - 1);
                        detail.useStime = obj.useStime;
                        detail.useEtime = obj.useEtime;
                    }
                    if (condition.valid_forever === '0' && condition.tomorrow) {
                        let obj = this.setTimeRange(detail.cdate, 1, condition.tomorrow * 1);
                        detail.useStime = obj.useStime;
                        detail.useEtime = obj.useEtime;
                    }
                    if (condition.valid_forever === '0' && condition.sday && condition.eday) {
                        let obj = this.setTimeRange(detail.cdate, parseInt(condition.sday) - 1, parseInt(condition.eday) - 1);
                        detail.useStime = obj.useStime;
                        detail.useEtime = obj.useEtime;
                    }
                    if((detail.useStime>0 && detail.useEtime>0) || condition.valid_forever === '1') {
                        detail.endDateStr = condition.valid_forever == '1' ? '永久有效' : (util.unixtoTime(detail.useStime, 'YYYY-MM-DD') + '至' + util.unixtoTime(detail.useEtime, 'YYYY-MM-DD'));
                    }
                })
                list = list.filter(item => {
                    return (this.data.dataStr < (item.useEtime * 1) || item.aexpiration.valid_forever == '1');
                })
                list.sort((a, b) => {
                    return (a.etime * 1) - (b.etime * 1)
                })
                let couponArr = list
                this.setData({
                    couponArr
                })
            }
        })
    },
    // 勾选券
    checkboxChange(e) {
        console.log('checkbox发生change事件,携带value值为:', e.detail.value)
        const list = this.data.couponArr
        const values = e.detail.value
        let arr = []
        let currentCoupon = '0'; //没选券 为0  可叠加券1  不可叠加券2
        let inputValue = parseFloat(this.data.inputValue)
        let val = 0; //勾选的券  优惠金额的和
        let descStr = 0; //勾选的券  每满金额的和
        for (let i = 0, lenI = list.length; i < lenI; ++i) {
            list[i].checked = false;
            for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
                if (list[i].activity_id === values[j]) {
                    val += parseFloat(list[i].price)
                    if (!list[i].desc || list[i].desc == 0) {
                        descStr += parseFloat(list[i].price)
                    } else {
                        descStr += parseFloat(list[i].desc)
                    }
                    arr.push({
                        ...list[i]
                    })
                    list[i].checked = true
                    if (list[i].accumulationShow == '1') {
                        currentCoupon = '1'
                        break
                    } else {
                        currentCoupon = '2'
                        break
                    }
                }
            }
        }
        let remaining = inputValue - val; //剩余金额
        console.log('没选券为0可叠加券1不可叠加券2', currentCoupon, remaining);
        //没选券 所有可选的打开 
        if (currentCoupon == '0') {
            list.forEach(item => {
                if (item.canCheck == "1") {
                    item.showCpupon = '1';
                }
            })
        }
        //选的不可叠加券  其他所有的可叠加券都不可选 
        if (currentCoupon == '2') {
            list.map((item) => {
                if (item.checked) {
                    item.showCpupon = '1'
                } else {
                    item.showCpupon = '0'
                }
            })
        }
        //选的可叠加券  其他所有的不可叠加券都不可选 
        if (currentCoupon == '1') {
            list.forEach(item => {
                if (item.checked || (item.accumulationShow == "1" && (inputValue - descStr) >= parseFloat(item.desc) && parseFloat(item.price) <= (inputValue - val))) {
                    item.showCpupon = '1';
                } else {
                    item.showCpupon = '0';
                }
            })
        }
        this.setData({
            couponArr: list
        })
    },
    // 输入金额
    bindKeyInput(e) {
        console.log('输入金额,bindchange携带value值为:', e.detail.value);
        let list = this.data.couponArr;
        // 所有的券重置
        list.forEach(i => {
            i.checked = false;
            i.showCpupon = '0'
        })
        this.setData({
            inputValue: e.detail.value,
            couponArr: list
        })
        if (e.detail.value == '') {
            this.setData({
                discountPrice: '',
                actualPrice: '',
                consumeDiscount: '',
                remainingConsume: this.data.consumePrice,
                soothPrice: '',
                balancePay: '',
                payType: '2',
            })
        } else {
            if (this.data.couponSwitch) {
                this.colationData()
            }
            if (this.data.consumeSwitch && !this.data.couponSwitch) {
                let val = parseFloat(this.data.inputValue);
                let consumeDiscount = this.calculateConsumeGold(val);
                let actualPrice = (val - consumeDiscount - this.data.discountPrice).toFixed(2)
                let remainingConsume = (this.data.consumePrice * 1 - consumeDiscount).toFixed(2)
                let myBalance = this.data.myBalance * 1;
                let balancePay = (this.data.payType == '1' && actualPrice > myBalance) ? myBalance : actualPrice;
                let soothPrice = this.data.payType == '1' ? (actualPrice - balancePay).toFixed(2) : actualPrice;
                this.setData({
                    consumeDiscount,
                    actualPrice: actualPrice,
                    remainingConsume: remainingConsume,
                    balancePay,
                    soothPrice
                })
            }
        }
    },
    // 点确认选择
    checkCertificate() {
        let inputValue = parseFloat(this.data.inputValue);
        this.closeCouponModal()
        if (!inputValue) return
        let list = this.data.couponArr;
        list = list.filter(i => {
            return i.checked
        })
        let price = 0;
        list.forEach(i => {
            price += parseFloat(i.price)
        })
        console.log('优惠金额----', price);
        let val =  parseFloat(this.data.inputValue);
        let actualPrice = (val - price - this.data.consumeDiscount).toFixed(2)
        price = price.toFixed(2)
        let myBalance = this.data.myBalance * 1;
        let balancePay = (this.data.payType == '1' && actualPrice > myBalance) ? myBalance : actualPrice;
        let soothPrice = this.data.payType == '1' ? (actualPrice - balancePay).toFixed(2) : actualPrice;
        this.setData({
            discountPrice: price,
            actualPrice,
            balancePay,
            soothPrice,
        })
        console.log('点确认选择后', list);
    },
    // 处理显示券可用、不可用的列表
    async colationData() {
        let list = this.data.couponArr;
        list = await this.filterCoupons(list);
        let obj = await this.findBestCoupons(list);
        list = obj.arr
        console.log('处理过后的券数据', list);
        list.sort((a, b) => b.canCheck - a.canCheck);
        list.sort((a, b) => b.showCpupon - a.showCpupon);
        let consumeDiscount = '';
        let amount = parseFloat(this.data.inputValue);
        if (this.data.consumeSwitch) {
            let num = (amount - this.data.discountPrice).toFixed(2);
            let val = parseFloat(num);
            consumeDiscount = this.calculateConsumeGold(val);
            this.setData({
                consumeDiscount,
            })
        }
        let actualPrice = (amount - consumeDiscount - this.data.discountPrice).toFixed(2)
        let remainingConsume = (this.data.consumePrice * 1 - consumeDiscount).toFixed(2)
        let myBalance = this.data.myBalance * 1;
        let balancePay = (this.data.payType == '1' && actualPrice > myBalance) ? myBalance : actualPrice;
        let soothPrice = this.data.payType == '1'?(actualPrice - balancePay).toFixed(2):actualPrice
        console.log('实际支付金额:', actualPrice);
        this.setData({
            consumeDiscount,
            actualPrice,
            remainingConsume: remainingConsume,
            soothPrice,
            balancePay,
            couponArr: list,
            finalList: obj.finalList
        })
    },
    // 付款
    confirmPayment: util.throttle(function () {
        let that = this;
        let soothPrice = this.data.soothPrice
        wx.showLoading({
          title: '支付中',
        })
        let str = this.data.finalList.map(item => item.activity_id).join(',');
        console.log('核销所勾选的券传参', str);
        let params = {
            sellerid: this.data.seller.sid,
            price: soothPrice,
        }
        if (this.data.consumeDiscount) {
            params.consume = this.data.consumeDiscount;
            params.phone = this.data.purePhoneNumber;
        }
        if (str) {
            params.activity_id = str;
        }
        // 用余额支付 || 支付金额为0
        if (this.data.soothPrice == '0.00') {
            let obj = {
                openid: getApp().openid,
                sellerid: this.data.seller.sid,
                price: this.data.inputValue,
                phone: this.data.purePhoneNumber,
                recharge_balance: this.data.balancePay * 1,
            }
            if (str) {
                obj.activity_id = str;
            }
            let consumeDiscount = this.data.consumeDiscount * 1
            if (consumeDiscount > 0) {
                obj.consume = this.data.consumeDiscount;
            }
            console.log('用余额支付objobj----', obj);
            App.Activity.CreateRechargeBalanceOrder({
                ...obj
            }).then(res => {
                console.log('付款信息', res.data);
                if (res.ret != '200') {
                    wx.hideLoading()
                    return wx.showToast({
                        title: res.msg,
                        duration: 1000,
                        icon: 'none',
                    })
                }
                if (res.ret == '200') {
                    that.deductBalance(soothPrice, res.data.id)
                }
            })
            return false
        }
        // 微信支付
        App.PayOnline.CombineTransactionsByNewActivity(params).then(res => {
            console.log('付款信息', res.data);
            if (res.ret != '200') {
                wx.hideLoading()
                wx.showToast({
                    title: res.msg,
                    duration: 1000,
                    icon: 'none',
                })
            }
            if (res.ret == '200') {
                wx.requestPayment({
                    timeStamp: res.data.timeStamp + '',
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: res.data.signType,
                    paySign: res.data.paySign,
                    success(ress) {
                        wx.hideLoading()
                        if (ress.errMsg == 'requestPayment:ok') {
                            that.giftCouponsFun(soothPrice,res.data.orderid) //送券
                            that.giftConsumeFun(soothPrice, res.data.orderid) //送消费金
                            setTimeout(() => {
                                console.log('2送券金额----', that.data.totalPrice);
                                console.log('2送消费金----', that.data.totalConsumePrice);
                                wx.reLaunch({
                                    url: util.http_build_query({
                                        totalPrice: that.data.totalPrice,
                                        totalConsumePrice: that.data.totalConsumePrice,
                                    }, '/pack-activity/pack/paySuccess')
                                })
                            }, 1000);
                            console.log('支付成功', ress);
                            return
                        }
                        that.payFail()
                        console.log('支付失败11', ress);
                        return that.myToast.showToast('支付失败,请重新下单', 2000)
                    },
                    fail(ress) {
                        wx.hideLoading()
                        that.payFail()
                        console.log('支付失败22', ress);
                        return that.myToast.showToast('支付失败,请重新下单', 2000)
                    },
                })
            }
        })
    },3000),
    // 扣除支付的余额
    deductBalance(actualPrice, id) {
        let that = this;
        let recharge_balance = this.data.balancePay * 1
        App.Activity.SetRechargeBalanceByOpenid({
            openid: getApp().openid,
            recharge_balance,
            sellerid: this.data.seller.sid,
            type: '2',
        }).then(res => {
            if (res.ret == 200) {
                wx.hideLoading()
                console.log('扣除余额成功');
                that.giftCouponsFun(actualPrice, id) //送券
                that.giftConsumeFun(actualPrice, id) //送消费金
                setTimeout(() => {
                    console.log('1送券金额----', that.data.totalPrice);
                    console.log('1送消费金----', that.data.totalConsumePrice);
                    wx.reLaunch({
                        url: util.http_build_query({
                            totalPrice: that.data.totalPrice,
                            totalConsumePrice: that.data.totalConsumePrice,
                        }, '/pack-activity/pack/paySuccess')
                    })
                }, 1000);
            } else {
                wx.hideLoading()
                that.myToast.showToast('支付失败,请重新下单', 2000)
            }
        })
    },
    payFail() {
        this.setData({
            inputValue: '',
            finalList: [],
            couponArr: [],
            discountPrice: '0.00',
            actualPrice: '',
            consumeDiscount: '0.00', //消费金抵扣金额
            balancePay:'',
            payType:'2',
            soothPrice: '',
        })
        this.getCoupon()
        this.getUserInfo()
    },
    giftConsumeFun(priceSum, orderid) {
        let isReturn = this.data.isReturn;
        let data = this.data.returnData;
        const now = Math.floor(Date.now() / 1000);
        let totalConsumePrice = 0;
        if (isReturn == '1' && data && now >= parseInt(data.stime) && now <= parseInt(data.etime)) {
            priceSum = parseFloat(priceSum)
            // 按百分比 is_ratio 1按比例 0按阶梯 ladder_data
            if (data.is_ratio == '1' && data.ratio_data) {
                totalConsumePrice = priceSum * (data.ratio_data / 100).toFixed(2);
                console.log('送消费金百分比----', totalConsumePrice);
            }
            // 阶梯
            if (data.is_ratio == '0' && data.ladder_data) {
                totalConsumePrice = this.calculateGiftAmount(priceSum, data.ladder_data)
                console.log('送消费金阶梯----', totalConsumePrice);
            }
            if (totalConsumePrice > 0) this.getConsumeFun(totalConsumePrice)
            this.setData({
                totalConsumePrice: (totalConsumePrice * 1).toFixed(2)
            })
        }
    },
    // 为用户增加消费金
    getConsumeFun(amount,type) {
        App.Activity.SetConsumeByOpenid({
            phone: this.data.purePhoneNumber,
            openid: getApp().openid,
            amount,
            sellerid: this.data.seller.sid
        }).then(res => {
            if(type == '1'){
                this.getUserInfo()
            }
        })
    },
    calculateGiftAmount(priceSum, ladder_data) {
        if (!ladder_data || ladder_data.length === 0) {
            return 0; // 没有阶梯数据,返回0
        }
        // 将阶梯数据按 give_price 从大到小排序,确保匹配最高阶梯
        const sortedLadder = [...ladder_data].sort((a, b) =>
            parseFloat(b.give_price) - parseFloat(a.give_price)
        );
        // 遍历排序后的阶梯,找到第一个满足条件的
        for (let i = 0; i < sortedLadder.length; i++) {
            const ladder = sortedLadder[i];
            const threshold = parseFloat(ladder.give_price);
            if (priceSum >= threshold) {
                return ladder.back_price;
            }
        }
        return 0; // 不满足任何阶梯条件
    },
    // 核销所勾选的券
    writeOff() {
        console.log('勾选的券', this.data.finalList);
        if (this.data.finalList.length > 0) {
            let str = this.data.finalList.map(item => item.activity_id).join(',');
            console.log('核销所勾选的券传参', str);
            App.Activity.SetActivityStatus({
                id: str,
            }).then(res => {
                if (res.ret == '200') {
                    console.log('核销成功', str);
                    this.setData({
                        inputValue: '',
                        finalList: [],
                        couponArr: [],
                        discountPrice: '0.00',
                        actualPrice: '',
                    })
                    this.getCoupon()
                }
            })
        }
    },
    // 判断券开启、有效期结束时间、领取后有效天数、领取当天可用、不可用日期
    filterCoupons(list) {
        const currentDate = new Date();
        currentDate.setHours(0, 0, 0, 0);
        let obj = this.data.canSolt
        console.log('当前餐段、是不是法定节假日', {
            ...obj
        });
        const isTimestampInRange = (startTimestamp, endTimestamp) => {
            const currentTimestamp = Math.floor(Date.now() / 1000);
            return currentTimestamp >= startTimestamp && currentTimestamp <= endTimestamp;
        };
        list.forEach(coupon => {
            // 判断当前时间在不在 券的有效期内
            const isUseDate = isTimestampInRange(coupon.useStime, coupon.useEtime);
            let selectedValue = true;
            let str = true
            if (coupon.exp_date && coupon.exp_date.week_data && coupon.exp_date.week_data.length > 0) {
                let today = new Date(); // 获取今天是星期几(0-6,0表示周日)
                let dayOfWeek = today.getDay();
                let arr = coupon.exp_date.week_data
                let todayArr = arr[dayOfWeek];
                let legalHolidayValue = arr[arr.length - 1];
                if (obj.can === "晚餐") {
                    selectedValue = todayArr.selectNig;
                } else if (obj.can === "午餐") {
                    selectedValue = todayArr.selectNoon;
                } else if (obj.can === "早餐") {
                    selectedValue = todayArr.selectMor;
                }
                selectedValue = !selectedValue
                // console.log(coupon.aname, coupon.exp_date.week_show, `今天是 ${todayArr.title},选择值为: ${selectedValue}`);
                // 根据 isshow 判断法定假日是否可用
                if (obj.isshow === "1") {
                    if (obj.can === "晚餐") {
                        str = legalHolidayValue.selectNig;
                    } else if (obj.can === "午餐") {
                        str = legalHolidayValue.selectNoon;
                    } else if (obj.can === "早餐") {
                        str = legalHolidayValue.selectMor;
                    }
                    str = !str
                }
                // console.log(coupon.aname, '法定节假期', `,选择值为: ${str}`);
            }
            let availableDate = true;
            if (str || selectedValue) {
                availableDate = true
            }
            if (!str || !selectedValue) {
                availableDate = false
            }
            if ((str && !selectedValue) || (!str && selectedValue)) {
                availableDate = false
            }
            coupon.isOk = (isUseDate || coupon.aexpiration.valid_forever == '1') && (availableDate || coupon.exp_date.week_show == '无') ? '1' : '0'; //是否在可用时间内 1可使用 2不可使用
        });
        return list;
    },
    // 最优惠的消费券组合(消费要求为无门槛 或者 满足优惠券使用金额 && 勾选最优的、最早到期的)
    findBestCoupons(arr) {
        console.log('勾选最优的之前', arr);
        let consumeDiscount = this.data.consumeDiscount;
        let inputValue = this.data.inputValue;
        const amount = parseFloat(inputValue - consumeDiscount);
        const validCoupons = arr.filter(coupon => (coupon.isOk == '1' && parseFloat(coupon.desc) <= amount) && amount>=parseFloat(coupon.price));
        // 排序后,优先选择最大优惠的券
        validCoupons.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
        arr.forEach(item => {
            const isValid = validCoupons.some(validCoupon => validCoupon.activity_id == item.activity_id);
            item.canCheck = isValid ? '1' : '0'; // 如果在 validCoupons 中,设置 canCheck 为 1,否则为 0
        });
        console.log('可以勾选的券 && 满足付款条件的券', validCoupons);
        let stackingCoupons = validCoupons.filter(i => {
            return i.accumulationShow == '1'
        })
        let list1 = []; // 可叠加的优惠券组合
        let list2 = []; // 最优惠的不可叠加的优惠券
        let finalList = []; //最终用的优惠券组合
        // 计算可叠加的组合
        let remainingPrice = amount; // 剩余金额
        let totalDiscount = 0; // 总优惠金额
        // 1. 优先排序 desc 为空或为 0 的,再根据 price 从大到小排序,再根据满减条件 desc 从大到小排序
        stackingCoupons.sort((a, b) => {
            if (a.desc === '0' || a.desc === '') return -1; // 优先选择 desc 为空或为 0 的
            if (b.desc === '0' || b.desc === '') return 1;
            if (parseFloat(b.price) !== parseFloat(a.price)) return parseFloat(b.price) - parseFloat(a.price); // 按 price 从大到小
            return parseFloat(b.desc) - parseFloat(a.desc); // 按满减条件 desc 从大到小
        });
        console.log('排序后的可叠加券列表',stackingCoupons);
        // 2. 从排序后的券中选择
        for (let coupon of stackingCoupons) {
            let couponDesc = parseFloat(coupon.desc);
            let couponPrice = parseFloat(coupon.price);
            let kyNum = Math.floor(remainingPrice / couponDesc);// 计算券可用张数
            if (couponDesc === 0) {// 如果满减条件为 0,直接选择
                list1.push(coupon);
                remainingPrice -= couponPrice; // 减去价格
                totalDiscount += couponPrice; // 计算优惠金额
                continue;
            }
            // 如果剩余金额足够,选择券
            if (remainingPrice >= couponDesc) {
                // 计算实际使用的张数,不能超过 kyNum
                let usedCount = Math.min(kyNum, 1); // 假设每次只使用一张
                let potentialDiscount = couponDesc * usedCount; // 计算潜在的优惠金额
                if (totalDiscount + potentialDiscount <= amount) {// 检查总优惠金额是否会超过总金额
                    list1.push(coupon);
                    remainingPrice -= couponPrice * usedCount; // 减去价格
                    totalDiscount += potentialDiscount; // 计算优惠金额
                }
            }
            // 如果剩余金额已经小于等于 0,停止选择
            if (remainingPrice <= 0) break;
        }
        // 遍历有效优惠券,寻找不可叠加的优惠券
        let maxNonStackableValue = 0
        validCoupons.forEach(coupon => {
            if (coupon.accumulationShow === '0') {
                const discountAmount = parseFloat(coupon.price);
                // 计算实际支付金额
                const finalAmount = amount - discountAmount;
                // 确保实际支付金额不小于0,并且是最优惠的
                if (finalAmount >= 0) {
                    if (maxNonStackableValue<discountAmount) {
                        maxNonStackableValue = discountAmount
                        list2=[{...coupon}]
                    }
                }
            }
        });
        console.log('可叠加优惠券组合', list1);
        console.log('不可叠加的优惠券', list2);
        // 计算两个列表的最大优惠值
        let maxStackableValue = list1.reduce((total, coupon) => total + parseFloat(coupon.price), 0);
        console.log('可叠加优惠券组合总金额', maxStackableValue);
        console.log('不可叠加的优惠券总金额', maxNonStackableValue);
        // 比较两个最大值并输出结果
        if (maxStackableValue > maxNonStackableValue) {
            finalList = list1
        } else if (maxStackableValue < maxNonStackableValue) {
            finalList = list2
        } else {
            console.log(`两者的优惠值相同: ${maxStackableValue}`);
            let copiedList1 = JSON.parse(JSON.stringify(list1));
            let copiedList2 = JSON.parse(JSON.stringify(list2));
            let minList1 = copiedList1.length > 0 ? Math.min(...copiedList1.map(item => item.useEtime)) : Infinity;
            let minList2 = copiedList2.length > 0 ? Math.min(...copiedList2.map(item => item.useEtime)) : Infinity;
            // 判断最小的 useEtime 是在 list1 还是 list2
            if (minList1 <= minList2) {
                console.log('最小的在 list1 中', list1);
                finalList = list1
            } else {
                console.log('最小的在 list2 中', list2);
                finalList = list2
            }
        }
        console.log('选中的券组合', finalList);
        let discountPrice = 0;
        // 更新选中的优惠券
        finalList.forEach(coupon => {
            let target = arr.findIndex(obj => obj.activity_id === coupon.activity_id);
            if (target>-1) {
                arr[target].showCpupon = 1;
                arr[target].checked = true;
                discountPrice += parseFloat(coupon.price); // 使用 parseFloat 确保类型正确
            }
            console.log('选中的券', {
                ...coupon
            });
        });
        discountPrice = discountPrice.toFixed(2)
        console.log('总优惠金额:', discountPrice);
        console.log('消费金抵扣:',this.data.consumeDiscount);
        this.setData({
            discountPrice,
        });
        return {
            arr,
            discountPrice,
            finalList, // 返回可叠加和不可叠加的优惠券组合
        };
    },
    // 计算免费券有效期的起始、结束日期
    setTimeRange(cdate, startOffset, endOffset) {
        const startDate = new Date((cdate + startOffset * 86400) * 1000);
        startDate.setHours(0, 0, 0, 0);
        let useStime = startDate.getTime() / 1000
        const endDate = new Date((cdate + endOffset * 86400) * 1000);
        endDate.setHours(23, 59, 59, 0);
        let useEtime = endDate.getTime() / 1000
        return { useStime, useEtime };
    },  
    // 处理优惠券不可用日期数据
    hasConsecutiveSelect(arr, type) {
        let firstTitle = null;
        let lastTitle = null;
        let rArr = []
        let num = 0
        for (let i = 0; i < arr.length; i++) {
            let str = type == '1' ? arr[i].selectMor : type == '2' ? arr[i].selectNoon : type == '3' ? arr[i].selectNig : '';
            if (str) {
                rArr.push(arr[i].title)
                num++
                if (num == 1) {
                    firstTitle = arr[i].title
                }
                if (num >= 5) {
                    lastTitle = arr[i].title
                }
                if (num >= 5 && i >= (arr.length - 1)) {
                    let fi = rArr.findIndex((item) => {
                        return item == firstTitle
                    })
                    rArr.splice(fi, num, firstTitle + '至' + lastTitle)
                    num = 0
                }
            } else {
                if (num < 5) {
                    num = 0
                    firstTitle = null;
                    lastTitle = null;
                } else {
                    let fi = rArr.findIndex((item) => {
                        return item == firstTitle
                    })
                    rArr.splice(fi, num, firstTitle + '至' + lastTitle)
                    num = 0
                }
            }
        }
        return {
            rArr,
            lastTitle,
            firstTitle
        };
    },
    // 判断当前时间餐段、节假日
    getSellerDailyFun(lunchDis) {
        let lunchDinnerList = [];
        if (lunchDis.morning) {
            lunchDinnerList.push({
                can: "早餐",
                solt: 1,
                class: "morning",
            })
        }
        if (lunchDis.noon) {
            lunchDinnerList.push({
                can: "午餐",
                solt: 2,
                class: "dinner",
            })
        }
        if (lunchDis.night) {
            lunchDinnerList.push({
                can: "晚餐",
                solt: 3,
                class: "lunch",
            })
        }
        const currentTime = new Date().toLocaleTimeString('en-US', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit'
        });
        let obj = this.checkTimeInInterval(currentTime, lunchDis, lunchDinnerList);
        //节假日数组
        var holidays = [
            '2025-1-1', // 元旦
            '2025-1-28', // 春节
            '2025-1-29', // 春节
            '2025-1-30', // 春节
            '2025-1-31', // 春节
            '2025-2-1', // 春节
            '2025-2-2', // 春节
            '2025-2-3', // 春节
            '2025-2-4', // 春节
            '2025-4-4', //清明
            '2025-4-5', //清明
            '2025-4-6', //清明
            '2025-5-1', // 劳动节
            '2025-5-2', // 劳动节
            '2025-5-3', // 劳动节
            '2025-5-4', // 劳动节
            '2025-5-5', // 劳动节
            '2025-5-31', // 端午节
            '2025-6-1', // 端午节
            '2025-6-2', // 端午节
            '2025-10-1', // 国庆节、中秋节
            '2025-10-2', // 国庆节、中秋节
            '2025-10-3', // 国庆节、中秋节
            '2025-10-4', // 国庆节、中秋节
            '2025-10-5', // 国庆节、中秋节
            '2025-10-6', // 国庆节、中秋节
            '2025-10-7', // 国庆节、中秋节
            '2025-10-8', // 国庆节、中秋节
        ];
        //周末上班日期数组
        var nWeekend = [
            '2025-1-26', //春节调整
            '2025-2-8', //春节调整
            '2025-4-27', //五一调整
            '2025-9-28', //国庆调整
            '2025-10-11', //国庆调整
        ];
        var curdate = new Date();
        var year = curdate.getFullYear();
        var month = curdate.getMonth() + 1;
        var date = Math.floor((curdate.getTime() % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60 * 24)) + 1; // 计算当前日期
        var formattedDate = year + "-" + month + "-" + date;
        //在节假日数组内
        if ((holidays.indexOf(formattedDate) >= 0) && nWeekend.indexOf(formattedDate) < 0) {
            obj.isshow = '1'
        } else {
            obj.isshow = '0'
        }
        console.log('不可用日期信息餐段节假日', {...obj});
        if (obj && obj.can && obj.solt) {
            this.setData({
                canSolt: {
                    ...obj
                }
            })
        }
        this.getCoupon()
    },
    // 传参currentTime 当前时间 例16:51 lunchDis 餐段 {morning: "07:00-10:00",night: "16:00-21:00",noon: "11:00-14:30"}
    // 判断当前时间餐段
    checkTimeInInterval(currentTime, lunchDis, lunchDinnerList) {
        const [currentHour, currentMinute] = currentTime.split(':');
        const [morningHour2, morningMinute2] = lunchDis.morning ? lunchDis.morning.split("-")[1].split(':') : [0, 0];
        const [noonHour1, noonMinute1] = lunchDis.noon ? lunchDis.noon.split("-")[0].split(':') : [0, 0];
        const [noonHour2, noonMinute2] = lunchDis.noon ? lunchDis.noon.split("-")[1].split(':') : [0, 0];
        const [nightHour1, nightMinute1] = lunchDis.night ? lunchDis.night.split("-")[0].split(':') : [0, 0];
        const currentTimestamp = new Date().setHours(currentHour, currentMinute, 0, 0); //当前时间
        const time1 = (morningHour2 && morningMinute2) ? new Date().setHours(morningHour2, morningMinute2, 0, 0) : ''; //早餐截止时间
        const time2 = (noonHour1 && noonMinute1) ? new Date().setHours(noonHour1, noonMinute1, 0, 0) : ''; //午餐开始时间
        const time3 = (noonHour2 && noonMinute2) ? new Date().setHours(noonHour2, noonMinute2, 0, 0) : ''; //午餐截止时间
        const time4 = (nightHour1 && nightMinute1) ? new Date().setHours(nightHour1, nightMinute1, 0, 0) : ''; //晚餐开始时间
        // 1个餐段
        if (lunchDinnerList.length == 1) {
            return {
                solt: lunchDinnerList[0].solt,
                can: lunchDinnerList[0].can
            };
        }
        // 2个餐段(早,午)(早,晚)(午,晚)
        if (lunchDinnerList.length == 2) {
            let obj1 = lunchDinnerList[0];
            let obj2 = lunchDinnerList[1];
            let timeA1 = obj1.solt == 1 ? time1 : time2;
            let timeA2 = obj2.solt == 2 ? time2 : time4;
            if (currentTimestamp < timeA1) { // 在早餐/午餐截止时间之前
                return obj1.solt == 1 ? {
                    solt: 1,
                    can: '早餐'
                } : {
                    solt: 2,
                    can: '午餐'
                }
            } else if (currentTimestamp > timeA1 && currentTimestamp < timeA2) { //在早餐/午餐截止时间之后 && 午餐/晚餐开始时间之前
                return obj1.solt == 1 ? {
                    solt: 1,
                    can: '早餐'
                } : {
                    solt: 2,
                    can: '午餐'
                };
            } else if (currentTimestamp > timeA2) { //在午餐/晚餐截止时间之后
                return obj2.solt == 2 ? {
                    solt: 2,
                    can: '午餐'
                } : {
                    solt: 3,
                    can: '晚餐'
                };
            }
        }
        // 3个餐段(早,午,晚)
        if (lunchDinnerList.length == 3) {
            if (currentTimestamp < time1) { //当前时间 在早餐截止时间之前
                return {
                    solt: 1,
                    can: '早餐'
                };
            } else if (currentTimestamp > time1 && currentTimestamp < time2) { //在早餐截止时间之后 && 午餐开始时间之前
                return {
                    solt: 1,
                    can: '早餐'
                };
            } else if (currentTimestamp > time2 && currentTimestamp < time3){
                return {
                    solt: 2,
                    can: '午餐'
                }
            } else if (currentTimestamp > time3 && currentTimestamp < time4) { //在午餐截止时间之后 && 晚餐开始时间之前
                return {
                    solt: 2,
                    can: '午餐'
                };
            } else {
                return {
                    solt: 3,
                    can: '晚餐'
                };
            }
        }
    },
    // 获取当前应该赠送的阶梯券
    findObjectByNum(arr, num) {
        let result = {};
        let maxPrice = -Infinity;
        for (let i = 0; i < arr.length; i++) {
            const price = parseFloat(arr[i].price, 10);
            if (price <= num && price > maxPrice) {
                maxPrice = price;
                result = arr[i];
            }
        }
        return result;
    },
    // 跳转到我的券列表
    certificate() {
        wx.reLaunch({
            url: '/pages/me/coupon_news'
        })
    },
    // 跳转到我的消费金列表
    gotoConsumeList() {
        wx.reLaunch({
            url: '/pages/me/consumeAmount'
        })
    },
    getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.myToast = this.selectComponent("#myToast")
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.payFail()
        this.getCheckUserHavePhone()
        this.getFreeMealConfigFun()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})