<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海口快推科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2019-1-7
 */

namespace app\common\model;

use think\Db;
use think\Cache;
use think\Config;
use think\Cookie;

/**
 * 商城优惠券处理模型
 */
load_trait('controller/Jump');
class ShopCouponHandle
{
    use \traits\controller\Jump;

    private $sendTerminal = '';

    // 构造函数
    public function __construct()
    {
        // 统一接收参数处理
        $this->times = getTime();
        $this->post = input('post.');
        $this->weappCoupons = Db::name('weapp_coupons');
        $this->weappCouponsUse = Db::name('weapp_coupons_use');
        $this->sendTerminal = input('param.sendTerminal/s', 'openSource');
        $this->sendTerminal = !empty($this->sendTerminal) ? trim($this->sendTerminal) : '';
    }

    // 获取商品可用的优惠券
    public function getGoodsUseCouponsList($list = [], $post = [], $usersData = [], $globalConfig = [])
    {
        // 计算所有商品总价
        $all_total_price = $no_discount_total_price = 0;
        foreach ($list as $key => $value) {
            // if (!empty($value['stop_buy']) && 1 == $value['stop_buy']) {
            //     unset($list[$key]); //去除本单不可使用商品
            //     continue;
            // }
            // if (empty($value['use_discount_price'])) $no_discount_total_price += $value['subtotal'];
            $all_total_price += $value['subtotal'];
            $no_discount_total_price += $value['subtotal'];
        }

        // 查出全部的没过期优惠券
        $where = [
            'a.use_status' => 0,
            'b.coupon_id' => ['>', 0],
            'a.end_time' => ['>=', $this->times],
            'a.start_time' => ['<=', $this->times],
            'a.users_id' => $usersData['users_id'],
        ];
        $usersCoupons = $this->weappCouponsUse
            ->alias('a')
            ->join('__WEAPP_COUPONS__ b', 'a.coupon_id = b.coupon_id', 'LEFT')
            ->where($where)
            ->getAllWithIndex('use_id');
        $couponsList = [];
        if (!empty($usersCoupons)) {
            $usersDiscount = !empty($usersData['level_discount']) ? strval($usersData['level_discount']) / strval(100) : 1;
            foreach ($usersCoupons as $key => $value) {
                // 如果会员有折扣且优惠券设置不与折扣同享则跳过
                if (!empty($value['use_limit']) && 1 != $usersDiscount) continue;

                // 满减额度
                $value['conditions_use'] = floatval($value['conditions_use']);

                // 满减类型
                if (1 === intval($value['coupon_form'])) {
                    $value['coupon_form_name'] = '满减券';
                } else if (2 === intval($value['coupon_form'])) {
                    $value['coupon_form_name'] = '满折券';
                    $value['coupon_discount'] = floatval($value['coupon_discount']);
                }

                // 开始时间和结束时间格式处理
                $value['end_time'] = model('ShopPublicHandle')->getTimesFormat($value['end_time']);
                $value['start_time'] = model('ShopPublicHandle')->getTimesFormat($value['start_time']);

                // 使用类型
                switch ($value['coupon_type']) {
                    case 2:
                        $value['coupon_type_name'] = '指定商品';
                        // 指定商品
                        if (!empty($value['product_id'])) {
                            $product_arr = explode(",", $value['product_id']);
                            // 本张优惠券可用的商品总价
                            $goodsTotalPrice = 0;
                            foreach ($list as $value_1) {
                                if (!empty($value['use_limit']) && 1 == $value_1['users_discount_type']) continue;
                                if (!empty($value['use_limit']) && 0 == $value_1['users_discount_type'] && 1 != $usersDiscount) continue;
                                if (in_array($value_1['aid'], $product_arr)) $goodsTotalPrice += $value_1['subtotal'];
                            }
                            if (floatval($goodsTotalPrice) >= floatval($value['conditions_use'])) {
                                // 满折券
                                if (2 === intval($value['coupon_form'])) {
                                    // 优惠的折扣
                                    $couponDiscount = 1 - round($value['coupon_discount'] / 10, 1);
                                    $value['coupon_price'] = unifyPriceHandle($goodsTotalPrice * round($couponDiscount, 1));
                                }
                                // 此优惠券可用
                                $couponsList[] = $value;
                            }
                        }
                        break;
                    case 3:
                        $value['coupon_type_name'] = '指定分类';
                        //指定分类
                        if (!empty($value['arctype_id'])) {
                            $arctype_arr = explode(",", $value['arctype_id']);
                            // 本张优惠券可用的商品总价
                            $goodsTotalPrice = 0;
                            foreach ($list as $value_1) {
                                if (!empty($value['use_limit']) && 1 == $value_1['users_discount_type']) continue;
                                if (!empty($value['use_limit']) && 0 == $value_1['users_discount_type'] && 1 != $usersDiscount) continue;
                                $stypeidArr = array_filter(explode(',', $value_1['stypeid']));
                                if (!empty($stypeidArr)) {
                                    foreach ($stypeidArr as $value_2) {
                                        if (in_array($value_2, $arctype_arr)) {
                                            $goodsTotalPrice += $value_1['subtotal'];
                                            break;
                                        }
                                    }
                                }
                            }
                            if (floatval($goodsTotalPrice) >= floatval($value['conditions_use'])) {
                                // 满折券
                                if (2 === intval($value['coupon_form'])) {
                                    // 优惠的折扣
                                    $couponDiscount = 1 - round($value['coupon_discount'] / 10, 1);
                                    $value['coupon_price'] = unifyPriceHandle($goodsTotalPrice * round($couponDiscount, 1));
                                }
                                // 此优惠券可用
                                $couponsList[] = $value;
                            }
                        }
                        break;
                    default:
                        $value['coupon_type_name'] = '全部商品';
                        // 不可与会员折扣同时使用 包括会员价和会员等级折扣
                        if (!empty($value['use_limit'])) {
                            $total_price = $no_discount_total_price;
                        } else {
                            $total_price = $all_total_price;
                        }

                        if (floatval($total_price) >= floatval($value['conditions_use'])) {
                            // 满折券
                            if (2 === intval($value['coupon_form'])) {
                                // 优惠的折扣
                                $couponDiscount = 1 - round($value['coupon_discount'] / 10, 1);
                                $value['coupon_price'] = unifyPriceHandle($total_price * round($couponDiscount, 1));
                            }
                            // 此优惠券可用
                            $couponsList[] = $value;
                        }
                        break;
                }
            }
        }
        return $couponsList;
    }

