<?php
# 电子刊购买接口，本接口下所有接口都无需缓存 做好配置：act/order
namespace Act\Src;

use Dever;
use Main\Lib\Core;

class Order extends Core
{
    public function setCache($id, $type)
    {
        # 清空缓存，重新生成
        if ($type == 1) {
            $key = 'journal_infos_' . $id;
            $journal = Dever::db('journal/info')->one($id);
            Dever::cache($key, $journal);
        } elseif ($type == 2) {
            $key = 'journal_buys_' . $id;
            $buy = Dever::db('journal/buy_num')->one($id);

            if (!$buy['name']) {
                $buy['name'] = '购买' . $buy['num'] . '本';
            }
            Dever::cache($key, $buy);
        } elseif ($type == 3) {
            $key = 'journal_actives_' . $id;
            $active = Dever::db('journal/active')->one($id);
            Dever::cache($key, $active);
        }
    }

    # 获取电子刊信息，走缓存，先不走接口
    public function getActive($journal_id = false)
    {
        $journal_id = Dever::input('journal_id', $journal_id, '> 0', '请传入正确的小刊ID');

        $key = 'journal_actives_' . $journal_id;

        $active = Dever::cache($key);

        if (!$active) {
            $active = Dever::db('journal/active')->one(array('info_id' => $journal_id, 'state' => 1));

            Dever::cache($key, $active);
        }
        return $active;
    }

	# 获取电子刊信息，走缓存，先不走接口
	public function getJournal($journal_id = false)
	{
        $journal_id = Dever::input('journal_id', $journal_id);

        $status = false;
        if (strstr($journal_id, 'preview_')) {
            $journal_id = str_replace('preview_', '', $journal_id);
            $status = true;
        }

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

        $key = 'journal_infos_' . $journal_id;

        $journal = Dever::cache($key);

        if (!$journal) {
        	$journal = Dever::db('journal/info')->one($journal_id);
	        if (!$journal) {
	            Dever::alert('请传入正确的小刊ID');
	        }

	        Dever::cache($key, $journal);
        }
        return $journal;
	}

	# 获取购买的信息，走缓存，先不走接口
	public function getBuy($buy_id = false)
	{
        $buy_id = Dever::input('buy_id', $buy_id, '> 0', '请传入正确的支付ID');

        $key = 'journal_buys_' . $buy_id;

        $buy = Dever::cache($key);

        if (!$buy) {
	        $buy = Dever::db('journal/buy_num')->one($buy_id);

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

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

	        Dever::cache($key, $buy);
        }
        return $buy;
	}

	# 根据分类获取我已订阅的小刊列表，我的订单列表，此处要修改为我的订单列表 getMyAll待增加
    public function getMyList()
    {
        if (!$this->data['uid']) {
            Dever::alert('错误的用户信息');
        }

        $cate = Dever::input('system', -1);

        if (!$cate) {
            Dever::alert('错误的信息');
        }

        # 我的订单列表
        $where = array();
        $where['uid'] = $this->data['uid'];
        if ($cate > 0) {
            $where['cate_id'] = $cate;
        }
        
        $where['status'] = 2;
        $where['type'] = 3;

        $this->data['order'] = Dever::db('act/order')->getMyAll($where);

        if ($this->data['order']) {
            foreach ($this->data['order'] as $k => $v) {
                $this->data['order'][$k]['cdate'] = date('Y年m月d日 H:i:s', $v['cdate']);
                $name = explode('-', $v['name']);
                $this->data['order'][$k]['name'] = $name[0];

                if (isset($v['buy_num']) && $v['buy_num'] <= 0 && $v['buy_id']) {
                    $buy = $this->getBuy($v['buy_id']);
                    $this->data['order'][$k]['buy_num'] = $buy['num']; 
                }

                if (!$v['order_id']) {
                    $this->data['order'][$k]['order_id'] = $v['id'];
                }
            }
        }

        return $this->data;
    }

