<?php


namespace app\api\controller;


use app\BaseController;
use think\facade\Db;

class Payreturn extends BaseController
{
    //支付宝支付成功后的异步通知地址
    public function  aliPayReturn() {

        require_once "../extend/aliPay/AopClient.php";
        //生成日志
        $this->createPayLog($_POST,"支付宝");

        $aop = new \AopClient();
        $public_key = config('app.pay_alipay_public_key');
        $aop->alipayrsaPublicKey = $public_key;
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
            if($this->changePayStatus($_POST['out_trade_no'])){
                die('success');
            }
        }
        die('fail');
    }

    //微信 值后的异步通知地址
    public function weiXinPayReturn(){
        $testxml  = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        //生成日志
        $this->createPayLog($result,"微信");
        if($result){
            //如果成功返回了
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                if($this->changePayStatus($result['out_trade_no'])){
                    die("<xml>
                              <return_code><![CDATA[SUCCESS]]></return_code>
                              <return_msg><![CDATA[OK]]></return_msg>
                            </xml>");
                }
            }
        }
    }

    //根据获取到的订单id,更改状态,更改房间的物业服务时间
    private function changePayStatus($out_trade_no) {
        $where['order_num'] = $out_trade_no;
        $save['pay_time'] = time();
        $save['is_pay'] = 1;
        $cost_ids = DB::name('pay_order')->where(['order_num'=>$out_trade_no])->value('cost_ids');
        $cost_ids_arr = json_decode($cost_ids);
        $costInfo = Db::name('cost')->where('cost_id','in',$cost_ids_arr)->where(['type'=>'property'])->order('cost_month','desc')->field('cost_month,vacancy_id')->find();
        Db::startTrans();
        try{
            if($costInfo) {
                $property_end_time = $costInfo['cost_month'];
                DB::name('house_vacancy')->where(['vacancy_id'=>$costInfo['vacancy_id']])->save(['property_end_time'=>$property_end_time]);
            }
            Db::name('pay_order')->where($where)->save($save);
            Db::name('cost')->where('cost_id','in',$cost_ids_arr)->save($save);
            Db::commit();
            return true;
        }catch(\Exception $e){
            Db::rollback();
            return false;
        }
    }

    public function createPayLog($data,$type){
        $save['create_time'] = time();
        $save['data'] = json_encode($data);
        $save['type'] = $type;
        $save['out_trade_no'] = $data['out_trade_no'];
        Db::name('pay_log')->insert($save);
    }
}