<?php
/**
 * 文件名称（同步京东供销平台数据数据）
 * 文件简单描述（同步京东供销平台数据数据）
 * @author DouBin
 * @Date: 2025/7/4
 * @Time: 16:13
 * @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\OrderaddService;
use App\Services\OrderService;
use App\Services\RefundService;
use Illuminate\Http\Request;
use DB;


class SynJdPurchaseController extends BaseController
{

    /**
     * @name 同步京东供销平台未出库定单
     * @param Request $request
     * @author du
     * @date 2022/4/27
     */
    public function addOrderData (){
        $time_start = date("Y-m-d H:i:s",strtotime(" -10 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',3)->select('app_key','app_secret','access_token','pt_id')->get()->toarray();
        foreach ($token as $k =>$v){
            $json['pageSize']='100';
            $json['startDate']=$time_start;
            $json['endDate']=$time_end;
            $json['orderStates']='0';
            $sysParams['method']="jingdong.purchase.order.select.infos.scroll";
            $sysParams['access_token']=$v['access_token'];
            $sysParams['app_key']=$v['app_key'];
            $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),$v['app_secret']);
            $apiParams=array_merge($sysParams, $apiParams);
            ksort($apiParams);
            foreach( $apiParams as $kd => $vd ){
                if(strpos($vd,' ')){
                    $urldata[]=$kd."=".urlencode ($vd);
                }else{
                    $urldata[]=$kd."=".$vd;
                }
            }
            $urldata=implode("&",$urldata);
            $url="https://api.jd.com/routerjson?".$urldata;
            $resp = $this->https_get($url);
            CommonService::addLog('token1--'.$v['pt_id'], json_encode($apiParams).'-获取京东供销数据-'.$resp, $v['pt_id'],'JdPurchase-getdata');
            $res_data = json_decode($resp, true, 100, JSON_BIGINT_AS_STRING);
            if (!is_array($res_data)) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($apiParams).'-获取京东供销数据失败1', $v['pt_id'],'JdPurchase-error');
                continue;
            }
            if (!isset($res_data['jingdong_purchase_order_select_infos_scroll_responce']['result'])) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($apiParams).'-获取京东供销数据失败2', $v['pt_id'],'JdPurchase-error');
                continue;
            }
            $result = $res_data['jingdong_purchase_order_select_infos_scroll_responce']['result'];
            if (!isset($result['code']) || $result['code']!=1) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($apiParams).'-'.$result['msg'], $v['pt_id'],'JdPurchase-error');
                continue;
            }
            if (!isset($result['data'])) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($apiParams).'-获取京东供销数据失败3', $v['pt_id'],'JdPurchase-error');
                continue;
            }
            $company_id = Pt::where("id",$v['pt_id'])->value('company_id');
            $data = $result['data'];
            $orderInfos=[];
            $num = 0;
            foreach($data as $ks => $vs){
                if(!empty($vs['oaid'])) {
                    $orderInfos[$num]['orderId'] = $vs['orderId'];
                    $orderInfos[$num]['oaid'] = $vs['oaid'];
                    $num++;
                }
            }
            if(!empty($orderInfos)){
                $poss['appKey'] = $v['app_key'];
                $poss['accessToken'] = $v['access_token'];
                $poss['appSecret'] = $v['app_secret'];
                $poss['orderInfos'] = json_encode($orderInfos);
                $user_data=$this->https_request('http://116.196.75.172/index.php/GetUserDataApi/getOaidDecrypt',$poss);
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($poss).'-获取脱敏信息失败'.json_encode($user_data), $v['pt_id'],'JdPurchase-getOaidDecrypt');
                $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($data as $ka => $va){
                            $data[$ka]['user_data_dou'] = isset($user_datas[$va['orderId']])?$user_datas[$va['orderId']]:'';
                        }
                    }
                }
            }
            $arr_goods = [];
            $arr = [];
            $ip = $_SERVER["REMOTE_ADDR"];
            foreach($data as $kk => $vv){
                $order_info = OrderService::getOrderBy('order_num', $vv['orderId'],['id']);
                if($order_info){
                    continue;
                }
                $flag = 1;
                $skuId = array_column($vv['skuList'], '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'],'JdPurchase-无sku');
                    $flag = 2;
                }
                if($goodids){
                    if(count($goodids)<count($vv['skuList'])){
                        $flag = 2;
                    }
                }
                $fullname = $vv['user_data_dou']['customerName']??$vv['consumerName'];
                $fullAddress = $vv['user_data_dou']['address']??$vv['consumerAddress'];
                $tel = $vv['user_data_dou']['consMobilePhone']??$vv['consumerTel'];
                $resjdgoods = DB::table('jdgoods')->where("order_id",$vv['orderId'])->value('id');
                $price = 0;
                $orderMsgData = [];
                foreach( $vv['skuList'] as $ka => $va ){
                    $price= $price+$va['cgPrice'];
                    if(!$resjdgoods){
                        $sql_dgoods .= "('".$vv['orderId']."',".$v['pt_id'].",'".$va['skuId']."','".$va['skuNum']."','".$va['cgPrice']."','".$va['cgPrice']."','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'];//平台id
                        $arr_goods[$kk]['sku_id'] = $va['skuId'];//京东sku
                        $arr_goods[$kk]['item_total'] = $va['skuNum'];//商品数量
                        $arr_goods[$kk]['jd_price'] = $va['cgPrice'];//京东单价
                        $arr_goods[$kk]['jd_cost'] = $va['cgPrice'];//采购价
                        $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['cgPrice'];//实收/商品单价
                            // $orderMsgData['goods_paid'] = $va['jdPrice'];//应收
                            $orderMsgData[$ka]['goods_num'] = $va['skuNum'];
                            $orderMsgData[$ka]['goods_brand'] = $goods_res['brand_name'];
                            $orderMsgData[$ka]['goods_number'] = $type;
                            $orderMsgData[$ka]['cd_id'] = 1;
                            // dump($orderMsgData);
                        }
                    }
                }
                /**********************************************添加订单信息******************************************/
                if($flag==1){

                    $orders[$kk]['sys_bh'] = $sys_num;
                    $orders[$kk]['skb_bh'] = $vv['orderId'];//平台单号
                    $orders[$kk]['pt_id'] = $v['pt_id'];//平台id
                    $orders[$kk]['ser_type'] = 1;//服务类型：1上门安装，2到店服务
                    $orders[$kk]['shr_name'] = $fullname;//姓名
                    $orders[$kk]['shr_phone'] = $tel;//$vv['telephone'];//电话
                    $orders[$kk]['shr_sheng'] = $vv['areaProvince'];//省份
                    $orders[$kk]['shr_shi'] = $vv['areaCity'];//城市
                    $orders[$kk]['shr_xian'] = $vv['areaCounty'];//区县
                    $fullAddress = str_replace($vv['areaProvince'].$vv['areaCity'].$vv['areaCounty'], '', $fullAddress);
                    $orders[$kk]['shr_adress'] = $fullAddress;//
                    $orders[$kk]['shr_other'] = $vv['orderRemark'].'接单后10分钟内务必联系客户核实车型跟安装时间！不断电安装、如果无法完成 请立刻反馈我们处理~！';
                    $orders[$kk]['car_audit'] = 2;//1:新订单；2：可派单；3：处理中
                    $orders[$kk]['order_type'] = 1;//订单类型：1：普通；20加急；10：夜间
                    $orders[$kk]['order_time'] = $vv['orderTime']??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'],'jd_addSelfOrder');
                    // $return['ErrorCode'] = 2;
                    if($return['ErrorCode']==1){
                        $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'];//平台id
                        $arr[$kk]['pay_type'] = $vv['paymentType'];//支付方式
                        $arr[$kk]['order_seller_price'] = $price;//订单金额
                        $arr[$kk]['freight_price'] = 0;//运费
                        $arr[$kk]['order_state'] = $vv['orderState'];//'WAIT_SELLER_STOCK_OUT';//订单状态 5新订单;9正在出库;10 出库成功;15正在发货;16发货成功;23等待退款
                        $arr[$kk]['invoice_info'] = '不需要开具发票';//'发票1开2不开'
                        $arr[$kk]['order_remark'] = $vv['orderRemark']??'';//订单备注
                        $arr[$kk]['order_start_time'] = $vv['orderTime']??date("Y-m-d H:i:s");//下单时间
                        $arr[$kk]['fullname'] = $fullname;//客户姓名
                        $arr[$kk]['mobile'] = $tel;//客户手机
                        $arr[$kk]['telephone'] = $tel;//客户电话
                        $arr[$kk]['province'] = $vv['areaProvince'];//省
                        $arr[$kk]['city'] = $vv['areaCity'];//市
                        $arr[$kk]['county'] = $vv['areaCounty'];//区县
                        $arr[$kk]['full_address'] = $fullAddress;//详细地址
                        $arr[$kk]['order_pay'] = $price;//实收金额
                        $arr[$kk]['is_show'] = 2;//'1 未填单 2 已填单 3 已删除 4 已完成'
                        $arr[$kk]['parent_orderid'] = $vv['purchaseId'];//父类单号
                        DB::table('jd_proprietary')->insert($arr[$kk]);
                        unset($arr[$kk]);
                    }
                }else{
                    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'];//平台id
                        $arr[$kk]['pay_type'] = $vv['paymentType'];//支付方式
                        $arr[$kk]['order_seller_price'] = $price;//订单金额
                        $arr[$kk]['freight_price'] = 0;//运费
                        $arr[$kk]['order_state'] = $vv['orderState'];//'WAIT_SELLER_STOCK_OUT';//订单状态 5新订单;9正在出库;10 出库成功;15正在发货;16发货成功;23等待退款
                        $arr[$kk]['invoice_info'] = '不需要开具发票';//'发票1开2不开'
                        $arr[$kk]['order_remark'] = $vv['orderRemark']??'';//订单备注
                        $arr[$kk]['order_start_time'] = $vv['orderTime']??date("Y-m-d H:i:s");//下单时间
                        $arr[$kk]['fullname'] = $fullname;//客户姓名
                        $arr[$kk]['mobile'] = $tel;//客户手机
                        $arr[$kk]['telephone'] = $tel;//客户电话
                        $arr[$kk]['province'] = $vv['areaProvince'];//省
                        $arr[$kk]['city'] = $vv['areaCity'];//市
                        $arr[$kk]['county'] = $vv['areaCounty'];//区县
                        $arr[$kk]['full_address'] = $fullAddress;//详细地址
                        $arr[$kk]['order_pay'] = $price;//实收金额
                        $arr[$kk]['is_show'] = 1;//'1 未填单 2 已填单 3 已删除 4 已完成'
                        $arr[$kk]['parent_orderid'] = $vv['purchaseId'];//父类单号
                        DB::table('jd_proprietary')->insert($arr[$kk]);
                        unset($arr[$kk]);
                    }
                }
                /*********************************************************************************************/
            }
            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;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取退款订单
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/7/20 17:09
     * |---------------------------------------------------------------------------------
     */
    public function getPurchaseRefund ( ){
        $time_start = date("Y-m-d H:i:s",strtotime(" -10 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();
        $token = DB::table('jdpop_token')->where('status',1)->where('type',3)->select('app_key','app_secret','access_token','pt_id')->get()->toarray();
        foreach ($token as $k =>$v) {
            $json['pageSize'] = '100';
            $json['updateBeginTime'] = $time_start;
            $json['updateEndTime'] = $time_end;
//            $json['orderStates'] = '2，6，7';
            $sysParams['method'] = "jingdong.purchase.order.select.infos.scroll";
            $sysParams['access_token'] = $v['access_token'];
            $sysParams['app_key'] = $v['app_key'];
            $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), $v['app_secret']);
            $apiParams = array_merge($sysParams, $apiParams);
            ksort($apiParams);
            foreach ($apiParams as $kd => $vd) {
                if (strpos($vd, ' ')) {
                    $urldata[] = $kd . "=" . urlencode($vd);
                } else {
                    $urldata[] = $kd . "=" . $vd;
                }
            }
            $urldata = implode("&", $urldata);
            $url = "https://api.jd.com/routerjson?" . $urldata;
            $resp = $this->https_get($url);
            CommonService::addLog('token1--' . $v['pt_id'], json_encode($apiParams) . '-获取京东供销数据-' . $resp, $v['pt_id'], 'JdPurchaseRefund-getdata');
            $res_data = json_decode($resp, true, 100, JSON_BIGINT_AS_STRING);
            if (!is_array($res_data)) {
                CommonService::addLog('token1--' . $v['pt_id'], json_encode($apiParams) . '-获取京东供销数据失败1', $v['pt_id'], 'JdPurchaseRefund-error');
                continue;
            }
            if (!isset($res_data['jingdong_purchase_order_select_infos_scroll_responce']['result'])) {
                CommonService::addLog('token1--' . $v['pt_id'], json_encode($apiParams) . '-获取京东供销数据失败2', $v['pt_id'], 'JdPurchaseRefund-error');
                continue;
            }
            $result = $res_data['jingdong_purchase_order_select_infos_scroll_responce']['result'];
            if (!isset($result['code']) || $result['code'] != 1) {
                CommonService::addLog('token1--' . $v['pt_id'], json_encode($apiParams) . '-' . $result['msg'], $v['pt_id'], 'JdPurchaseRefund-error');
                continue;
            }
            if (!isset($result['data'])) {
                CommonService::addLog('token1--' . $v['pt_id'], json_encode($apiParams) . '-获取京东供销数据失败3', $v['pt_id'], 'JdPurchaseRefund-error');
                continue;
            }
            $data = $result['data'];
            foreach($data as $kk => $vv) {
                if (in_array($vv['orderState'], [2, 6, 7])) {
                    $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 ($order_info['lock_type'] == 2 || in_array($order_info['order_status'], [50, 55])) {
                            continue;
                        } 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;
                            if ($vv['orderState'] == '2') {
                                $content = '平台已经取消订单';
                            } elseif ($vv['orderState'] == '6') {
                                $content = '平台已经锁定订单';
                            } else {
                                $content = '平台订单待审核';
                            }
                            $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,JSON_UNESCAPED_UNICODE).'-----'.json_encode($datar,JSON_UNESCAPED_UNICODE), $vv['orderId'], 'JdPurchaseRefund-cancel');
                            continue;
                        }
                    }else{
                        continue;
                    }
                }
            }
        }
    }

    private function generateSign($params,$sec='8de8b7903e7740abb9ac6ec39f22c0e5') {
        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(){
      /*  $str = "AAQLAodRrJ360+b6qYevz+HgyXHUehSiWki+A9YqUJVvonqI1G8rNALcCZYF9eo5A5M=";
        $data['accessToken'] = 'e0a1c90e617f4b3a9865ed059f99c5f42ztb';
        $data['appKey'] = '41D9668E8CB81C9890A065BEC300FD84';
        $data['appSecret'] = '93bff142bf5c4422ae7bec9eb992e751';

        return $this->decrypt($data,$str);
        exit;*/

        $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')->value('new_customer_id');
                    //解密
                $fullname = $this->decrypt($res_ult[$k],$item['name_code']);
              //  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']);
                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){
        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;
        //CommonService::addLog('URL', $url, 111,'url');
        return (string)$this->https_request($url);

       /* // 判断是否需要解密 ReceiverAddress  ReceiverMobile ReceiverName
        if ($pop_ptdata['is_decrypt'] == 2) {

            $jmdecrypt_num = 0;
            if (mb_strlen($data['ReceiverName']) > 50) {
                $decrypt_data = [];
                $decrypt_data['dp'] = $pop_ptdata['pt_name'];
                $decrypt_data['jmstr'] = str_replace('+', '%2B', $data['ReceiverName']);
                $decrypt_data = json_encode($decrypt_data);
                $url = "http://jm.bluearp.com/jd/test?str=" . $decrypt_data;
                $data['ReceiverName'] = (string)$this->https_request($url);
                $jmdecrypt_num++;
            }

            if (mb_strlen($data['ReceiverMobile']) > 30) {
                $decrypt_data = [];
                $decrypt_data['dp'] = $pop_ptdata['pt_name'];
                $decrypt_data['jmstr'] = str_replace('+', '%2B', $data['ReceiverMobile']);
                $decrypt_data = json_encode($decrypt_data);
                $url = "http://jm.bluearp.com/jd/test?str=" . $decrypt_data;
                $data['ReceiverMobile'] = (string)$this->https_request($url);
                $jmdecrypt_num++;
            }
            if (strpos($data['ReceiverMobile'], "*") !== false) {
                $phone = $this->PopOrderGetPhone($pop_ptdata['appKey'], $pop_ptdata['appSecret'], $pop_ptdata['accessToken'], $data['TidStr']);
                if ($phone != '') {
                    $data['ReceiverMobile'] = $phone;
                }
            }

            if ($jmdecrypt_num > 0) {
                $decrypt_data = [];
                $decrypt_data['dp'] = $pop_ptdata['pt_name'];
                $decrypt_data['jmstr'] = str_replace('+', '%2B', $data['ReceiverAddress']);
                $decrypt_data = json_encode($decrypt_data);
                $url = "http://jm.bluearp.com/jd/test?str=" . $decrypt_data;
                $data['ReceiverAddress'] = (string)$this->https_request($url);
            }
        }*/
    }


    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;
    }
    public function https_get ($url){
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );
        $resp = file_get_contents($url, false, stream_context_create($arrContextOptions));
        return $resp;
    }
}
