<?php namespace Phpcmf\Controllers;

class Buy extends \Phpcmf\Common {

    // 订单付款
    public function index() {

        !$this->uid && exit($this->_msg(0, '你还没有登录'));

        $ids = dr_safe_replace(\Phpcmf\Service::L('input')->get('id'));
        !$ids && exit($this->_msg(0, dr_lang('订单参数不存在')));

        $arr = explode(',', $ids);
        $money = 0;
        foreach ($arr as $id) {
            $order = \Phpcmf\Service::M('Order', 'order')->info($id);
            !$order && exit($this->_msg(0, dr_lang('订单记录不存在')));
            $order['uid'] != $this->uid && exit($this->_msg(0, dr_lang('你无查看此订单')));
            $money+= floatval($order['money']);
        }



        if ($money > 0) {
            // 创建支付
            $pay = [
                'mark' => 'orders-'.$order['uid'].'-'.$ids,
                'sn' => count($arr) > 1 ? '多订单组合付款' : $order['sn'],
                'uid' => $order['uid'],
                'username' => $order['username'],
                'type' => $order['pay_type'],
                'url' => count($arr) > 1 ? dr_member_url('order/home/index') : dr_member_url('order/home/show', ['id' => $id]),
                'money' => $money,
            ];
            $rt = \Phpcmf\Service::M('Pay')->post($pay);
            if (!$rt['code']) {
                $this->_msg(0, $rt['msg']);exit;
            }
            // 跳转到支付页面
            $url = ROOT_URL.'index.php?s=api&c=pay&id='.$rt['code'];
            dr_redirect($url, 'auto');
            exit;
        } else {
            // 免费订单，直接标志付款
            foreach ($arr as $id) {
                \Phpcmf\Service::M('Order', 'order')->pay($this->uid, $id, 0);
            }
            exit($this->_json(
                1, dr_lang('订单付款成功'), [
                    'url' => dr_member_url('order/home/index')
                ]
            ));
        }
    }

}
