<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/9/19
 * Time: 下午6:48
 */

require_once (BASE_ROOT_PATH . '/helper/activity_helper.php');
require_once (BASE_ROOT_PATH . '/helper/goods_helper.php');
require_once (BASE_ROOT_PATH . '/helper/pay_helper.php');
require_once (BASE_ROOT_PATH . '/helper/predeposit_helper.php');

class buy_first
{
    private $mLogicOut;
    private $mUserFcode;

    public function __construct($logic_out)
    {
        $this->mLogicOut = $logic_out;
        $this->mUserFcode = null;
    }
    //商品金额相关信息
    private function payinfo()
    {
        $result = [];

        //商品总价,红包可抵扣,满减金额
        $goods_amount = 0.00;
        $store_goods_total = $this->mLogicOut['store_goods_total'];
        foreach ($store_goods_total as $store_id => $value) {
            $goods_amount += doubleval($value);
        }
        $result['goods_amount'] = $goods_amount;

        //满送
        $full_discount = 0.00;
        $full_desc = '';
        $store_mansong_rule_list = $this->mLogicOut['store_mansong_rule_list'];
        foreach ($store_mansong_rule_list as $store_id => $value) {
            $full_discount += doubleval($value['discount']);
            $full_desc = $this->full_desc($value['desc']);
        }
        $result['full_discount'] = $full_discount;
        $result['full_desc'] = $full_desc;
        $result['full_goods'] = $this->full_goods();

        //运费
        if($this->freight($freight,$offpay_hash,$offpay_hash_batch) == true) {
            $result['freight'] = $freight;
            $result['offpay_hash_batch'] = $offpay_hash_batch;
            $result['offpay_hash'] = $offpay_hash;
        } else {
            $result['freight'] = 0;
            $result['offpay_hash_batch'] = "";
            $result['offpay_hash'] = "";
        }
        $result['freight_hash'] = $this->mLogicOut['freight_list'];

        //红包信息
        $result['total_pred'] = doubleval($this->mLogicOut['available_predeposit']);
        $result['opgoods_discount'] = $this->optional_goods();
        $result['opgoods_desc'] = 'N元任选优惠';
        $result['available_pred']  = $this->available_pred($goods_amount,$full_discount,$result['total_pred'],$rates,$discount_gap,$gap_show);
        $result['discount_gap'] = $discount_gap;
        $result['bonus_rates'] = $this->formate_rates($rates);
        $result['gap_show'] = $gap_show;

        global $config;
        if($gap_show == true)
        {
            if(intval($discount_gap * 100 + 0.5) == 0) {
                $result['gap_desc'] = $config['bonus_gap']['no_gap'];
            } else {
                $result['gap_desc'] = sprintf($config['bonus_gap']['have_gap'],$discount_gap);
            }
        } else {
            $result['gap_desc'] = "";
        }
        $result['earn_bonus'] = $config['bonus_gap']['earn_bonus'];

        $result['usable_pred'] = true;
        $result['pay_cash_pred'] = $result['goods_amount'] + $result['freight'] - $result['full_discount'] - $result['available_pred'] - $result['opgoods_discount'];
        $result['pay_cash_nopred'] = $result['goods_amount'] + $result['freight'] - $result['full_discount'] - $result['opgoods_discount'];

        //购物车显示应付现金
        $result['pay_car_pred'] = $result['goods_amount'] - $result['full_discount'] - $result['available_pred'] - $result['opgoods_discount'];
        //商品总价
        $result['pay_car_nopred'] = $result['goods_amount'] - $result['full_discount'] - $result['opgoods_discount'];

        //是否可以开增值税发票
        $result['vat_deny'] = $this->mLogicOut['vat_deny'];
        //发票
        $result['vat_hash'] = $this->mLogicOut['vat_hash'];

        if(intval($result['goods_amount'] + 0.005) > 0) {
            $discount_rate   = intval($result['pay_car_pred'] * 100 / $result['goods_amount'] + 0.5);
            $discount_amount = $result['goods_amount'] - $result['pay_car_pred'];
        } else {
            $discount_rate = 0;
            $discount_amount = 0;
        }
        $result['discount_desc'] = $this->discount_desc($discount_rate,$discount_amount);

        return $result;
    }

    private function discount_desc($rate,$amount)
    {
        if($rate > 0) {
            $rate = $rate / 10;
            return "相比官旗店，折扣率为{$rate}折，节省{$amount}元";
        }
        elseif ($rate == 100) {
            return "";
        }
        else {
            return "相比官旗店，折扣率为全抵，节省{$amount}元";
        }
    }