    // 获取商品不可用的优惠券
    public function getGoodsUnuseCouponsList($coupon_ids = [], $users_id = 0)
    {
        // 查出全部的没过期优惠券
        $where = [
            'a.use_status' => 0,
            'a.users_id' => $users_id,
            'a.end_time' => ['>=', $this->times],
            'b.coupon_id' => ['NOT IN', $coupon_ids],
        ];
        $usersCoupons = $this->weappCouponsUse
            ->alias('a')
            ->join('__WEAPP_COUPONS__ b', 'a.coupon_id = b.coupon_id', 'LEFT')
            ->where($where)
            ->getAllWithIndex('use_id');
        $couponsList = [];
        if (!empty($usersCoupons)) {
            foreach ($usersCoupons as $value) {
                // 满减额度
                $value['conditions_use'] = floatval($value['conditions_use']);

                // 满减类型
                if (1 === intval($value['coupon_form'])) {
                    $value['coupon_form_name'] = '满减券';
                } else if (2 === intval($value['coupon_form'])) {
                    $value['coupon_form_name'] = '满折券';
                    $value['coupon_discount'] = floatval($value['coupon_discount']);
                }

                // 开始时间和结束时间格式处理
                $value['end_time'] = model('ShopPublicHandle')->getTimesFormat($value['end_time']);
                $value['start_time'] = model('ShopPublicHandle')->getTimesFormat($value['start_time']);

                // 使用类型
                switch ($value['coupon_type']) {
                    case 1:
                        $value['coupon_type_name'] = '全部商品';
                        break;
                    case 2;
                        $value['coupon_type_name'] = '指定商品';
                        break;
                    case 3;
                        $value['coupon_type_name'] = '指定分类';
                        break;
                }
                $couponsList[] = $value;
            }
        }
        return $couponsList;
    }

