<?php
/**
 * 文件名称（同步京东秒送数据）
 * 文件简单描述（同步京东秒送数据）
 * @author DouBin
 * @Date: 2025/9/1
 * @Time: 10:36
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\Pt;
use App\Models\User;
use App\Services\CommonService;
use App\Services\JdDataService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use App\Services\RefundService;
use Illuminate\Http\Request;
use DB;


class SynJdRapidController extends BaseController
{

   /**|---------------------------------------------------------------------------------
    * @name 同步token
    * @param string token token
    * @retrun \Illuminate\Http\JsonResponse
    * @author dou 2025/9/1 10:37
    * |---------------------------------------------------------------------------------
   */
    public function receiveToken ( Request $request ){
        if(!$request->filled('token')){
            $post = file_get_contents('php://input');
        }else{
            $post = $request->input('token');
        }
        CommonService::addLog('接收秒送同步token信息', $post, '','receiveToken-JdRapid');
        $post = json_decode($post,true);
        if(isset($post['venderId'])) {
            $rea = DB::table('jdpop_token')->where('venderId',$post['venderId'])->update(['access_token'=>$post['token'],'update_time'=>date("Y-m-d H:i:s")]);
        }
        return Response()->json(["code"=>"200","msg"=>"success","data"=>""]);
    }

    /**|---------------------------------------------------------------------------------
     * @name 接收秒送推送的订单
     * @param string
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/9/18 10:21
     * |---------------------------------------------------------------------------------
    */
    public function newOrder ( Request $request ){
        $post = file_get_contents('php://input');
        parse_str($post, $outputArray);
        if (isset($outputArray['jd_param_json'])) {
            // 注意：parse_str 已经对 %7B 等编码进行了解码，现在的值是合法的 JSON 字符串
            $jsonDecodedValue = json_decode($outputArray['jd_param_json'], true); // true 表示返回关联数组
            if (json_last_error() === JSON_ERROR_NONE) {
                $rea = DB::table("order_jd")->insert(['oj_billId'=>$jsonDecodedValue['billId'],'oj_statusId'=>$jsonDecodedValue['statusId'],'oj_creact_time'=>date("Y-m-d H:i:s"),'oj_update_time'=>date("Y-m-d H:i:s"),'oj_token'=>$outputArray['token'],'oj_type'=>1]);
                if($rea) {
                    $billId = $jsonDecodedValue['billId'];
                    $token = $outputArray['token'];
                    app()->terminating(function () use ($billId, $token) {
                        // 这里的代码会在响应发送后执行
                        self::sysJdData($billId, $token,1);
                    });
                }
                $outputArray['jd_param_json'] = $jsonDecodedValue;
            } else {
                // JSON 解析错误处理
                $outputArray['jd_param_json_error'] = json_last_error_msg();
            }
        }
        CommonService::addLog('接收秒送同步post', json_encode($outputArray), '','receiveNewOrder-JdRapid');
        return Response()->json(["code"=>"0","msg"=>"success","data"=>""]);
    }
    /**|---------------------------------------------------------------------------------
     * @name 接收秒送取消订单
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/9/22 14:39
     * |---------------------------------------------------------------------------------
    */
    public function userCancelOrder ( Request $request ){
        $post = file_get_contents('php://input');
        parse_str($post, $outputArray);
        if (isset($outputArray['jd_param_json'])) {
            // 注意：parse_str 已经对 %7B 等编码进行了解码，现在的值是合法的 JSON 字符串
            $jsonDecodedValue = json_decode($outputArray['jd_param_json'], true); // true 表示返回关联数组
            if (json_last_error() === JSON_ERROR_NONE) {
                $rea = DB::table("order_jd")->insert(['oj_billId'=>$jsonDecodedValue['billId'],'oj_statusId'=>$jsonDecodedValue['statusId'],'oj_creact_time'=>date("Y-m-d H:i:s"),'oj_update_time'=>date("Y-m-d H:i:s"),'oj_token'=>$outputArray['token'],'oj_type'=>2]);
                if($rea) {
                    $billId = $jsonDecodedValue['billId'];
                    $token = $outputArray['token'];
                    app()->terminating(function () use ($billId, $token) {
                        // 这里的代码会在响应发送后执行
                        self::sysJdData($billId, $token,2);
                    });
                }
                $outputArray['jd_param_json'] = $jsonDecodedValue;
            } else {
                // JSON 解析错误处理
                $outputArray['jd_param_json_error'] = json_last_error_msg();
            }
        }
        CommonService::addLog('接收秒送同步post', json_encode($outputArray), '','userCancelOrder-JdRapid');
        return Response()->json(["code"=>"0","msg"=>"success","data"=>""]);
    }
    /**|---------------------------------------------------------------------------------
     * @name 接收秒送用户申请取消
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/9/22 14:39
     * |---------------------------------------------------------------------------------
     */
    public function applyCancelOrder ( Request $request ){
        $post = file_get_contents('php://input');
        parse_str($post, $outputArray);
        if (isset($outputArray['jd_param_json'])) {
            // 注意：parse_str 已经对 %7B 等编码进行了解码，现在的值是合法的 JSON 字符串
            $jsonDecodedValue = json_decode($outputArray['jd_param_json'], true); // true 表示返回关联数组
            if (json_last_error() === JSON_ERROR_NONE) {
                $rea = DB::table("order_jd")->insert(['oj_billId'=>$jsonDecodedValue['billId'],'oj_statusId'=>$jsonDecodedValue['statusId'],'oj_creact_time'=>date("Y-m-d H:i:s"),'oj_update_time'=>date("Y-m-d H:i:s"),'oj_token'=>$outputArray['token'],'oj_type'=>3]);
                if($rea) {
                    $billId = $jsonDecodedValue['billId'];
                    $token = $outputArray['token'];
                    app()->terminating(function () use ($billId, $token) {
                        // 这里的代码会在响应发送后执行
                        self::sysJdData($billId, $token,3);
                    });
                }
                $outputArray['jd_param_json'] = $jsonDecodedValue;
            } else {
                // JSON 解析错误处理
                $outputArray['jd_param_json_error'] = json_last_error_msg();
            }
        }
        CommonService::addLog('接收秒送同步post', json_encode($outputArray), '','applyCancelOrder-JdRapid');
        return Response()->json(["code"=>"0","msg"=>"success","data"=>""]);
    }
    /**|---------------------------------------------------------------------------------
     * @name 计划执行未处理订单
     * @retrun /multitype:array
     * @author dou 2025/9/22 14:12
     * |---------------------------------------------------------------------------------
    */
    public function searchJdOrder ( ){
        $list = DB::table("order_jd")->where('oj_state',1)->where('oj_num','<',2)->limit(10)->get();
        $list = CommonService::dataToArray($list);
        if($list){
            foreach($list as $k => $v){
                self::sysJdData($v['oj_billId'],$v['oj_token'],$v['oj_type']);
            }
        }
        return ["code"=>"200","msg"=>"操作完成","data"=>"操作完成"];
    }
    /**|---------------------------------------------------------------------------------
     * @name 加载数据状态
     * @param string $billId 订单单号
     * @param string $type 处理类型 1创建订单2取消订单
     * @retrun /multitype:array
     * @author dou 2025/9/22 11:21
     * |---------------------------------------------------------------------------------
    */
    public function sysJdData ( $oj_billId,$token='',$type=1 ){
        $res = self::searchOrder($oj_billId,$token,$type);
        CommonService::addLog('接收秒送同步post', json_encode($res), '','sysJdData-JdRapid');
        if($res['code']==200){
            $post['oj_state']=2;
        }else{
            $post['oj_state']=3;
        }
        $post['oj_centent']=$res['msg'];
        $post['oj_update_time']=date("Y-m-d H:i:s");
        DB::table("order_jd")->where('oj_billId',$oj_billId)->where('oj_type',$type)->increment('oj_num');
        DB::table("order_jd")->where('oj_billId',$oj_billId)->where('oj_type',$type)->update($post);
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取订单信息
     * @param string oj_billId 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/9/18 14:58
     * |---------------------------------------------------------------------------------
    */
    public function searchOrder ( $oj_billId ,$token='',$type = 1){
        if($token=='') {
            $token = DB::table("jdpop_token")->where("pt_id", '50')->first();
        }else{
            $token = DB::table("jdpop_token")->where("access_token", $token)->first();
        }
        if(!empty($token)){
            $json['orderId']=$oj_billId;
            $sysParams['token']=$token['access_token'];
            $sysParams['app_key']=$token['app_key'];
            $sysParams['format']='json';
            $sysParams['timestamp']=date("Y-m-d H:i:s");
            $sysParams['v']='1.0';
            $apiParams["jd_param_json"]=json_encode($json);
            $sysParams["sign"] = JdDataService::generateSign(array_merge($sysParams, $apiParams),$token['app_secret']);
            $apiParams=array_merge($sysParams, $apiParams);
            ksort($apiParams);
            foreach( $apiParams as $k => $v ){
                if(strpos($v,' ')){
                    $urldata[]=$k."=".urlencode ($v);
                }else{
                    $urldata[]=$k."=".$v;
                }
            }
            $urldata=implode("&",$urldata);
            $url="https://openapi.jddj.com/djapi/order/es/query?".$urldata;
            $resp=CommonService::https_get($url);
            $resp = json_decode($resp,true);
            if(isset($resp['encryptData']) && !empty($resp['encryptData'])){
                $data = JdDataService::decryptAES($resp['encryptData'], $token['app_secret']);
                $data = json_decode($data,true);
                if($data['code']=='0' && isset($data['result']) && !empty($data['result'])){
                    $goods = DB::table('pj_goods')->select('pg_id','brand_name','pg_series','version','goods_pic_path','national_version')->get()->toarray();
                    $goods = CommonService::jointArrayKey($goods, 'pg_id');
                    $result = $data['result'];
                    $result = json_decode($result,true);
                    $result = $result['resultList'];
                    $arr_goods = [];
                    $arr = [];
                    $company_id = Pt::where("id",$token['pt_id'])->value('company_id');
                    $ip = $_SERVER["REMOTE_ADDR"];
                    foreach( $result as $kk => $vv ){
                        $order_info = OrderService::getOrderBy('order_num', $vv['orderId'],['id','order_status','lock_type','sys_num','order_num','p_id','ser_id','create_time','new_customer_id','lock_type','new_money','company_id']);
                        if($order_info){
                            if(in_array($vv['orderStatus'], ['20010','20020','20030','20040']) || $type==2 || $type==3) {
                                if ($order_info['lock_type'] == 2 || in_array($order_info['order_status'], [50, 55])) {
                                    return ["code"=>"200","msg"=>"订单已取消1","data"=>"订单已取消"];
                                } else {
                                    $datar['allprice'] = $order_info['new_money'];
                                    $goods_arr = OrderMsg::where('sys_num', $order_info['sys_num'])->get(['id as msg_id', 'goods_name', 'goods_price', 'goods_id as good_id']);
                                    $datar['goodsArr'] = CommonService::dataToArray($goods_arr);
                                    $datar['goods_state'] = 2;//2:平台; 4:财务
                                    $datar['sys_num'] = $order_info['sys_num'];
                                    $datar['order_num'] = $order_info['order_num'];
                                    $datar['apply_type'] = 1;
                                    $content = $vv['orderCancelRemark'];
                                    $datar['content'] = $content;
                                    $datar['p_id'] = $order_info['p_id'];
                                    $datar['ser_id'] = $order_info['ser_id'];
                                    $datar['new_customer_id'] = $order_info['new_customer_id'];
                                    $datar['order_status'] = $order_info['order_status'];
                                    $datar['create_time'] = $order_info['create_time'];
                                    $userArr = User::where('id', $order_info['new_customer_id'])->first();
                                    $session['admin_groupnew'] = 7;
                                    $session['admin_acc'] = '系统录入';
                                    $session['id'] = 164;
                                    $session['company_id'] = $order_info['company_id'];
                                    $ret = OrderService::lockByRefund($datar, $session, $userArr);
                                    CommonService::addLog('取消订单', json_encode($ret), $vv['customOrderId'], 'JdRapid-cancel');
                                    return ["code"=>"200","msg"=>"订单已取消2","data"=>"订单已取消"];
                                }
                            }
                            return ["code"=>"200","msg"=>"订单已存在","data"=>"订单已存在"];
                        }
                        if(in_array($vv['orderStatus'], ['20010','20020','20030','20040'])|| $type==2 || $type==3) {
                            return ["code"=>"200","msg"=>"success","data"=>"订单已取消无需创建"];
                        }
                        $flag = 1;
                        $skuId = array_column($vv['product'], 'skuId');
                        $goodids = DB::table("jd_bound")->whereRaw("sku_id in (".implode(',',$skuId).")")->pluck('goods_id','sku_id')->toarray();
                        if(empty($goodids)){
                            CommonService::addLog('无sku', json_encode($skuId), $vv['orderId'],'JdRapid-无sku');
                            $flag = 2;
                        }
                        if($goodids){
                            if(count($goodids)<count($vv['product'])){
                                $flag = 2;
                            }
                        }

                        /**********************************************整理商品信息******************************************/
                        $resjdgoods = DB::table('jdgoods')->where("order_id",$vv['orderId'])->value('id');
                        $price = 0;
                        $orderMsgData = [];
                        foreach( $vv['product'] as $ka => $va ){
                            $price= $price+$va['skuStorePrice']/100;
                            if(!$resjdgoods){
                                if(in_array($vv['orderId'], $arr_goods)){
                                    unset($arr_goods[$kk]);
                                }

                                $arr_goods[$kk]['order_id'] = $vv['orderId'];//订单单号
                                $arr_goods[$kk]['pt_id'] = $token['pt_id'];//平台id
                                $arr_goods[$kk]['sku_id'] = $va['skuId'];//京东sku
                                $arr_goods[$kk]['item_total'] = $va['skuCount'];//商品数量
                                $arr_goods[$kk]['jd_price'] = $va['skuJdPrice']/100;//京东单价
                                $arr_goods[$kk]['jd_cost'] = $va['skuStorePrice']/100;//采购价
                                $arr_goods[$kk]['sku_name'] = $va['skuName'];//商品名称
                                DB::table('jdgoods')->insert($arr_goods[$kk]);
                                unset($arr_goods[$kk]);

                            }
                            $sys_num = 'L'.date("YmdHis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT).'-'.$kk;
                            if($flag==1) {
                                $goodid = $goodids[$va['skuId']];
                                if($goodid){
                                    $goods_res = $goods[$goodid];
                                    if($goods_res['pg_series']==''){
                                        $type = $goods_res['version'];
                                    }else{
                                        $type = $goods_res['pg_series']."-".$goods_res['version'];
                                    }
                                    $goods_name = $goods_name.$goods_res['brand_name'].",".$type.",".$goods_res['general_version'].",";
                                    $good_brand[] = $goods_res['brand_name'];

                                    $orderMsgData[$ka]['goods_id'] = $goodid;
                                    $orderMsgData[$ka]['goods_name'] = $goods_res['brand_name']."-".$type;
                                    $orderMsgData[$ka]['goods_price'] = $va['skuStorePrice']/100;//实收/商品单价
                                    // $orderMsgData['goods_paid'] = $va['jdPrice'];//应收
                                    $orderMsgData[$ka]['goods_num'] = $va['skuCount'];
                                    $orderMsgData[$ka]['goods_brand'] = $goods_res['brand_name'];
                                    $orderMsgData[$ka]['goods_number'] = $type;
                                    $orderMsgData[$ka]['cd_id'] = 1;
                                    // dump($orderMsgData);
                                }
                            }
                        }
                        /*********************************************************************************************/
                        /**********************************************添加订单信息******************************************/
                        $newOrderId = false;
                        if($flag==1){

                            $orders[$kk]['sys_bh'] = $sys_num;
                            $orders[$kk]['skb_bh'] = $vv['orderId'];//平台单号
                            $orders[$kk]['pt_id'] = $token['pt_id'];//平台id
                            $orders[$kk]['ser_type'] = 1;//服务类型：1上门安装，2到店服务
                            $orders[$kk]['shr_name'] = $vv['buyerFullName'];//姓名
                            $tel = explode(',', $vv['buyerMobile']);
                            $orders[$kk]['shr_phone'] = $tel[0].'-'.$tel[1];//$vv['telephone'];//电话
                            if(in_array($vv['buyerCityName'], ['北京市','北京'])){
                                $areaProvince[0] = '北京';
                            }elseif(in_array($vv['buyerCityName'], ['上海市','上海'])){
                                $areaProvince[0] = '上海';
                            }elseif(in_array($vv['buyerCityName'], ['天津市','天津'])){
                                $areaProvince[0] = '天津';
                            }elseif(in_array($vv['buyerCityName'], ['重庆市','重庆'])){
                                $areaProvince[0] = '重庆';
                            }else {
                                $areaProvince = explode($vv['buyerCityName'], $vv['buyerFullAddress']);
                            }
                            $orders[$kk]['shr_sheng'] = $areaProvince[0];//省份
                            $orders[$kk]['shr_shi'] = $vv['buyerCityName'];//城市
                            $orders[$kk]['shr_xian'] = $vv['buyerCountryName'];//区县
                            $fullAddress = str_replace($orders[$kk]['shr_sheng'].$vv['buyerCityName'].$vv['buyerCountryName'], '', $vv['buyerFullAddress']);
                            $orders[$kk]['shr_adress'] = $fullAddress;//
                            $orders[$kk]['shr_other'] = '店铺名称'.$vv['produceStationName'].';'.$vv['orderBuyerRemark'].'接单后10分钟内务必联系客户核实车型跟安装时间！不断电安装、如果无法完成 请立刻反馈我们处理~！';
                            $orders[$kk]['car_audit'] = 2;//1:新订单；2：可派单；3：处理中
                            $orders[$kk]['order_type'] = 1;//订单类型：1：普通；20加急；10：夜间
                            $orders[$kk]['order_time'] = date("Y-m-d H:i:s");
                            $orders[$kk]['pay_type'] = 1;//支付方式：1在线支付；2货到付款
                            $orders[$kk]['goods'] = $orderMsgData;

                            //   $session = $request->get('session_token');//获取操作人信息
                            $session['admin_groupnew'] = 7;
                            $session['admin_acc'] = '系统录入';
                            $session['id'] = 164;
                            $session['company_id'] = $company_id;
                            // dump($orders[$kk]);
                            $return = OrderaddService::addOrder($orders[$kk], $session, $ip);
                            //    dump($return);
                            CommonService::addLog('添加定单', json_encode($return)."--".json_encode($orders[$kk]).'--'.json_encode($goodids), $vv['orderId'],'JdRapid_addOrder');
                            // $return['ErrorCode'] = 2;
                            if($return['ErrorCode']==1){
                                $newOrderId = true;
                            }
                        }
                        /*********************************************************************************************/
                        /**********************************************添加同步记录******************************************/
                        $rea = DB::table('jd_proprietary')->where("order_id",$vv['orderId'])->value('id');
                        if(in_array($vv['orderId'], array_column($arr, 'order_id'))){
                            unset($arr[$kk]);
                        }
                        $arr[$kk]['order_id'] = $vv['orderId'];//订单单号
                        $arr[$kk]['admin_acc'] = '系统录入';//操作人
                        $arr[$kk]['pt_id'] = $token['pt_id'];//平台id
                        $arr[$kk]['pay_type'] = $vv['payChannel']??1;//支付方式
                        $arr[$kk]['order_seller_price'] = $price;//订单金额
                        $arr[$kk]['freight_price'] = 0;//运费
                        $arr[$kk]['order_state'] = $vv['orderStatus'];//订单状态（20010:锁定，20020:订单取消，20030:订单取消申请，20040:超时未支付系统取消，31000:等待付款，31020:已付款，41000:待处理，32000:等待出库，33040:配送中，33060:已妥投，90000:订单完成）
                        $arr[$kk]['invoice_info'] = '不需要开具发票';//'发票1开2不开'
                        $arr[$kk]['order_remark'] = $vv['orderBuyerRemark']??'';//订单备注
                        $arr[$kk]['order_start_time'] = date("Y-m-d H:i:s");//下单时间
                        $arr[$kk]['fullname'] = $vv['buyerFullName'];//姓名
                        $tel = explode(',', $vv['buyerMobile']);
                        $arr[$kk]['mobile'] = $tel[0].'-'.$tel[1];//$vv['telephone'];//电话
                        $arr[$kk]['telephone'] = $tel;//客户电话
                        if(in_array($vv['buyerCityName'], ['北京市','北京'])){
                            $areaProvince[0] = '北京';
                        }elseif(in_array($vv['buyerCityName'], ['上海市','上海'])){
                            $areaProvince[0] = '上海';
                        }elseif(in_array($vv['buyerCityName'], ['天津市','天津'])){
                            $areaProvince[0] = '天津';
                        }elseif(in_array($vv['buyerCityName'], ['重庆市','重庆'])){
                            $areaProvince[0] = '重庆';
                        }else {
                            $areaProvince = explode($vv['buyerCityName'], $vv['buyerFullAddress']);
                        }
                        $arr[$kk]['province'] = $areaProvince[0];//省份
                        $arr[$kk]['city'] = $vv['buyerCityName'];//城市
                        $arr[$kk]['county'] = $vv['buyerCountryName'];//区县
                        $fullAddress = str_replace($orders[$kk]['shr_sheng'].$vv['buyerCityName'].$vv['buyerCountryName'], '', $vv['buyerFullAddress']);
                        $arr[$kk]['full_address'] = $fullAddress;//详细地址
                        $arr[$kk]['order_pay'] = $price;//实收金额
                        $arr[$kk]['parent_orderid'] = $vv['orderId'];//父类单号
                        if (!$newOrderId || $flag=='2'){
                            //echo '添加订单信息失败';
                            if(!$rea){
                                $arr[$kk]['is_show'] = 2;//'1 未填单 2 已填单 3 已删除 4 已完成'
                                DB::table('jd_proprietary')->insert($arr[$kk]);
                                unset($arr[$kk]);
                            }
                            return ["code"=>"201","msg"=>"建单失败","data"=>"建单失败"];
                        }else{
                            if(!$rea){
                                $arr[$kk]['is_show'] = 1;//'1 未填单 2 已填单 3 已删除 4 已完成'
                                DB::table('jd_proprietary')->insert($arr[$kk]);
                                unset($arr[$kk]);
                            }
                            return ["code"=>"200","msg"=>"建单成功","data"=>"建单成功"];
                        }
                        /*********************************************************************************************/
                    }
                }
            }
        }
        return ["code"=>"201","msg"=>"获取订单信息失败","data"=>"获取订单信息失败"];
    }

    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
