<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/7/25
 * Time: 10:29
 */

namespace App\Http\Controllers\Wap\Pay;

use App\Jobs\SendTexts;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Subscribe\Models\Order;
use App\Modules\Subscribe\Services\OrderService;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserDivisionCpcPropertyService;
use App\Modules\User\Services\UserMonthService;
use App\Modules\User\Services\UserService;
use GuzzleHttp\Client;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Log;
use Redis;
use DB;
use EasyWeChat\Support\XML;

class MonthOrderController extends Controller
{


    public function signCallBack(Request $request)
    {
        Log::info('signCallBack------------------------------------------signCallBack');
        Log::info($request->all());
        Log::info($request->getMethod());
        //$key = 'sn7wluq5716brp8fzm';
        $key = env('MONTH_ORDER_KEY');
        $app_id = $request->post('app_id');
        $plan_id = $request->post('plan_id');
        $type = 'MONTH';
        if($plan_id == env('MONTH_ORDER_PLAN_ID')){
            $type = 'MONTH';
        }

        if($plan_id == env('MONTH_WEEK_ORDER_PLAN_ID')){
            $type = 'WEEK';
        }

        $user_id = $request->post('user_id');
        $change_type = $request->post('change_type');
        if ($check = checkParam($request->except('_url'), ['app_id', 'plan_id', 'user_id', 'change_type'])) {
            //return response()->error('PARAM_EMPTY', ['msg' => $check]);
            return response('fail');
        }
        $sign = _sign(compact('app_id', 'plan_id', 'user_id', 'change_type'), $key . $key);
        $sign = strtoupper($sign);
        $user_info = UserService::getById($user_id);
        if (!$user_info) {
            Log::error('signCallBack user is not exist,uid is :' . $user_id);
            return response('fail');
        }
        if ($sign == $request->post('sign')) {
            UserMonthService::createSign($user_id, $plan_id, $change_type, $user_info->openid,$type);
        }
        Log::info('signCallBack-------------------end-----------------------signCallBack');
        return response('success');
    }


    public function orderCallBack(Request $request)
    {
        Log::info('orderCallBack------------------------------------------orderCallBack');
        Log::info($request->all());
        Log::info($request->getMethod());

        $key = env('MONTH_ORDER_KEY');//'sn7wluq5716brp8fzm';
        $app_id = $request->post('app_id');
        $plan_id = $request->post('plan_id', 0);
        $user_id = $request->post('user_id');
        $total_fee = $request->post('total_fee');
        $trade_no = $request->post('trade_no');
        $out_trade_no = $request->post('out_trade_no');
        $result_code = $request->post('result_code',0);
        $type = 'MONTH';
        $product_id = 6826;
        if($plan_id == env('MONTH_ORDER_PLAN_ID')){
            $type = 'MONTH';
            $product_id = 6826;
        }

        if($plan_id == env('MONTH_WEEK_ORDER_PLAN_ID')){
            $type = 'WEEK';
            $product_id =7394;
        }

        $this->recordOrderCallBack($request,$type);
        if(!$result_code) return response('success');

        if ($check = checkParam($request->except('_url'), ['app_id', 'user_id', 'total_fee', 'trade_no', 'out_trade_no'])) {
            return response()->error('PARAM_EMPTY', ['msg' => $check]);
        }
        $sign = _sign(compact('app_id', 'user_id', 'total_fee', 'trade_no', 'out_trade_no'), $key . $key);
        $sign = strtoupper($sign);
        //if($sign == $request->post('sign')){
        if (!UserMonthService::getOrderByOrder($trade_no, $out_trade_no)) {
            UserMonthService::createLOrder($user_id, $plan_id, $total_fee, $trade_no, $out_trade_no,$type);
            $this->addOrderAndVip($user_id, $out_trade_no, $trade_no, $total_fee,$product_id,$type);
            $this->successPayPushMsg($user_id,$type);
            $this->userProperty($user_id);
        }
        //}

        Log::info('orderCallBack--------------------endend----------------------orderCallBack');
        return response('success');
    }