    // 获取使用的优惠券详情及使用后的订单价格
    public function orderUseCouponHandle($post = [], $list = [])
    {
        $where = [
            'a.use_status' => 0,
            'a.end_time' => ['>=', $this->times],
            'a.start_time' => ['<=', $this->times],
            'a.users_id' => intval($post['users_id']),
            'a.coupon_id' => intval($post['coupon_id']),
        ];
        $usersCoupons = $this->weappCouponsUse->alias('a')->join('__WEAPP_COUPONS__ b', 'a.coupon_id = b.coupon_id', 'LEFT')->where($where)->find();

        // 如果会员有折扣且优惠券设置不与折扣同享则跳过
        $usersDiscount = !empty($usersData['level_discount']) ? strval($usersData['level_discount']) / strval(100) : 1;
        if (!empty($usersCoupons['use_limit']) && 1 != $usersDiscount) return [];

        // 使用优惠券处理
        if (!empty($usersCoupons) && 2 === intval($usersCoupons['coupon_form'])) {
            $couponDiscount = 1 - round($usersCoupons['coupon_discount'] / 10, 1);

            // 全部商品
            if (1 === intval($usersCoupons['coupon_type'])) {
                // 获取订单总价格
                $goodsTotalPrice = unifyPriceHandle(array_sum(get_arr_column($list, 'subtotal')));
                // 满折券，优惠的折扣
                if (floatval($goodsTotalPrice) >= floatval($usersCoupons['conditions_use']) && 2 === intval($usersCoupons['coupon_form'])) {
                    $usersCoupons['coupon_price'] = unifyPriceHandle($goodsTotalPrice * round($couponDiscount, 1));
                }
            }
            // 指定商品
            else if (2 === intval($usersCoupons['coupon_type'])) {
                // 指定商品
                if (!empty($usersCoupons['product_id'])) {
                    $product_arr = explode(",", $usersCoupons['product_id']);
                    // 本张优惠券可用的商品总价
                    $goodsTotalPrice = 0;
                    foreach ($list as $value_1) {
                        if (!empty($usersCoupons['use_limit']) && 1 == $value_1['users_discount_type']) continue;
                        if (!empty($usersCoupons['use_limit']) && 0 == $value_1['users_discount_type'] && 1 != $usersDiscount) continue;
                        if (in_array($value_1['aid'], $product_arr))  $goodsTotalPrice += $value_1['subtotal'];
                    }
                    // 满折券，优惠的折扣
                    if (floatval($goodsTotalPrice) >= floatval($usersCoupons['conditions_use']) && 2 === intval($usersCoupons['coupon_form'])) {
                        $usersCoupons['coupon_price'] = unifyPriceHandle($goodsTotalPrice * round($couponDiscount, 1));
                    }
                }
            }
            // 指定分类
            else if (3 === intval($usersCoupons['coupon_type'])) {
                if (!empty($usersCoupons['arctype_id'])) {
                    $arctype_arr = explode(",", $usersCoupons['arctype_id']);
                    // 本张优惠券可用的商品总价
                    $goodsTotalPrice = 0;
                    foreach ($list as $value_2) {
                        if (!empty($usersCoupons['use_limit']) && 1 == $value_2['users_discount_type']) continue;
                        if (!empty($usersCoupons['use_limit']) && 0 == $value_2['users_discount_type'] && 1 != $usersDiscount) continue;
                        $stypeidArr = array_filter(explode(',', $value_2['stypeid']));
                        if (!empty($stypeidArr)) {
                            foreach ($stypeidArr as $value_3) {
                                if (in_array($value_3, $arctype_arr)) {
                                    $goodsTotalPrice += $value_2['subtotal'];
                                    break;
                                }
                            }
                        }
                    }
                    // 满折券，优惠的折扣
                    if (floatval($goodsTotalPrice) >= floatval($usersCoupons['conditions_use']) && 2 === intval($usersCoupons['coupon_form'])) {
                        $usersCoupons['coupon_price'] = unifyPriceHandle($goodsTotalPrice * round($couponDiscount, 1));
                    }
                }
            }
        }

        return $usersCoupons;
    }

