buyFreeCoupon.js 17.5 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
// pack-activity/pack/buyFreeCoupon.js
import util from '../../utils/util';
import App from '../../utils/api';
Page({
    /**
     * 页面的初始数据
     */
    data: {
        options: {},
        available: '1', //输入金额够优惠券最低消费1  不够0
        couponArr: [], //所有券列表
        dataStr: Date.now() * 1 / 1000,
        discountPrice: '', //优惠价格
        actualPrice: '', //实付价格
    },
    couponModal: '',
    monidata: [{
        desc: "0", //优惠条件
        price: "6", //优惠金额
        showCpupon: '1', //是否可选
        checked: true, //是否勾选
        activity_id: "566",
        aid: "948",
        aname: "新测试一下",
        cdate: "1739429461", //领取日期
        arule: {
            commission: "1",
            is_accumulation: "1",
            is_appointment: "1",
            is_commission: "1",
            is_compartment: "1",
            is_eatin: "1",
            is_same_day: "1", //领取当日是否可用
            is_share_have: "1",
            is_share_lose: "1",
            is_takeout: "1",
        },
        etime: "1739635199",
        exp_date: '{"week_show":"无","week_data":[{"id":null,"title":"周日","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"周一","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"周二","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"周三","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"周四","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"周五","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"周六","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false},{"id":null,"title":"法定假日","select":false,"roleName":null,"phone":null,"account":null,"selectMor":false,"selectNoon":false,"selectNig":false}]}',
        explain: "",
        grant_last: "93",
        grant_num: "100",
        id: "948",
        is_examine: "1",
        is_open: "1",
        is_type: "3",
        lite_qrcode: "https://xt04.colorcun.com/activity/LiteQRcode/activity_948.jpeg",
        map_address: "陕西省西安市沣惠南路36号",
        openid: "oB-xJ5NGdgXHM0Pdsq2kAf7z-n9k",
        phone: "15715807436",
        seller_image: "http://libpc.colorcun.com/20241118173230_b2dbe5ec7ca79a64bf7eea6f0cab3dca",
        seller_tel: "010-6257270,15236523652336",
        sellerid: "4352",
        sellername: "长安大排档总店",
        status: "1",
        stime: "1739289600",
        uid: "7035",
        uid_list: null,
        urllink: "https://wxaurl.cn/m7EcFm28Kfr",
    }],
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.couponModal = this.selectComponent("#couponModal");
        // this.couponModal.showModal()
        this.setData({
            ...options
        })
        if (options.sid) {
            this.getSellerDetail(options.sid)
        }
    },
    // 打开优惠券弹框
    showCouponModal() {
        this.couponModal.showModal()
    },
    // 关闭优惠券弹框
    closeCouponModal() {
        this.couponModal.closeModal()
    },
    // 获取店铺名称
    getSellerDetail(sid) {
        App.Customer.GetSellerDetail({
            sid
        }).then(res => {
            let data = res.data;
            this.setData({
                seller: {
                    seller_image: data.seller_image,
                    sellername: data.sellername

                }
            })
            this.getCoupon()
        })
    },
    // 获取所有优惠券列表
    getCoupon() {
        App.Activity.ActivityListByOpenid().then(res => {
            if (res.ret == 200 && res.data && res.data.length > 0) {
                let list = res.data.filter(item => {
                    return this.data.dataStr < (item.etime * 1) && item.is_open == '1'
                })
                list.forEach(detail => {
                    detail.stringifyUse = detail.use ? JSON.stringify(detail.use) : '';
                    detail.exp_date = detail.exp_date ? util.determine(detail.exp_date) : '';
                    detail.arule = detail.arule ? util.determine(detail.arule) : '';
                    if (detail.arule) {
                        detail.accumulationShow = detail.arule.is_accumulation
                    }
                    if (detail.exp_date && detail.exp_date.week_data) {
                        let noon = this.hasConsecutiveSelect(detail.exp_date.week_data, '1').rArr.join('、')
                        let nig = this.hasConsecutiveSelect(detail.exp_date.week_data, '2').rArr.join('、')
                        if (noon) noon = '午餐:' + noon
                        if (nig) nig = '晚餐:' + nig
                        detail.noonText = noon;
                        detail.nigText = nig;
                    }
                    detail.checked = false;
                    detail.showCpupon = '0';
                    detail.cdateText = util.unixtoTime(detail.cdate, 'YYYY-MM-DD')
                    detail.endDateStr = util.unixtoTime(detail.stime, 'YYYY-MM-DD') + '至' + util.unixtoTime(detail.etime, 'YYYY-MM-DD')
                })
                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
        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]) {
                    list[i].checked = true
                    break
                }
            }
        }
        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
        })

        this.colationData()
    },
    // 点确认选择
    checkCertificate() {
        this.closeCouponModal()
        let list = this.data.couponArr;
        list = list.filter(i => {
            return i.checked
        })
        let price = 0;
        list.forEach(i => {
            price += i.price * 1
        })
        console.log('优惠金额----', price);
        let val = this.data.inputValue * 1;
        let actualPrice = val - price.toFixed(2)
        this.setData({
            discountPrice: price,
            actualPrice: actualPrice > 0 ? actualPrice : 0.1,
        })
        console.log('点确认选择后', list);
    },
    // 处理显示券可用、不可用的列表
    async colationData() {
        let list = this.data.couponArr;
        // list = list
        list = await this.filterCoupons(list);
        list = await this.findBestCoupons(list);
        console.log('eeeeeeeeeeee', list);
        list.sort((a, b) => b.showCpupon - a.showCpupon);
        // list.filter(i=>{return i.aexpiration!='0' && i.aexpiration>0})
        this.setData({
            couponArr: list
        })
    },
    filterCoupons(list) {
        console.log(1111111, list);
        // const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间的 Unix 时间戳(秒)
        // const today = new Date(); // 获取今天的日期
        // today.setHours(0, 0, 0, 0); // 将时间设为今天的开始时间
        // const todayTimestamp = Math.floor(today.getTime() / 1000); // 获取今天的开始时间戳

        // return list.filter(coupon => {
        //     const couponCDate = parseInt(coupon.cdate); // 领取日期
        //     const validDays = parseInt(coupon.aexpiration); // 有效天数
        //     const isSameDay = parseInt(coupon.arule.is_same_day); // 领取当日是否可用

        //     // 计算有效期结束时间
        //     const couponExpirationDate = couponCDate + validDays * 24 * 60 * 60; // 有效期结束时间戳
        //     // 筛选条件
        //     const isWithinValidity = todayTimestamp >= couponCDate && todayTimestamp <= couponExpirationDate;
        //     return (
        //         (todayTimestamp > couponCDate && isWithinValidity) || // 今天不是领取当日,但在有效天数内
        //         (todayTimestamp === couponCDate && isSameDay === 1 && validDays >= 1) // 今天是领取当日且可用
        //     );
        // });


        // const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间的 Unix 时间戳(秒)
        // const today = new Date(); // 获取今天的日期
        // today.setHours(0, 0, 0, 0); // 将时间设为今天的开始时间
        // const todayTimestamp = Math.floor(today.getTime() / 1000); // 获取今天的开始时间戳

        // list.forEach(coupon => {
        //     const couponCDate = parseInt(coupon.cdate); // 领取日期
        //     const validDays = parseInt(coupon.aexpiration); // 有效天数
        //     const isSameDay = parseInt(coupon.arule.is_same_day); // 领取当日是否可用
        //     // const couponExpirationDate = couponCDate + validDays * 24 * 60 * 60; // 有效期结束时间戳

        //     let date = new Date(couponCDate * 1000);
        //     date.setDate(date.getDate() + validDays);
        //     date.setHours(23, 59, 59, 0);
        //     let couponExpirationDate = Math.floor(date.getTime() / 1000);
        //         // 今天的开始时间戳 <= 领取日期
        //     const isWithinValidity = (todayTimestamp <= couponCDate) && (todayTimestamp <= couponExpirationDate);
        //     console.log('领取日期---',couponCDate);
        //     console.log('有效天数---',validDays);
        //     console.log('领取当日是否可用---',isSameDay);
        //     console.log('有效期结束时间戳---',couponExpirationDate);
        //     console.log('isWithinValidity---',isWithinValidity);
        //     console.log('获取今天的开始时间戳---',todayTimestamp);
        //     console.log('wwwwwwwwwww---',(todayTimestamp >= couponCDate));
        //     console.log('ggggggggggg---',(todayTimestamp <= couponExpirationDate));
        //     // 今天不是领取当日,但在有效天数内 || 今天是领取当日且可用
        //     if ((todayTimestamp > couponCDate && isWithinValidity) || (todayTimestamp === couponCDate && isSameDay === 1 && validDays >= 1)) {
        //         coupon.aa = '1';
        //         console.log('可用',coupon.aname);
        //     } else {
        //         coupon.aa = '0'; 
        //         console.log('不可用',coupon.aname);
        //     }
        // });


        const currentTime = Math.floor(Date.now() / 1000); // 获取当前时间的 Unix 时间戳(秒)

        // 获取今天的开始时间和结束时间
        const today = new Date();
        today.setHours(0, 0, 0, 0); // 设置为今天的开始时间
        const todayStartTimestamp = Math.floor(today.getTime() / 1000); // 今天的开始时间戳

        today.setHours(23, 59, 59); // 设置为今天的结束时间
        const todayEndTimestamp = Math.floor(today.getTime() / 1000); // 今天的结束时间戳

        list.forEach(coupon => {
            const couponCDate = parseInt(coupon.cdate); // 领取日期
            const validDays = parseInt(coupon.aexpiration); // 有效天数
            const isSameDay = parseInt(coupon.arule.is_same_day); // 领取当日是否可用

            // 计算有效期结束时间
            const couponExpirationDate = couponCDate + validDays * 24 * 60 * 60; // 有效期结束时间戳

            // 判断条件
            const isWithinValidity = todayStartTimestamp > couponCDate && todayEndTimestamp < couponExpirationDate;

            if (
                (todayStartTimestamp > couponCDate && isWithinValidity) || // 今天不是领取当日,但在有效天数内
                (todayStartTimestamp === couponCDate && isSameDay === 1 && validDays >= 1) // 今天是领取当日且可用
            ) {
                coupon.aa = '1'; // 符合条件,设置为可选
            } else {
                coupon.aa = '0'; // 不符合条件,设置为不可选
            }
        });








        console.log('1111', list);
        return list
    },
    // (消费要求为无门槛 或者 小于输入金额的) && 勾选最优的
    findBestCoupons(arr) {
        console.log(333333333);
        let inputValue = this.data.inputValue;
        const amount = parseFloat(inputValue); // 将输入金额转换为数字
        const validCoupons = arr.filter(coupon => (coupon.aa == '1' && parseFloat(coupon.desc) <= amount)); // 筛选符合条件的优惠券
        console.log('validCouponsvalidCoupons', validCoupons);
        let bestDiscount = 0;
        let bestCoupons = [];

        // 按到期时间排序,确保优先选择最早到期的券
        validCoupons.sort((a, b) => parseInt(a.etime) - parseInt(b.etime));

        // 使用递归函数来查找所有组合
        function findBestCombination(currentCoupons, currentDiscount, remainingCoupons) {
            const totalDiscount = currentDiscount;
            const finalPrice = amount - totalDiscount;
            // 检查当前组合是否是最佳组合且实付价格不小于0
            if (finalPrice >= 0 && totalDiscount > bestDiscount) {
                bestDiscount = totalDiscount;
                bestCoupons = currentCoupons.slice(); // 复制当前组合
            }

            // 遍历剩余的优惠券
            for (let i = 0; i < remainingCoupons.length; i++) {
                const nextCoupon = remainingCoupons[i];
                currentCoupons.push(nextCoupon); // 选择当前优惠券
                findBestCombination(currentCoupons, currentDiscount + parseFloat(nextCoupon.price), remainingCoupons.slice(i + 1)); // 递归查找
                currentCoupons.pop(); // 回溯
            }
        }

        findBestCombination([], 0, validCoupons);


        let totalDiscountPrice = 0;
        // 更新选中的优惠券
        bestCoupons.forEach(coupon => {
            console.log('选中的券', {
                ...coupon
            });
            coupon.showCpupon = '1';
            coupon.checked = true;
            totalDiscountPrice += parseFloat(coupon.price); // 使用 parseFloat 确保类型正确
        });

        console.log('总优惠金额:', totalDiscountPrice);
        let actualPrice = (amount - totalDiscountPrice).toFixed(2);
        console.log('实际支付金额:', actualPrice);

        this.setData({
            discountPrice: totalDiscountPrice,
            actualPrice: actualPrice > 0 ? actualPrice : '0.1', // 确保实际支付金额不小于0.01
        });

        return arr; // 返回更新后的数组
    },
    // 处理优惠券不可用日期数据
    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].selectNoon : 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
        };
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})