<?php namespace Phpcmf\Controllers;

class Order extends \Phpcmf\Common {

    public function index() {

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

        $ids = \Phpcmf\Service::L('Input')->get_post_ids();
        !$ids && exit($this->_json(0, dr_lang('购物车无商品')));

        $cart = \Phpcmf\Service::M('Order', 'order')->my_cart_items($ids);
        !$cart && exit($this->_json(0, dr_lang('购物车中商品无效')));

        $cid = [];
        $mid = [];
        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);
            !$field && exit($this->_json(0, dr_lang('支付字段#%s不存在', $fid)));
            $rt = \Phpcmf\Service::M('Pay')->get_pay_info($rid, $field, $t['quantity'], $t['sku_value']);
            isset($rt['code']) && !$rt['code'] && exit($this->_msg(0, $rt['msg']));
            !$rt['quantity'] && exit($this->_msg(0, dr_lang('该商品【%s】已销售完', $rt['title'])));
            $rt['quantity'] < $t['quantity'] && exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));
            $cid[] = $t['id'];
        }

        count($mid) > 2 && exit($this->_json(0, dr_lang('购物车中商品格式不正确')));

        $cid = implode(',', $cid);
        $order = \Phpcmf\Service::M('Order', 'order')->my_order_cart_items($cid);
        if (!$order) {
            $rt = \Phpcmf\Service::M('Order', 'order')->add_my_order_cart($cid);
            !$rt['code'] && exit($this->_msg(0, $rt['msg']));
            $order['id'] = $rt['code'];
        }

        exit($this->_json(
            1, dr_lang('正在为您下订单'), [
                'url' => dr_url('order/checkout/index', ['id' => $order['id']])
            ]
        ));
    }
}
