<?php

namespace app\controller\api\store\product;

use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\user\UserThirdRepository;
use app\model\common\JdOrderModel;
use DateTime;
use think\App;
use crmeb\basic\BaseController;
use think\db\exception\DbException;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\common\repositories\user\UserRepository;

class Jd extends BaseController
{
    public $appid = '';
    public $key = '';
    public $appKey = '';
    public $secretKey = '';
    public $userThird;
    public $url;

    public function __construct(App $app)
    {

        parent::__construct($app);
        $this->appid = '4101490811';
        $this->key = 'a7c43c21f3e156d2fd41dfbe884b9f62592ceb03b9f199c0811c82e35be53c0580a2638a7af39e74';
        $this->appKey = 'e99703d01cbb6a2e48a8a34f19af9d87';
        $this->secretKey = 'cea7578d5a314ef88086daa4ee3a5b4d';
        // $this->appid = '4100076550';
        // $this->key = '5ce3da55dc739b6e7d9021d59618c5faa3b4030f41c5699658c7ca30cfd19f09b4046d606d196f1d';
        // $this->appKey = 'a2ad5078501e928b991cd8aaeb0446dc';
        // $this->secretKey = 'fd8aab59e9b94d9e889cb22838c03f2a';
        $this->userThird = app()->make(UserThirdRepository::class);
        $this->url = 'https://api.jd.com/routerjson';
    }