    # 根据订单id获取我的兑换码列表
    public function getMyCodeList()
    {
        if (!$this->data['uid']) {
            Dever::alert('错误的用户信息');
        }

        $order_id = Dever::input('order_id');

        if (!$order_id) {
            Dever::alert('错误的信息');
        }

        if (strstr($order_id, 'D')) {
            $temp = explode('D', $order_id);
            $order_id = $temp[1];
        }

        # 我的订单列表
        $order = $this->getOrder($order_id);

        $where = array();
        $where['create_uid'] = $this->data['uid'];
        $where['order_id'] = $order['order_id'];
        $where['type'] = 4;

        Dever::setInput('set_product_id', $order['product_id']);

        $this->data['code'] = Dever::db('code/info')->getMyAll($where);

        if ($this->data['code']) {
            foreach ($this->data['code'] as $k => $v) {
                $this->data['code'][$k]['code'] = Dever::load('code/lib/core')->view($v['id'], $v['create_uid']);
            }
        }

        return $this->data;
    }

    # 购买 改成直接购买兑换码
    public function pay()
    {
        if (!$this->data['uid']) {
            Dever::alert('错误的用户信息');
        }

        $journal = $this->getJournal();
        $buy = $this->getBuy();

        $user = Dever::db('passport/user')->one($this->data['uid']);
        $wechat = Dever::db('passport/wechat')->one(array('uid' => $this->data['uid'], 'type' => 1, 'system_id' => $journal['cate_id']));

        $source_type = Dever::input('source_type');

        if ($source_type == 'ios') {
            $method = 'apple';
            $order_data['system'] = 3;
            $account_id = 3;
            # 使用苹果内购支付
            $receipt = Dever::input('receipt');
            if (!$receipt) {
                Dever::alert('苹果内购支付失败，没有receipt参数');
            }
        } elseif ($source_type == 'android') {
            $method = 'app';
            $order_data['system'] = 4;
            $account_id = 3;
        } else {
            $method = 'applet';
            $order_data['system'] = 1;
            $account_id = 1;
            # 根据cate_id走不同的支付id，暂时不需要
            if ($journal['cate_id'] == 2) {
                $account_id = 4;
            } elseif ($journal['cate_id'] == 3) {
                $account_id = 5;
            }
            //$account_id = $cate['pay_id'];
        }

        //$order_id = $this->createOrder('JP');
        $order_data['cate_id'] = $journal['cate_id'];
        //$order_data['order_id'] = $order_id;
        $order_data['product_id'] = $journal['id'];
        $order_data['buy_id'] = $buy['id'];
        $order_data['uid'] = $this->data['uid']; 
        $order_data['type'] = 3;
        $order_data['status'] = 1;

        $order_data['name'] = $journal['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'] = $journal['cash'] * $order_data['buy_num'];
        }

        $source = Dever::input('source');
        $system = Dever::input('system', 1);
        if (!$source) {
            $source = $system;
        }
        if ($source) {
            $order_data['source'] = $source;
        }
        $seller = Dever::input('seller');
        if ($seller) {
            $order_data['seller_id'] = $seller;
        }

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

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

        $order_id = $this->createOrderId($order_data, $id);

        //$param参数
        $param = array
        (
            'account_id' => $account_id,
            'project_id' => 3,
            'uid' => $this->data['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,
        );

        if ($method == 'apple') {
            $param['other'] = $receipt;
        }

        $this->data['pay'] = Dever::load('pay/api.' . $method, $param);

        if ($order_data['system'] == 1) {
            if (isset($this->data['pay']['prepay_id'])) {
                Dever::load('act/lib/form')->submit($this->data['uid'], $this->data['pay']['prepay_id'], 2, $journal['cate_id']);
            } else {
                Dever::alert('支付失败');
            }
        }

        $this->data['order_id'] = $order_id;
        //$this->data['order_id'] = $id;

        return $this->data;
    }

    # 开始兑换
    public function checkCode()
    {
        return 'ok';
    }