    private function optional_goods()
    {
        $discount = 0;
        $result = [];
        $store_cart_list = $this->mLogicOut['store_cart_list'];
        foreach ($store_cart_list as $store_id => $cart_list)
        {
            if($store_id == 6)
            {
                $matcher = new optional_match($cart_list);
                $op_result = $matcher->match();
                if($op_result != false) {
                    $result[$store_id] = $op_result;
                    $discount += $op_result['discount'];
                } else {
                    $result[$store_id] = array('discount' => 0,'goods_nums' => []);
                }
            }
            else {
                $result[$store_id] = array('discount' => 0,'goods_nums' => []);
            }
        }
        $this->mLogicOut['optional_goods'] = $result;

        return $discount;
    }

    private function formate_rates($rates)
    {
        if(empty($rates)) return null;

        $result = [];
        foreach ($rates as $rate => $val) {
            $item['rate'] = $rate;
            $item['total'] = $val;
            $result[] = $item;
        }
        return $result;
    }

    private function full_desc($desc)
    {
        $ret = preg_match('#(.*?)<a.*?title=("|\')(.*?)\2.*?>.*?</a>#s',$desc,$matches);
        if($ret != false && count($matches) == 4) {
            $desc = $matches[1] . $matches[3];
        }

        return $desc;
    }

    private function full_goods()
    {
        $store_mansong_rule_list = $this->mLogicOut['store_mansong_rule_list'];
        foreach ($store_mansong_rule_list as $store_id => $value) {
            return intval($value['goods_id']);
        }

        return 0;
    }

    private function city_id()
    {
        $address_info = $this->mLogicOut['address_info'];
        if(empty($address_info)) {
            return false;
        } else {
            return intval($address_info['city_id']);
        }
    }
    private function area_id()
    {
        $address_info = $this->mLogicOut['address_info'];
        if(empty($address_info)) {
            return false;
        } else {
            return intval($address_info['area_id']);
        }
    }
    private function paytype()
    {
        return pay_helper::pay_types();
    }
    //运费相关信息
    private function freight(&$freight,&$offpay_hash,&$offpay_hash_batch)
    {
        $logic_buy = Logic("buy");
        $freight_hash = $this->mLogicOut['freight_list'];
        $city_id = $this->city_id();
        $area_id = $this->area_id();
        $data = $logic_buy->changeAddr($freight_hash, $city_id, $area_id, $_SESSION['member_id']);
        if (!empty($data) && $data['state'] == 'success')
        {
            $offpay_hash = $data['offpay_hash'];
            $offpay_hash_batch = $data['offpay_hash_batch'];

            $freight = 0.00;
            foreach ($data['content'] as $value) {
                $freight += $value['value'];
            }
            return true;
        }
        else {
            return false;
        }
    }

    private function goods_ids()
    {
        $ids = [];
        $sent_id = $this->full_goods();
        if($sent_id > 0) {
            $ids[] = $sent_id;
        }

        $carts = $this->goods_list();
        foreach ($carts as $item)
        {
            if($item['bl_id'] > 0)
            {
                $bl_goods = activity_helper::bundling_goods($item['bl_id']);
                if($bl_goods != false) {
                    foreach ($bl_goods as $gid) {
                        $ids[] = $gid;
                    }
                }
            }
            else
            {
                $ids[] = $item['goods_id'];
            }
        }

        return $ids;
    }
    private function summary()
    {
        $goods_ids = $this->goods_ids();

        $helper = new goods_helper();
        $summaries = $helper->online_summary($goods_ids,$related_goods);
        $summary_list = $summaries['summary'];
        if(!empty($related_goods)) {
            $related_summary = $helper->cart_summary($related_goods,$x);
            $summary_list = array_merge($summary_list,$related_summary['summary']);
        }

        $ret['summary']  = $summary_list;
        $ret['groupbuy'] = $summaries['groupbuy'];
        $ret['limitime'] = $summaries['limitime'];
        $ret['bundling'] = $summaries['bundling'];

        return $ret;
    }

    private function address()
    {
        return $this->mLogicOut['address_info'];
    }

    private function goods_list()
    {
        //购物车中商品列表
        $goods_list = [];
        $store_cart_list = $this->mLogicOut['store_cart_list'];
        foreach ($store_cart_list as $store_id => $carts)
        {
            foreach ($carts as $value) {
                $item['goods_id'] = intval($value['goods_id']);
                $item['goods_num'] = intval($value['goods_num']);
                $item['bl_id'] = intval($value['bl_id']);

                $goods_list[] = $item;
            }
        }

        return $goods_list;
    }

    private function invoice()
    {
        return $this->mLogicOut['inv_info'];
    }

