<?php namespace Buy\Src;

use Dever;

# 必须登录才能购买小刊
class Buy extends Base
{
    public function __construct()
    {
        parent::__construct();
    }
    
    # 列表页
    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['buy'] == 1 && $v['cash'] > 0) {
                    $data[$k]['price'] = '￥' . number_format($v['cash'], 2);
                } else {
                    $data[$k]['price'] = '免费';
                }

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

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

                if ($v['buy'] == 1) {
                    $data[$k]['button'] = '订阅';
                    $data[$k]['act'] = 'pay';
                    $data[$k]['code'] = $this->url('pay', array('id' => $v['id']));
                } else {
                    $data[$k]['act'] = 'read';
                    # 小刊阅读码
                    $data[$k]['code'] = $this->create_code($v['id']);
                    $data[$k]['button'] = '阅读';
                }
            }
        }

        return $data;
    }

    # 列表页 我已购买的兑换码
    public function lists_code()
    {
        $where['cate_id'] = $this->cate;
        $where['uid'] = $this->user['id'];
        $where['status'] = 2;
        $where['type'] = 3;
        $data = Dever::db('act/order')->getMyAll($where);

        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['cdate'] = date('Y年m月d日 H:i', $v['cdate']);
                if (!$v['order_id']) {
                    $v['order_id'] = $v['id'];
                }
                $data[$k]['link'] = $this->url('codedetail', array('order_id' => $v['order_id'], 'id' => $v['product_id']));
                if (isset($v['buy_num']) && $v['buy_num'] <= 0 && $v['buy_id']) {
                    $buy = Dever::load('act/order')->getBuy($v['buy_id']);
                    $data[$k]['buy_num'] = $v['buy_num'] = $buy['num']; 
                }
                $data[$k]['desc'] = $v['buy_num'] . '本 ¥' . number_format($v['cash'], 2);
                $name = explode('-', $v['name']);
                $data[$k]['name'] = $name[0];
            }
        }

        return $data;
    }

    # 列表页 我已购买的兑换码
    public function code_detail()
    {
        $where['cate_id'] = $this->cate;
        $where['create_uid'] = $this->user['id'];
        $where['order_id'] = Dever::input('order_id');
        if (!$where['order_id']) {
            Dever::alert('错误的订单');
        }
        $where['type'] = 4;
        $order = Dever::load('act/order')->getOrder($where['order_id']);
        Dever::setInput('set_product_id', $order['product_id']);
        $where['order_id'] = $order['order_id'];
        $data = Dever::db('code/info')->getAll($where);

        if ($data) {
            foreach ($data as $k => $v) {
                $code = Dever::load('code/lib/core')->view($v['id'], $v['create_uid']);
                $data[$k]['code'] = '<i class="ico-code"></i>兑换码：'.$code;
                if ($v['type'] == 1) {
                    $data[$k]['txt'] = '未使用';
                    $data[$k]['class'] = '';
                    $data[$k]['copy'] = '<a href="javascript:;" class="button" node-id="copy" data-clipboard-text="'.$code.'">复制</a>';
                } else {
                    $data[$k]['txt'] = '已使用';
                    $data[$k]['class'] = 'used';
                    $data[$k]['copy'] = '<a href="javascript:;" class="button disabled">复制</a>';
                }
            }
        }

        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']);

        
        $buy_num = Dever::input('buy_num');
        if ($buy_num > 0) {
            $info += $this->success();
        } else {
            $info['buy_class'] = 'mask fn-hide';
            $info['buy_code'] = '';
            $info['buy_yes'] = '';
        }
        
        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()
    {
        $id = Dever::input('id');
        $buy_id = Dever::input('buy');
        
        $order_id = Dever::input('order_id');
        $create = Dever::input('create');
        if ($order_id && $create == 1) {
            $order = Dever::load('act/order')->getOrder($order_id);

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

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

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

        $result['buy_code'] = $this->url('codedetail', array('order_id' => $order_id, 'id' => $id));
        $result['buy_yes'] = '您已成功购买' . Dever::input('buy_num') . '本电子刊';
        $result['buy_class'] = 'mask';
        return $result;
    }

    # 小刊购买 一个兑换码的
    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) {
                $data[$k]['class'] = 'item';
                if ($k == 0) {
                    $data[$k]['class'] .= ' active';
                }
                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()
    {
        if (!$this->user) {
            //return $this->location('home');
        }
        $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::load('act/order')->getJournal($journal_id);
        $buy = Dever::load('act/order')->getBuy($buy_id);

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

        $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'] = 3;
        $order_data['status'] = 1;
        $order_data['name'] = $info['name'] . '-' . $buy['name'];
        $order_data['buy_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['buy_num'];
        }

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

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

        $id = Dever::db('act/order_temp')->insert($order_data);

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

        $order_id = Dever::load('act/order')->createOrderId($order_data, $id);

        //$param参数
        $param['id'] = $journal_id;
        $parma['buy'] = $buy_id;
        $param['buy_num'] = $order_data['buy_num'];
        $param['order_id'] = $id;
        # 立刻创建兑换码
        //$param['create'] = 1;
        $refer = $this->url('pay', $param);
        //$refer = 'callback.success';
        $param = array
        (
            'account_id' => 2,
            'project_id' => 3,
            '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
        );

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