<?php namespace Service\Src;

use Dever;

# 必须登录才能购买小刊
class Buy extends Base
{
	public function __construct()
    {
    	parent::__construct();

    	if (!$this->user) {
    		return $this->location('home');
    	}

        if ($this->type == 1) {
            $this->type = 2;
            return $this->location('list');
        }
    }
    
    # 列表页
    public function lists()
    {
        # 记录列表页渠道pv、uv数
        if (Dever::project('source')) {
            Dever::load('source/lib/core')->save($this->user['id'], 'list', $this->source);
        }
        $where['cate_id'] = $this->cate;
        $where['buy'] = 1;
        $data = Dever::db('journal/info')->getAllByPage($where);

        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['cash'] > 0) {
                    $data[$k]['price'] = '￥' . number_format($v['cash'], 2);
                } else {
                    $data[$k]['price'] = '免费';
                }

                $data[$k]['ding'] = '销量：' . $v['num_ding'];

                $data[$k]['pay_url'] = $this->url('pay', array('id' => $v['id']));

                $data[$k]['pic_gd'] .= '?imageView2/2/w/375';
            }
        }

        return $data;
    }

    # 列表页 我已购买的兑换码
    public function lists_code()
    {
        $where['cate_id'] = $this->cate;
        $where['create_uid'] = $this->user['id'];
        //$where['type'] = 3;
        $where['type'] = 4;
        $data = Dever::db('code/info')->getAll($where);

        if ($data) {
            foreach ($data as $k => $v) {
                $info = Dever::db('journal/info')->one($v['product_id']);

                $data[$k]['code'] = str_replace("\n", '', trim($v['code']));

                $data[$k]['code_string'] = '阅读码：' . trim($v['code']);

                if ($v['type'] == 3) {
                    $data[$k]['code_string'] .= ' 已兑换';
                } else {
                    $data[$k]['code_string'] .= ' <font style="color:red">未兑换</font>';
                }

                $data[$k]['name'] = $info['name'];

                $data[$k]['pic_gd'] = $info['pic_gd'] ? $info['pic_gd'] : $info['pic_view_cover'];

                $data[$k]['pic_gd'] .= '?imageView2/2/w/375';

                //$data[$k]['code_pic'] = '';
                $data[$k]['code_pic'] = $this->create_code($info['id']);
            }
        }

        return $data;
    }

    # 详细信息
    public function info()
    {
        $id = Dever::input('id');

        # 记录购买页渠道pv、uv数
        if (Dever::project('source')) {
            Dever::load('source/lib/core')->save($this->user['id'], 'buy', $this->source, array('journal_id' => $id));
        }

        $info = Dever::db('journal/info')->one($id);

        $info['buy'] = '正在购买《' . $info['name'] . '》';

        $buy = Dever::db('journal/buy')->one(array('id' => $id));

        $info['buy_desc'] = '';
        $info['buy_notice'] = '一次购买多本将生成一个兑换码用于兑换，如需多个兑换码，请多次购买。';
        $info['buy_notices'] = '购买兑换码赠送好友：点击下方购买后，将生成多个兑换码。
积分规则：使用兑换码兑换后，使用人获得积分，购买人不增加积分。';
        if ($buy) {
            $info['buy_desc'] = $buy['buy_content'];
            if ($buy['buy_notice']) {
                $info['buy_notice'] = $buy['buy_notice'];
            }
            if ($buy['buy_notices']) {
                $info['buy_notices'] = $buy['buy_notices'];
            }
        }

        $info['buy_notices'] = str_replace("\n", '<br />', $info['buy_notices']);
        
        return $info;
    }

    # 生成二维码
    public function code()
    {
        $id = Dever::input('id');

        return $this->create_code($id);
    }

    private function create_code($id)
    {
        $type = 4;
        $uid = $this->user['id'];
        
        $scene = $uid . ',' . $type . ',' . $id;

        $path = Dever::config('base')->applet_index;
        $send['project'] = Dever::input('project', $this->cate);
        $send['send'] = $scene;
        $send['width'] = 152;
        $send['path'] = $path; 
        $code = Dever::load('wechat_applet/code.get', $send);

        return $code;
    }

    # 小刊购买成功
    public function success()
    {
        $config = Dever::db('main/config')->one(1);

        $id = Dever::input('id');
        $buy_id = Dever::input('buy');
        $config['list'] = $this->url('list');
        $config['buy'] = $this->url('pay', array('id' => $id));

        $order_id = Dever::input('order_id');
        $order = Dever::db('journal/order')->one($order_id);

        if ($order['uid'] != $this->user['id']) {
            $this->location('list');
        }

        $uid = $this->user['id'];

        $code = Dever::load('code/lib/core')->createCodeByOrder($order);
        if ($code) {
            $update['where_id'] = $order['id'];
            $order['code'] = $update['code'] = $code;
            Dever::db('journal/order')->update($update);
        }

        $config['code_show'] = 'display:none;';
        $config['button'] = '继续购买';
        $config['button_node'] = '';
        $config['button_span'] = '';
        $config['reload'] = 1;
        if ($order && $order['type'] == 3) {
            $config['code_show'] = '';
            $config['button_node'] = 'copy';
            $order['code'] = str_replace("\n", '', trim($order['code']));
            $config['button_span'] = $order['code'];
            if (!$order['code']) {
                $order['code'] = '生成中...';
                $config['reload'] = 2;
                $config['button_node'] = 'refresh';
                $config['button_span'] = '';
                $config['button'] = '刷新';
                //$this->location('success', array('id' => $id, 'buy' => $buy_id, 'order_id' => $order_id));
            } else {
                $config['button'] = '继续购买<span>'.$order['code'].'</span>';
            }
            
            $config['code'] = '<p class="single"><span>'.$order['code'].'</span></p>';
            $buy = Dever::db('journal/buy_num')->one($buy_id);
            if ($buy && $buy['code'] > 1) {
                $uid = $this->user['id'];
                $code = Dever::db('code/info')->state(array('create_uid' => $uid, 'order_id' => $order['order_id']));
                $config['code'] = '<p>';
                foreach ($code as $k => $v) {
                    $config['code'] .= '<span>'.$v['code'].'</span>';
                }
                $config['code'] .= '</p>';
            }
        }

        return $config;
    }

    # 小刊购买 一个兑换码的
    public function buy()
    {
        $id = Dever::input('id');
        $data = Dever::db('journal/buy_num')->getAllCode(array('info_id' => $id));
        $info = Dever::db('journal/info')->one($id);

        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['price'] > 0) {
                    $data[$k]['price'] = '￥' . number_format($v['price'], 2);
                } elseif ($info['cash'] > 0) {
                    $data[$k]['price'] = '￥' . number_format($info['cash'] * $v['num'], 2);
                } else {
                    $data[$k]['price'] = '免费';
                }

                if (!$v['name']) {
                    $data[$k]['name'] = '购买' . $v['num'] . '本';
                }
                $data[$k]['cate'] = $info['cate_id'];

                $data[$k]['pay_url'] = $this->url('buy.pay', array('buy_id' => $v['id'], 'journal_id' => $v['info_id']));
            }
        }
        return $data;
    }

    # 小刊购买 多个兑换码的
    public function buys()
    {
        $id = Dever::input('id');
        $data = Dever::db('journal/buy_num')->getAllCodes(array('info_id' => $id));
        $info = Dever::db('journal/info')->one($id);

        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['price'] > 0) {
                    $data[$k]['price'] = '￥' . number_format($v['price'], 2);
                } elseif ($info['cash'] > 0) {
                    $data[$k]['price'] = '￥' . number_format($info['cash'] * $v['num'], 2);
                } else {
                    $data[$k]['price'] = '免费';
                }

                if (!$v['name']) {
                    $data[$k]['name'] = '购买' . $v['num'] . '本';
                }
                $data[$k]['cate'] = $info['cate_id'];

                $data[$k]['pay_url'] = $this->url('buy.pay', array('buy_id' => $v['id'], 'journal_id' => $v['info_id']));
            }
        }
        return $data;
    }

    # 小刊购买
    public function pay()
    {
        $uid = $this->user['id'];

        $buy_id = Dever::input('buy_id');
        $journal_id = Dever::input('journal_id');

        if (!$buy_id) {
            Dever::alert('请传入正确的支付ID');
        }
        if (!$journal_id) {
            Dever::alert('请传入正确的小刊ID');
        }

        $info = Dever::db('journal/info')->one($journal_id);
        $buy = Dever::db('journal/buy_num')->one($buy_id);

        if (!$buy || !$info) {
            Dever::alert('请传入正确的小刊ID');
        }

        if (!$buy['name']) {
            $buy['name'] = '购买' . $buy['num'] . '本';
        }

        $user = Dever::db('passport/user')->one($uid);
        $wechat = Dever::db('passport/wechat')->one(array('uid' => $uid, 'type' => 2));

        $order_id = $this->createOrder('JP');
        $order_data['cate_id'] = $this->cate;
        $order_data['order_id'] = $order_id;
        $order_data['product_id'] = $journal_id;
        $order_data['buy_id'] = $buy_id;
        $order_data['uid'] = $uid;

        $order_data['type'] = 1;
        $order_data['status'] = 1;
        $order_data['name'] = $info['name'] . '-' . $buy['name'];
        //$order_data['num'] = Dever::input('num', 1);
        $order_data['num'] = $buy['num'];
        if (isset($buy['price']) && $buy['price'] && $buy['price'] > 0) {
            $order_data['cash'] = $buy['price'];
        } else {
            $order_data['cash'] = $info['cash'] * $order_data['num'];
        }

        $order_data['system'] = 2;
        if ($this->source) {
        	$order_data['source'] = $this->source;
        }

        if ($this->seller) {
            $order_data['seller_id'] = $this->seller;
        }

        if ($this->type == 2) {
            # 购买兑换码
            $order_data['type'] = 3;
        }

        $id = Dever::db('journal/order')->insert($order_data);

        if (!$id) {
            Dever::alert('支付失败');
        }

        //$param参数
        $refer = $this->url('success', array('id' => $journal_id, 'buy' => $buy_id, 'order_id' => $id));
        $param = array
        (
            'account_id' => 2,
            'project_id' => 1,
            'uid' => $uid,
            'username' => $user['username'],
            'name' => $order_data['name'],
            'cash' => $order_data['cash'],
            //'cash' => '0.01',
            'openid' => $wechat['openid'],
            'product_id' => $journal_id . '-' . $buy_id,
            'order_id' => $order_id,
            'refer' => $refer
        );

        return Dever::load('pay/api.page', $param);
    }
}