<?php namespace Phpcmf\Controllers;

class Checkout extends \Phpcmf\Common {

    public function __construct(...$params) {
        parent::__construct(...$params);
        !$this->uid && exit($this->_msg(0, '你还没有登录'));
    }

    // 直接付款
    public function buy() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        $fid = (int)\Phpcmf\Service::L('input')->get('fid');

        !$id && exit($this->_msg(0, dr_lang('id参数不存在')));
        !$fid && exit($this->_msg(0, dr_lang('字段fid参数不存在')));

        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        $sku = dr_safe_replace(\Phpcmf\Service::L('input')->get('sku'), 'undefined');

        $field = $this->get_cache('table-field', $fid);
        !$field && exit($this->_msg(0, dr_lang('支付字段不存在')));

        // 获取订单最终价格和库存信息
        $rt = \Phpcmf\Service::M('order', 'order')->get_goods_info($id, $field, $num, $sku);
        if (isset($rt['code']) && !$rt['code']) {
            exit($this->_msg(0, $rt['msg']));
        } elseif (!$rt['quantity']) {
            exit($this->_msg(0, dr_lang('该商品已销售完')));
        } elseif ($rt['quantity'] < $num) {
            exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));
        }
        
        // 获取模块id
        list($a, $rid, $fid) = explode('-', $rt['mid']);
        list($s, $mid) = explode('_', $a);

        if (!isset($rt['data']['mall_cid']) || !isset($rt['data']['mall_name'])) {
            exit($this->_msg(0, dr_lang('没有找到商品【%s】的所属店铺', $rt['data']['title'])));
        }

        $list[] = $rt;


        $this->_checkout([
            [[$mid, $rt['data']['mall_cid']], $list, $rt['total'], $rt['give_score'], $rt['give_money']]
        ]);
    }

    // 购物车的确认结算
    public function index() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        !$id && exit($this->_msg(0, dr_lang('%s，请重新下单', '订单失效')));

        $ocart = \Phpcmf\Service::M('Order', 'order')->my_order_cart_info($id);
        !$ocart && exit($this->_msg(0, dr_lang('%s，请重新下单', '订单不存在')));

        $cart = \Phpcmf\Service::M('Order', 'order')->my_cart_items(explode(',', $ocart['cid']));
        !$cart && exit($this->_msg(0, dr_lang('%s，请重新下单', '无可用订单')));

        $mall_list = []; // 按店铺分组
        foreach ($cart as $t) {
            $mall_list[$t['mall_cid']][] = $t;
        }

        $p = []; // 参数

        foreach ($mall_list as $cid => $cart) {
            $mid = []; // 模块id
            $list = []; // 商品列表
            $total = $give_money = $give_score = 0;

            foreach ($cart as $t) {
                list($a, $rid, $fid) = explode('-', $t['mid']);
                list($s, $name) = explode('_', $a);
                $mid[$name] = $name;
                $field = $this->get_cache('table-field', $fid);
                if (!$field) {
                    \Phpcmf\Service::M('Order', 'order')->delete_order_cart($id);
                    exit($this->_msg(0, dr_lang('%s#%s，请重新下单', '支付字段不存在', $fid)));
                } elseif (!isset($t['mall_cid']) || !isset($t['mall_name'])) {
                    exit($this->_msg(0, dr_lang('没有找到商品【%s】的所属店铺', $t['title'])));
                }

                // 获取订单最终价格和库存信息
                $rt = \Phpcmf\Service::M('order', 'order')->get_goods_info($rid, $field, $t['quantity'], $t['sku_value']);
                if (isset($rt['code']) && !$rt['code']) {
                    \Phpcmf\Service::M('order', 'order')->delete_order_cart($id);
                    exit($this->_msg(0, dr_lang('%s，请重新下单', $rt['msg'])));
                }

                !$rt['quantity'] && exit($this->_msg(0, dr_lang('该商品已销售完')));
                $rt['quantity'] < $t['quantity'] && exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));

                $list[$t['id']] = $rt;
                $total+= $rt['total'];

                $give_money+= $rt['give_money'];
                $give_score+= $rt['give_score'];

            }

            count($mid) >= 2 && exit($this->_msg(0, dr_lang('不能选择多个模块商品同时下单')));

            $p[] = [
                [array_shift($mid), $cid], $list, $total, $give_score, $give_money, $ocart
            ];
        }

        $this->_checkout($p);
    }

    // 直接确认结算
    public function _checkout($params) {

        $order = [];
        $pay_total = 0;

        $freight = [];
        $freight_total = 0;

        foreach ($params as $param) {

            list($p, $list, $total, $give_score, $give_money, $ocart) = $param;
            list($mid, $mall_id) = $p;
            // 查询店铺信息
            $mall = \Phpcmf\Service::M('order', 'order')->get_mall_info_id($mall_id);
            if (!$mall) {
                exit($this->_msg(0, dr_lang('此店铺（#%s）不存在或者已被关闭', $mall_id)));
            } elseif ($mall['uid'] == $this->uid) {
                exit($this->_msg(0, dr_lang('不能购买自己的商品')));
            }

            // 判断是否存在订单优惠
            $jian = 0;
            $discount = \Phpcmf\Service::M('order', 'order')->get_order_discount($total, $mall['uid'], $this->member);
            if ($discount) {
                $jian = $discount['jian'];
            }

            if (isset($_GET['is_ajax_get']) && $_GET['is_ajax_get']) {
                // ajax请求运费和总价
                $v = \Phpcmf\Service::M('order', 'order')->get_freight_price((int)$_GET['city'], $list);
                $freight_total+= $total + $v - $jian;
                $freight[] = number_format($v, 2);
            }

            $pay = $total - $jian;
            $order[$mall['id']] = [
                'mid' => $mid,
                'mall' => $mall,
                'list' => $list,
                'discount' => $discount,
                'order_total' => $total,
                'pay_total' => $pay,
                'give_score' => $give_score,
                'give_money' => $give_money,
            ];
            $pay_total+= $pay;

        }


        // ajax请求运费和总价
        if (isset($_GET['is_ajax_get']) && $_GET['is_ajax_get']) {
            $this->_json(1, '', ['total' => number_format($freight_total, 2), 'freight' => $freight]);
        }


        // 可用优惠券
        $my_coupon = [];

        // 付款方式
        list($pay_type, $pay_default) = order_get_pay_type();

        // 提交订单
        if (IS_POST) {
            // 收货地址
            if ($this->mall_info['order']['buy_address']) {
                $address = \Phpcmf\Service::M('Address', 'mall')->info((int)\Phpcmf\Service::L('input')->post('address'));
                !$address && exit($this->_json(0, dr_lang('收货人信息不存在')));
                $address['address'] = dr_linkagepos(FC_ADDRESS_CITY, $address['city'], '', '').$address['address'];
            }
            // 付款方式
            $pay_name = \Phpcmf\Service::L('input')->post('paytype');
            !$pay_type[$pay_name] && exit($this->_json(0, dr_lang('付款方式不存在')));

            $remark = \Phpcmf\Service::L('input')->post('remark', true);

            $oids = [];

            // 遍历商户商品
            foreach ($order as $io => $o) {

                $mid = $o['mid'];
                $list = $o['list'];
                $mall = $o['mall'];
                $discount = $o['discount'];
                $give_score = $o['give_score'];
                $give_money = $o['give_money'];
                $total = $o['order_total'];

                // 优惠券
                $jian = 0;
                $coupon = 0;
                /*
                $coupon = (int)\Phpcmf\Service::L('input')->post('coupon');
                if ($coupon && isset($my_coupon[$coupon]) && $my_coupon[$coupon]) {
                    // 重新获取优惠价格
                    $jian += (float)$my_coupon[$coupon]['money'];
                }*/
                // 获取运费
                $freight = \Phpcmf\Service::M('order', 'order')->get_freight_price($address['city'], $list);
                // 计算付款价格
                $money = max(0, $total + $freight - $jian);
                // 免费订单余额支付
                floatval($money) == 0 && $pay_name = 'finecms';
                $post = [
                    'mall' => $mall,
                    'sn' => order_get_order_sn(),
                    'mid' => $mid,
                    'money' => $money, //订单付款总金额
                    'freight' => $freight, // 运费
                    'discount' => $jian, // 优惠的金额
                    'coupon' => $coupon, // 优惠卷id
                    'give_score' => $give_score, // 赠送积分
                    'give_money' => $give_money, // 赠送金额
                    'promotion_name' => $discount ? $discount['title'] : '', // 订单折扣名称
                    'promotion_info' => $discount ? $discount['info'] : '', // 定制折扣详情
                    'source' => order_get_agent_name(), // 来源
                    'name' => $address ? $address['name'] : '',
                    'email' => $this->member['email'],
                    'phone' => $address ? $address['phone'] : '',
                    'address' => $address ? $address['address'] : '',
                    'pay_type' => $pay_name, // 付款方式
                    'remark' => dr_safe_replace($remark[$io]), // 订单备注
                ];

                $rt = \Phpcmf\Service::M('order', 'order')->checkout($post, $list, $ocart);
                !$rt['code'] && $this->_json(0, $rt['msg']);

                $oids[] = $rt['code'];

            }

            // 下单成功，跳转支付
            exit($this->_json(
                1, dr_lang('下单成功，正在跳转支付页面'), [
                    'url' => dr_url('order/buy/index', ['id' => implode(',', $oids)])
                ]
            ));
        }

        \Phpcmf\Service::V()->assign([
            'order' => $order,
            'pay_total' => $pay_total,
            'pay_type' => $pay_type,
            'pay_default' => $pay_default,
            'is_address' => $this->mall_info['order']['buy_address'],
            'address' => \Phpcmf\Service::M('address', 'mall')->my_address(),
            'meta_title' => dr_lang('订单结算').SITE_SEOJOIN.SITE_NAME,
            'meta_keywords' => $this->get_cache('site', SITE_ID, 'config', 'SITE_KEYWORDS'),
            'meta_description' => $this->get_cache('site', SITE_ID, 'config', 'SITE_DESCRIPTION')
        ]);
        \Phpcmf\Service::V()->display('checkout.html');
    }
}