    private function addOrderAndVip($uid, $out_trade_no, $trade_no, $price,$product_id,$type)
    {
        $order_info = OrderService::getByTradeNo($out_trade_no);
        //订单已经存在
        if ($order_info) {
            return;
        }
        $user_info = UserService::getById($uid);
        if (!$user_info) return;
        $this->createOrder($uid, $user_info->distribution_channel_id, $product_id, $price, $out_trade_no, $trade_no,$type);
        if($type == 'MONTH'){
            YearOrderService::save_month_order([
                'uid' => $uid,
                'distribution_channel_id' => $user_info->distribution_channel_id,
                'fee' => $price / 100,
                'send_order_id' => 0
            ]);
        }
        if($type == 'WEEK'){
            YearOrderService::save_vip_order_daynum([
                'uid' => $uid,
                'distribution_channel_id' => $user_info->distribution_channel_id,
                'fee' => $price / 100,
                'send_order_id' => 0,
                'day_num'=>7
            ]);
        }

        if($type == 'QUARTER'){
            YearOrderService::save_vip_order_daynum([
                'uid' => $uid,
                'distribution_channel_id' => $user_info->distribution_channel_id,
                'fee' => $price / 100,
                'send_order_id' => 0,
                'day_num'=>92
            ]);
        }
    }


    private function createOrder($uid, $distribution_channel_id, $product_id, $price, $trade_no, $transaction_id,$type)
    {
        $count = OrderService::getUserChargeTimes($uid);
        $count = $count + 1;
        $send_order_id = 0;
        try {
            $send_order_id = (int)Redis::hget('book_read:' . $uid, 'send_order_id');
        } catch (\Exception $e) {
        }
        $send_order_name = '';
        if ($send_order_id) {
            $send_order_info = SendOrderService::getById($send_order_id);
            if ($send_order_info && isset($send_order_info->name) && !empty($send_order_info->name)) {
                $send_order_name = $send_order_info->name;
            }
        }
        $from_bid = ReadRecordService::getSimpleFirstReadRecord($uid);
        $init_order = [
            'distribution_channel_id' => $distribution_channel_id,
            'uid' => $uid,
            'product_id' => $product_id,
            'price' => $price / 100,
            'pay_type' => $count,
            'trade_no' => $trade_no,
            'pay_merchant_source' => $type,
            'pay_merchant_id' => 99,
            'create_ip' => '',
            'send_order_id' => $send_order_id,
            'send_order_name' => $send_order_name,
            'order_type' => 'RECHARGE',
            'from_bid' => $from_bid,
            'from_type' => 'auto_'.strtolower($type),
            'activity_id' => 0,
            'inner_send_order_id' => '',
            'status' => 'PAID',
            'transaction_id' => $transaction_id,
            'pay_end_at' => date('Y-m-d H:i:s')
        ];
        OrderService::save_order($init_order);
    }

    public function wait(Request $request)
    {
        //$user_cookie = \Cookie::get(env('COOKIE_AUTH_WEB_WECHAT'));
        //$uid = $user_cookie ? decrypt($user_cookie) : null;
        $r = $request->get('r');
        $r = urldecode($r);
        return view('pay.order.monthpaywait', ['url' => $r]);
    }

    public function issuccess(Request $request)
    {
        $uid = \Cookie::get(env('COOKIE_AUTH_WEB_WECHAT'));
        //$uid = $user_cookie ? decrypt($user_cookie) : null;
        if (!$uid) {
            return response()->success();
        }
        $last = UserMonthService::getLastOrder($uid);
        if (!$last) {
            return response()->error('WAP_SYS_ERROR');
        }
        if (time() - strtotime($last->created_at) < 20) {
            return response()->success();
        }
        return response()->error('WAP_SYS_ERROR');
    }

    private function recordOrderCallBack(Request $request,$type){
        $app_id = $request->post('app_id','');
        $plan_id = $request->post('plan_id',0);
        $uid = $request->post('user_id','');
        $total_fee = $request->post('total_fee',0);
        $trade_no = $request->post('trade_no','');
        $out_trade_no = $request->post('out_trade_no','');
        $result_code = $request->post('result_code',-1);
        $sign = $request->post('sign',-1);
        $created_at = date('Y-m-d H:i:s');
        $updated_at = date('Y-m-d H:i:s');
        $origin_data = json_encode($request->except('_url'));
        try{
            DB::table('user_month_order_callback')->insert([
                compact('uid','app_id','plan_id','total_fee','out_trade_no','origin_data',
                    'trade_no','result_code','sign','created_at','updated_at','type'
                )
            ]);
        }catch (\Exception $e){Log::error('recordOrderCallBack error');}
    }

