<?php
/**
 * 测试文件（权限服务）
 * 文件简单描述（权限基础操作权限）
 * @author DouBin
 * @Date: 2023-07-07 007
 * @Time: 下午 3:59:11
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Http\Controllers\Dou;

use App\Exports\BasicExport;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Orders\AotuorderController;
use App\Models\Admin;
use App\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\OrderRejected;
use App\Models\Orders;
use App\Models\User;
use App\Services\CommonService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use Chumper\Zipper\Zipper;
use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\TechnicalLevelService;
use BlueCity\Core\Inc\ErrorInc;
use DB;

class MyTestController extends BaseController
{
    public function test ( Request $request ){
        $input = $request->all();
        $AotuorderController = new AotuorderController();
        $data = $AotuorderController->Distrib($input['sys_num'], '192.168.1.140');
        return response()->json(['code'=>201, 'msg'=>'授权失败', 'data'=>$data]);
    }

    /**|---------------------------------------------------------------------------------
     * @name 方法入口
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/8/20 10:59
     * |---------------------------------------------------------------------------------
     */
    public function dataApi ( Request $request ){
        $input = $request->all();
        if(empty($input['method'])){
            return $this->error('缺少必要参数1',ErrorInc::FAILED_PARAM);
        }
        $api=['getSerStatistics','getSerStatisticsDetail','BasicExport','addOrderData'];
        if(!in_array($input['method'],$api)){
            return $this->error('接口不参数异常',ErrorInc::INVALID_PARAM,$input);
        }else {
            $api = (string)$input['method'];
            return $this->$api($input);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取京东token
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/29 8:56
     * |---------------------------------------------------------------------------------
    */
    public function getSerStatistics ( $input ){
        if(empty($input['company_id'])){
            $html="<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><h1>请输入公司id</h1></html>";
            echo $html;exit;
        }
        $admindata = Admin::whereRaw("((company_id='".$input['company_id']."' and admin_groupnew=2) or admin_groupnew=3) and enable=1")
            ->select('id','company_name')
            ->get();
        $admindata = CommonService::dataToArray($admindata);
        if($admindata){
            $time_start = $input['time_start'];
            $time_end = date("Y-m-d", strtotime($input['time_end'] . " +1 day"));
            $html = "<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><table>";
            $html .= "<tr>";
            $html .= "<td rowspan='2'>序号</td><td rowspan='2'>服务商（公司名称）</td><td colspan='6'>本周".date("m-d", strtotime($input['time_start']))."-".date("m-d", strtotime($input['time_end']))."</td><td colspan='6'>累计至今</td>";
            $html .= "</tr>";
            $html .= "<tr>";
            $html .= "<td>总推送单量</td><td>接单量</td><td>拒单量</td><td>拒单率</td><td>接单时效</td><td>履约时效</td><td>总推送单量</td><td>接单量</td><td>拒单量</td><td>拒单率</td><td>接单时效</td><td>履约时效</td>";
            $html .= "</tr>";
            foreach($admindata as $k => $v){
                $order_listnum = OrderList::whereRaw("ser_id='".$v['id']."' and create_time BETWEEN '".$time_start."' and '".$time_end."' and is_delete=1 and get_time != '' and company_id = '".$input['company_id']."'")->count();//接单数量
                $order_rejectednum = OrderRejected::leftjoin('orders', 'or_order_num', '=', 'order_num')->whereRaw("or_ser_id='".$v['id']."' and or_creact_time BETWEEN '".$time_start."' and '".$time_end."' and or_show=1 and company_id = '".$input['company_id']."'")->count();//拒单数量
                $order_listAllnum = OrderList::whereRaw("ser_id='".$v['id']."' and create_time BETWEEN '2024-08-19' and '".$time_end."' and is_delete=1 and get_time != '' and company_id = '".$input['company_id']."'")->count();//总接单数量
                $order_rejectedAllnum = OrderRejected::leftjoin('orders', 'or_order_num', '=', 'order_num')->whereRaw("or_ser_id='".$v['id']."' and or_creact_time BETWEEN '2024-08-19' and '".$time_end."' and or_show=1 and company_id = '".$input['company_id']."'")->count();//总拒单数量
                $sql = "SELECT CAST((SUM(UNIX_TIMESTAMP(feeds_time))-SUM(UNIX_TIMESTAMP(get_time)))/COUNT(id) as SIGNED) as timenum FROM gone_order_list WHERE ser_id='".$v['id']."' and get_time != '' and get_time!='0000-00-00 00:00:00' and feeds_time != '' and feeds_time!='0000-00-00 00:00:00' and create_time BETWEEN '".$time_start."' and '".$time_end."' and is_delete=1 and company_id = '".$input['company_id']."'";
                $data = DB::select($sql);
                $sql1 = "SELECT CAST((SUM(UNIX_TIMESTAMP(get_time))-SUM(UNIX_TIMESTAMP(create_time)))/COUNT(id) as SIGNED) as pdnum FROM gone_order_list WHERE ser_id='".$v['id']."' and get_time != '' and get_time!='0000-00-00 00:00:00' and create_time BETWEEN '".$time_start."' and '".$time_end."' and time(create_time)>='08:30:00' and time(create_time)<='18:00:00' and is_delete=1 and company_id = '".$input['company_id']."'";
                $data1 = DB::select($sql1);
                $sqls = "SELECT CAST((SUM(UNIX_TIMESTAMP(feeds_time))-SUM(UNIX_TIMESTAMP(get_time)))/COUNT(id) as SIGNED) as timenum FROM gone_order_list WHERE ser_id='".$v['id']."' and create_time BETWEEN '2024-08-19' and '".$time_end."' and get_time != '' and get_time!='0000-00-00 00:00:00' and feeds_time != '' and feeds_time!='0000-00-00 00:00:00' and is_delete=1 and company_id = '".$input['company_id']."'";// and is_delete=1
                $datas = DB::select($sqls);
                $sqls1 = "SELECT CAST((SUM(UNIX_TIMESTAMP(get_time))-SUM(UNIX_TIMESTAMP(create_time)))/COUNT(id) as SIGNED) as pdnum FROM gone_order_list WHERE ser_id='".$v['id']."' and create_time BETWEEN '2024-08-19' and '".$time_end."' and get_time != '' and get_time!='0000-00-00 00:00:00' and time(create_time)>='08:30:00' and time(create_time)<='18:00:00' and is_delete=1 and company_id = '".$input['company_id']."'";// and is_delete=1
                $datas1 = DB::select($sqls1);
                $html .= "<tr>";
                $html .= "<td>".$v['id']."</td>";
                $html .= "<td>".$v['company_name']."</td>";
                $html .= "<td>".($order_listnum+$order_rejectednum)."</td>";
                $html .= "<td>".$order_listnum."</td>";
                $html .= "<td>".$order_rejectednum."</td>";
                if(($order_listnum+$order_rejectednum) == 0){
                    $html .= "<td>0.00%</td>";
                }else {
                    $gl = sprintf("%.2f", $order_rejectednum / ($order_listnum + $order_rejectednum) * 100);
                    $html .= "<td>" . $gl . "%</td>";
                }
                if($data){
                    $html .= "<td>".self::Compute_Time($data1[0]['pdnum'])."</td>";
                    $html .= "<td>".self::Compute_Time($data[0]['timenum'])."</td>";
                }else{
                    $html .= "<td>0时0分0秒</td>";
                    $html .= "<td>0时0分0秒</td>";
                }
                $html .= "<td>".($order_listAllnum+$order_rejectedAllnum)."</td>";
                $html .= "<td>".$order_listAllnum."</td>";
                $html .= "<td>".$order_rejectedAllnum."</td>";
                if(($order_listAllnum+$order_rejectedAllnum) == 0){
                    $html .= "<td>0.00%</td>";
                }else {
                    $gls = sprintf("%.2f", $order_rejectedAllnum / ($order_listAllnum + $order_rejectedAllnum) * 100);
                    $html .= "<td>" . $gls . "%</td>";
                }
                if($data){
                    $html .= "<td>".self::Compute_Time($datas1[0]['pdnum'])."</td>";
                    $html .= "<td>".self::Compute_Time($datas[0]['timenum'])."</td>";
                }else{
                    $html .= "<td>0时0分0秒</td>";
                    $html .= "<td>0时0分0秒</td>";
                }
                $html .= "</tr>";

            }
            $html .= "<table></html>";
            echo $html;
        }else{
            $html="<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><h1>无相应公司信息</h1></html>";
            echo $html;exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取订单门店施工明细
     * @param string company_id 公司id
     * @param string time_start 开始时间
     * @param string time_end 结算是啊金
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 17:27
     * |---------------------------------------------------------------------------------
     */
    public function getSerStatisticsDetail ( $input ){
        if(empty($input['company_id'])){
            $html="<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><h1>请输入公司id</h1></html>";
            echo $html;exit;
        }
//        $admindata = Admin::where('company_id',$input['company_id'])
//            ->where('admin_groupnew',2)
//            ->where('enable',1)
//            ->pluck('company_name','id');
        $admindata = Admin::whereRaw("((company_id='".$input['company_id']."' and admin_groupnew=2) or admin_groupnew=3) and enable=1")
            ->pluck('company_name','id');
        $time_start = $input['time_start'];
        $time_end = date("Y-m-d", strtotime($input['time_end'] . " +1 day"));
        $sql = "SELECT (UNIX_TIMESTAMP(feeds_time)-UNIX_TIMESTAMP(get_time)) AS sgtime,(UNIX_TIMESTAMP(get_time)-UNIX_TIMESTAMP(create_time)) AS jdtime,stauas,order_num,ser_id,create_time,get_time,feeds_time FROM gone_order_list WHERE create_time BETWEEN '".$time_start."' and '".$time_end."' and is_delete=1 and company_id = ".$input['company_id']." order by create_time";
        $datas = DB::select($sql);
        $statusName = ['10'=>'未接单','20'=>'未接单','30'=>'安装中','34'=>'待审核','40'=>'已完成','50'=>'已撤销','55'=>'已撤销（补邮费）'];
        $html = "<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><table>";
        $html .= "<tr>";
        $html .= "<td>门店名称</td><td>单号</td><td>订单状态</td><td>创建时间</td><td>接单时间</td><td>反馈时间</td><td>接单时效</td><td>5分钟接单达标</td><td>10钟接单达标</td><td>履约时效</td><td>12小时履约达标</td><td>24小时履约达标</td><td>是否计入时效考核</td>";
        $html .= "</tr>";
        foreach($datas as $k => $v){
            $html .= "<tr>";
            $html .= "<td>".$admindata[$v['ser_id']]."</td>";
            $html .= "<td>".$v['order_num']."</td>";
            $html .= "<td>".$statusName[$v['stauas']]."</td>";
            $html .= "<td>".$v['create_time']."</td>";
            $html .= "<td>".$v['get_time']."</td>";
            $html .= "<td>".$v['feeds_time']."</td>";
            if($v['get_time'] != '' && $v['get_time'] != '0000-00-00 00:00:00'){
                $html .= "<td>".self::Compute_Time($v['jdtime'])."</td>";
                if($v['jdtime']<300){
                    $html .= "<td>达标</td>";
                }else{
                    $html .= "<td>不达标</td>";
                }
                if($v['jdtime']<600){
                    $html .= "<td>达标</td>";
                }else{
                    $html .= "<td>不达标</td>";
                }
            }else{
                $html .= "<td></td>";
                $html .= "<td>不达标</td>";
                $html .= "<td>不达标</td>";
            }

            if($v['feeds_time'] != '' && $v['feeds_time'] != '0000-00-00 00:00:00'){
                $html .= "<td>".self::Compute_Time($v['sgtime'])."</td>";
                if($v['sgtime']<43200){
                    $html .= "<td>达标</td>";
                }else{
                    $html .= "<td>不达标</td>";
                }
                if($v['sgtime']<86400){
                    $html .= "<td>达标</td>";
                }else{
                    $html .= "<td>不达标</td>";
                }
            }else{
                $html .= "<td></td>";
                $html .= "<td>不达标</td>";
                $html .= "<td>不达标</td>";
            }
            $time = explode(' ', $v['create_time'])[1];
            if($time>='08:30:00' && $time<='18:00:00'){
                $html .= "<td>是</td>";
            }else{
                $html .= "<td>否</td>";
            }
            $html .= "</tr>";
        }
        $html .= "<table></html>";
        echo $html;
    }
    /**|---------------------------------------------------------------------------------
     * @name 转化为时分秒
     * @param string timediff 时间
     * @retrun  /multitype:string
     * @author dou 2024/8/23 11:43
     * |---------------------------------------------------------------------------------
     */
    private function Compute_Time( $timediff ){
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        //$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $res = $days.'天'.$hours.'时'.$mins.'分'.$secs.'秒';
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 自定义表头
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/10/22 14:43
     * |---------------------------------------------------------------------------------
    */
    public function BasicExport ( $input ){
        $exporter = New BasicExport();
//        $ewa = $exporter->creacrExporSerStatisticsDetail(json_decode($data,true));
//        $data = [];
//        $data[0] = $ewa;
//        return $this->error('接口不参数异常',ErrorInc::INVALID_PARAM,$data);
        $con='SerStatisticsDetail';
//        $id = intval($request->input('el_id'));
        $id = $input['el_id'];
        $res = DB::table("excel_list")
            ->where('el_id',$id)
            ->where('el_state','1')
            ->select("el_action","el_id","el_sql","el_path","el_item","el_adminid","company_id")
            ->orderBy('el_id','ASC')->first();
        if($res) {
            if (!file_exists($res['el_path'])) {
                // 创建文件夹
                mkdir($res['el_path'], 0775, true);
                chmod($res['el_path'], 0775);
            }
            $detail = DB::table("excel_detail")->where("ed_elid", $res['el_id'])->where("ed_state", '1')->first();
            if ($detail) {
                $data = $exporter->creacrExporHeader($con, $res, $detail, 'B2');
                if ($data['db']) {
                    $return = $exporter->addExceleDara($res, $detail, $data['file'], $data['db'], $data['group']);
                    return $this->success('操作成功1');
                } else {
                    DB::table("excel_detail")->where("ed_id", $detail['ed_id'])->update(['ed_state' => 2]);
                    return $this->success('操作成功2');
                }
            } else {
                DB::table("excel_list")->where('el_id', $res['el_id'])->update(['el_state' => 2]);
                return $this->success('操作成功3');
            }
        }else{
            $path = DB::table('excel_list')->where('el_id',$id)->value('el_path');
            $zipper = new Zipper();
            $arr = glob(public_path($path));   //$public_path  被压缩的文件名
            $reduce_path = $path.'.zip';
            $zipper->make(public_path($reduce_path))->add($arr)->close();  //public_path($reduce_path)  压缩之后 */
            $zip = new \ZipArchive();
            $zipStatus = $zip->open($reduce_path);
            if ($zipStatus !== true) {
                return $this->error('压缩失败', ErrorInc::FAILED_PARAM);exit;
            }
            DB::table("excel_list")->where('el_id',$id)->update(['el_state'=>2]);
            //	 = $this->baseurl().$reduce_path;
            return response()->json(['Data' =>'', 'ErrorMessage' => '执行完毕', 'ErrorCode' => 222]);exit;
        }

    }

    /**
     * @name 同步京东POP店未出库定单
     * @param Request $request
     * @author du
     * @date 2022/4/27
     */
    public function addOrderData ($input){
        $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(" -3420 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';    //获取的订单字段

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

            $res_ult[$k]['page'] = 1;
            $res = $this->request_post($url,$res_ult[$k]);
            $ip = $_SERVER["REMOTE_ADDR"];
            $res='{"jingdong_pop_order_enSearch_responce":{"code":"0","request_id":"161875.39587.17333121021090126","searchorderinfo_result":{"apiResult":{"chineseErrCode":"成功","numberCode":10100000,"englishErrCode":"success","success":true},"orderTotal":35,"orderInfoList":[{"orderSellerPrice":"10.00","orderType":"22","venderRemark":"","logisticsId":"","orderId":"300473755730","sendpayMap":"{\"9\":\"2\",\"20\":\"5\",\"26\":\"2\",\"29\":\"1\",\"34\":\"3\",\"36\":\"1\",\"39\":\"1\",\"50\":\"1\",\"51\":\"6\",\"62\":\"1\",\"64\":\"2\",\"84\":\"1\",\"96\":\"1\",\"173\":\"2\",\"186\":\"1\",\"188\":\"3\",\"190\":\"2\",\"191\":\"1\",\"229\":\"1\",\"235\":\"2\",\"239\":\"2\",\"342\":\"1\",\"402\":\"3\",\"847\":\"1\",\"860\":\"1\",\"943\":\"1\",\"1007\":\"1\"}","orderRemark":"","venderId":"18433933","paymentConfirmTime":"2024-12-04 19:03:51","orderStateRemark":"等待出库","orderState":"WAIT_SELLER_STOCK_OUT","popSignMap":"{\"11\":\"1\",\"19\":\"1\"}","itemInfoList":[{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFB60/探界者/别克E5E6/本田/大众/奥迪","itemTotal":"1","outerSkuId":"","jdPrice":"608.00","invoiceContentId":"","skuId":"10127082830913","productNo":"","newStoreId":"0"},{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFB70/昂科拉/君越/创酷/科沃兹/威朗/丰田","itemTotal":"1","outerSkuId":"","jdPrice":"678.00","invoiceContentId":"","skuId":"10127082830914","productNo":"","newStoreId":"0"},{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFB80/君越/君威/威朗","itemTotal":"1","outerSkuId":"","jdPrice":"769.00","invoiceContentId":"","skuId":"10127082830915","productNo":"","newStoreId":"0"},{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFBQ85/马自达/奔腾/铃木/凯美瑞/汉兰达","itemTotal":"1","outerSkuId":"","jdPrice":"609.00","invoiceContentId":"","skuId":"10127082830916","productNo":"","newStoreId":"0"}],"payType":"4-在线支付","totalSellerReceivable":"10.000000","modified":"2024-12-04 19:04:05","freightPrice":"0.00","vatInfo":{},"balanceUsed":"0.00","orderSource":"移动端订单","invoiceInfo":"不需要开具发票","totalSellerDiscount":"2654.000000","shouldPay":"10.00","orderTotalPrice":"2664.00","storeId":"0","orderPayment":"10.00","consigneeInfo":{"town":"八五四农场","city":"鸡西市","mobile":"136*******2","county":"虎林市","telephone":"134*******7","cityId":"737","townId":"33230","provinceId":"10","province":"黑龙江","countyId":"740","fullAddress":"黑龙江鸡西市******","fullname":"张**","oaid":"ZDBjYzg5ABT5Yz05DTH47QCKVJNOXZu1Yjk1MpfVuAfLrAuYkgdrs9d5Bp2TQM4aJwTxKNDu3zmQuHGWJKJEPLnp2lNcsr3oS95J14OMddvp9OKcr8ed8KMSd0efsxC1QbLSjRc38HhZQq1AhUV2Jxhx38JXewtHLNDMiQ=="},"sellerDiscount":"2654.00","returnOrder":"0","invoiceEasyInfo":{"invoiceType":"0","invoiceContentId":"1","invoiceTitle":"个人"},"storeOrder":"","totalOriginalPrice":"2664.00","actualPay":"10.00","orderStartTime":"2024-12-04 19:03:38"},{"orderSellerPrice":"10.00","orderType":"22","venderRemark":"","logisticsId":"","orderId":"306537548398","sendpayMap":"{\"9\":\"2\",\"26\":\"2\",\"29\":\"1\",\"34\":\"3\",\"36\":\"1\",\"39\":\"1\",\"50\":\"1\",\"51\":\"6\",\"62\":\"1\",\"64\":\"3\",\"84\":\"1\",\"96\":\"1\",\"173\":\"2\",\"186\":\"1\",\"188\":\"3\",\"190\":\"2\",\"191\":\"1\",\"229\":\"1\",\"235\":\"2\",\"239\":\"2\",\"342\":\"1\",\"860\":\"1\",\"943\":\"1\",\"945\":\"1\",\"1007\":\"1\"}","orderRemark":"","venderId":"18433933","paymentConfirmTime":"2024-12-04 19:03:45","orderStateRemark":"等待出库","orderState":"WAIT_SELLER_STOCK_OUT","popSignMap":"{\"11\":\"1\",\"19\":\"1\"}","itemInfoList":[{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFB80/君越/君威/威朗","itemTotal":"1","outerSkuId":"","jdPrice":"769.00","invoiceContentId":"","skuId":"10127082830915","productNo":"","newStoreId":"0"},{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFB60/探界者/别克E5E6/本田/大众/奥迪","itemTotal":"1","outerSkuId":"","jdPrice":"608.00","invoiceContentId":"","skuId":"10127082830913","productNo":"","newStoreId":"0"},{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFB70/昂科拉/君越/创酷/科沃兹/威朗/丰田","itemTotal":"1","outerSkuId":"","jdPrice":"678.00","invoiceContentId":"","skuId":"10127082830914","productNo":"","newStoreId":"0"},{"wareId":"10027478481650","giftPoint":"0","skuName":"德科汽车电瓶启停蓄电池EFB系列 EFBQ85/马自达/奔腾/铃木/凯美瑞/汉兰达","itemTotal":"1","outerSkuId":"","jdPrice":"609.00","invoiceContentId":"","skuId":"10127082830916","productNo":"","newStoreId":"0"}],"payType":"4-在线支付","totalSellerReceivable":"10.000000","modified":"2024-12-04 19:04:05","freightPrice":"0.00","vatInfo":{},"balanceUsed":"0.00","orderSource":"移动端订单","invoiceInfo":"不需要开具发票","totalSellerDiscount":"2654.000000","shouldPay":"10.00","orderTotalPrice":"2664.00","storeId":"0","orderPayment":"10.00","consigneeInfo":{"town":"江南镇","city":"杭州市","mobile":"156*******0","county":"桐庐县","telephone":"158*******7","cityId":"1213","townId":"50207","provinceId":"15","province":"浙江","countyId":"1218","fullAddress":"浙江杭州市桐庐县******","fullname":"陈**","oaid":"N2I3NzIxABT5Yz05DTH47QCKVJNOXZu1Yjk1ModIy85ZAbUxhW/omviTzIpOU4//lMWfUJfEpEAxlJ6ozZBMc4QPnIb1c7ljRN6vP82dS2slRdr0284q4riuyKbnD/kJnmQbk5knzyKvUES/QPbPbPVL0ISQ19GJ1Ht3IQ=="},"sellerDiscount":"2654.00","returnOrder":"0","invoiceEasyInfo":{"invoiceType":"0","invoiceContentId":"1","invoiceTitle":"个人"},"storeOrder":"","totalOriginalPrice":"2664.00","actualPay":"10.00","orderStartTime":"2024-12-04 19:03:36"}]}}}';
            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){

                $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'];
                            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');
                            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'.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;

                                return response()->json(['Data' =>$orders, 'ErrorMessage' => '执行完毕', 'ErrorCode' => 222]);exit;
                                //   $session = $request->get('session_token');//获取操作人信息
                                $session['admin_groupnew'] = 7;
                                $session['admin_acc'] = '系统录入';
                                $session['id'] = 1133;
                                $session['company_id'] = 11;
                                // 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){
                                    //调用京东出库


                                    $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);
        CommonService::addLog('URL', $order_num.'---'.$url.'----'.$res, 111,'url');
        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;
    }

}
