<?php
/**
 * 文件名称（同步京东自营店数据）
 * 文件简单描述（用于同步京京东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\User;
use App\Services\CommonService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use App\Services\RefundService;
use Illuminate\Http\Request;
use DB;


class SynJdSelfDataNewController extends BaseController
{

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

        $url_ex = "http://116.196.75.172/index.php/GetOrder/Shhdelivery";//出库
        $url_mobile = "http://116.196.75.172/index.php/GetOrder/getmobilelist";//出库

        $time_start = date("Y-m-d H:i:s",strtotime(" -6 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',2)->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
            $res_ult[$k]['time_start'] = $time_start;				//开始时间
            $res_ult[$k]['time_end'] = $time_end;				//结束时间
            $res_ult[$k]['setPageSize'] = 20;
            $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'],'JDshh-all');


            $res_data = json_decode($res, true, 100, JSON_BIGINT_AS_STRING);
            if (!is_array($res_data)) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($res_ult[$k]).'-获取京东自营社会化数据失败', $v['pt_id'],'JDSelfShh-error');
                continue;
            }

            if (!isset($res_data['jingdong_socializationinventory_searchAllOrders_responce']['searchallorders_result'])) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($res_ult[$k]).'-获取京东自营数据失败', $v['pt_id'],'JDSelfShh-error');
                continue;
            }

            $searchResult = $res_data['jingdong_socializationinventory_searchAllOrders_responce']['searchallorders_result'];
            if (!isset($searchResult['queryAllOrdersForJosResult'])) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($res_ult[$k]).'-无可添加数据', $v['pt_id'],'JDSelfShh-error');
                continue;
            }
            $arr_goods = [];
            $arr = [];
            $order_data = $searchResult['queryAllOrdersForJosResult'];
            foreach( $order_data as $kk => $vv ){
                $order_info = OrderService::getOrderBy('order_num', $vv['customOrderId'],['id','order_status','lock_type','sys_num','order_num','p_id','ser_id','create_time','new_customer_id','lock_type']);
                if($order_info){
                    continue;
                }
                $flag = 1;
                $skuId = array_column($vv['orderDetailList'], 'sku');
                $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['customOrderId'],'JDSelfShh-无sku');
                    $flag = 2;
                }
                if($goodids){
                    if(count($goodids)<count($vv['orderDetailList'])){
                        $flag = 2;
                    }
                }
                //解密
                /*****************************************解密姓名*************************************************/
                $str = $vv['consigneeName'];
                $data['accessToken'] = $v['access_token'];//'e0a1c90e617f4b3a9865ed059f99c5f42ztb';
                $data['appKey'] = $v['app_key'];;//'41D9668E8CB81C9890A065BEC300FD84';
                $data['appSecret'] = $v['app_secret'];//'93bff142bf5c4422ae7bec9eb992e751';

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

                $fullname = $fullname??$vv['consigneeName'];
                /************************************************************************************************/
                /**********************************************解密地址******************************************/
                $fullAddress = $this->decrypt($data,$vv['address']);

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

                $fullAddress = $fullAddress??$vv['address'];
                /************************************************************************************************/
                /**********************************************整理商品信息******************************************/
                $resjdgoods = DB::table('jdgoods')->where("order_id",$vv['customOrderId'])->value('id');
                foreach( $vv['orderDetailList'] as $ka => $va ){
                    if(!$resjdgoods){
                        $sql_dgoods .= "('".$vv['customOrderId']."',".$v['pt_id'].",'".$va['sku']."','".$va['commodityName']."','".$va['jdPrice']."','".$va['jdPrice']."','0'),";
                        if(in_array($vv['customOrderId'], $arr_goods)){
                            unset($arr_goods[$kk]);
                        }

                        $arr_goods[$kk]['order_id'] = $vv['customOrderId'];//订单单号
                        $arr_goods[$kk]['pt_id'] = $v['pt_id'];//平台id
                        $arr_goods[$kk]['sku_id'] = $va['sku'];//京东sku
                        $arr_goods[$kk]['item_total'] = $va['wareNum'];//商品数量
                        $arr_goods[$kk]['jd_price'] = $va['jdPrice'];//京东单价
                        $arr_goods[$kk]['jd_cost'] = $va['jdPrice'];//采购价
                        $arr_goods[$kk]['sku_name'] = $va['wareName'];//商品名称
                        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['sku']];
                        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['wareNum'];
                            $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]['customOrderId'] = $vv['customOrderId'];
                $data_m[$kk]['appKey'] = $v['app_key'];		//appkey
                $data_m[$kk]['appSecret'] = $v['app_secret'];	//secret
                $data_m[$kk]['accessToken'] = $v['access_token'];	//token

                $tel = $this->request_post($url_mobile,$data_m[$kk]);//同步手机号
                $phone=json_decode($tel,true);
                $phone = $phone['jingdong_pop_order_getmobilelist_responce']['result']['data'];
                $tel =  isset($phone[$vv['customOrderId']]['consMobilePhone'])?$phone[$vv['customOrderId']]['consMobilePhone']:$vv['phone'];
                /*********************************************************************************************/

                /**********************************************添加订单信息******************************************/
                if($flag==1){

                    $orders[$kk]['sys_bh'] = $sys_num;
                    $orders[$kk]['skb_bh'] = $vv['customOrderId'];//平台单号
                    $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['phone'];//$vv['telephone'];//电话
                    $orders[$kk]['shr_sheng'] = $vv['provinceName'];//省份
                    $orders[$kk]['shr_shi'] = $vv['cityName'];//城市
                    $orders[$kk]['shr_xian'] = $vv['countyName'];//区县
                    $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'] = 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'] = 1133;
                    $session['company_id'] = 11;
                    // dump($orders[$kk]);
                    $return = OrderaddService::addOrder($orders[$kk], $session, $ip);
                    //    dump($return);
                    CommonService::addLog('添加定单', json_encode($return), $vv['customOrderId'],'jd_addSelfShhOrder');
                    // $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['customOrderId'] = $vv['customOrderId'];//$vv['orderId'];
                        $res_ex['carrierId'] = 1274;
                        $res_ex['phone'] = '4000773321';