    protected function successPayPushMsg($uid,$type)
    {
        try {
            $force_sub_info = DB::table('force_subscribe_users')->where('uid', $uid)->where('is_subscribed', 1)->first();
            $data = UserService::getById($uid);
            if (!$force_sub_info) {
                return;
            }
            $content_format = '';
            if($type == 'MONTH'){
                $content_format = "包月购买成功通知:\r\n购买类型: 30元包月\r\n><a href='%s'>点击继续上次阅读</a>\r\n包月特权:\r\n 💝 全站所有作品免费阅读\r\n 💝 全站无广告\r\n 💝 阅读管家1对1服务\r\n为保障包月权益，请<a href='%s'>置顶公众号</a> ";
            }
            if($type == 'WEEK'){
                $content_format = "包周购买成功通知:\r\n购买类型: 7元包月\r\n><a href='%s'>点击继续上次阅读</a>\r\n包月特权:\r\n 💝 全站所有作品免费阅读\r\n 💝 全站无广告\r\n 💝 阅读管家1对1服务\r\n为保障包周权益，请<a href='%s'>置顶公众号</a> ";
            }

            $delay = 0;
            $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($data->distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/continue';;
            $top_url = 'https://help.zhuishuyun.com/top.html';

            $content = sprintf($content_format, $url, $top_url);

            $res['openid'] = $force_sub_info->openid;
            $res['appid'] = $force_sub_info->appid;
            $res['content'] = $content;
            $res['type'] = 'one_task';
            $res['send_time'] = date("Y-m-d H:i:s");
            $res['task_id'] = md5('month_pay_success_push');
            $send_data = array(
                'send_time' => date("Y-m-d H:i:s"),
                'data' => $res
            );
            dispatch((new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list'));


        } catch (\Exception $e) {
            Log::error('pay_success_push error');
            Log::error($e);
        }
        return;
    }

    private function userProperty($uid){
        try{
            $userproperty = UserDivisionCpcPropertyService::calculateUserPropertyV2($uid);
            if(!$userproperty) return ;
            UserDivisionCpcPropertyService::createorUpdateV2($userproperty);
        }catch (\Exception $e){
            Log::error('month userProperty error');
            Log::error($e);
        }
    }

    public function signCallBackV2(Request $request)
    {
        Log::info('V2--signCallBack--------------------------------------V2----signCallBack');
        Log::info($request->all());
        Log::info($request->getMethod());

        $content = $request->getContent();
        Log::info('$request->getContent() is :');
        Log::info($content);
        libxml_disable_entity_loader(true);
        $xml = XML::parse(strval($content));
        Log::info('xml is');
        Log::info($xml);
        if (!$xml || !is_array($xml)) return response(XML::build(['return_code'=>'fail','return_msg'=>'fail']));
        if($xml['return_code'] != 'SUCCESS' && $xml['result_code'] != 'SUCCESS'){
            $result = ['return_code'=>'SUCCESS','return_msg'=>'OK'];
            return response(XML::build($result));
        }
        $sign = _sign($xml,UserMonthService::MONTH_PAY_KEY);
        if(strtoupper($sign) != strtoupper($xml['sign'])){
            Log::info('sign error');
            Log::info('request sign is: '.$xml['sign'].',my sign is :'.$sign);
            $result = ['return_code'=>'fail','return_msg'=>'sign fail'];
            return response(XML::build($result));
        }
        $plan_id = $xml['plan_id'];
        $type = 'MONTH';
        $fee = 0;
        $day = 0;
        $body = '';
        if($plan_id == env('MONTH_ORDER_PLAN_ID')){
            $fee = 3000;
            $type = 'MONTH';
            $day = 30;
            $body = '追书云包月扣款';
        }

        if($plan_id == env('MONTH_WEEK_ORDER_PLAN_ID')){
            $fee = 700;
            $type = 'WEEK';
            $day = 7;
            $body = '追书云包周扣款';
        }

        if($plan_id == env('MONTH_QUARTER_ORDER_PLAN_ID')){
            $fee = 9800;
            $type = 'QUARTER';
            $day = 92;
            $body = '追书云包季扣款';
        }

        $user_id = $xml['contract_code'];
        $change_type = $xml['change_type'];
        if (in_array($user_id, explode(',', env('TEST_UID')))) {
            $fee = 1;
        }

        $user_info = UserService::getById($user_id);
        if (!$user_info) {
            Log::error('signCallBack user is not exist,uid is :' . $user_id);
            $result = ['return_code'=>'fail','return_msg'=>'user not exist'];
            return response(XML::build($result));
        }
        UserMonthService::monthOrderSignRecord([
            'uid'=>$user_id,
            'plan_id'=>$plan_id,
            'contract_code'=>$xml['contract_code'],
            'openid'=>$xml['openid'],
            'change_type'=>$change_type,
            'operate_time'=>$xml['operate_time'],
            'contract_id'=>$xml['contract_id'],
            'contract_expired_time'=>isset($xml['contract_expired_time'])?$xml['contract_expired_time']:'',
            'contract_termination_mode'=>isset($xml['contract_termination_mode'])?$xml['contract_termination_mode']:0,
            'request_serial'=>$xml['request_serial']

        ]);
        UserMonthService::createSign($user_id, $plan_id, $change_type, $user_info->openid,$type);
        if($change_type == 'ADD'){
            //获取上次扣费时间
            $info = UserMonthService::getLastMonthOrderInfo($user_id,$type);
            if(!$info || time() >= (strtotime($info->created_at)+$day*86400) ){
                UserMonthService::monthPayApplypap($user_id,$xml['contract_id'],$fee,$body,'47.97.95.151','sign_back',\GuzzleHttp\json_encode(['uid'=>$user_id,'plan_id'=>$plan_id]));
            }
        }
        Log::info('signCallBack-------------------end-----------------------signCallBack');
        $result = ['return_code'=>'SUCCESS','return_msg'=>'OK'];
        return response(XML::build($result));
    }

    public function orderCallBackV2(Request $request)
    {
        Log::info('V2--------orderCallBack-----------------------------------v2-------orderCallBack');
        $content = $request->getContent();
        Log::info('orderCallBackV2 $request->getContent() is :');
        Log::info($content);
        libxml_disable_entity_loader(true);
        $xml = XML::parse(strval($content));
        Log::info('orderCallBackV2 xml is:');
        Log::info($xml);
        if (!$xml || !is_array($xml)) return response(XML::build(['return_code'=>'fail','return_msg'=>'fail']));

        UserMonthService::monthCallBackRecordV2([
            'openid'=>isset($xml['openid'])?$xml['openid']:'',
            'bank_type'=>isset($xml['bank_type'])?$xml['bank_type']:'',
            'total_fee'=>isset($xml['total_fee'])?$xml['total_fee']:0,
            'cash_fee'=>isset($xml['cash_fee'])?$xml['cash_fee']:0,
            'trade_state'=>isset($xml['trade_state'])?$xml['trade_state']:'',
            'transaction_id'=>isset($xml['transaction_id'])?$xml['transaction_id']:'',
            'out_trade_no'=>isset($xml['out_trade_no'])?$xml['out_trade_no']:'',
            'attach'=>isset($xml['attach'])?$xml['attach']:'',
            'time_end'=>isset($xml['time_end'])?$xml['time_end']:'',
            'contract_id'=>isset($xml['contract_id'])?$xml['contract_id']:'',
            'result_code'=>isset($xml['result_code'])?$xml['result_code']:'',
            'err_code'=>isset($xml['err_code'])?$xml['err_code']:'',
            'result'=>json_encode($xml),
            'uid'=>isset($xml['attach']) && !empty($xml['attach']) ? json_decode($xml['attach'],1)['uid']:0
        ]);

        $sign = _sign($xml,UserMonthService::MONTH_PAY_KEY);
        if(strtoupper($sign) != strtoupper($xml['sign'])){
            Log::info('orderCallBackV2 sign error');
            Log::info('orderCallBackV2 request sign is: '.$xml['sign'].',my sign is :'.$sign);
            $result = ['return_code'=>'fail','return_msg'=>'sign fail'];
            return response(XML::build($result));
        }

        if($xml['return_code'] == 'SUCCESS' && $xml['result_code'] == 'SUCCESS') {
            $attach = json_decode($xml['attach'], 1);
            $plan_id = $attach['plan_id'];
            $user_id = $attach['uid'];
            $total_fee = $xml['total_fee'];
            $trade_no = $xml['transaction_id'];
            $out_trade_no = $xml['out_trade_no'];

            $type = 'MONTH';
            $product_id = 6826;
            if ($plan_id == env('MONTH_ORDER_PLAN_ID')) {
                $type = 'MONTH';
                $product_id = 6826;
            }

            if ($plan_id == env('MONTH_WEEK_ORDER_PLAN_ID')) {
                $type = 'WEEK';
                $product_id = 7394;
            }

            if($plan_id == env('MONTH_QUARTER_ORDER_PLAN_ID')){
                $type = 'QUARTER';
                $product_id = 7685;
            }
            if (!UserMonthService::getOrderByOrder($trade_no, $out_trade_no)) {
                UserMonthService::createLOrder($user_id, $plan_id, $total_fee, $trade_no, $out_trade_no, $type);
                $this->addOrderAndVip($user_id, $out_trade_no, $trade_no, $total_fee, $product_id, $type);
                $this->successPayPushMsg($user_id, $type);
                $this->userProperty($user_id);
            }
        }
        Log::info('orderCallBack--------------------endend----------------------orderCallBack');
        $result = ['return_code'=>'SUCCESS','return_msg'=>'OK'];
        return response(XML::build($result));
    }
}