<?php
/**
 * 支付管理
 */

namespace App\Http\Controllers\Service;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Services\WashPayservice;
use App\Services\PayService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use BlueCity\Core\Sdk\MiscSapi;
use Illuminate\Support\Facades\DB;
use App\Services\CommonService;
use App\Models\RechargeOrder;
use App\Services\BmmcService;

class PayController extends BaseController
{
    public function __construct()
    {
        // $service = new ServiceProviderService();
        $this->bootWithService($service);
    }

    // 商户号 1619735999 
    protected $mchid = '1643850123';
    protected $appid = 'wx5a9e016f8ebb40c7';
    // protected $apiKey = 'a92d64dd5fcf2d72cd12df9aeb9c7a5a';
    protected $apiKey = '43424c7e0ddb071d42b783216d8f09cc';
    public $dataService = null;

    /**
     * 充值扣费记录
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-06
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function index(Request $request) {
        $session = Request()->get('session_token');//用户信息
        $Db = new RechargeOrder();
        if($request->filled('order_number')){ //单号
            $order_number = $request->input('order_number');
            $Db = $Db->where('reo_order_number', 'like','%'.$order_number.'%');
        }
        if($request->filled('reo_type')){ //类型
            $reo_type = $request->input('reo_type');
            $Db = $Db->where('reo_type',$reo_type);
        }
        if($request->filled('reo_client_type')){ //类型
            $reo_client_type = $request->input('reo_client_type');
            $Db = $Db->where('reo_client_type',$reo_client_type);
        }
        if($request->filled('com_id')){ //类型
            $reo_company_id = $request->input('com_id');
            $Db = $Db->where('reo_company_id',$reo_company_id);
        }
        if($request->filled('time_start')){ //类型
            $time_start = $request->input('time_start');
            $Db = $Db->where('reo_create_time', '>=', $time_start);
        }
        if($request->filled('time_end')){ //类型
            $time_end = $request->input('time_end');
            $Db = $Db->where('reo_create_time', '<=', $time_end." 23:59:59");
        }
        $page_size = $request->input('page_size',10);
        $page = $request->input('page',1);
        if ($session['admin_groupnew'] != 7) {
            $Db = $Db->where('reo_company_id', $session['company_id']);
        }
        if($page<1){
            $page = 1;
        }
       // ->select('pg_id','is_delect','brand_name','pg_series','version','general_version','gs_bid','cd_id','gs_id','goods_pic_path','pieces','sort_directory','pg_assurance')
        $paginate = $Db->orderBy('reo_id','DESC')->paginate($page_size);
        $list = self::dataToArray($paginate->items());
        //dump($list);exit;

        //导出 end

        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        if($list){
            foreach ($list as $k =>$v){
                $button = [];
                if ($v['reo_pay_state'] == 1){
                    $button[] = 'payment';
                }
                $button = BmmcService::getListButton($button,$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];

                if ($v['reo_type'] == 1){
                    $list[$k]['reo_type_name'] = "充值";
                }elseif($v['reo_type'] == 2){
                    $list[$k]['reo_type_name'] = "扣费";
                } else {
                    $list[$k]['reo_type_name'] = "--";
                }

                if ($v['reo_pay_state'] == 1){
                    $list[$k]['reo_pay_state_name'] = "未支付";
                }elseif($v['reo_pay_state'] == 2){
                    $list[$k]['reo_pay_state_name'] = "已支付";
                }

                if ($v['reo_client_type'] == 1){
                    $list[$k]['reo_client_type_name'] = "服务商";
                }elseif($v['reo_client_type'] == 2){
                    $list[$k]['reo_client_type_name'] = "经销商";
                } else {
                    $list[$k]['reo_client_type_name'] = "其他";
                }

                if ($v['reo_pay_way'] == 1){
                    $list[$k]['reo_pay_way_name'] = "微信";
                }elseif($v['reo_pay_way'] == 2){
                    $list[$k]['reo_pay_way_name'] = "支付宝";
                }elseif($v['reo_pay_way'] == 3){
                    $list[$k]['reo_pay_way_name'] = "线下打款";
                } else {
                    $list[$k]['reo_pay_way_name'] = "--";
                }
                if ($v['reo_pay_time'] == '0000-00-00 00:00:00') {
                    $list[$k]['reo_pay_time'] = "--";
                }
                $list[$k]['com_name'] = DB::table('company')
                    ->where('com_id', $v['reo_company_id'])
                    ->value('com_name');
            }

           $data['list'] = $list;
           $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            return $this->success('获取成功', $data);
        }else{

            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }

    public function getClientType(Request $request) {
        $data[0]['client_type'] = 1;
        $data[0]['client_type_name'] = '服务商';
        $data[1]['client_type'] = 2;
        $data[1]['client_type_name'] = '经销商';
        return response()->json(['Data' =>$data, 'ErrorMessage' => '成功', 'ErrorCode' => 1]);
    }
    public function getPrice(Request $request) {
        $data['string'][0] = '1、充值前请先确认是否已删除控制台中不再继续使用的欠费资源，否则充值成功后系统会自动开启资源服务并计费。';
        $data['string'][1] = '2、线上充值金额会在当天到账。如需帮助，可查看 如何充值付款，如支付遇到问题，请查阅相关支付帮助。';
        $data['string'][2] = '3、线下汇款(对公转账)充值一般同行一天以内到账，跨行3-5天，请您耐心等待。超出3个工作日未对账，您也可以前往线下汇款单管理提交汇款信息。';
        $data['price'] = [0.01,1,100,500,1000,5000,10000];
        return response()->json(['Data' =>$data, 'ErrorMessage' => '成功', 'ErrorCode' => 1]);
    }
    /**
     * 充值
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-05
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function recharge(Request $request) {
        if ($request['reo_price'] <= 0) {
            return response()->json(['Data' =>'', 'ErrorMessage' => '请输入正确的金额', 'ErrorCode' => 1]);
        }
        DB::beginTransaction();
        $session = Request()->get('session_token');//用户信息
        $order_number = 'CZ'.date('YmdHis').rand(1000,9999);
        $add_data['reo_adm_id'] = $session['id'];
        $add_data['reo_company_id'] = $session['company_id'];
        $add_data['reo_order_number'] = $order_number;
        $add_data['reo_price'] = $request['reo_price'];
        $add_data['reo_pay_state'] = 1;
        $add_data['reo_state'] = 1;
        $add_data['reo_type'] = 1;
        if ($session['admin_groupnew'] == 2) {
            $add_data['reo_client_type'] = 1;
        } elseif ($session['admin_groupnew'] == 3) {
            $add_data['reo_client_type'] = 2;
        } else {
            $add_data['reo_client_type'] = 3;
        }
        $add_data['reo_pay_way'] = $request['reo_pay_way'];
        $add_data['reo_create_time'] = date('Y-m-d H:i:s');
        $add_data['reo_pay_time'] = '';
        $add_res = DB::table('recharge_order')->insertGetId($add_data);
        $return['order_number'] = $order_number;
        $return['reo_price'] = $request['reo_price'];
        $return['reo_create_time'] = $add_data['reo_create_time'];
        $return['good_name'] = '充值'.$request['reo_price'].'元';
        if ($add_res) {
            $this->insertingLog('充值', '', '', '充值管理', $request->ip(), $session['admin_acc']);//日志
            DB::commit();
            return response()->json(['Data' => $return, 'ErrorMessage' => '添加成功', 'ErrorCode' => 1]);
        } else {
            DB::rollback();
            return response()->json(['Data' => '', 'ErrorMessage' => '添加失败', 'ErrorCode' => 2]);
        }
    }

    /**
     * 获取余额
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-06
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getAdminRecharge(Request $request) {
        $session = Request()->get('session_token');//用户信息
        $find_data = DB::table('admin_recharge')
            ->where('adre_company_id', $session['company_id'])
            ->first();
        
        if (empty($find_data)) {
            $add_data['adre_company_id'] = $session['company_id'];
            $add_data['adre_adm_id'] = $session['id'];
            $add_data['adre_banlance'] = 0;
            $add_data['adre_credit_limit'] = 100;
            $add_res = DB::table('admin_recharge')->insertGetId($add_data);
            $find_data = $add_data;
        }
        $find_data['admin_acc'] = $session['admin_acc'];
        return response()->json(['Data' =>$find_data, 'ErrorMessage' => '成功', 'ErrorCode' => 1]);
    }

    public function wxpay(Request $request)
    {
        $find_order = DB::table('recharge_order')
            ->where('reo_order_number', $request['order_number'])
            ->first();
        if (empty($find_order)) {
            return response()->json(['code'=>500,'msg'=>'未找到该订单','data'=>'']);
        }
        if ($find_order['reo_pay_state'] != 1) {
            return response()->json(['code'=>500, 'msg'=>'此订单不是待付款状态', 'data'=>'']);
        }
        if (empty($find_order['reo_price'])) {
            return response()->json(['code'=>500, 'msg'=>'支付金额错误', 'data'=>'']);
        }
        $config = array(
          'mch_id' => $this->mchid,
          'appid' => $this->appid,
          'key' => $this->apiKey,
        );
        $out_trade_no = $find_order['reo_order_number'];
        $body = '商品详情';
        $total_fee = $find_order['reo_price']*100;
        $trade_type = 'NATIVE';
        $product_id = '001';
        $notify_url = 'http://jdh.bluearp.com/index.php/api/service/Pay/notify';
        $timestamp = time();
        $wepay_res = WashPayservice::createJsBizPackage($total_fee, $out_trade_no, $body, $notify_url, $timestamp, $config);
        // 新增在线支付记录
        $were_add_data['were_company_id'] = $find_order['reo_company_id']; //所属公司id
        $were_add_data['were_admin_id'] = $find_order['reo_adm_id']; //客户单位id，会员id
        $were_add_data['were_type'] = 1;
        $were_add_data['out_trade_no'] = $find_order['reo_order_number']; //商户订单号
        $were_add_data['were_description'] = '充值-'.$find_order['reo_price'].'元'; //商品描述
        $were_add_data['were_pay_total_money'] = $find_order['reo_price']; //支付总金额(单位分)
        $were_add_data['were_pay_way'] = 1; //在线支付方式1微信小程序支付
        $were_add_data['were_pay_type'] = 1; //在线支付类型1付款2退款
        $were_add_data['were_create_time'] = date('Y-m-d H:i:s');

        $were_add_data_res = DB::table('weixin_record')->insert($were_add_data);
        return response()->json($wepay_res);
    }

    /**
     * 微信支付回调
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-06
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function notify(Request $request) {
        $get_input = file_get_contents("php://input");
        $data['get_input'] = $get_input;
        CommonService::addLog('支付回调:', json_encode($data,true), 1, 'wxpayNotify');
        $config = array(
          'mch_id' => $this->mchid,
          'appid' => $this->appid,
          'key' => $this->apiKey,
        );
        $notify_res = WashPayservice::notify($get_input, $config);
        echo $notify_res;
    }
    
    public function aliPay(Request $request) {
        // 获取用户信息
        $config = array (
            //应用ID,您的APPID。
            // 'app_id' => "2021003192659498",
            'app_id' => "2021004171690646",

            //商户私钥
            'merchant_private_key' => "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJeBj2yeWhaYHfX9sdez2WPuX4dGkB7X+OOksGiyEt0jwbnKUoM9+AnqGf5tNL/I/7qbf9fJwpxYTx92mOfmuOe4Z45VzBmGgNm0hx2GdvfS8+9WoW2JPJD0aZlZOq/Y0OW6V4N/Yk4JtxR8hfEUqO4c0i3F3RFcQzW7KL5Knpp10GTDYnjyTPLlmza8HhXoDN4rcyCG8u7OibZfydPsvRojh26RVpbhDyQhOy6dcD2CIgMOjupmpHCpXbxWm06kXRokaROf+Ws1kzRPXgW5Czy/8g8HB9VwAYM7Q2CoG8GADBLUhXjlHegf7ELtvBdWJ68xo8UyhRcT5q3Sn49CwxAgMBAAECggEAfKyED4ZKEVrr41c/FPzJfTLsRKnm9k2cCrTJiFS0MadixjQKAW0SPccglDG23kpflwF0kZvq0WOG0B/wBsCW8XEMIyb5OcbsT7LOQBngrVdeev3+Slv/pDCLeg0TENfFjwkFCAPQ498ketd8XOQEt5MIBZ7QIylXeLCoPIGUrAewKIZFVQPZ3RFAkU9rUT9eaYL0GP7wvYA5a6qKi1MdENXvM6pYNoDRRgkChKP5DV5YO83ArtXl/BUOENj3jVq20u2S74Z5NybZr3cUV27PJh7sMDuvczX9yO6iiZZEdr+kY4BfxwAy4OrfWhSx3oSCKMU9YONMpcEPacdqfy9KAQKBgQD6VWDLnIuh5GDZe93sA6pTjrdnESH5zV9v4RgSedqybYsenEpfkmSXPXuOaNJrIBRJHt7qYMZg0Y5LI1UinSDdiNbEWPtwI5ntpn16JxtBr4jnus7+IcatUIaWCzQbS76CFSVpBYRiOxTbWYs4hXdGdS5OjV9rS0AwdrDv6ihREQKBgQCMlLKfpeo6trDcPnZw4jXbFvYE0/nARmajqCraozw7LQqbIfxnHItoeWJHkgjs1WmBCWROU9JhRZPiq5/34mHRJWbmb7sSEVmMiD2WrwrzNQs0qAIMqMiVHRng1EiB57GtaoeY/0Py3Se7nbiTFypaawN52BCIgN8ZQIDriGYpIQKBgQCSzbjrDw3vzb9iKzrUqr2bLMmvPqPfG6pJMQbt5tny4zy/ocYX0AD/lIW92Qj026Ypz1nItyH/K0U4GStXFjBs2k+ga9JgS/B8JrPVC9P3LFqsEqhK7kHV57BVk5JmI4BARuhec2bUOHOdwyBa8CInhpa2aD+56zJkeWZ/+6DTEQKBgFo6ShcbdyVuAj+pu30iQyy2JPreTorw5ImfsrmXUV4tv4PoIUbQ1E0es0x6V04if0+5hm6bcAjMjmlKfCauXtfMqKm4BppHFnGTM+xVtrJ4VhPazU3wuqSyA90AgvUVjz1dhWBWXfcvqIPLbB7EHIPh8V4vphTmmcpsUxJY/jDhAoGAUoajMqVC308jlKQgBYFOemeD0s3zVkEUq+uqIZOQeTfbuDSGDF5pClJeAalwlfJ/PXyDu8vTJn5u2wc+HNNH5r5JsFF6IK5ZfQbCbPp3MoiGFbbotJ9a333GLJOl3SaKO/Heq/pdIO4VUkc1qmqDrGuzDyttJjSNTIaUuS31e9M=",

            //异步通知地址
            'notify_url' => 'http://jdh.bluearp.com/index.php/api/service/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_order = DB::table('recharge_order')
            ->where('reo_order_number', $request['order_number'])
            ->first();
        if (empty($find_order)) {
            return response()->json(['code'=>500,'msg'=>'未找到该订单','data'=>'']);
        }
        if ($find_order['reo_pay_state'] != 1) {
            return response()->json(['code'=>500, 'msg'=>'此订单不是待付款状态', 'data'=>'']);
        }
        if (empty($find_order['reo_price'])) {
            return response()->json(['code'=>500, 'msg'=>'支付金额错误', 'data'=>'']);
        }
        //$body="购买企业特惠套餐";
        //$subject="购买企业特惠套餐";
        $out_trade_no=$request['order_number'];
        $total_amount= $find_order['reo_price'];
        /*** 请填写以下配置信息 ***/
        $appid = $config["app_id"];  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        $notifyUrl = $config["notify_url"];     //付款成功后的异步回调地址
        $outTradeNo = $out_trade_no;     //你自己的商品订单号，不能重复
        $payAmount = $total_amount;          //付款金额，单位:元
        $orderName = '充值'.$total_amount.'元';    //订单标题
        $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'){
            // 新增在线支付记录
            $were_add_data['were_company_id'] = $find_order['reo_company_id']; //所属公司id
            $were_add_data['were_admin_id'] = $find_order['reo_adm_id']; //客户单位id，会员id
            $were_add_data['were_type'] = 1;
            $were_add_data['out_trade_no'] = $find_order['reo_order_number']; //商户订单号
            $were_add_data['were_description'] = '充值-'.$find_order['reo_price'].'元'; //商品描述
            $were_add_data['were_pay_total_money'] = $find_order['reo_price']; //支付总金额(单位分)
            $were_add_data['were_pay_way'] = 2; //在线支付方式1微信小程序支付
            $were_add_data['were_pay_type'] = 1; //在线支付类型1付款2退款
            $were_add_data['were_create_time'] = date('Y-m-d H:i:s');
            $were_add_data_res = DB::table('weixin_record')->insert($were_add_data);
            //这里处理你的业务逻辑，如生成订单
            // 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;
        CommonService::addLog('支付回调:', json_encode($data,true), 1, 'aliPayNotify');
        if ($request['trade_status'] == 'TRADE_SUCCESS') {
            $find_order = DB::table('recharge_order')
                ->where('reo_order_number', $request['out_trade_no'])
                ->first();
            
            if ($find_order['reo_pay_state'] == 1) {
                echo "success"; //请不要修改或删除
                die;
            }
            $update_were = DB::table('weixin_record')
                ->where('out_trade_no', $request['out_trade_no'])
                ->update(['were_pay_state'=>2,'were_transaction_id'=>$request['trade_no']]);
            $update_order = DB::table('recharge_order')
                ->where('reo_order_number', $request['out_trade_no'])
                ->update(['reo_pay_state'=>2,'reo_paid_money'=>$find_order['reo_price'],'reo_pay_way'=>2,'reo_pay_check'=>1, 'reo_pay_time'=>date('Y-m-d H:i:s')]);
            $find_data = DB::table('admin_recharge')
                ->where('adre_company_id', $find_order['reo_company_id'])
                ->first();
            if ($find_data) {
                $adre_banlance = $find_data['adre_banlance'] + $find_order['reo_price'];
                $update_res = DB::table('admin_recharge')
                    ->where('adre_id', $find_data['adre_id'])
                    ->update(['adre_banlance'=>$adre_banlance]);
            }
            
            $find_data['find_order'] = $find_order;
            $find_data['update_order'] = $update_order;
            CommonService::addLog('支付回调:', json_encode($find_data,true), 1, 'aliPayNotify');
            echo "success"; //请不要修改或删除
        } elseif($request['trade_status'] == 'TRADE_FINISHED') {
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
            //如果有做过处理，不执行商户的业务程序

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

    //获取订单状态
    public function getOrderState(Request $request){
        // 根据订单id查询订单支付状态
        $find_order = DB::table('recharge_order')
            ->where("reo_order_number", $request['order_number'])
            ->first();
        if (empty($find_order)) {
            return ['code'=>500, 'msg'=>'没有该订单', 'data'=>'没有该订单'];
        }
        // 返回数据
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_order]);
    }
}
