<?php
/**
 * 文件名称（同步京东POP店数据）
 * 文件简单描述（用于同步京京东POP店数）
 * @author du
 * @Date: 2022/04/29
 * @Time: 10:19
 * @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\OrderaddService;
use App\Services\OrderService;
use Illuminate\Http\Request;
use DB;


class SynJdPopDataController extends BaseController
{

    /**
     * @name 同步京东POP店未出库定单
     * @param Request $request
     * @author du
     * @date 2022/4/27
     */
    public function addOrderData (){
        $url = "http://116.196.75.172/index.php/GetOrder/index";

        $url_ex = "http://116.196.75.172/index.php/GetOrder/syncExpress";//出库

        $time_start = date("Y-m-d H:i:s",strtotime(" -720 minute".date("Y-m-d H:i:s")));
        $time_end = date("Y-m-d H:i:s");
        $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');
        $token = DB::table('jdpop_token')->where('status',1)->where('type',1)->select('app_key','app_secret','access_token','pt_id','appName')->get()->toarray();

        foreach ($token as $k =>$v){
            //  CommonService::addLog('token', json_encode($v['app_key']), $v['pt_id'],'jd_token');
            $res_ult = [];
            $res_ult[$k]['appKey'] = $v['app_key'];		//appkey
            $res_ult[$k]['appSecret'] = $v['app_secret'];	//secret
            $res_ult[$k]['accessToken'] = $v['access_token'];	//token
            $res_ult[$k]['time_start'] = $time_start;				//开始时间
            $res_ult[$k]['time_end'] = $time_end;				//结束时间
            $res_ult[$k]['setPageSize'] = 10;						//每页条数
            $res_ult[$k]['setOrderState']  = 'WAIT_SELLER_STOCK_OUT';	//订单状态 WAIT_SELLER_STOCK_OUT 等待出库 ,TRADE_CANCELED,POP_ORDER_PAUSE,LOCKED,WAIT_GOODS_RECEIVE_CONFIRM,WAIT_SELLER_DELIVERY
            $res_ult[$k]['setOptionalFields'] ='orderInfo,orderId,orderType,payType,orderTotalPrice,orderSellerPrice,open_id_buyer,open_id,orderMarkDesc,storeId,tuiHuoWuYou,taxFee,scDT,storeOrder,orderSource,customsModel,customs,parentOrderId,directParentOrderId,modified,vatInfo,logisticsId,paymentConfirmTime,returnOrder,balanceUsed,venderRemark,itemInfoList,consigneeInfo,orderEndTime,orderStartTime,orderRemark,invoiceCode,invoiceInfo,invoiceEasyInfo,orderStateRemark,orderState,sellerDiscount,orderPayment,venderId,pauseBizInfo,freightPrice,pin';    //获取的订单字段

            /**TRADE_CANCELED,POP_ORDER_PAUSE,LOCKED
            这三个是取消的状态，还是通过获取订单那个接口，触发时间和获取订单时间一致就行，这个没有变更状态一说，所以需要你判定，比如五分钟查一次最近六分钟的取消订单，如果系统中未取消就锁定订单生成退款单，如果过系统中已经取消或者已经锁定退款单就不用管了**/

            $res_ult[$k]['page'] = 1;
            $res = $this->request_post($url,$res_ult[$k]);
            $ip = $_SERVER["REMOTE_ADDR"];

            CommonService::addLog('token1--'.$v['pt_id'], $res, $v['pt_id'],'SynJdPopData-getOrder');

            $data = json_decode($res,true);
            if($data['jingdong_pop_order_enSearch_responce']['code']==0){
                $company_id = Pt::where("id",$v['pt_id'])->value('company_id');

                $order_data = $data['jingdong_pop_order_enSearch_responce']['searchorderinfo_result']['orderInfoList'];
                if(!empty($order_data)){
                    $arr_goods = [];
                    $arr = [];
                    $num = 0;
                    foreach($order_data as $ksa => $vsa){
                        if(!empty($vsa['consigneeInfo']['oaid'])) {
                            $orderInfos[$num]['orderId'] = $vsa['orderId'];
                            $orderInfos[$num]['oaid'] = $vsa['consigneeInfo']['oaid'];
                            $num++;
                        }
                    }
                    if(!empty($orderInfos)){
                        $poss['appKey'] = $v['app_key'];
                        $poss['accessToken'] = $v['access_token'];
                        $poss['appSecret'] = $v['app_secret'];
                        $poss['orderType'] = 'POP';
                        $poss['appName'] = $v['appName'];
                        $poss['orderInfos'] = json_encode($orderInfos);
                        $user_data=$this->https_request('http://zptzchat.bluearp.com/m/index.php/GetUserDataApi/getOaidDecrypt',$poss);
                        $user_data = json_decode($user_data,true);
                        if($user_data['jingdong_jos_order_oaid_decrypt_responce']['returnType']['code']==200){
                            $user_data = $user_data['jingdong_jos_order_oaid_decrypt_responce']['returnType']['data'];
                            $user_datas = [];
                            foreach($user_data as $ks => $vs){
                                $user_datas[$vs['orderId']] = $vs;
                            }
                            if(!empty($user_datas)){
                                foreach($order_data as $ka => $va){
                                    $order_data[$ka]['user_data_dou'] = isset($user_datas[$va['orderId']])?$user_datas[$va['orderId']]:'';
                                }
                            }
                        }
                    }
                    // CommonService::addLog('token3', json_encode($order_data), $v['pt_id'],'jd_token');
                    foreach ($order_data 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','company_id']);
                        $order_info = CommonService::dataToArray($order_info);
                        if(!empty($order_info)&&in_array($vv['orderState'], ['TRADE_CANCELED','POP_ORDER_PAUSE','LOCKED'])){
                            if($order_info['lock_type']==2||in_array($order_info['order_status'], [50,55])){
                                continue;
                            }else{
                                $datar['allprice'] = $vv['orderTotalPrice'];
                                $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;
                                $datar['content'] = $vv['orderStateRemark'];
                                $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'] = 1133;
                                $session['company_id'] = $order_info['company_id'];
                                $ret = OrderService::lockByRefund($datar , $session , $userArr);
                                CommonService::addLog('取消订单', json_encode($ret), $vv['orderId'],'JDPOP-cancel');
                                continue;
                            }

                        }

                        // CommonService::addLog('token4', json_encode( $vv['orderId']), $v['pt_id'],'jd_token');
                        $exsit = OrderService::getOrderBy('order_num', $vv['orderId'],['id']);
                        $eisit_jd = DB::table('jd_proprietary')->where('order_id',$vv['orderId'])->value('id');
                        if(!$exsit||!$eisit_jd){
                            $flag = 1;
                            unset($skuId);
                            foreach( $vv['itemInfoList'] as $ka => $va ){
                                $skuId[] = "'".$va['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'],'JDPOP-无sku');
                                $flag = 2;
                            }
                            if($goodids){
                                if(count($goodids)<count($vv['itemInfoList'])){
                                    $flag = 2;
                                }
                            }

                            //解密
                            if(isset($vv['user_data_dou'])){
                                $str = $vv['user_data_dou']['customerName'];
                            }else {
                                $str = $vv['consigneeInfo']['fullname'];
                            }
                            $datafullname['accessToken'] = $v['access_token'];//'e0a1c90e617f4b3a9865ed059f99c5f42ztb';
                            $datafullname['appKey'] = $v['app_key'];;//'41D9668E8CB81C9890A065BEC300FD84';
                            $datafullname['appSecret'] = $v['app_secret'];//'93bff142bf5c4422ae7bec9eb992e751';

                            $fullname =  $this->decrypt($datafullname,$str,$vv['orderId']);
                            if(strpos($fullname,'<body>' )!==false){
                                //存另一数据库中
                                //是否存在
                                $exs_code = DB::table('jdpop_encode')->where('order_id',$vv['orderId'])->value('id');
                                if($exs_code){
                                    DB::table('jdpop_encode')->where('order_id',$vv['orderId'])->update(['name_code'=>$vv['consigneeInfo']['fullname']]);
                                }else{
                                    DB::table('jdpop_encode')->insert(['order_id'=>$vv['orderId'],'pt_id'=>$v['pt_id'],'name_code'=>$vv['consigneeInfo']['fullname']]);
                                }
                                $fullname = '无';
                            }
                            $fullname = $fullname??$vv['consigneeInfo']['fullname'];

//                            $pin = $vv['pin'];
//                            $fullpin =  $this->decrypt($datafullname,$pin,$vv['orderId']);
//                            if(strpos($fullpin,'<body>' )!==false){
//                                //存另一数据库中
//                                //是否存在
//                                $exs_code = DB::table('jdpop_encode')->where('order_id',$vv['orderId'])->value('id');
//                                if($exs_code){
//                                    DB::table('jdpop_encode')->where('order_id',$vv['orderId'])->update(['pin_code'=>$vv['pin']]);
//                                }else{
//                                    DB::table('jdpop_encode')->insert(['order_id'=>$vv['orderId'],'pt_id'=>$v['pt_id'],'pin_code'=>$vv['pin']]);
//                                }
//                                $fullpin = '无';
//                            }
//                            $fullpin = $fullpin??$vv['pin'];
                            if(isset($vv['user_data_dou'])){
                                $Address = $vv['user_data_dou']['address'];
                            }else {
                                $Address = $vv['consigneeInfo']['fullAddress'];
                            }
                            $fullAddress = $this->decrypt($datafullname,$Address,$vv['orderId']);

                            if(strpos($fullAddress,'<body>' )!==false){
                                //存另一数据库中
                                //是否存在
                                $exs_code = DB::table('jdpop_encode')->where('order_id',$vv['orderId'])->value('id');
                                if($exs_code){
                                    DB::table('jdpop_encode')->where('order_id',$vv['orderId'])->update(['address_code'=>$vv['consigneeInfo']['fullAddress']]);
                                }else{
                                    DB::table('jdpop_encode')->insert(['order_id'=>$vv['orderId'],'address_code'=>$vv['consigneeInfo']['fullAddress'],'pt_id'=>$v['pt_id']]);
                                }
                                $fullAddress = '无';
                            }

                            $fullAddress = $fullAddress??$vv['consigneeInfo']['fullAddress'];
                            $fullAddress = str_replace("'", '', $fullAddress);
                            $resjdgoods = DB::table('jdgoods')->where("order_id",$vv['orderId'])->value('id');
                            unset($orderMsgData);
                            foreach( $vv['itemInfoList'] as $ka => $va ){
                                if(!$resjdgoods){
                                    $sql_dgoods .= "('".$vv['orderId']."',".$v['pt_id'].",'".$va['skuId']."','".$va['skuName']."','".$va['itemTotal']."','".$va['jdPrice']."','0'),";
                                    if(in_array($vv['orderId'], $arr_goods)){
                                        unset($arr_goods[$kk]);
                                    }

                                    $arr_goods[$kk]['order_id'] = $vv['orderId'];
                                    $arr_goods[$kk]['pt_id'] = $v['pt_id'];
                                    $arr_goods[$kk]['sku_id'] = $va['skuId'];
                                    $arr_goods[$kk]['item_total'] = $va['itemTotal'];
                                    $arr_goods[$kk]['jd_price'] = $va['itemTotal'];
                                    $arr_goods[$kk]['jd_cost'] = $va['jdPrice'];
                                    $arr_goods[$kk]['sku_name'] = $va['skuName'];
                                    DB::table('jdgoods')->insert($arr_goods[$kk]);
                                    unset($arr_goods[$kk]);

                                }
                                $sys_num = 'L'.$v['pt_id'].'P'.$kk.date("YmdHis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                                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['jdPrice'];//实收/商品单价
                                        // $orderMsgData['goods_paid'] = $va['jdPrice'];//应收
                                        $orderMsgData[$ka]['goods_num'] = $va['itemTotal'];
                                        $orderMsgData[$ka]['goods_brand'] = $goods_res['brand_name'];
                                        $orderMsgData[$ka]['goods_number'] = $type;
                                        $orderMsgData[$ka]['cd_id'] = 1;
                                        // dump($orderMsgData);
                                    }
                                }
                            }

                            //添单
//转换手机号
                            // $data['pt_name'] = $pt_name;//店铺名
                            $data_m[$kk]['order_id'] = $vv['orderId'];
                            $data_m[$kk]['appkey'] = $v['app_key'];		//appkey
                            $data_m[$kk]['appsecret'] = $v['app_secret'];	//secret
                            $data_m[$kk]['acctoken'] = $v['access_token'];	//token
                            $tel = $this->changeTelphone($data_m[$kk]);
                            if($flag==1){

                                $orders[$kk]['sys_bh'] = $sys_num;
                                $orders[$kk]['skb_bh'] = $vv['orderId'];
                                $orders[$kk]['pt_id'] = $v['pt_id'];
                                $orders[$kk]['ser_type'] = 1;//服务类型：1上门安装，2到店服务
                                $orders[$kk]['shr_name'] = $fullname;
                                $orders[$kk]['shr_phone'] = $tel??$vv['consigneeInfo']['telephone'];//$vv['consigneeInfo']['telephone'];//
                                $orders[$kk]['shr_sheng'] = $vv['consigneeInfo']['province'];//
                                $orders[$kk]['shr_shi'] = $vv['consigneeInfo']['city'];//
                                $orders[$kk]['shr_xian'] = $vv['consigneeInfo']['county'];//
                                $orders[$kk]['shr_adress'] = $fullAddress;//
                                $orders[$kk]['shr_other'] = '接单后10分钟内务必联系客户核实车型跟安装时间！不断电安装、如果无法完成 请立刻反馈我们处理~！';
                                $orders[$kk]['car_audit'] = 2;//1:新订单；2：可派单；3：处理中
                                $orders[$kk]['order_type'] = 1;//订单类型：1：普通；20加急；10：夜间
                                $orders[$kk]['order_time'] = $vv['orderStartTime'];
                                $orders[$kk]['pay_type'] = 1;//支付方式：1在线支付；2货到付款
                                $orders[$kk]['goods'] = $orderMsgData;
//                                $orders[$kk]['clientAccount'] = $fullpin;

                                //   $session = $request->get('session_token');//获取操作人信息
                                $session['admin_groupnew'] = 7;
                                $session['admin_acc'] = '系统录入';
                                $session['id'] = 1133;
                                $session['company_id'] = $company_id;
                                // dump($orders[$kk]);
                                $return = OrderaddService::addOrder($orders[$kk], $session, $ip);
                                //    dump($return);
                                CommonService::addLog('添加定单', json_encode($return), $vv['orderId'],'jd_addOrder');
                                // $return['ErrorCode'] = 2;
                                if($return['ErrorCode']==1 && $company_id!=14){
                                    //调用京东出库


                                    $res_ex = [];
                                    $res_ex['appKey'] = $v['app_key'];	//appkey
                                    $res_ex['appSecret'] = $v['app_secret'];//secret
                                    $res_ex['accessToken'] = $v['access_token'];	//token
                                    $res_ex['skb_bh'] = $vv['orderId'];//$vv['orderId'];
                                    $res_ex['jdid'] = 1274;
                                    $res_ex['kd_number'] = '';
                                    $res_ex['estimateDate'] = date("Y-m-d H:i:s");
                                    $result = $this->request_post($url_ex,$res_ex);//出库同步

                                    $filename = 'pop_ex'.date('Ym');
                                    CommonService::addLog('出库', json_encode($res_ex), $vv['orderId'],$filename);
                                    $reta = json_decode($result,true);
                                    if($reta['jingdong_pop_order_shipment_responce']['sopjosshipment_result']['success']==true){
                                        CommonService::addLog('添单成功出库', $result, $vv['orderId'],$filename);
                                    }else{
                                        CommonService::addLog('添单出库失败', $result, $vv['orderId'],$filename);
                                    }
                                    $newOrderId = true;
                                }else{
                                    $newOrderId = false;
                                }
                            }
                            $rea = DB::table('jd_proprietary')->where("order_id",$vv['orderId'])->value('id');
                            if (!$newOrderId || $flag=='2'){
                                //echo '添加订单信息失败';
                                if(!$rea){
                                    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'] = $v['pt_id'];
                                    $arr[$kk]['pay_type'] = $vv['payType'];
                                    $arr[$kk]['order_seller_price'] = $vv['orderSellerPrice'];
                                    $arr[$kk]['freight_price'] = $vv['freightPrice'];
                                    $arr[$kk]['order_state'] = $vv['orderState'];//'WAIT_SELLER_STOCK_OUT';
                                    $arr[$kk]['invoice_info'] = '不需要开具发票';
                                    $arr[$kk]['order_remark'] = '';
                                    $arr[$kk]['order_start_time'] = $vv['orderStartTime'];
                                    $arr[$kk]['fullname'] = $fullname;
                                    $arr[$kk]['mobile'] = $tel??$vv['consigneeInfo']['mobile'];
                                    $arr[$kk]['telephone'] = $tel??$vv['consigneeInfo']['telephone'];//
                                    $arr[$kk]['province'] = $vv['consigneeInfo']['province'];
                                    $arr[$kk]['city'] = $vv['consigneeInfo']['city'];
                                    $arr[$kk]['county'] = $vv['consigneeInfo']['county'];
                                    $arr[$kk]['full_address'] = $fullAddress;
                                    $arr[$kk]['order_pay'] = $vv['orderPayment'];
                                    $arr[$kk]['is_show'] = 1;
                                    $arr[$kk]['parent_orderid'] = $vv['parentOrderId'];
                                    DB::table('jd_proprietary')->insert($arr[$kk]);
                                    unset($arr[$kk]);
                                }
                            }else{
                                $reas = DB::table('jd_proprietary')->where("order_id",$vv['orderId'])->value('id');
                                if(!$reas){
                                    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'] = $v['pt_id'];
                                    $arr[$kk]['pay_type'] = $vv['payType'];
                                    $arr[$kk]['order_seller_price'] = $vv['orderSellerPrice'];
                                    $arr[$kk]['freight_price'] = $vv['freightPrice'];
                                    $arr[$kk]['order_state'] = 'WAIT_SELLER_STOCK_OUT';
                                    $arr[$kk]['invoice_info'] = '不需要开具发票';
                                    $arr[$kk]['order_remark'] = '';
                                    $arr[$kk]['order_start_time'] = $vv['orderStartTime'];
                                    $arr[$kk]['fullname'] = $fullname;
                                    $arr[$kk]['mobile'] = $tel??$vv['consigneeInfo']['mobile'];
                                    $arr[$kk]['telephone'] = $vv['consigneeInfo']['mobile'];//
                                    $arr[$kk]['province'] = $vv['consigneeInfo']['province'];
                                    $arr[$kk]['city'] = $vv['consigneeInfo']['city'];
                                    $arr[$kk]['county'] = $vv['consigneeInfo']['county'];
                                    $arr[$kk]['full_address'] = $fullAddress;
                                    $arr[$kk]['order_pay'] = $vv['orderPayment'];
                                    $arr[$kk]['is_show'] = 1;
                                    $arr[$kk]['parent_orderid'] = $vv['parentOrderId'];
                                    DB::table('jd_proprietary')->insert($arr[$kk]);
                                    unset($arr[$kk]);
                                }
                            }
                        }
                    }
                    echo '添加成功---';
                }
            }
            echo '操作成功--****';
        }
    }

    /**
     * @name 手机号转换
     * @param $data
     * @param $url
     * @author du
     * @date 2023/12/12
     * @Time: 10:51
     */
    public function changeTelphone($data){
        // $result = $this->request_post($url,$data);
        $url = 'jx.bluearp.com/m/index.php/Automatic/TzPopOrderGetPhone';
        $ret = $this->request_post($url, $data);
        $result = json_decode($ret,true);
        CommonService::addLog('手机号', $result['jingdong_pop_order_getmobilelist_responce']["result"]["data"][$data['order_id']]['consMobilePhone'].'----'.$ret.'---'.json_encode($data).'---'.$url, $data['order_id'],'jd_mobile');
        return $result['jingdong_pop_order_getmobilelist_responce']["result"]["data"][$data['order_id']]['consMobilePhone'];
    }

    /**
     * @name 出库
     * @param $data
     * @author du
     * @date 2024/3/21
     * @Time: 8:54
     */
    public function jdOrderEx($data){
        $json['orderId'] = $data['order_num'];
        $json['logiCoprId'] = 1274;
        $sysParams['method'] = "jingdong.pop.order.shipment";
        $sysParams['access_token'] = $data['accessToken'];
        $sysParams['app_key'] = $data['appKey'];//
        $sysParams['timestamp'] = date("Y-m-d H:i:s");
        $sysParams['v'] = '2.0';
        $apiParams["360buy_param_json"] = json_encode($json);
        $sysParams["sign"] = $this->generateSign(array_merge($sysParams, $apiParams),$data['appsecret']);
        $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://api-dev.jd.com/routerjson?".$urldata;
        $url = "https://api.jd.com/routerjson?".$urldata;
        $resp = $this->https_get($url);
        echo $resp;
    }

    private function generateSign($params,$sec) {
        if ($params != null) { // 所有请求参数按照字母先后顺序排序
            ksort($params);
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
            // 把所有参数名和参数值串在一起
            foreach ($params as $k => $v) {
                $stringToBeSigned .= "$k$v";
            }
            unset($k, $v);

            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
        } else {
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
        }
        // 使用MD5进行加密，再转化成大写

        return strtoupper(md5($stringToBeSigned));
    }

    /**
     * @name 定时解密
     * @author du
     * @date 2024/4/10
     * @Time: 10:14
     */
    public function decOrder(){

        $token = DB::table('jdpop_token')->where('status',1)->select('app_key','app_secret','access_token','pt_id')->get()->toarray();
        foreach ($token as $k =>$v) {
            //  CommonService::addLog('token', json_encode($v['app_key']), $v['pt_id'],'jd_token');
            $res_ult = [];
            $res_ult[$k]['appKey'] = $v['app_key'];        //appkey
            $res_ult[$k]['appSecret'] = $v['app_secret'];    //secret
            $res_ult[$k]['accessToken'] = $v['access_token'];    //token

            $list = DB::table('jdpop_encode')->where('is_enj',1)->where('pt_id',$v['pt_id'])->OrderBy('id','desc')->limit(10)->get();
            $list = CommonService::dataToArray($list);

            if($list){
                foreach ($list as $item) {
                    $user_id = Orders::where('order_num',$item['order_id'])->value('new_customer_id');
                    //解密
                    $fullname = $this->decrypt($res_ult[$k],$item['name_code'],$item['order_id']);
                    //  echo $fullname;
                    if(strpos($fullname,'<body>' )!==false){

                    }else{
                        //修改用户表
                        $res = User::where('id',$user_id)->update(['shr_name'=>$fullname]);
                    }
                    $address = $this->decrypt($res_ult[$k], $item['address_code'],$item['order_id']);
                    if(strpos($address,'<body>' )!==false){
                    }else{
                        //修改用户表
                        $ret = User::where('id',$user_id)->update(['shr_adress'=>$address]);
                    }
                    if($res && $ret){
                        DB::table('jdpop_encode')->where('order_id',$item['order_id'])->update(['is_enj'=>2]);
                    }

                    CommonService::addLog('JD', $fullname.'--'.$address, $item['order_id'],'JDPOP-dec');

                }
            }

        }
    }


    /**
     * @name 解密
     * @param $data
     * @return string
     * @author du
     * @date 2024/3/29
     * @Time: 9:54
     */
    public function decrypt($data,$str,$order_num = ''){
        if(preg_match("/[\x7f-\xff]/",$str)){
            return $str;
        }
        $data['str'] = str_replace('+', '%2B', $str);
        $decrypt_data = json_encode($data);
        $url = "http://jm.bluearp.com/jd/jdDecrypt?data=".$decrypt_data;
        $res = (string)$this->https_request($url);
        $filename = 'url'.date('Ymd');
        CommonService::addLog('URL', $order_num.'---'.$url.'----'.$res, 111,$filename);
        return $res;
    }


    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;
    }
}
