<?php namespace Phpcmf\Controllers;

class Home extends \Phpcmf\Common {

    public function index() {

        if (IS_POST) {
            $ids = \Phpcmf\Service::L('Input')->get_post_ids();
            !$ids && exit($this->_json(0, dr_lang('你还没有选择呢')));
            $data = \Phpcmf\Service::M('Cart', 'cart')->my_items($ids);
            !$data && exit($this->_json(0, dr_lang('无可用商品')));

            foreach ($data as $t) {
                list($a, $rid, $fid) = explode('-', $t['mid']);
                $field = $this->get_cache('table-field', $fid);
                !$field && exit($this->_json(0, dr_lang('支付字段不存在')));
                $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']));
                \Phpcmf\Service::M('cart', 'cart')->update_cart($t['id'], $rt);
            }
            exit($this->_json(1, dr_lang('操作成功')));
        }

        $list = \Phpcmf\Service::M('cart', 'cart')->my_list($this->uid);
        $mall = $my_list = [];
        if ($list) {
            foreach ($list as $t) {
                list($name) = explode('-', $t['mid']);
                list($s, $name) = explode('_', $name);
                if ($name) {
                    $my_list[$name][$t['mall_cid']][] = $t;
                    $mall[$t['mall_cid']] = [
                        'url' => $t['mall_url'],
                        'cid' => $t['mall_cid'],
                        'name' => $t['mall_name'],
                    ];
                } else {
                    // 删除商品
                    \Phpcmf\Service::M('cart', 'cart')->my_delete($this->uid, $t['id']);
                }
            }
        }

        \Phpcmf\Service::V()->assign([
            'list' => $list,
            'mall' => $mall,
            'form' => dr_form_hidden(),
            'module' => $this->get_cache('module-'.SITE_ID),
            'my_list' => $my_list,
            '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('cart.html');
    }
}