    // 更新优惠券状态已使用
    public function updateUsersCouponStatus($orderUseCoupon = [])
    {
        if (!empty($orderUseCoupon['use_id']) && !empty($orderUseCoupon['users_id']) && !empty($orderUseCoupon['coupon_id'])) {
            $where = [
                'use_id' => $orderUseCoupon['use_id'],
                'users_id' => $orderUseCoupon['users_id'],
                'coupon_id' => $orderUseCoupon['coupon_id'],
                'use_status' => 0,
            ];
            $update = [
                'use_status' => 1,
                'use_time' => $this->times,
                'update_time' => $this->times
            ];
            $this->weappCouponsUse->where($where)->update($update);
        }
    }

    // 获取订单信息并计算商品优惠券金额合并返回
    public function getOrderUseCouponsHandle($param = [], $orderGoods = [], $allReturn = false)
    {
        // 查询相关订单信息
        $list = $orderGoods;
        $where = [
            'order_id' => intval($param['order_id'])
        ];
        if (!empty($param['users_id'])) $where['users_id'] = intval($param['users_id']);
        $field = 'details_id, product_id, product_price, num, data';
        $details = Db::name("shop_order_details")->field($field)->where($where)->select();
        foreach ($details as $key => $value) {
            $valueData = !empty($value['data']) ? unserialize($value['data']) : [];
            $details[$key]['goodsStypeid'] = !empty($valueData['goods_stypeid']) ? $valueData['goods_stypeid'] : '';
        }
        $list['Details'] = $details;

        // 获取商品优惠券金额
        $details = [];
        $this->showOrderUseCouponsHandle([$list], $details);
        // 如果定义返回全部则执行
        if (!empty($allReturn)) return $details;
        // 返回单个商品数据
        $details = !empty($details) ? convert_arr_key($details, 'details_id') : [];
        $details = !empty($details[$orderGoods['details_id']]) ? $details[$orderGoods['details_id']] : [];
        if (!empty($details)) $orderGoods = array_merge($orderGoods, $details);

        // 返回计算后的数据
        return $orderGoods;
    }