    # 开始兑换
    public function code()
    {
        if (!$this->data['uid']) {
            Dever::alert('错误的用户信息');
        }

        $code = Dever::input('code');

        if ($code) {
            $code = trim($code);
            $code = str_replace("\n", '', $code);

            $journal_id = Dever::input('journal_id');
            if (strstr($journal_id, 'preview_')) {
                $journal_id = str_replace('preview_', '', $journal_id);
            }

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

            if (strpos($code, 'M') === 0) {
                Dever::setInput('set_product_id', $journal_id);
                $code = substr($code, 1);
                $code = Dever::uid($code, 'decode');
                $code = $code / 10000000;
                $info = Dever::db('code/info')->one($code);

                /*
                $check = true;
                $uid = substr($code, 1, 4);
                $code = substr($code, 1);
                
                
                $info = Dever::db('code/info')->one($code);

                if (!$info) {
                    $check = false;
                    $code = str_replace('M', '', $code);
                    $info = Dever::db('code/info')->one($code);
                }

                if ($check) {
                    $uid = Dever::uid($uid, 'decode');
                    if ($info && $info['create_uid'] != $uid) {
                        Dever::alert('请正确使用小刊兑换码');
                    }
                }
                */
                
            } else {
                $info = Dever::db('code/info')->one(array('code' => $code));
            }

            if (!$info) {
                Dever::alert('兑换码不存在');
            }

            if ($info['type'] == 3) {
                Dever::alert('兑换码已被使用');
            }

            if ($info['state'] != 1) {
                Dever::alert('兑换码已作废');
            }

            if ($info['type'] == 4) {
                Dever::alert('兑换码已作废');
            }

            /*
            if ($info['type'] == 2 && $this->data['uid'] != $info['uid']) {
                //Dever::alert('兑换码已被领取');
            }
            */

            if ($info['product_id'] > 0 && $info['product_id'] != $journal_id) {
                Dever::alert('请正确使用小刊兑换码');
            }

            if (isset($info['order_id']) && $info['order_id']) {
                $order_info = $this->getOrder($info['order_id']);
                if (!$order_info) {
                    Dever::alert('您要使用的兑换码还未支付');
                }

                if ($order_info && $order_info['status'] != 2) {
                    Dever::alert('您要使用的兑换码还未支付');
                }
            } else {
                # 通用兑换码 只加本数
                if ($info['product_num'] > 0) {
                    # 增加本数 用通用码的人不多，所以直接跨库查询吧
                    $journal = Dever::db('journal/info')->one($journal_id);
                    if ($journal) {
                        $num = $journal['num_up'] + $info['product_num'];
                        Dever::db('journal/info')->update(array('where_id' => $journal_id, 'num_up' => $num));
                    }
                }
            }

            Dever::db('code/info')->update(array('where_id' => $info['id'], 'type' => 3, 'uid' => $this->data['uid'], 'ldate' => time()));

            # 订阅
            Dever::load('act/lib/subscribe')->submit($this->data['uid'], $journal_id, 2);

        } else {
            Dever::alert('请输入正确的兑换码');
        }

        return 'ok';
    }

    public function createOrder($prefix = 'JP')
    {
        $order = Dever::order($prefix);

        //$order = Dever::rand(2, 2) . Dever::rand(6, 0);

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

        if ($info) {
            return $this->createOrder($prefix);
        }

        return $order;
    }

    public function createOrderId($data, $id)
    {
        # O 是 支付系统里的project_id的标识符，带有此项标识的均为无需支付系统进行订单记录
        $order_id = 'JMO3OC' . $data['cate_id'] . 'P' . $data['product_id'] . 'B' . $data['buy_id'] . 'U' . $data['uid'] . 'D' . $id;

        //$order_id = 'JM_' . $id;

        return $order_id;
    }

    public function getOrderId($id)
    {
        if (is_numeric($id)) {
            $info = Dever::db('act/order')->one($id);
            if ($info['order_id']) {
                return $info['order_id'] . '/' . $id;
            }

            return $this->createOrderId($info, $id) . '/' . $id;
        }
        return '';
    }

    public function getOrderTempId($id)
    {
        $info = Dever::db('act/order')->one($id);
        return $this->createOrderId($info, $id) . '/' . $id;
    }

    public function getOrder($order_id)
    {
        if (!is_numeric($order_id)) {
            $order = Dever::db('act/order')->one(array('order_id' => $order_id));
        } else {
            $order = Dever::db('act/order')->one($order_id);
            $order['order_id'] = $order['id'];
        }

        return $order;
    }
}