<?php
namespace App\Http\Controllers\Api;
use ACES\TDEClient;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Orders\OrderListController;
use App\Models\Admin;
use App\Models\Feedback;
use App\Models\InstallLine;
use App\Models\JdBound;
use App\Models\JdServiceProvider;
use App\Models\OrderList;
use App\Models\OrderListMsg;
use App\Models\Orders;
use App\Models\PjGoods;
use App\Models\Pt;
use App\Models\SettlementList;
use App\Models\SettlementThree;
use App\Services\CommonService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use App\Services\RefundService;
use App\Services\SettlementThreeService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use DB;
use OSS\OssClient;
use ACES\SecretJdClient;
class JdOrderApiController extends BaseController
{
    /**
     * @name 获取京东定单
     * @author du
     * @date 2024/3/13
     * @Time: 10:53
     */
    public function getOrderByJd( ){

        $startDate = date("Y-m-d H:i:s",strtotime(" -6 minute".date("Y-m-d H:i:s")));
        $endDate = date("Y-m-d H:i:s");
        $url = "http://116.196.75.172/index.php/SaasApiGetOrder/index?startDate=".$startDate."&endDate=".$endDate."&status=300";
        $token = DB::table('jdpop_token')->where('status',1)->where('type',2)->select('app_key','app_secret','access_token','pt_id','auth_key')->get()->toarray();
        foreach($token as $k => $vs) {
            $urls = $url."&authKey=".$vs['auth_key']."&access_token=".$vs['access_token']."&app_key=".$vs['app_key']."&app_secret=".$vs['app_secret'];
            $company_id = Pt::where('id',$vs['pt_id'])->value('company_id');
//            echo $urls;
            $res = $this->http_get($urls);
            $ip = $_SERVER["REMOTE_ADDR"];
            $data = json_decode($res, true);
            // dump($data);
            $pt_id = $vs['pt_id'];
            CommonService::addLog('获取订单', $urls.'---'.$res, $vs['pt_id'], 'JdOrderApi-getOrder');
            $result = $data['jingdong_omnic_order_getorderlist_responce']['result'];
            $result = json_decode($result, true);
            //        dump($result['success']);
            if ($result['success'] == true) {
                $order_data = $result['data'];
                if (!empty($order_data)) {
                    $arr = [];
                    $arr_goods = [];
//                    dd($order_data);
                    if (isset($order_data['data'])) {
                        $order_data = $order_data['data'];
//                        dd($order_data);
//                        dump($order_data);
                        foreach ($order_data as $kkk => $vvv) {
                            if ($vvv['orderDetailList']) {
                                $sku_ids = array_unique(array_column($vvv['orderDetailList'], 'skuId'));
                                $goods_ids = JdBound::whereIn('sku_id', $sku_ids)->pluck('goods_id', 'sku_id');
                                $goods_ids = CommonService::dataToArray($goods_ids);
                                if (empty($goods_ids)) {
                                    CommonService::addLog('SKU_all_no', json_encode($sku_ids), $vvv['orderInfo']['salesChannelOrderId'], 'SKU_all_no');
                                    continue;
                                }
                                $goods_idss = JdBound::whereIn('sku_id', $sku_ids)->pluck('goods_id');
                                $goods_idss = CommonService::dataToArray($goods_idss);
                                if (empty($goods_idss)) {
                                    continue;
                                }
                                $goods = PjGoods::whereIn('pg_id', $goods_idss)->select('pg_id', 'brand_name', 'pg_series', 'version', 'goods_pic_path', 'national_version')->get()->toarray();
                                if ($goods) {
                                    $brand_name = array_unique(array_column($goods, 'brand_name'));
                                } else {
                                    CommonService::addLog('SKU_all_no', json_encode($sku_ids), $vvv['orderInfo']['salesChannelOrderId'], 'nogood');
                                    continue;
                                }
                                $goods = CommonService::jointArrayKey($goods, 'pg_id');
                                if (count($goods) < count($vvv['orderDetailList'])) {
                                    CommonService::addLog('SKU_all_no', json_encode($sku_ids), $vvv['orderInfo']['salesChannelOrderId'], 'SKU_all_no');
                                    continue;
                                }

                                $exsit = Orders::where('order_num', $vvv['orderInfo']['salesChannelOrderId'])->value('id');
                                //存订单
                                $eisit_jd = DB::table('jd_proprietary')->where('order_id', $vvv['orderInfo']['salesChannelOrderId'])->value('id');
                                if (!$exsit && !$eisit_jd) {
                                    $resjdgoods = DB::table('jdgoods')->where("order_id", $vvv['orderInfo']['salesChannelOrderId'])->value('id');
                                    $sys_num = 'L' . date("YmdHis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
                                    foreach ($vvv['orderDetailList'] as $k => $v) {
                                        //  dd($v);
                                        // dump($arr);

                                        //存商品
                                        //`gone_jdgoods` (`order_id`,`pt_id`,`sku_id`,`sku_name`,`item_total`,`jd_price`,`jd_cost`)
                                        if (!$resjdgoods) {
                                            if (in_array($vvv['orderInfo']['salesChannelOrderId'], array_column($arr_goods, 'order_id'))) {
                                                unset($arr_goods[$k]);
                                                // echo 1;echo '---'.$v['orderId'].'---';
                                            }
                                            $arr_goods[$k]['order_id'] = $vvv['orderInfo']['salesChannelOrderId'];
                                            $arr_goods[$k]['pt_id'] = $pt_id;
                                            $arr_goods[$k]['sku_id'] = $v['skuId'];
                                            $arr_goods[$k]['item_total'] = $v['num'];
                                            $arr_goods[$k]['jd_price'] = $v['skuAmount'];
                                            $arr_goods[$k]['jd_cost'] = $v['skuPrice'];
                                            $arr_goods[$k]['sku_name'] = $v['skuName'];
                                            DB::table('jdgoods')->insert($arr_goods[$k]);
                                            unset($arr_goods[$k]);

                                        }
                                        $goodid = $goods_ids[$v['skuId']];
                                        if ($goodid) {
                                            $goods_res = $goods[$goodid];
                                            //    dd($goods_res);
                                            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[$k]['goods_id'] = $goodid;
                                            $orderMsgData[$k]['goods_name'] = $goods_res['brand_name'] . "-" . $type;
                                            $orderMsgData[$k]['goods_price'] = $v['skuPrice'];//实收/商品单价
                                            $orderMsgData[$k]['goods_paid'] = $v['skuPrice'];
                                            $orderMsgData[$k]['goods_num'] = $v['num'];
                                            $orderMsgData[$k]['goods_brand'] = $goods_res['brand_name'];
                                            $orderMsgData[$k]['goods_number'] = $type;
                                            $orderMsgData[$k]['cd_id'] = 1;
                                        } else {
                                            //未绑定SKU
                                            CommonService::addLog('未绑定SKU', $v['skuId'], $vvv['orderInfo']['salesChannelOrderId'], 'jdAPI_sku');
                                            continue;
                                        }
                                    }

                                    $orders[$kkk]['sys_bh'] = $sys_num;
                                    $orders[$kkk]['skb_bh'] = $vvv['orderInfo']['salesChannelOrderId'];
                                    $orders[$kkk]['pt_id'] = $pt_id;
                                    $orders[$kkk]['ser_type'] = 1;//服务类型：1上门安装，2到店服务
                                    $orders[$kkk]['shr_name'] = $vvv['orderShip']['consignee'] ?? '空';
                                    $orders[$kkk]['shr_phone'] = $vvv['consigneePhone'] ?? $vvv['orderShip']['consigneeMobile'];//$vv['consigneeInfo']['telephone'];//
                                    $orders[$kkk]['shr_sheng'] = $vvv['orderShip']['addressLevel1Name'];//
                                    $orders[$kkk]['shr_shi'] = $vvv['orderShip']['addressLevel2Name'];//
                                    $orders[$kkk]['shr_xian'] = $vvv['orderShip']['addressLevel3Name'];//
                                    $orders[$kkk]['shr_adress'] = $vvv['orderShip']['deliveryAddress'];//
                                    $orders[$kkk]['shr_other'] = '接单后10分钟内务必联系客户核实车型跟安装时间！不断电安装、如果无法完成 请立刻反馈我们处理~！';
                                    $orders[$kkk]['car_audit'] = 2;//1:新订单；2：可派单；3：处理中
                                    $orders[$kkk]['order_type'] = 1;//订单类型：1：普通；20加急；10：夜间
                                    $orders[$kkk]['order_time'] = date('Y-m-d H:i:s', $v['createTime'] / 1000);
                                    $orders[$kkk]['pay_type'] = 1;//支付方式：1在线支付；2货到付款 $input['shr_other']
                                    $orders[$kkk]['goods'] = $orderMsgData;
                                    $orders[$kkk]['shr_other'] = $vvv['orderInfo']['promiseMsg'];
                                    //   $session = $request->get('session_token');//获取操作人信息
                                    $session['admin_groupnew'] = 7;
                                    $session['admin_acc'] = '系统录入';
                                    $session['id'] = 1133;
                                    $session['company_id'] = $company_id;
//                                    dd($orders[$kkk]);
                                    $return = OrderaddService::addOrder($orders[$kkk], $session, $ip);
                                    CommonService::addLog('添加定单', json_encode($return), $vvv['orderInfo']['salesChannelOrderId'], 'jdAPI_addOrder');
                                    if ($return['ErrorCode'] == 1 && $vs['pt_id']!=33) {
                                        $url = "http://116.196.75.172/index.php/SaasApiGetOrder/updatestatus?orderId=" . $vvv['orderInfo']['salesChannelOrderId'] . "&storeId=" . $vvv['orderInfo']['warehouseId'];
                                        $urls = $url."&authKey=".$vs['auth_key']."&access_token=".$vs['access_token']."&app_key=".$vs['app_key']."&app_secret=".$vs['app_secret'];
                                        $ck = $this->http_get($urls);
                                        CommonService::addLog('订单出库', $ck, $vvv['orderInfo']['salesChannelOrderId'], 'jdAPI_addOrderck');
                                    }
                                    //    dump($return);
                                    unset($orderMsgData);
                                    unset($orders[$kkk]);

                                    if (in_array($vvv['orderInfo']['salesChannelOrderId'], array_column($arr, 'order_id'))) {
                                        unset($arr[$kkk]);
                                        // echo 2;echo '---'.$v['orderId'].'---';
                                    }
//                                    $arr[$kkk]['salesChannelOrderId'] = $v['orderId'];
                                    //
                                    $arr[$kkk]['order_id'] = $vvv['orderInfo']['salesChannelOrderId'];
                                    $arr[$kkk]['admin_acc'] = '系统';
                                    $arr[$kkk]['pt_id'] = $pt_id;
                                    $arr[$kkk]['pay_type'] = '在线支付';
                                    $arr[$kkk]['order_seller_price'] = $v['skuAmount'];
                                    $arr[$kkk]['freight_price'] = $v['transactionPrice'] ?? $vvv['orderInfo']['orderTotalAmount'];
                                    $arr[$kkk]['order_state'] = 'WAIT_SELLER_STOCK_OUT';
                                    $arr[$kkk]['invoice_info'] = '不需要开具发票';
                                    $arr[$kkk]['order_remark'] = $vvv['orderInfo']['promiseMsg'];
                                    $arr[$kkk]['order_start_time'] = date('Y-m-d H:i:s', $v['createTime'] / 1000);
                                    $arr[$kkk]['fullname'] = $vvv['orderShip']['consignee'];
                                    $arr[$kkk]['mobile'] = $vvv['orderShip']['consigneeMobile'];
                                    $arr[$kkk]['telephone'] = $vvv['orderShip']['consigneePhone'];//
                                    $arr[$kkk]['province'] = $vvv['orderShip']['addressLevel1Name'];
                                    $arr[$kkk]['city'] = $vvv['orderShip']['addressLevel2Name'];
                                    $arr[$kkk]['county'] = $vvv['orderShip']['addressLevel3Name'];
                                    $arr[$kkk]['full_address'] = $vvv['orderShip']['deliveryAddress'];
                                    $arr[$kkk]['order_pay'] = $v['skuAmount'];
                                    $arr[$kkk]['is_show'] = 1;
                                    $arr[$kkk]['parent_orderid'] = 0;
                                    DB::table('jd_proprietary')->insert($arr[$kkk]);
//                                    dd($arr[$kkk]);
                                    unset($arr[$kkk]);

                                } else {
                                    CommonService::addLog('单号已存在', json_encode($vvv), $vvv['orderInfo']['salesChannelOrderId'], 'jdAPI_addOrder');
                                }

                            }
                        }
                    }
                    echo "succese";
                }
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取退款订单
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/10/25 14:19
     * |---------------------------------------------------------------------------------
    */
    public function getOrderCancelAuditList ( ){
        $startDate = date("Y-m-d H:i:s",strtotime(" -6 minute".date("Y-m-d H:i:s")));
        $endDate = date("Y-m-d H:i:s");
        $url = "http://116.196.75.172/index.php/SaasApiGetOrder/getOrderCancelAuditList?applyDateBegin=".$startDate."&applyDateEnd=".$endDate;
        $token = DB::table('jdpop_token')->where('status',1)->where('type',2)->select('app_key','app_secret','access_token','pt_id','auth_key')->get()->toarray();
        foreach($token as $k => $vs) {
            $urls = $url."&authKey=".$vs['auth_key']."&access_token=".$vs['access_token']."&app_key=".$vs['app_key']."&app_secret=".$vs['app_secret'];
//            echo $urls;
            $res = $this->http_get($urls);
            $ip = $_SERVER["REMOTE_ADDR"];
            $data = json_decode($res, true);
            CommonService::addLog('获取退款订单', $urls.'---'.$res, $vs['pt_id'], 'getOrderCancel');
            $result = $data['jingdong_omnic_order_getOrderCancelAuditList_responce']['result'];
            $result = json_decode($result, true);
            if ($result['success'] == true) {
                if (isset($result['data'])) {
                    $order_data = $result['data'];
                    if (!empty($order_data)) {
                        if (isset($order_data['data'])) {
                            $order_data = $order_data['data'];
                            foreach ($order_data as $k => $v) {
                                $flag = 1;
                                $refundlist = RefundService::getInfoByKeyValue('order_num', $v['saleOrderId'], ['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['requestionId'], $roPreNo)) {
                                            $rea = '退款单已同步';
                                            $flag = 2;
                                        }
                                    }
                                }
                                if ($flag == 1) {
                                    $refund['order_num'] = $v['saleOrderId'];
                                    $refund['refund'] = 1;
                                    $refund['content'] = $v['applyReason'] . ",平台申请时间：(" . $v['applyDate'] . ")";
                                    $refund['urgent'] = 1;
                                    $refund['recycle_type'] = 0;
                                    $refund['roPreNo'] = $v['requestionId'];
                                    $sys_num = OrderService::getOrderBy('order_num', $v['saleOrderId'], ['sys_num', 'order_status', 'new_money']);
                                    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';
                                            $refund['allprice'] = $sys_num['new_money'];
                                            $session['id'] = '1133';
                                            $session['admin_acc'] = '系统操作';
                                            $session['admin_groupnew'] = 7;
                                            //                                        dump($refund);
                                            $rea = OrderService::lockOrder($refund, $session, '39.105.188.64');
                                        } else {
                                            $rea = '无订单商品';
                                        }

                                    } else {
                                        $rea = '无订单号';
                                    }
                                }
                                $return[$k]['lockOrder'] = $rea;
                                $return[$k]['order_num'] = $v['saleOrderId'];
                            }
                            CommonService::addLog('添加退款单', json_encode($return), $vs['pt_id'], 'addOrderCancel');
                        }
                    }
                }
            }
            echo "succese";
        }
    }


}