    // 显示订单使用优惠券详情处理
    public function showOrderUseCouponsHandle($orderList = [], &$details = [])
    {
        // 计算订单详情使用优惠券详情
        foreach ($orderList as $key => $value) {
            $orderGoods = !empty($value['Details']) ? $value['Details'] : [];
            $couponPrice = !empty($value['coupon_price']) ? unifyPriceHandle($value['coupon_price']) : 0;
            $useCoupons = !empty($value['use_coupon_data']) ? unserialize($value['use_coupon_data']) : [];
            $orderTotalAmount = !empty($value['order_total_amount']) ? unifyPriceHandle($value['order_total_amount']) : 0;
            if (!empty($orderGoods) && !empty($useCoupons) && !empty($couponPrice)) {
                // 全部商品
                if (1 === intval($useCoupons['coupon_type'])) {
                    foreach ($orderGoods as $key_1 => $value_1) {
                        $orderGoods[$key_1] = $this->findGoodsUseCouponsPrice($value_1, $couponPrice, $orderTotalAmount);
                    }
                    $orderList[$key]['Details'] = $details = $orderGoods;
                }
                // 指定商品
                else if (2 === intval($useCoupons['coupon_type'])) {
                    if (!empty($useCoupons['product_id'])) {
                        $useOrderGoods = [];
                        $productArr = explode(",", $useCoupons['product_id']);
                        foreach ($orderGoods as $key_2 => $value_2) {
                            if (in_array($value_2['product_id'], $productArr)) {
                                $value_2['findGoodsPrice'] = floatval($value_2['product_price']) * floatval($value_2['num']);
                                $useOrderGoods[$value_2['details_id']] = $value_2;
                            }
                        }
                        $orderTotalAmount = !empty($useOrderGoods) ? array_sum(get_arr_column($useOrderGoods, 'findGoodsPrice')) : 0;
                        foreach ($useOrderGoods as $key_3 => $value_3) {
                            $useOrderGoods[$key_3] = $this->findGoodsUseCouponsPrice($value_3, $couponPrice, $orderTotalAmount);
                        }
                        foreach ($orderGoods as $key_5 => $value_5) {
                            $orderGoods[$key_5] = !empty($useOrderGoods[$value_5['details_id']]) ? $useOrderGoods[$value_5['details_id']] : $value_5;
                        }
                        $orderList[$key]['Details'] = $details = $orderGoods;
                    }
                }
                // 指定分类
                else if (3 === intval($useCoupons['coupon_type'])) {
                    if (!empty($useCoupons['arctype_id'])) {
                        $useOrderGoods = [];
                        $arctypeArr = explode(",", $useCoupons['arctype_id']);
                        foreach ($orderGoods as $value_6) {
                            $stypeidArr = array_filter(explode(',', $value_6['goodsStypeid']));
                            if (!empty($stypeidArr)) {
                                foreach ($stypeidArr as $value_8) {
                                    if (in_array($value_8, $arctypeArr)) {
                                        $value_6['findGoodsPrice'] = floatval($value_6['product_price']) * floatval($value_6['num']);
                                        $useOrderGoods[$value_6['details_id']] = $value_6;
                                    }
                                }
                            }
                        }
                        $orderTotalAmount = !empty($useOrderGoods) ? array_sum(get_arr_column($useOrderGoods, 'findGoodsPrice')) : 0;
                        foreach ($useOrderGoods as $key_9 => $value_9) {
                            $useOrderGoods[$key_9] = $this->findGoodsUseCouponsPrice($value_9, $couponPrice, $orderTotalAmount);
                        }
                        foreach ($orderGoods as $key_10 => $value_10) {
                            $orderGoods[$key_10] = !empty($useOrderGoods[$value_10['details_id']]) ? $useOrderGoods[$value_10['details_id']] : $value_10;
                        }
                        $orderList[$key]['Details'] = $details = $orderGoods;
                    }
                }
            }
        }

        return $orderList;
    }

    // 单个商品使用优惠券额度
    private function findGoodsUseCouponsPrice($content = [], $couponPrice = 0, $orderTotalAmount = 0)
    {
        // 计算单个商品总额
        $findGoodsPrice = floatval($content['product_price']) * floatval($content['num']);
        // 计算单个商品占订单商品总金额比例
        $findGoodsRatio = round(floatval($findGoodsPrice) / floatval($orderTotalAmount), 1);
        // 计算优惠券单个商品使用比例额度
        $findGoodsCoupons = unifyPriceHandle(floatval($couponPrice) * floatval($findGoodsRatio));
        $content['couponsPrice'] = $findGoodsCoupons;
        // 单个商品实际付款金额
        $content['actualPayPrice'] = unifyPriceHandle(floatval($findGoodsPrice) - floatval($findGoodsCoupons));
        // 返回结果
        return $content;
    }
}