    private function available_pred($goods_amount,$full_discount,$pd_total,&$rates,&$discount_gap,&$gap_show)
    {
        $full = intval($full_discount * 100 + 0.5);
        $pred_amound = $this->pred_goods_amount();
        $pred_cent = intval($pred_amound * 100 + 0.5);
        if($pred_cent > 0)
        {
            $gap_show = true;
            if($full > 0) {
                $pred_amound = $pred_amound - ($pred_amound / $goods_amount) * $full_discount;
            }
            $bonus_goods_amount = $pred_amound;
            $pred_amound = $pred_amound - predeposit_helper::order_cash($pred_amound,$rates);

            $pred_cend = intval($pred_amound * 100 + 0.5);
            $pd_total  = intval($pd_total * 100 + 0.5);

            $ret = ($pred_cend > $pd_total) ? ($pd_total / 100) : ($pred_cend / 100);
            $discount_gap = predeposit_helper::discount_gap($bonus_goods_amount - $ret,$bonus_goods_amount);

            return $ret;
        }
        else
        {
            $rates = [];
            $gap_show = false;
            $discount_gap = 0.00;

            return 0.00;
        }
    }

    private function pred_goods_amount()
    {
        $pred_amount = 0.00;
        $store_cart_list = $this->mLogicOut['store_cart_list'];
        foreach ($store_cart_list as $store_id => $cart_list)
        {
            $opgoods = $this->mLogicOut['optional_goods'][$store_id];

            foreach ($cart_list as $cart)
            {
                $goods_total = $cart['goods_total'];
                if(intval($cart['bl_id']) > 0) {
                }
                elseif(!empty($cart['groupbuy_info'])) {
                }
                elseif(!empty($cart['xianshi_info'])) {
                }
                else
                {
                    if(empty($opgoods)) {
                        $pred_amount += $goods_total;
                    }
                    else
                    {
                        $goods_id    = intval($cart['goods_id']);
                        if(array_key_exists($goods_id,$opgoods['goods_nums']))
                        {
                            $goods_price = $cart['goods_price'];
                            $goods_num = intval($cart['goods_num']);
                            $opnum = $opgoods['goods_nums'][$goods_id];
                            if($goods_num > $opnum) {
                                $pred_amount += $goods_price * ($goods_num - $opnum);
                            }
                        }
                        else {
                            $pred_amount += $goods_total;
                        }
                    }
                }
            }
        }
        return $pred_amount;
    }

    public function check_fcode(&$err)
    {
        $cids = [];

        $store_cart_list = $this->mLogicOut['store_cart_list'];
        foreach ($store_cart_list as $store_id => $carts)
        {
            foreach ($carts as $value)
            {
                $bl_id = intval($value['bl_id']);
                if($bl_id > 0) continue;

                $fcode = intval($value['is_fcode']) == 1 ? true : false;
                if($fcode)
                {
                    $goods_id  = intval($value['goods_id']);
                    $goods_num = intval($value['goods_num']);
                    $commonid = commonid_helper::instance()->common_id($goods_id);

                    if(isset($cids[$commonid])) {
                        $cids[$commonid]['num'] += $goods_num;
                    } else {
                        $cids[$commonid]['num']  = $goods_num;
                        $cids[$commonid]['name'] = $value['goods_name'];
                    }
                }
            }
        }

        if(!empty($cids))
        {
            if($this->mUserFcode == null) {
                $this->mUserFcode = new user_session\fcode();
                $this->mUserFcode->onStatus();
            }

            foreach ($cids as $commonid => $val)
            {
                $goods_num = $val['num'];
                $name = $val['name'];

                if($goods_num <= 0) continue;

                $num = $this->mUserFcode->usable_num($commonid,$lock_num);
                if($num == false)
                {
                    if(isset($lock_num) && $lock_num > 0) {
                        $err = "您购买<{$name}>的F码处于锁定状态，激活后可以购买.";
                    } else {
                        $err = "您没有购买<{$name}>的F码，请重新选择商品.";
                    }


                    return false;
                }
                elseif($num < $goods_num) {
                    $err = "您只有购买{$num}支<{$name}>的F码, 请修改商品数量.";
                    return false;
                }
            }
        }
        return true;
    }

    public function format()
    {
        $result = [];
        $result['payinfo'] = $this->payinfo();
        $result['paytype'] = $this->paytype();
        $result['address'] = $this->address();
        $result['invoice'] = $this->invoice();
        $result['goods_list'] = $this->goods_list();

        $summary = $this->summary();
        $result['summary']  = $summary['summary'];
        $result['groupbuy'] = $summary['groupbuy'];
        $result['limitime'] = $summary['limitime'];
        $result['bundling'] = $summary['bundling'];

        return $result;
    }
}