<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class CardsController extends BaseController
{	
	/**
	 * [cards 获取充值列表 method POST]
	 * @AuthorHTL
	 * @DateTime  2018-02-09T15:04:36+0800
	 * @return    [type]                   [description]
	 */
	public function cards()
	{
		$list = M('cards')->where(array('admin_id' => $this->data['business']))->field('money, preferential_money')->select();

		if (empty($list)) $this->ajaxReturn(['status' => -1, 'msg' => '没有数据']);

		$this->ajaxReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $list]);
	}

	/**
	 * [up_money 添加充值订单 method POST]
	 * @AuthorHTL
	 * @DateTime  2018-02-09T15:06:17+0800
	 * @return    [type]                   [description]
	 */
	public function up_money()
	{
		if (empty($this->data['money'])) $this->ajaxReturn(['status' => -1, 'msg' => '充值金额为空']);

		if (empty($this->data['preferential_money'])) $this->ajaxReturn(['status' => -1, 'msg' => '到账金额为空']);

		if (empty($this->data['openid'])) $this->ajaxReturn(['status' => -1, 'msg' => 'openid为空']);

		$user_id = M('users')->where(array('admin_id' => $this->data['business_id'], 'openid' => $this->data['openid']))->getFeild('id');

		$pay_no = str_replace(' ', '', str_replace(':', '', str_replace('-', '', date('Y-m-d H:i:s').rand(100000, 999999))));

		$add = array(
				'user_id' => $user_id,
				'money' => $this->data['money'],
				'preferential_money' => $this->data['preferential_money'],
				'status' => 1,
				'title' => '储值卡充值',
				'pay_no' => $pay_no,
				'create_time' => time()
			);
		$result = M('cards_log')->add($add);
		if ($result) {
			$this->ajaxReturn(['status' => 1, 'msg' => '订单生成成功', 'pay_no' => $pay_no]);
		} else {
			$this->ajaxReturn(['status' => -1, 'msg' => '订单生成失败']);
		}
	}

	/**
	 * [pay 支付]
	 * @AuthorHTL
	 * @DateTime  2018-02-09T16:03:38+0800
	 * @return    [type]                   [description]
	 */
	public function pay()
	{
		if (empty($this->data['pay_no'])) $this->ajaxReturn(['status' => -1, 'msg' => '支付编号为空']);

		try{
            $cards_info = M('cards_log')->where(array('pay_no' => $this->data['pay_no']))->find();

            $users = M('users')->where('id='.$cards_info['user_id'])->find();
            $admin_id=$users['admin_id'];
            $openid=$users['openid'];
            $out_trade_no=$cards_info['pay_no'];
            $prepayid=$cards_info['pay_return'];

            if($prepayid!=""||$prepayid!=null) $this->ajaxReturn(['status' => 1, 'msg' => '已获取预支付信息', 'pay_return' => json_decode($prepayid, true)]);
            if($openid==""||$openid=="") $this->ajaxReturn(['status' => -1, 'msg' => '该用户不存在']);
            
            $notify_url='https://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'], '/')+1)."paysuccess";
            // 实例支付接口
            $pay = & load_wechat('Pay',$admin_id);
            
            // 获取预支付ID
            $result = $pay->getPrepayId($openid, $cards_info['title'], $out_trade_no, $cards_info['price']*100, $notify_url, $trade_type = "JSAPI");

            // 处理创建结果
            if($result===FALSE){
                // 接口失败的处理
                $this->ajaxReturn(['status' => -1, 'msg' => '订单生成失败']);
            }else{
                $time="".time();
                $prepay_id='prepay_id='.$result['prepay_id'];

                $result_ = M('wechat_config')->where('admin_id='.$admin_id)->field('partnerkey')->find();  

                $post="appId=".$result['appid']."&nonceStr=".$result['nonce_str']."&package=".$prepay_id."&signType=MD5&timeStamp=".$time."&key=".$result_['partnerkey'];
                $key=md5($post);
                $prepay_id='prepay_id='.$result['prepay_id'];
                $result=['appId'=>$result['appid'],'timeStamp'=>$time,'nonceStr'=>$result['nonce_str'],'package'=>$prepay_id,'signType'=>'MD5','paySign'=>$key];
                $cards_info = M('cards_log')->where(array('pay_no' => $this->data['pay_no']))->save(['pay_return' => json_encode($result)]);
                $this->ajaxReturn(['status' => 1, 'msg' => '已获取预支付信息', 'pay_return' => $result]);
            }

        }catch (Exception $e){
            $this->ajaxReturn(['status' => -1, 'msg' => $e->getMessage()]);
        }
	}

	/**
     * 支付成功回调
     * @param $id
     * @param $tenant_id
     * @return \think\\Xml
     */
    public function paysuccess(){

        // 实例支付接口
        $pay = & load_wechat('Pay');

        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        Log::record($notifyInfo);

        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            Log::record($pay->errMsg);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                // 支付状态完全成功，可以更新订单的支付状态了
                $trade_no=$notifyInfo['out_trade_no'];
                $transaction_id=$notifyInfo['transaction_id'];
                $this->paychange($trade_no,$transaction_id);

                // @todo
                // 返回XML状态，至于XML数据可以自己生成，成功状态是必需要返回的。
                // <xml>
                //    return_code><![CDATA[SUCCESS]]></return_code>
                //    return_msg><![CDATA[OK]]></return_msg>
                // </xml>
                return xml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
            }
        }
    }

    /**
     * 修改订单状态
     * @param $trade_no
     * @param $transaction_id
     */
    private function paychange($trade_no,$transaction_id)
    {
        $info = M('cards_log')->where(array('pay_no' => $trade_no))->find();

        if ($info['status'] == 1) {
        	$result = M('cards_log')->where(array('pay_no' => $trade_no))->save(array('status' => 2, 'transaction_id' => $transaction_id, 'pay_time' => time()));
        	if ($result) {
        		// 增加账户余额
        		$balance = M('user_money')->where(array('user_id' => $info['user_id']))->getFeild('balance');
        		M('user_money')->where(array('user_id' => $info['user_id']))->setFeild('balance', $balance + $info['preferential_money']);
        		return array('status' => 1, 'msg' => '订单状态改变成功');
        	} else {
        		return array('status' => -1, 'msg' => '订单状态改变失败');
        	}
        }
    }

    /**
     * [log 获取充值记录]
     * @AuthorHTL
     * @DateTime  2018-02-09T17:11:11+0800
     * @return    [type]                   [description]
     */
    public function log()
    {
    	if (empty($this->data['openid'])) $this->ajaxReturn(['status' => -1, 'msg' => 'openid为空']);
    	if (empty($this->data['page'])) $this->ajaxReturn(['status' => -1, 'msg' => '分页为空']);

    	$user_id = M('users')->where(array('admin_id' => $this->data['business_id'], 'openid' => $this->data['openid']))->getFeild('id');

    	$list = M('cards_log')->where(array('user_id' => $user_id))->field('id, money, preferential_money, status, pay_no, create_time')->page($this->data['page'])->select();

    	if (empty($list)) $this->ajaxReturn(['status' => -1, 'msg' => '没有数据']);

    	$this->ajaxReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $list]);
    }

    /**
     * [balance 获取我的储值卡余额]
     * @AuthorHTL
     * @DateTime  2018-02-24T15:08:55+0800
     * @return    [type]                   [description]
     */
    public function balance()
    {
        if (empty($this->data['openid'])) $this->ajaxReturn(['status' => -1, 'msg' => 'openid为空']);
        $user_id = M('users')->where(array('admin_id' => $this->data['business_id'], 'openid' => $this->data['openid']))->getFeild('id');

        $info = M('user_money')->where(array('user_id' => $user_id))->field('money, balance')->find();

        if (empty($info)) {
            $this->ajaxReturn(['status' => 1, 'msg' => '已获取数据', 'data' => ['money' => 0.00, 'balance' => 0.00]]);
        } else {
            $this->ajaxReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $info]);
        }
    }
}