<?php

# 支付类

namespace Res\Lib;

use Dever;

class Pay extends Data
{
	# 发需求需要支付
    public function post_info()
    {
    	$this->action(1);
    }

    # 查看需求也需要支付
    public function view_info()
    {
        $this->action(2);
    }

    private function action($type = 1)
    {
    	$this->checkDemand();
        if (!$this->data['uid']) {
            Dever::alert('错误的用户信息');
        }

        $product = $this->demand->getInfo($id, false);

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

        if ($this->source_type == 'ios') {
            $method = 'apple';
            $account_id = 3;
            # 使用苹果内购支付
            $receipt = Dever::input('receipt');
            if (!$receipt) {
                Dever::alert('苹果内购支付失败，没有receipt参数');
            }
        } elseif ($this->source_type == 'android') {
            $method = 'app';
            $account_id = 3;
        } elseif ($this->source_type == 'applet') {
            $method = 'applet';
            $account_id = 1;
        } else {
        	# 默认是网页支付
        	$method = 'page';
        	$account_id = 2;
        }

        //$order_id = $this->createOrder('JP');
        $order_data['category'] = $product['category'];
        //$order_data['order_id'] = $order_id;
        $order_data['product_id'] = $product['id'];
        $order_data['uid'] = $this->data['uid']; 
        $order_data['type'] = $type;

        # 验证是否已经支付过
        $one = Dever::db('demand/order')->one($order_data);

        if (!$one) {
            Dever::alert('您已经支付过了');
        }

        $order_data['status'] = 1;

        $order_data['name'] = $product['name'];

        if ($type == 1) {
        	$cash = $this->demand->getPayState($this->data['uid'], $product['id'], $product['category']);

        	$order_data['cash'] = $cash;
        } else {
        	$cash = $product['view_price'];
        }

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

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

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

        //$param参数
        $param = array
        (
            'account_id' => $account_id,
            'project_id' => 1,
            'uid' => $this->data['uid'],
            'username' => $user['username'],
            'name' => $order_data['name'],
            'cash' => $order_data['cash'],
            'cash' => '0.01',
            'openid' => $wechat['openid'],
            'product_id' => $product['id'],
            'order_id' => $order_id,
        );

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

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

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

        return $this->data;
    }

    private function createOrderId($data, $id)
    {
        
    }
}