//                        $res_ex['estimateDate'] = date("Y-m-d H:i:s");
                        $result = $this->request_post($url_ex,$res_ex);//出库同步

                        $filename = 'selfShh_ex'.date('Ym');
                        CommonService::addLog('出库', json_encode($res_ex), $vv['customOrderId'],$filename);

                        // $result['code'] = 200;
                        $reta = json_decode($result,true);
                        if($reta['jingdong_socializationinventory_delivery_responce']['returnType']['status']==1){
                            CommonService::addLog('添单成功出库', $result, $vv['customOrderId'],$filename);
                        }else{
                            CommonService::addLog('添单出库失败', $result, $vv['customOrderId'],$filename);
                        }
                        $newOrderId = true;
                    }else{
                        $newOrderId = false;
                    }
                }
                /*********************************************************************************************/

                /**********************************************添加同步记录******************************************/
                $rea = DB::table('jd_proprietary')->where("order_id",$vv['customOrderId'])->value('id');
                if (!$newOrderId || $flag=='2'){
                    //echo '添加订单信息失败';
                    if(!$rea){
                        if(in_array($vv['customOrderId'], array_column($arr, 'order_id'))){
                            unset($arr[$kk]);
                        }
                        $arr[$kk]['order_id'] = $vv['customOrderId'];//订单单号
                        $arr[$kk]['admin_acc'] = '系统录入';//操作人
                        $arr[$kk]['pt_id'] = $v['pt_id'];//平台id
                        $arr[$kk]['pay_type'] = $vv['paymentCategory'];//支付方式
                        $arr[$kk]['order_seller_price'] = $vv['pay'];//订单金额
                        $arr[$kk]['freight_price'] = 0;//运费
                        $arr[$kk]['order_state'] = $vv['orderState'];//'WAIT_SELLER_STOCK_OUT';//订单状态7 新订单；10等待发货；16等待确认收货；19订单完成；22锁定，29删除
                        $arr[$kk]['invoice_info'] = '不需要开具发票';//'发票1开2不开'
                        $arr[$kk]['order_remark'] = '';//订单备注
                        $arr[$kk]['order_start_time'] = date("Y-m-d H:i:s");//下单时间
                        $arr[$kk]['fullname'] = $fullname;//客户姓名
                        $arr[$kk]['mobile'] = $tel??$vv['phone'];//客户手机
                        $arr[$kk]['telephone'] = $tel??$vv['telephone'];//客户电话
                        $arr[$kk]['province'] = $vv['provinceName'];//省
                        $arr[$kk]['city'] = $vv['cityName'];//市
                        $arr[$kk]['county'] = $vv['countyName'];//区县
                        $arr[$kk]['full_address'] = $fullAddress;//详细地址
                        $arr[$kk]['order_pay'] = $vv['pay'];//实收金额
                        $arr[$kk]['is_show'] = 2;//'1 未填单 2 已填单 3 已删除 4 已完成'
                        $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['customOrderId'])->value('id');
                    if(!$reas){
                        if(in_array($vv['customOrderId'], array_column($arr, 'order_id'))){
                            unset($arr[$kk]);
                        }
                        $arr[$kk]['order_id'] = $vv['customOrderId'];//订单单号
                        $arr[$kk]['admin_acc'] = '系统录入';//操作人
                        $arr[$kk]['pt_id'] = $v['pt_id'];//平台id
                        $arr[$kk]['pay_type'] = $vv['paymentCategory'];//支付方式
                        $arr[$kk]['order_seller_price'] = $vv['pay'];//订单金额
                        $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'] = '';//订单备注
                        $arr[$kk]['order_start_time'] = date("Y-m-d H:i:s");//下单时间
                        $arr[$kk]['fullname'] = $fullname;//客户姓名
                        $arr[$kk]['mobile'] = $tel??$vv['phone'];//客户手机
                        $arr[$kk]['telephone'] = $tel??$vv['telephone'];//客户电话
                        $arr[$kk]['province'] = $vv['provinceName'];//省
                        $arr[$kk]['city'] = $vv['cityName'];//市
                        $arr[$kk]['county'] = $vv['countyName'];//区县
                        $arr[$kk]['full_address'] = $fullAddress;//详细地址
                        $arr[$kk]['order_pay'] = $vv['pay'];//实收金额
                        $arr[$kk]['is_show'] = 2;//'1 未填单 2 已填单 3 已删除 4 已完成'
                        $arr[$kk]['parent_orderid'] = $vv['parentOrderId'];//父类单号
                        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 getSelfRefund ( ){
        $url = "http://116.196.75.172/index.php/GetOrder/getSelfRefund";
        $token = DB::table('jdpop_token')->where('status',1)->where('type',2)->select('app_key','app_secret','access_token','pt_id')->get()->toarray();
        $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");
        foreach($token as $k => $v){
            $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'] = 20;
            $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'],'JDSelf-refund');

            $res_data = json_decode($res, true, 100, JSON_BIGINT_AS_STRING);
            if (!is_array($res_data)) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($res_ult[$k]).'-获取京东自营数据失败', $v['pt_id'],'JDSelf-refundError');
                continue;
            }
            if (!isset($res_data['jingdong_dropship_dps_searchpre_responce']['searchPreResult'])) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($res_ult[$k]).'-获取京东自营数据失败', $v['pt_id'],'JDSelf-refundError');
                continue;
            }
            $searchResult = $res_data['jingdong_dropship_dps_searchpre_responce']['searchPreResult'];
            if (!isset($searchResult['resultDtoList'])) {
                CommonService::addLog('token1--'.$v['pt_id'], json_encode($res_ult[$k]).'-无可添加数据', $v['pt_id'],'JDSelf-refundError');
                continue;
            }
            $data = $searchResult['resultDtoList'];
            $return = [];
            foreach($data as $k => $v){
//                $v['customOrderId'] ='20240328111';
                if($v['approvalState']===0 || $v['approvalState']===1) {
                    $flag = 1;
                    $refundlist = RefundService::getInfoByKeyValue('order_num', $v['customOrderId'], ['state', 'roPreNo']);
                    if ($refundlist) {
                        $state = array_column($refundlist, 'state');
                        $state = min($state);
                        if ($state < 5) {
                            $rea = '存在未完成的退款数据';
                            $flag = 2;
                        } else {
                            $roPreNo = array_column($refundlist, 'roPreNo');
                            if (in_array($v['roPreNo'], $roPreNo)) {
                                $rea = '退款单已同步';
                                $flag = 2;
                            }
                        }
                    }
                    if ($flag == 1) {
                        $refund['order_num'] = $v['customOrderId'];
                        $refund['refund'] = 1;
                        $refund['content'] = $v['roReason'] . ",平台申请时间：(" . date("Y-m-d H:i:s", mb_substr($v['roApplyDate'], 0, 10)) . ")";
                        $refund['urgent'] = 1;
                        $refund['allprice'] = $v['roApplyFee'];
                        $refund['recycle_type'] = 0;
                        $refund['roPreNo'] = $v['roPreNo'];
                        $sys_num = OrderService::getOrderBy('order_num', $v['customOrderId'], ['sys_num','order_status','company_id']);
                        if ($sys_num) {
                            $refund['sys_num'] = $sys_num['sys_num'];
                            if($sys_num['order_status']>10) {
                                $msg = OrderService::getOrderListMsg($sys_num['sys_num']);
                            }else{
                                $msg = OrderService::getOrderMsg($sys_num['sys_num']);
                            }
                            if ($msg['orderMsgArr']) {
                                $msg = $msg['orderMsgArr'];
                                $goodsArr = [];
                                foreach ($msg as $ka => $va) {
                                    $goodsArr[$ka]['goods_name'] = $va['goods_name'];
                                    $goodsArr[$ka]['goods_price'] = $va['goods_price'];
                                    $goodsArr[$ka]['msg_id'] = $va['id'];
                                    $goodsArr[$ka]['goods_num'] = $va['goods_num'];
                                    $goodsArr[$ka]['goods_id'] = $va['goods_id'];
                                }
                                $refund['goodsArr'] = $goodsArr;
                                $refund['goods_state'] = 2;
                                $refund['info_ing'] = '';
                                $refund['info_acc'] = '';
                                $refund['info_name'] = '';
                                $refund['addType'] = 'jdRefund';
                                $session['id'] = '1133';
                                $session['admin_acc'] = '系统操作';
                                $session['admin_groupnew'] = 7;
                                $session['company_id'] = $sys_num['company_id'];
                                $rea = OrderService::lockOrder($refund, $session, '39.105.188.64');
                            } else {
                                $rea = '无订单商品';
                            }

                        } else {
                            $rea = '无订单号';
                        }
                    }
                }else{
                    $rea = '平台已处理'.$v['approvalState'];
                }
                $return[$k]['lockOrder'] = $rea;
                $return[$k]['order_num'] = $v['customOrderId'];
            }
            CommonService::addLog('token1--'.$v['pt_id'], json_encode($return).'-执行退款信息', $v['pt_id'],'JDSelf-addRefundData');
            echo '操作成功--****';
        }
    }

    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(){
      /*  $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;
    }
}
