<?php

namespace App\Http\Controllers\Mounting\Pay;

use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Pay\PayService;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
use App\Services\LoginUserService;
// 支付
class PayController extends Controller
{
    public function __construct()
    {
        $this->dataService = $service = new PayService();
        $this->bootWithService($service);
    }

    public function aliPay(Request $request) {
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $config = array (
            //应用ID,您的APPID。
            'app_id' => "2021003192659498",

            //商户私钥
            'merchant_private_key' => "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCWP791grPfhIp4s16ZDhR5dCBgfOHcFUgTevEzF7aTb6JO890r9NfSJ8d9hNGpNvVFtTobi/TVhHU5tG6Ly8A4JZSRycGkt7+ZdpnT3ckZgK89YnoVvYCnlF/lpjAI2pOR1w/EJtbIZ4bnCbtId4mDvPuz/qirqlYU43mPMPHv6Pk2BfnmpxBa07RFP571IAEYme9G9HYyIN51SwcgeSSHUeJCFMMddyBCAUedFLUPKzHQgq14PxJPDDVAeg01mwf6e+ge9tv1YnjwkGr60fOTq7I6tdvqkKK8RDkogbAK0Dyep7LnE5sObZebe4mi36kQPof7YgVtRW9enqxxpAMTAgMBAAECggEAE/tubyZu3a82606PqjNhLbXwCGUTdL2v1EdphK4Grh0OrQlpxMrPWTfJJDxh1etlO1wa2kcGzM7M+FuyyAzVB6KX27vFcS6u4K4RT0gT0rx2kedi7TlCvwbQqi4r/UF0ltTPV/sCXazHGDsHGWAsfcTIhOu9avdAc469P/n2cz2Ikg3dSO8po0yyvSVlP2bOoKdJEDiCxfg5itg8A/lvb9zN7GuYsMtQXC2IZdD4iQkoTemwh0jGYLWKb3FiVtsKeocT+VYq+ixIQJkO689mo/3J/AnhxWMb+Bi3cvNKJSkAL0wmUHmKvOHwouK9FgKe8LxVVfYl6fjS+PiU7zUwoQKBgQDMGBBiQYLLshp5x54VWdheDtmAji/dUzQlDaV+cRu2fbP3cCXF1jQO9LzSm3gd8fUAH04ae3qqqCB42go7ZnkMUh2jDWuUMWnb8M6g04P8T8bHqHqWKL8Yd1F7MifZMPYSmrbdtBv/5MiBUKxgGOHHYHuyZRIKD3vc1uxez361tQKBgQC8dgBrn5tSkUaAz2WMwVfoXsE0WJ5xrOfN3+YvJ76bd1dBmwX722kZTkTo+7J9rasrfiiE3E2UIqKRXyh0KpzzYz3FO4py313uggJrq4ZJZ7br7Wdky20rAyLsnRls3cEZrRwFHVqrTe2H4ETEAoo/k3fve+S4v7CFM5cbtVnSpwKBgQCv+ROvVGLtNOylEduY9zWaq90XfgGBKKtuQ1ztL6NAbxQMBhNbiDyspJJmWQxxbVzctSFHri3vFTWiXgWyf8FhQTAylXCrfwuSSwguHRHRLAvtvLOt4wYZl0+XFIDNQOz6z5FaiWAW/HFxJljqJqoNmYAuKf0q1XzrxhhaCzhqfQKBgF8BZajbpyNylQYuh1TzyusbiW5oFkfcEGdareGruY0KFnS+P7/9lffp2xdQe2Sb/iRIzwhbPsikxStfuzcEnGad6u/Y2iyaqfGonKvGpkWvASniXjMT0g7S3/JEKCMXj1bwS6XQbHrbKBlNV50wYp02LEoQPPdduxELNuwC+isVAoGAKvkTTMsPazcwJUUrT8sDz7GRvP738vy1o6xUsJKmc8lHOmjOLvXQh+jt+yS96Ga76DrLWE/69hn0mVi4x3BsbmkBjpsFZSsXzRgb2iavWDC6E1mOXy6XANRhc0D7QbBtnq/8ssZoiFuUgmFX5onWyVmXOYrShNEU8nSI5Vmtf48=",

            //异步通知地址
            'notify_url' => config('apisystem.server_name_https')."/index.php/api/v1/Pay/aliPayNotify",

            //同步跳转
            'return_url' => "",

            //编码格式
            'charset' => "UTF-8",

            //签名方式
            'sign_type'=>"RSA2",

            //支付宝网关
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",

            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuayX6iUPWwTgIkp+i+16wSW5W/9UNHVH5SsEaL8e1Qmwh9983b04dbFwxgteOI1A02xB+rp0B/mG/55D1jwfW7PE1ePxujK/UGHFpGS4lqXHprTHILlcg9Jk7PBes7kCbfCoWOUCG2OVNt+GdidU8XIcBk+ETMKKnOtAOv1YB3KA91sNZBReXMOXfc4WG4jEDQruT9ENAhrrZeuiQbdtZwXVTtqa9jwoYDkw/q7eqDKC/+Vxf8gYQSwDJwqC2cnCz5Jl+vuBPYnpH5jMEW1WdqVBlIc0al7gM9QEbxDo3XKMAxZAdZArvhkWDY8Lwye9WwHfXyVeRXZalWWVeO2t4wIDAQAB",
        );

        $find_shop_order = DB::table('shop_order')
            ->leftJoin('shop', 'shop_id', '=', 'shor_shop_id')
            ->where('shor_number', $request['shor_number'])
            ->select('shor_state', 'shor_goo_price', 'shor_goo_num', 'shor_pay_amount', 'shor_goo_name', 'shop_shve_id', 'type', 'shor_goo_id')
            ->first();
        if ($find_shop_order->type == 1 || $find_shop_order->type == 2) {
            if ($find_shop_order->shor_goo_id < $find_shop_order->shop_shve_id) {
                return response()->json(['code'=>500, 'msg'=>'此订单版本低于店铺版本', 'data'=>'']);
            }
        }
        if ($find_shop_order->shor_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'此订单不是待付款状态', 'data'=>'']);
        }
        if (empty($find_shop_order->shor_pay_amount)) {
            return response()->json(['code'=>500, 'msg'=>'支付金额错误', 'data'=>'']);
        }
        //$body="购买企业特惠套餐";
        //$subject="购买企业特惠套餐";
        $out_trade_no=$request['shor_number'];
        $total_amount= round($find_shop_order->shor_pay_amount/100, 2);
        /*** 请填写以下配置信息 ***/
        $appid = $config["app_id"];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        $notifyUrl = $config["notify_url"];     //付款成功后的异步回调地址
        $outTradeNo = $out_trade_no;     //你自己的商品订单号，不能重复
        $payAmount = $total_amount;          //付款金额，单位:元
        $orderName = $find_shop_order->shor_goo_name;    //订单标题
        $signType = 'RSA2';         //签名算法类型，支持RSA2和RSA，推荐使用RSA2
        $rsaPrivateKey=$config["merchant_private_key"];     //商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        /*** 配置结束 ***/
        $aliPay = new PayService();
        $aliPay->setAppid($appid);
        $aliPay->setNotifyUrl($notifyUrl);
        $aliPay->setRsaPrivateKey($rsaPrivateKey);
        $aliPay->setTotalFee($payAmount);
        $aliPay->setOutTradeNo($outTradeNo);
        $aliPay->setOrderName($orderName);
        $result = $aliPay->aliPay();
        $result = $result['alipay_trade_precreate_response'];
        if($result['code'] && $result['code']=='10000'){
            //这里处理你的业务逻辑，如生成订单
            // return $result['qr_code'];//这里是支付宝返回的付款url，需要返回到页面生成二维码
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$result['qr_code']]);
        }else{
            // return $result['msg'].' : '.$result['sub_msg'];
            return response()->json(['code'=>500, 'msg'=>'支付失败', 'data'=>'']);
        }
    }

    public function aliPayNotify(Request $request) {
        $get_input = file_get_contents("php://input");
        $data['get_input'] = $get_input;
        Common::write_log($data, 1, 'aliPayNotify');
        if ($request['trade_status'] == 'TRADE_SUCCESS') {
            $find_order = DB::table('shop_order')
                ->leftJoin('shop', 'shop_id', '=', 'shor_shop_id')
                ->where('shor_number', $request['out_trade_no'])
                ->first();
            if ($find_order->inv_code) {
                $find_shic_data = DB::table('shop_invitate_code_config')
                    ->where('shic_code', $find_order->inv_code)
                    ->first();
                if ($find_shic_data) {
                    if ($find_order->shop_buy == 1 && $find_shic_data->shic_code_type == 2) {//购买过版本 不能使用版本类型
                        return ['code'=>500, 'msg'=>'此邀请码类型只能用于购买版本', 'data'=>''];
                    }
                    if ($find_shic_data->shic_state != 1) {
                        return ['code'=>500, 'msg'=>'此邀请码已失效', 'data'=>''];
                    }
                    if ($find_shic_data->shic_use_num >= $find_shic_data->shic_num) {
                        return ['code'=>500, 'msg'=>'此邀请码数量已超出限制', 'data'=>''];
                    }
                    if ($find_shic_data->shic_end_date < date('Y-m-d H:i:s')) {
                        return ['code'=>500, 'msg'=>'此邀请码过期', 'data'=>''];
                    }
                }
                $update_shic_data['shic_use_num'] = $find_shic_data->shic_use_num + 1;
                if ($update_shic_data['shic_use_num'] >= $find_shic_data->shic_num) {
                    $update_shic_data['shic_state'] = 2;
                }
                $update_shic_res = DB::table('shop_invitate_code_config')
                    ->where('shic_id', $find_shic_data->shic_id)
                    ->update($update_shic_data);
            }
            if ($find_order->type == 3) {//短信充值
                $update_order = DB::table('shop_order')
                    ->where('shor_number', $request['out_trade_no'])
                    ->update(['shor_pay_state'=>2,'shor_state'=>3,'shor_paid_money'=>$find_order->shor_pay_amount,'shor_other_num'=>$postObj->transaction_id,'shor_pay_way'=>2,'shor_pay_check'=>1, 'shor_pay_time'=>date('Y-m-d H:i:s')]);
                // 修改店铺短信数量
                $find_shop = DB::table('shop')
                    ->where('shop_id', $find_order->shor_shop_id)
                    ->first();
                $update_shop = DB::table('shop')
                    ->where('shop_id', $find_order->shor_shop_id)
                    ->update(['shop_message_num'=>($find_shop->shop_message_num + $find_order->shor_goo_num)]);
                $update_log = DB::table('sms_log')
                    ->where('smlo_ord_num', $request['out_trade_no'])
                    ->update(['smlo_state'=>1]);
                $msg_remind_log = DB::table('msg_remind_log')
                    ->where('mrlo_shop_id', $find_order->shor_shop_id)
                    ->where('mrlo_state', 2)
                    ->first();
                if ($msg_remind_log) {//已提醒过
                    if (($find_shop->shop_message_num + $find_order->shor_goo_num) > $find_shop->shop_msg_remind) {
                        $update_remind['mrlo_state'] = 1;
                        $msg_remind_log = DB::table('msg_remind_log')
                            ->where('mrlo_shop_id', $find_order->shor_shop_id)
                            ->where('mrlo_state', 2)
                            ->update($update_remind);
                    }
                }
                $find_data['find_order'] = $find_order;
                $find_data['update_shop'] = $update_shop;
                $find_data['find_shop'] = $find_shop;
                Common::write_log($find_data, 1, 'aliPayNotify1');
                echo "success"; //请不要修改或删除
                exit;
            }

            if ($find_order->type == 4) {//空间充值
                $update_order = DB::table('shop_order')
                    ->where('shor_number', $request['out_trade_no'])
                    ->update(['shor_pay_state'=>2,'shor_state'=>3,'shor_paid_money'=>$find_order->shor_pay_amount,'shor_other_num'=>$request['trade_no'],'shor_pay_way'=>2,'shor_pay_check'=>1, 'shor_pay_time'=>date('Y-m-d H:i:s')]);
                // 修改店铺空间数量
                $find_shop = DB::table('shop')
                    ->where('shop_id', $find_order->shor_get_shop_id)
                    ->first();
                $update_shop = DB::table('shop')
                    ->where('shop_id', $find_order->shor_get_shop_id)
                    ->update(['shop_toll_space'=>($find_shop->shop_toll_space + $find_order->shor_goo_num)]);
                $find_data['find_order'] = $find_order;
                $find_data['update_shop'] = $update_shop;
                $find_data['find_shop'] = $find_shop;
                Common::write_log($find_data, 1, 'aliPayNotify1');
                echo "success"; //请不要修改或删除
                exit;
            }

            if ($find_order->type == 5) {//购买分店
                $update_order = DB::table('shop_order')
                    ->where('shor_number', $request['out_trade_no'])
                    ->update(['shor_pay_state'=>2,'shor_state'=>3,'shor_paid_money'=>$find_order->shor_pay_amount,'shor_other_num'=>$request['trade_no'],'shor_pay_way'=>2,'shor_pay_check'=>1, 'shor_pay_time'=>date('Y-m-d H:i:s')]);
                // 修改店铺空间数量
                $find_shop = DB::table('shop')
                    ->where('shop_id', $find_order->shor_shop_id)
                    ->first();
                $update_shop = DB::table('shop')
                    ->where('shop_id', $find_order->shor_shop_id)
                    ->update(['shop_toll_shop'=>($find_shop->shop_toll_shop + $find_order->shor_goo_num)]);
                $find_data['find_order'] = $find_order;
                $find_data['update_shop'] = $update_shop;
                $find_data['find_shop'] = $find_shop;
                Common::write_log($find_data, 1, 'aliPayNotify1');
                echo "success"; //请不要修改或删除
                exit;
            }
            sqlLog();
            $shop_update['shop_state'] = 1;
            if (($find_order->type == 1 || $find_order->type == 2) && $find_order->shor_goo_id == 3) {
                $adm_update = DB::table('admin_shop_role')
                    ->where('shop_id', $find_order->shor_shop_id)
                    ->where('adm_shop_leave', 1)
                    ->update(['login_bind_shop'=>1]);
            }
            $shop_update['shop_shve_id'] = $find_order->shor_goo_id;
            $shop_update['shop_shpr_id'] = $find_order->shor_shpr_id;
            $shop_update['shop_opening_type'] = 2;
            $shop_update['shop_buy'] = 1;
            $shop_update['shop_update_time'] = date('Y-m-d H:i:s');
            if ($find_order->shop_opening_start_time == '0000-00-00 00:00:00') {
                $shop_update['shop_opening_start_time'] = date('Y-m-d H:i:s');
            }
            $find_shop_versions = DB::table('shop_price')
                ->where('shpr_id', $find_order->shor_shpr_id)
                ->first();
            if($find_order->type ==1){
                $find_shop_level = DB::table('shop_price')
                    ->where('shpr_id', $find_order->shor_shpr_id)
                    ->select('shpr_price', 'shpr_month', 'shpr_unit')
                    ->first();
                if ($find_shop_level->shpr_unit == '天') {
                    $day_string = '+'.$find_shop_level->shpr_month.' day';
                } elseif ($find_shop_level->shpr_unit == '周') {
                    $day_string = '+'.$find_shop_level->shpr_month.' week';
                } elseif ($find_shop_level->shpr_unit == '月') {
                    $day_string = '+'.$find_shop_level->shpr_month.' month';
                } elseif ($find_shop_level->shpr_unit == '年') {
                    $day_string = '+'.$find_shop_level->shpr_month.' year';
                }
                if ($find_order->shop_opening_end_time == '0000-00-00 00:00:00') {
                    $shop_update['shop_opening_end_time'] = date('Y-m-d H:i:s', strtotime($day_string));
                } else {
                    $shop_opening_end_time = strtotime($day_string,strtotime($find_order->shop_opening_end_time));
                    $shop_update['shop_opening_end_time'] = date('Y-m-d H:i:s', $shop_opening_end_time);
                }
                $find_bind_shop = DB::table('bind_shop')
                    ->leftJoin('shop', 'shop_id', '=', 'bish_lshop_id')
                    ->where('bish_fshop_id', $find_order->shor_shop_id)
                    ->where('bish_state', 1)
                    ->get()->toArray();
                foreach ($find_bind_shop as $key => $value) {
                    $update_bind['shop_opening_type'] = $shop_update['shop_opening_type'];
                    $update_bind['shop_opening_end_time'] = $shop_update['shop_opening_end_time'];
                    $update_bind['shop_update_time'] = date('Y-m-d H:i:s');
                    $update_bind_res = DB::table('shop')
                        ->where('shop_id', $value->bish_lshop_id)
                        ->update($update_bind);
                }
            }
            if ($find_order->type == 1 || $find_order->type == 2) {//升级赠送空间
                if ($find_order->shor_goo_id == 1) {
                    $update_res = DB::table('service_project')
                        ->where('sepr_shop_id', $find_order->shor_shop_id)
                        ->update(['sepr_work_type'=>2]);
                    $shop_free_space = 3;
                }
                if ($find_order->shor_goo_id == 2) {
                    $shop_free_space = 5;
                }
                if ($find_order->shor_goo_id == 3) {
                    $shop_free_space = 10;
                }
                $shop_update['shop_free_space'] = $shop_free_space;
            }
            if (($find_order->type == 1 && $find_order->shop_shve_id != $find_order->shor_goo_id)|| $find_order->type == 2) {//初次购买此版本或者升级版本送短信
                if ($find_order->shor_goo_id == 1) {
                    $shop_message_num = 200;
                } elseif ($find_order->shor_goo_id == 2) {
                    $shop_message_num = 300;
                } elseif ($find_order->shor_goo_id == 3) {
                    $shop_message_num = 500;
                }
                if ($find_order->shop_shve_id == 1) {
                    $old_message_num = 200;
                } elseif ($find_order->shop_shve_id == 2) {
                    $old_message_num = 300;
                } elseif ($find_order->shop_shve_id == 3) {
                    $old_message_num = 500;
                } else {
                    $old_message_num = 20;
                }
                $shop_update['shop_message_num'] = $find_order->shop_message_num + $shop_message_num - $old_message_num;
            }
            $find_order_res = DB::table('shop_order')
                ->where('shor_number', $request['out_trade_no'])
                ->update(['shor_pay_state'=>2,'shor_pay_way'=>2,'shor_paid_money'=>$find_order->shor_pay_amount,'shor_pay_check'=>1,'shor_other_num'=>$request['trade_no'],'shor_pay_time'=>date('Y-m-d H:i:s')]);
            $find_shop = DB::table('shop')
                ->where('shop_id', $find_order->shor_shop_id)
                ->update($shop_update);
            //店铺升级修改店铺权限
            $find_role = DB::table('role')
                ->where('rol_shop_id', $find_order->shor_shop_id)
                ->get()->toArray();
                
            $find_pc_pri = DB::table('privileges')
                ->where('pri_shop_version', 'like', '%'.$find_order->shor_goo_id.'%')
                ->select('pri_id')
                ->get()->toArray();

            $pc_pri = array_column($find_pc_pri, 'pri_id');

            $find_applet_pri = DB::table('privileges_technician_applet')
                ->where('pri_shop_version', 'like', '%'.$find_order->shor_goo_id.'%')
                ->select('pri_id')
                ->get()->toArray();

            $applet_pri = array_column($find_applet_pri, 'pri_id');
            $data_pri['pc'] = implode(',',$pc_pri);
            $data_pri['applet'] = implode(',',$applet_pri);
            $new_data = json_encode($data_pri, true);
            foreach ($find_role as $key => $value) {
                if ($value->rol_type == 1) {//店长
                    $updata_res = DB::table('role')
                        ->where('rol_id', $value->rol_id)
                        ->update(['rol_privilege_multiple'=>$new_data,'rol_update_time'=>date('Y-m-d H:i:s')]);
                } else {
                    $rol_privilege_multiple = json_decode($value->rol_privilege_multiple, true);

                    $rol_pc = explode(',', $rol_privilege_multiple['pc']);
                    $rol_applet = explode(',', $rol_privilege_multiple['applet']);
                    $new_rol_pc = array_intersect($pc_pri,$rol_pc);
                    $new_rol_applet = array_intersect($applet_pri,$rol_applet);
                    $json_data['pc'] = implode(',',$new_rol_pc);
                    $json_data['applet'] = implode(',',$new_rol_applet);
                    $update_data['rol_privilege_multiple'] = json_encode($json_data, true);
                    $update_data['rol_update_time'] = date('Y-m-d H:i:s');
                    $updata_res = DB::table('role')
                        ->where('rol_id', $value->rol_id)
                        ->update($update_data);
                }
            }
            $find_data['find_order'] = $find_order;
            $find_data['shop_update'] = $shop_update;
            $find_data['find_shop'] = $find_shop;
            Common::write_log($find_data, 1, 'aliPayNotify1');
            echo "success"; //请不要修改或删除
        } elseif($request['trade_status'] == 'TRADE_FINISHED') {
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
            //如果有做过处理，不执行商户的业务程序

            //注意：
            //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
        }
    }

    // 官网扫码获取token
    public function getToken(Request $request) {
        $xm_id = 'xm'.md5(time().rand(10000,99999));
        setcookie('csrf_token',$xm_id);
        $getcookie = session_get_cookie_params();
        $time_rand = md5(time().rand(10000,99999));
        $data['token'] =  'XM'.$time_rand;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 官网扫码获取token
    public function getQr(Request $request) {
        $add_data['shqr_number'] = $request['shqr_number'];
        $add_data['shqr_source'] = 1;
        $add_data['shqr_create_time'] = date('Y-m-d H:i:s');
        $add_res = DB::table('shop_qr')->insertGetId($add_data);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'']);
    }

    // 官网扫码状态查询
    public function getQrState(Request $request) {
        $find_qrstate = DB::table('shop_qr')
            ->where('shqr_number', $request['shqr_number'])
            ->first();
        if ($find_qrstate) {
            if ($find_qrstate->shqr_state == 1) {
                $shqr_create_time = strtotime($find_qrstate->shqr_create_time);
                if (time() - $shqr_create_time > 600) {
                    $update_qrstate = DB::table('shop_qr')
                        ->where('shqr_number', $request['shqr_number'])
                        ->update(['shqr_state'=>2,'shqr_update_time'=>date('Y-m-d H:i:s')]);
                    return response()->json(['code'=>500, 'msg'=>'二维码已过期1', 'data'=>'']);
                } else {
                    return response()->json(['code'=>200, 'msg'=>'用户未扫码', 'data'=>'']);
                }
            } elseif ($find_qrstate->shqr_state == 2) {
                return response()->json(['code'=>500, 'msg'=>'二维码已过期2', 'data'=>'']);
            } elseif ($find_qrstate->shqr_state == 3) {
                return response()->json(['code'=>500, 'msg'=>'二维码已失效', 'data'=>'']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'查无数据', 'data'=>'']);
        }
    }
}