    //排序ksort
    public function paramOrder($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v)) {
                $v = $this->characet($v, 'utf-8');
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "$v";
                } else {
                    $stringToBeSigned .= "$k" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }

    //为空检查
    protected function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }

    //编码设置
    public function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = 'utf-8';
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
            }
        }
        return $data;
    }

    //签名
    public function paramSign($params)
    {
        $str = $this->secretKey . $params . $this->secretKey;
        $sign = md5($str);
        return strtoupper($sign);
    }

    public function apiSign($param)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    //返回请求参数链接
    public function getUrlResult($apiName = "", $params = [])
    {
        if (empty($apiName)) {
            return false;
        }
        // log::info("url京东111");
        //公共请求参数
        $requestParams = [
            'method'            => $apiName,
            'format'            => 'json',
            'app_key'           => $this->appKey,
            'timestamp'         => date('Y-m-d H:i:s'),
            'v'                 => '1.0',
            'sign_method'       => 'md5',
            '360buy_param_json' => json_encode($params)
        ];
        $orderData = $this->paramOrder($requestParams);
        $sign = $this->paramSign($orderData);
        $requestParams['sign'] = $sign;
        $res = $this->apiSign($requestParams);
        // log::info("url京东end");
        // log::info($res);
        return $res;
    }


    /*
     * 创建京东用户标识(推广位)
     * */
    public function create_pid(string $uid)
    {
        //获取拼多多的pid拼接uid作为京东的用户的标示
        $result = $this->userThird->getDetail(['uid' => $uid, 'type' => 1]);
        $data =
            [
                'pid'         => $result['pid'] . '_' . $uid,
                'pid_name'    => 'jd' . $uid,
                'create_time' => date("Y-m-d H:i:s"),
                'type'        => 6,
                'uid'         => $uid,
            ];
        $vip_id = $this->userThird->createPid($data);
        return $vip_id;
    }

    /*京粉精选商品查询接口*/
    public function jdList(UserRepository $repository)
    {
        $keyword = request()->param('keyword', '');
        $_cid = request()->param('cid', '');

        [$page, $limit] = $this->getPage();


        $goods_obj = Db::name('third_party_goods')
            ->where('type', 2);
        if ($keyword) {
            $goods_obj = $goods_obj->where('json', 'like', '%' . $keyword . '%');
        }
        if ($_cid) {
            /**
             * 旧品类标识到新品类eliteId的映射关系
             *
             * 映射规则：
             * 1. 精品(0) -> 精选卖场(2) + 自营热卖榜(41)
             * 2. 其他品类按最接近的京东新分类映射
             * 3. 未明确对应的品类映射到通用分类（好券商品+京东好物）
             */
            $oldToNewMapping = [
                // 精品 -> 精选卖场 + 自营热卖榜
                0 => [2, 41],
                // 居家日用 -> 家具日用
                1 => [27],
                // 食品 -> 超市
                2 => [25],
                // 生鲜 -> 超市
                3 => [25],
                // 图书 -> 图书文具
                4 => [30],
                // 美妆个护 -> 美妆穿搭
                5 => [28],
                // 母婴 -> 母婴玩具
                6 => [26],
                // 数码家电 -> 数码家电 + 3C新品 + 3C长尾商品
                7 => [24, 341, 343],
                // 内衣 -> 京东好物（通用分类）
                8 => [32],
                // 配饰 -> 京东好物（通用分类）
                9 => [32],
                // 女装 -> 美妆穿搭（服装相关）
                10 => [28],
                // 男装 -> 京东好物（通用分类）
                11 => [32],
                // 鞋品 -> 京东好物（通用分类）
                12 => [32],
                // 家装家纺 -> 家具日用
                13 => [27],
                // 文娱车品 -> 图书文具 + 京东好物
                14 => [30, 32],
                // 箱包 -> 京东好物（通用分类）
                15 => [32],
                // 户外运动 -> 京东好物（通用分类）
                16 => [32],
            ];
            $goods_obj = $goods_obj->whereIn('cid', $oldToNewMapping[$_cid]);
        }
        $salt = (int)(time() / 100);
        $list = $goods_obj->page($page, $limit)
            ->orderRaw("RAND({$salt})")
            ->select()->toArray();

        $formatList = [];
        foreach ($list as $value) {
            $json = json_decode($value['json'], true);
            $json['commission_'] = $json['lowestCouponPrice'];
            $json['monthSales'] = 0;
            $json['cid'] = $value['cid'] ?? 0;
            $formatList[] = $json;
        }
        shuffle($formatList);
        $uid = $uid ?? 0;
        $repository->sproductkeywordHistory($uid, $keyword, 2);
        return app("json")->success($formatList);
    }

    /*京粉精选商品查询接口*/
    public function search()
    {
        $keyword = request()->param('keyword', '');
        $_cid = request()->param('cid', '');

        [$page, $limit] = $this->getPage();
        try {
            $uid = $this->request->uid();
            TaoKe::set_third_history($uid, $keyword);
        } catch (\Exception $exception) {

        }

        $goods_obj = Db::name('third_party_goods')
            -> where('type',2);
        // -> when(!empty($keyword),function($query) use ($keyword) {
        //     $query -> where('json',"like",'%'.$keyword.'%');
        // })
        // -> page($page,$limit)
        // -> field('json')
        // -> select()
        // -> toArray();

        if($keyword){
            $goods_obj=$goods_obj->where('json', 'like', '%' . $keyword . '%');
        }
        if($_cid){
            $goods_obj=$goods_obj->where('cid', $_cid);
        }
        $list=$goods_obj->page($page, $limit)
            ->select()->toArray();

        $formatList = [];
        foreach ($list as $value){
            $formatList[] = json_decode($value['json'],true);
        }
        return app("json")->success($formatList);


        //        [$page, $limit] = $this->getPage();
//        $apiName = 'jd.union.open.goods.query';
//        $keyword = $this->request->param(['keyword']);
//        $params = [
//            'goodsReqDTO'=>[
//                'keyword'=>$keyword['keyword'],
//                'pageIndex'=>$page??1,
//                'pageSize' =>20,
//            ]
//        ];
//        $result = $this->getUrlResult($apiName,$params);
//        $result =  json_decode($result,true);
//        if($result['jd_union_open_goods_query_response']['code'] == '0'){
//            return app('json')->success('未查询到商品',[]);
//        }
//
//        $result =  json_decode($result['jd_union_open_goods_query_response']['queryResult'],true);
//        $result =$result['data']??[];
//        $goodsList = [];
//        foreach ($result as $k=> $goods) {
//            $goodsList[] = [
//                'type' => 6,//京东商品
//                'skuId' =>$goods['skuId'],//skuid
//                'id' => $goods['brandCode']??'', //id
//                'thumb' => $goods['imageInfo']['imageList'][0]['url']??'',//商品缩略图
//                'name' => $goods['skuName'],//名称
//                'commission' =>app()->make(ProductRepository::class)->yanglaojin(0,$goods['commissionInfo']['commission']??''),//佣金
//                'commission_rate' => $goods['commissionInfo']['commissionShare']??'',//佣金比例
//                'sales' => "",
//                'coupon_money' => $goods['couponInfo']['couponList'] ?? [],
//                'lowestCouponPrice' => $goods['priceInfo']['price']??'', //券后价lowestCouponPrice
//                'price' => $goods['priceInfo']['price']??'', //价格
//            ];
//        }

        // $keyword = request()->param('keyword', '');
        // [$page, $limit] = $this->getPage();
        // $uid = $this->request->uid();
        // TaoKe::set_third_history($uid, $keyword);
        //
        // $list = Db::name('third_party_goods')
        //     ->where('type', 2)
        //     ->when(!empty($keyword), function ($query) use ($keyword) {
        //         $query->where('json', "like", '%' . $keyword . '%');
        //     })
        //     ->page($page, $limit)
        //     ->field('json')
        //     ->select()
        //     ->toArray();
        // $formatList = [];
        // foreach ($list as $value) {
	    // $json = json_decode($value['json'], true);
        //     $json['pension'] = $json['pension']??'0';
        //     $json['pv'] = $json['pension']*0.5;
        //     $json['yanglaojin'] = $json['pv']*0.05;
        //
        //     $json['shopName'] = "";
        //     $json['monthSales'] = "0";
        //     $json['cid'] = "0";
        //     $formatList[] = $json;
        // }
        // return app("json")->success($formatList);
    }


    /*京东商品详情*/
    public function jdDetail()
    {
        try {
            $sku = request()->param('skuId', '');
            if (empty($sku)) {
                return app('json')->fail('商品下架不存在', null, 401);
            }
            // 老版本
            // $apiName = 'jd.union.open.goods.promotiongoodsinfo.query';
            // $params = [
            //     'skuIds' => $sku['skuId'],
            // ];
            // $result = $this->getUrlResult($apiName, $params);
            // $result = json_decode($result, true);
            // $result = json_decode($result['jd_union_open_goods_promotiongoodsinfo_query_responce']['queryResult'], true);
            // $result = $result['data'][0] ?? [];
            // $goodsDetail = $this->doGetJtDetail($result);

            $third_party_goods_detail = Db::name('third_party_goods')
                ->whereLike('json', '%' . $sku . '%')
                ->find();
            $third_party_goods_json_detail = json_decode($third_party_goods_detail['json'], true);
            $formatData = [
                'goodsName' => $third_party_goods_json_detail['name'],
                'imgUrl' => $third_party_goods_json_detail['imageList'][0],
                'unitPrice' => $third_party_goods_json_detail['price'],//原价
                'wlUnitPrice' => $third_party_goods_json_detail['lowestCouponPrice'],
                'couMoney' => $third_party_goods_json_detail['coupon_money'][0]['discount'],
                'nowPrice' => $third_party_goods_json_detail['lowestCouponPrice'],//现价
                'detail' => $third_party_goods_json_detail['imageList'],

                'commission' => $third_party_goods_json_detail['commission'],
                'pv' => $third_party_goods_json_detail['pv'],
                'yanglaojin' => $third_party_goods_json_detail['yanglaojin'],
                'gongxian' => $third_party_goods_json_detail['gongxian'],
                'jifen' => $third_party_goods_json_detail['jifen'],
                'discount_link' => $third_party_goods_json_detail['coupon_link'],
                'materialUrl' => ''
            ];

            return app("json")->success([$formatData]);
        } catch (\Exception $e) {
            return app('json')->fail('商品下架不存在', null, 401);
        }
    }

    //实际执行活动经推推商品详情方法
    public function doGetJtDetail($goodsDetail)
    {

        $third_party_goods_detail = Db::name('third_party_goods')->whereLike('json', '%' . $goodsDetail['skuId'] . '%')->find();
        $third_party_goods_json_detail = json_decode($third_party_goods_detail['json'], true);

//        var_dump($goodsDetail);
//        return $goodsDetail;
        $discount = $third_party_goods_json_detail['coupon_money'] ? array_column($third_party_goods_json_detail['coupon_money'], 'discount') : [0];
        $discount = (float)min($discount);
        $return = [];

        $formatData = [
            'goodsName'   => $goodsDetail['goodsName'],
            'imgUrl'      => $goodsDetail['imgUrl'],
            'unitPrice'   => $goodsDetail['unitPrice'],//原价
            'wlUnitPrice' => $goodsDetail['wlUnitPrice'],
            'couMoney'    => $discount,                                      //折扣价
            'nowPrice'    => decimal2($goodsDetail['unitPrice'] - $discount),//现价
            'detail'      => $third_party_goods_json_detail['imageList'] ?? [],
            'yanglao'     => $third_party_goods_detail['pension'] ?? Db::name('order_jd')->where('uid',$this->request->uid())->where('sku_id',$goodsDetail['skuId'])->value('commission'),
        ];
//        var_dump($third_party_goods_json_detail['coupon_money'][0]['link']);
        //加入转链地址
        $formatData['materialUrl'] = $this->linkChange($goodsDetail['materialUrl'], $this->request->uid(), $third_party_goods_json_detail['coupon_money'][0]['link'] ?? '');
        $return[] = $formatData;
        return $return;
    }

    public function changLinkApi()
    {
        $skuId = request()->param('skuId', '');
        if (empty($skuId)) {
            return app('json')->fail('商品下架不存在', null, 401);
        }
        $uid = $this->request->uid();
        if (empty($uid)) {
            return app('json')->fail('请重新登录', null, 401);
        }
        $third_party_goods_detail = Db::name('third_party_goods')->where('type', '=', 2)->whereLike('json', '%' . $skuId . '%')->find();
        $third_party_goods_json_detail = json_decode($third_party_goods_detail['json'], true);

        $subUnionId = (int)($third_party_goods_json_detail['commission'] * 1000) . '_' . (int)($third_party_goods_json_detail['yanglaojin'] * 1000);
        $url = $this->linkChange($third_party_goods_json_detail['materialUrl'], $uid, $third_party_goods_json_detail['coupon_link'] ?? '', $subUnionId);

        return app("json")->success(['url' => $url]);
    }

    /*转链*/
    public function linkChange($url, $uid,$couponUrl, $subUnionId)
    {

        if (!$uid) {
            return $url;
        }
//        $pid = $this->userThird->getDetail(['uid' => $uid, 'type' => 6]);
//        //上线后这几行可屏蔽
//        if (!$pid) {
//            $this->create_pid($uid);
//            $pid = $this->userThird->getDetail(['uid' => $uid, 'type' => 6]);
//        }
        //end
        $apiName = 'jd.union.open.promotion.common.get';
        $params = [
            'promotionCodeReq' => [
                'materialId' => $url,
                'siteId'     => $this->appid,
                'positionId' => $uid, //自定义,和订单关联
                'couponUrl'  => $couponUrl,
                'sceneId' => 1,
                'subUnionId' => $subUnionId
            ],
        ];
        $result = $this->getUrlResult($apiName, $params);
        $result = json_decode($result, true);
        $result = json_decode($result['jd_union_open_promotion_common_get_responce']['getResult'], true);
        $result = $result['data']['clickURL'];
        log::info("京东详情==========");
        log::info($result);
        return $result ?? '';
    }

    public function get_jd_goods_list()
    {
        set_time_limit(0);

        $eliteIdList = [
            '1', //好券商品
            '2', //精选卖场
            '10', //9.9包邮
            '15', //京东配送
            '22', //实时热销榜
            //            '23', //为你推荐
            '24', //数码家电
            '25', //超市
            '26', //母婴玩具
            '27', //家具日用
            '28', //美妆穿搭
            '30', //图书文具
            '31', //今日必推
            '32', //京东好物
            '33', //京东秒杀
            '34', //拼购商品
            '40', //高收益榜
            '41', //自营热卖榜
            //            '108', //秒杀进行中
            '109', //新品首发
            '110', //自营
            '112', //京东爆品
            // '125', //首购商品
            '129', //高佣榜单
            //            '130', //视频商品
            //            '153', //历史最低价商品榜
            //            '238', //新人价商品
            //            '315', //秒杀未开始
            '341', //3C新品
            // '342', //智能新品
            '343', //3C长尾商品
            // '345', //时尚新品
            // '346', //时尚爆品
            //            '1001', //选品库
            //            '515', //订单接龙商品
            //            '519', //官方活动
            '12254', //超级补贴
            // '12318', //便宜包邮
            '12339', //超市卡
        ];
        $maxExecutionTime = 1800; // 最大执行时间5分钟
        $startTime = time();

        foreach ($eliteIdList as $eliteId) {
            // 检查是否超时
            if (time() - $startTime > $maxExecutionTime) {
                log::info("JD API error (eliteId:{$eliteId}): timeout");
                break; // 或记录日志
            }

            $page = 1;
            $maxPage = 1; // 默认值

            Db::startTrans();
            try {
                // 清除数据
                Db::name("third_party_goods")->where('type', '=', 2)->where('cid', '=', $eliteId)->delete();
                do {
                    try {
                        $result = $this->jd_query($eliteId, $page);
                        // 安全退出条件
                        if (empty($result) || !is_array($result)) {
                            break;
                        }
                        // 首次请求获取总页数
                        if ($page === 1 && isset($result['totalCount'])) {
                            $maxPage = max(1, (int)ceil($result['totalCount'] / 50));
                        }
                        // 处理数据
                        if (!empty($result['data'])) {
                            // 写入数据
                            $this->formatGoodsList($result['data'], $eliteId);
                        }
                        $page++;
                    } catch (\Exception $e) {
                        // 记录错误并继续下一个分类
                        log::info("JD API error (eliteId:{$eliteId}, page:{$page}): " . $e->getMessage());
                        break;
                    }
                } while ($page <= $maxPage);
                Db::commit();
            } catch (DbException $e) {
                Db::startTrans();
            }
        }

        return 'ok';
    }
    //请求京东联盟接口描述：京东联盟精选优质商品，每日更新，可通过频道ID查询各个频道下的精选商品。用获取的优惠券链接调用转链接口时，需传入搜索接口link字段返回的原始优惠券链接，切勿对链接进行任何encode、decode操作，否则将导致转链二合一推广链接时校验失败。
    public function jd_query($eliteId, $page)
    {
        $apiName = 'jd.union.open.goods.jingfen.query';
        $params = [
            'goodsReq' => [
                'eliteId' => $eliteId,
                'pageIndex' => $page ?? 1,
                'pageSize' => 50,
            ]
        ];
        $result = $this->getUrlResult($apiName, $params);
        $result = json_decode($result, true);

        $result = json_decode($result['jd_union_open_goods_jingfen_query_responce']['queryResult'], true);
        //        $result = $result['data'] ?? [];
        return $result;
    }

    //格式化从京东联盟获取到的商品列表
    public function formatGoodsList($goodsList, $eliteId)
    {
        $install = [];
        foreach ($goodsList as $goods) {
            // 售价
            if (!isset($goods['priceInfo']['price'])) {
                continue;
            }

            // 获取最优优惠券信息
            // 优惠券信息
            $maxCoupon = [];
            if (!empty($goods['couponInfo']['couponList'])) {
                foreach ($goods['couponInfo']['couponList'] as $coupon) {
                    // isBest 最优 优惠券
                    if ($coupon['isBest'] == 1) {
                        $maxCoupon = [
                            'discount' => $coupon['discount'],//优惠券金额
                            'getStartTime' => date('Y-m-d', intval($coupon['getStartTime'] / 1000)),
                            'getEndTime' => date('Y-m-d', intval($coupon['getEndTime'] / 1000)),
                            'link' => $coupon['link'],
                            'useStartTime' => date('Y-m-d', intval($coupon['useStartTime'] / 1000)),
                            'useEndTime' => date('Y-m-d', intval($coupon['useEndTime'] / 1000)),
                        ];
                        break;
                    }
                }
            }

            if (empty($maxCoupon)) {
                continue;
            }

            // 最低到手价
            $purchasePrice = $goods['priceInfo']['price'];
            // 券后价
            if (!empty($maxCoupon['discount'])) {
                // 拥有优惠券
                $purchasePrice = bcsub($goods['priceInfo']['price'], $maxCoupon['discount'], 2);
            }
            // 到手价
            if (!empty($goods['purchasePriceInfo']['purchasePrice']) && $goods['purchasePriceInfo']['purchasePrice'] < $purchasePrice) {
                $purchasePrice = $goods['purchasePriceInfo']['purchasePrice'];
            }

            // 券后佣金，（促销价-优惠券面额）*佣金比例
            $commissionMoney = bcmul($purchasePrice, bcdiv($goods['commissionInfo']['commissionShare'] ?? 0.00, 100, 5), 2);
            $commissionMoney = bcmul($commissionMoney, 0.8, 2);

            $formatList = [
                'type' => 6,//京东商品
                'skuId' => $goods['itemId'] ?? '',//itemId 京东官方 已不返回skuId , 使用 联盟商品ID 代替skuId
                'id' => $goods['brandCode'] ?? '', //id
                'name' => $goods['skuName'],//名称
                'thumb' => $goods['imageInfo']['imageList'][0]['url'] ?? '',//商品缩略图

                'pv' => bcmul($commissionMoney, 0.7, 2),//PV金额
                'gongxian' => bcmul($commissionMoney, 0.7, 2),
                'jifen' => bcmul($commissionMoney, 0.7, 2),
                'yanglaojin' => bcmul($commissionMoney, 0.3, 2),

                'commission' => $commissionMoney,//佣金
                'commission_rate' => $goods['commissionInfo']['commissionShare'] ?? 0.00,//佣金比例
                'coupon_money' => [$maxCoupon],
                'coupon_link' => $maxCoupon['link'] ?? '',
                'lowestCouponPrice' => $purchasePrice,
                'price' => $goods['priceInfo']['price'], //价格
                'imageList' => array_column($goods['imageInfo']['imageList'], 'url'), //图片合集
                'materialUrl' => $goods['materialUrl']
            ];
            $install[] = ['json' => json_encode($formatList, JSON_UNESCAPED_UNICODE), 'pension' => $commissionMoney, 'type' => 2, 'cid' => $eliteId];
        }
        if ($install) {
            Db::name("third_party_goods")->insertAll($install);
        }
    }

    /*订单获取(时间段,时间不能超过一小时)*/
    public function orderList()
    {
        // $time = $this->request->params([
        //     'startTime',
        //     'endTime'
        // ]);
        $time['startTime'] = request()->param('startTime', '');
        $time['endTime'] = request()->param('endTime', '');
        if (!$time['startTime'] && !$time['endTime']) {
            // $time['startTime'] = date("Y-m-d H:i:s", strtotime("-1 hour"));
            // $time['endTime'] = date('Y-m-d H:i:s');
            // 获取当前时间
            $currentTime = new DateTime();

            // 生成时间范围数组
            $timeRanges = [];
            for ($i = 0; $i < 30 * 24; $i++) {
                $endTime = clone $currentTime;
                $endTime->modify("-$i hour");

                $startTime = clone $endTime;
                $startTime->modify("-1 hour");
                $startTime->modify("+1 second");

                $timeRanges[] = [
                    'startTime' => $startTime->format('Y-m-d H:i:s'),
                    'endTime' => $endTime->format('Y-m-d H:i:s')
                ];
            }
        } else {
            $timeRanges[] = $time;
        }
        try {
            foreach ($timeRanges as $time) {
                $orderLists = [];
                $page = 1;
                $pageSize = 200;
                $apiName = 'jd.union.open.order.row.query';
                do {
                    $params = [
                        'orderReq' => [
                            'pageIndex' => $page,
                            'pageSize' => $pageSize,
                            'type' => 3,//(1：下单时间，2：完成时间（购买用户确认收货时间），3：更新时间
                            'startTime' => $time['startTime'],//格式2020-01-02 21:23:00
                            'endTime' => $time['endTime'], //格式2020-01-02 21:24:00
                            'fields' => 'goodsInfo'
                        ],
                    ];
                    $result = $this->getUrlResult($apiName, $params);
                    $result = json_decode($result, true);
                    $result = json_decode($result['jd_union_open_order_row_query_responce']['queryResult'], true);
                    $lists = $result['data'] ?? [];
                    $countList = count($lists);
                    if (!empty($countList)) {
                        $orderLists = array_merge($orderLists, $lists);
                    }

                    $page++;
                } while ($countList == $pageSize && $result['hasMore'] ?? false);
                if (!empty($orderLists)) {
                    //格式化从京东拉取的订单列表
                    $formatLists = $this->formatOrderList($orderLists);
                    //将京东订单列表中的订单进行处理
                    $this->operatePinOrder($formatLists);
                }
            }
            return app("json")->success("京东订单写入成功");
        } catch (\Exception $e) {
            return app("json")->fail($e->getMessage());
        }
    }


    //格式化从京东拉取的订单列表
    public function formatOrderList($orderLists)
    {
        $formatList = [];
        foreach ($orderLists as $order) {
            switch ($order['validCode']) {
                case 15://待付款订单
                    $billStatus = 0;
                    break;
                case 16://已付款订单
                    $billStatus = 0;
                    break;
                case 17://已完成状态
                    $billStatus = 0;
                    break;
                default://失效订单
                    $billStatus = 2;
            }
            if ($order['validCode'] == 15) { //未支付的不处理
                continue;
            }
            //通过订单关联
            $positionId = $order['positionId'];
            $userId = $positionId;
            if ($userId <= 0) {//拉取的订单没有匹配到用户
                continue;
            }

            //订单实际计算佣金的金额（订单完成时，会将误扣除的运费券金额更正，如订单完成后发生退款，此金额会更新）
            $goodsInfo = $order['goodsInfo'] ?? [];
            $createTime = strtotime($order['orderTime']);
            //平台可以进行结算的时间戳=订单创建时间+系统设置的间隔时间
            $billEndTime = $this->userThird->getSettleTime($createTime);

            $address = Db::name('user_address')->field('code_list,village_id')->where('uid', $userId)->where('is_default', 1)->find();

            $commission = $order['actualFee'] ?: $order['estimateFee'];
            // 生成推广链接时自定义放里边的参数（佣金_养老金）
            if (!empty($order['subUnionId'])) {
                $subUnionIdList = explode('_', $order['subUnionId']);
                if (!empty($subUnionIdList[0])) {
                    $commission = bcdiv($subUnionIdList[0], 1000, 2);
                }
            }
            $formatList[] = [
                'uid' => $userId,
                'commission' => $commission,//佣金
                'commission_share' => $order['finalRate'],
                'order_sn' => $order['orderId'],
                'pay_money' => $order['actualCosPrice'] ?: $order['estimateCosPrice'],
                'jd_id' => $order['id'],
                'create_time' => $order['orderTime'],
                'finish_time' => $order['finishTime'],//用户确认收货时间
                'modify_time' => $order['modifyTime'],//更新时间
                'sku_num' => $order['skuNum'],
                'sku_id' => $order['itemId'] ?? '', // 目前京东官方不返回 skuId
                'sku_name' => $order['skuName'],
                'price' => $order['price'],//原价
                'sub_union_id' => $order['positionId'],
                'image_url' => $goodsInfo['imageUrl'] ?? '',
                'shop_name' => $goodsInfo['shopName'] ?? '京东',
                'shop_id' => $goodsInfo['shopId'] ?? 0,
                'status' => $order['validCode'],//订单状态
                'bill_status' => $billStatus,        //平台是否结算
                'bill_end_time' => $billEndTime,
                'user_address_ids' => !empty($address) ? $address['code_list'] . ',' . $address['village_id'] : '',
                'type' => 1
            ];
        }
        return $formatList;
    }

    //将拼多多订单列表中的订单写入第三方平台订单表
    public function operatePinOrder($orderLists)
    {
        /** @var UserThirdRepository $orderThird */
        $orderThird = app()->make(UserThirdRepository::class);
        $type_shop = 6;
        foreach ($orderLists as $k => $order) {
            if (empty($order)) continue;
            //判断数据库有无此订单
            $localOrder = JdOrderModel::getInstance()->getOne(['order_sn' => $order['order_sn']]);
            if (empty($localOrder)) {
                //订单写入数据库,bill_end_time再格式化订单的时候已经加入,所以写入订单的时候就不需要在计算了
                $localOrder = JdOrderModel::create($order);
                //预估养老金
                $orderThird->yuguOrder(
                    $localOrder['order_jd_id'],
                    $localOrder['commission'],
                    $localOrder['uid'],
                    $localOrder['order_sn'],
                    $type_shop,
                    'order_jd');
                //预估积分
                $orderThird->yuguJifen(
                    $localOrder['order_jd_id'],
                    $localOrder['commission'],
                    $localOrder['uid'],
                    $localOrder['order_sn'],
                    $type_shop
                );
            } else {
                if($localOrder['status']!=$order['status']) {
                    $localOrder->save($order);//更新订单信息
                    if(!in_array($order['status'],[15,16,17])){
                        //修改积分和贡献,yanglaojin值记录
                        $orderThird->updateJilu(
                            $localOrder['uid'],
                            $localOrder['order_jd_id'],
                            $type_shop);
                    }
                }
            }

            // $orderVip = $orderThird->getOrderDetail("order_jd", ['order_sn' => $order['order_sn'], 'sub_union_id' => $order['sub_union_id']]);
            // if (!$orderVip) {
            //     // 读取商品详情 拿到商品图
            //     $third_party_goods_detail = Db::name('third_party_goods')->whereLike('json', '%' . $order['sku_id'] . '%')->find();
            //     $third_party_goods_json_detail = json_decode($third_party_goods_detail['json'], true);
            //     $order['image_url'] =  $third_party_goods_json_detail['thumb']??'';
            //
            //     $orderThird->createOrder('order_jd', $order, strtotime($order['create_time'])); //订单写入数据库
            //     //预估养老金
            //     $orderThird->yuguOrder(
            //         $order['jd_id'],
            //         $order['commission'],
            //         $order['uid'],
            //         $order['order_sn'],
            //         6,
            //         'order_jd');
            //     //预估积分
            //     $orderThird->yuguJifen(
            //         $order['jd_id'],
            //         $order['commission'],
            //         $order['uid'],
            //         $order['order_sn'],
            //         6
            //     );
            // } else {
            //     //更新
            //     if ($orderVip['status'] != $order['status']) {
            //         $saveOrderPdd['status'] = $order['status'];
            //         if(isset($order['bill_status'])){
            //             $saveOrderPdd['bill_status'] = $order['bill_status'];
            //         }
            //         $orderThird->saveOrder("order_jd", ['order_jd_id' => $orderVip['order_jd_id']], $saveOrderPdd); //修改订单
            //     }
            // }
        }
    }

    /*京东返利*/
    public function JdMoney()
    {
        //查询满足返利的数据
        $orderThird = $orderThird = app()->make(UserThirdRepository::class);
        $orderList = $orderThird->JdOrder();
        try {
            if ($orderList) {
                foreach ($orderList as $k => $order) {
                    $orderThird->successOrder($order['order_jd_id'], $order['commission'], $order['sub_union_id'], $order['order_sn'], 6, 'order_jd');
                }
                return app("json")->success("京东返利成功");
            } else {
                return app("json")->success("暂无可返利的数据");
            }
        } catch (\Exception $e) {
            return app("json")->fail($e->getMessage());
        }

    }


}
