<?php

namespace app\controller\api\store\product;

use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\user\UserThirdRepository;
use think\App;
use crmeb\basic\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

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 = '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()
    {
//         [$page, $limit] = $this->getPage();
//         $apiName = 'jd.union.open.goods.jingfen.query';
//         $params = [
//             'goodsReq'=>[
//                 'eliteId'=>2,
//                 'pageIndex'=>$page??1,
//                 'pageSize' =>20,
//             ]
//         ];
//         $result = $this->getUrlResult($apiName,$params);
//         $result =  json_decode($result,true);
//         $result =  json_decode($result['jd_union_open_goods_jingfen_query_responce']['result'],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']??'', //价格
//             ];
//         }

        [$page, $limit] = $this->getPage();
        $list = Db::name('third_party_goods')
            ->where('type', 2)
            ->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'];
            $json['yanglaojin'] = $json['pension'];

            // $json['shopName'] = "";
            // $json['monthSales'] = "0";
            // $json['cid'] = "0";
            $json['shopName'] = isset($json['shopName'])?$json['shopName']:"";
            $json['monthSales'] = isset($json['monthSales'])?$json['monthSales']:0;
            $json['cid'] = isset($value['cid'])?$json['cid']:0;
            $formatList[] = $json;
        }
        shuffle($formatList);
        return app("json")->success($formatList);
    }

    /*京粉精选商品查询接口*/
    public function search()
    {
//        [$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 = $this->request->param(['skuId']);
            $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);
            return app("json")->success($goodsDetail);
        } catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'微信审核------'.$e->getMessage().$e->getFile().$e->getLine()]);

            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 linkChange($url, $uid,$couponUrl)
    {

        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' => pow(11, 5) + $uid, //自定义,和订单关联
                'couponUrl'  => $couponUrl
            ],
        ];
        $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', //超市卡
        ];
        Log::info("===============get_jd_goods_list===================");
//        $eliteIdList = [1];
        foreach ($eliteIdList as $eliteId) {
            $jq_query=$this->jd_query($eliteId,1);
            $yema=(int)ceil($jq_query['totalCount']/50);
            for ($page = 1; $page <= $yema; $page++) {
                $result=$this->jd_query($eliteId,$page);
                if(isset($result['data']) && $result['data']){
                    $this->formatGoodsList($result['data']);
                }
            }
        }
        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)
    {
        $install = [];
        foreach ($goodsList as $goods) {
            $commissionMoney = $goods['commissionInfo']['couponCommission'] ?? 0;
            //养老金
            $oldMoney = app()->make(ProductRepository::class)->yanglaojin(0, $commissionMoney);
//            var_dump($goods);
//            return;
            if ($oldMoney < 0.1) continue;
            if (!isset($goods['couponInfo']['couponList'][0])) continue;
            foreach ($goods['couponInfo']['couponList'] as $coupon){

            }
            $goods['couponInfo']['couponList'][0]['getStartTime'] = date('Y-m-d', intval($goods['couponInfo']['couponList'][0]['getStartTime'] / 1000));
            $goods['couponInfo']['couponList'][0]['getEndTime'] = date('Y-m-d', intval($goods['couponInfo']['couponList'][0]['getEndTime'] / 1000));
            $formatList = [
                'type'              => 6,//京东商品
                'skuId'             => $goods['skuId'],//skuid
                'id'                => $goods['brandCode'] ?? '', //id
                'thumb'             => $goods['imageInfo']['imageList'][0]['url'] ?? '',//商品缩略图
                'name'              => $goods['skuName'],//名称
                'commission'        => $oldMoney,//佣金
                'commission_rate'   => $goods['commissionInfo']['commissionShare'] ?? '',//佣金比例
                'sales'             => "",
                'coupon_money'      => $goods['couponInfo']['couponList'] ?? [],
                'lowestCouponPrice' => decimal2($goods['priceInfo']['lowestCouponPrice']), //券后价lowestCouponPrice
                'price'             => $goods['priceInfo']['price'], //价格
                'imageList'         => array_column($goods['imageInfo']['imageList'], 'url'), //图片合集
            ];
            $install[]=['json' => json_encode($formatList, JSON_UNESCAPED_UNICODE), 'pension' => $oldMoney, 'type' => 2];
//            Db::name("third_party_goods")->insert(['json' => json_encode($formatList, JSON_UNESCAPED_UNICODE), 'pension' => $oldMoney, 'type' => 2]);
        }
        if($install){
            Db::name("third_party_goods")->insertAll($install);
        }

//        return $formatList;
    }

    /*订单获取(时间段,时间不能超过一小时)*/
    public function orderList()
    {
        $time = $this->request->params([
            'startTime',
            'endTime'
        ]);
        //自定义时间  每20分钟执行一次查询前半小时的数据
        if (!$time['startTime'] && !$time['endTime']) {
            $time['startTime'] = date("Y-m-d H:i:s", strtotime("-200 minute"));
            $time['endTime'] = date('Y-m-d H:i:s');
        }
//        var_dump($time);
        try {
            $orderLists = [];
            $page = 1;
            $pageSize = 40;
            $apiName = 'jd.union.open.order.row.query';
            do {
                $params = [
                    'orderReq' => [
                        'pageNo'    => $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
                    ],
                ];
                $result = $this->getUrlResult($apiName, $params);
//                var_dump($result);
                $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);
                }

//                var_dump($result);
                $page++;
            } while ($countList == $pageSize);
            if (!empty($orderLists)) {
                //格式化从京东拉取的订单列表
                $formatLists = $this->formatOrderList($orderLists);
//                var_dump($formatLists);
                //将京东订单列表中的订单进行处理
                $this->operatePinOrder($formatLists);
                return app("json")->success("京东订单写入成功");
            } else {
                return app("json")->success("暂无最新数据");
            }
        } catch (\Exception $e) {
            return app("json")->fail($e->getMessage());
        }
    }


    //格式化从京东拉取的订单列表
    public function formatOrderList($orderLists)
    {
//        $user = app()->make(UserThirdRepository::class);
        $formatLists = [];
        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 - pow(11, 5);
            //订单关联推广位ID
//            $pid = $order['subUnionId'] ?: '';
            // if (empty($pid)) continue;
            //订单关联推广位ID
//            $chanTag = $user->getDetail(['pid' => $order['subUnionId'], 'type' => 6], 'uid,pid');
            //if(!$chanTag){continue;}
            $formatLists[] = [
                'uid'              => $userId,
                'sku_id'           => $order['skuId'],
                'jd_id'            => $order['id'],
                'order_sn'         => $order['orderId'],                              //订单编号
                'sku_num'          => $order['skuNum'],                               //购买商品的数量
                'image_url'        => $order['goodsInfo']['imageUrl'] ?? '',
                'sku_name'         => $order['skuName'],
                //订单中sku的单件价格，单位为分
                'price'            => $order['price'],
                //未知,2.无效-拆单,3.无效-取消,4.无效-京东帮帮主订单,5.无效-账号异常,6.无效-赠品类目不返佣,7.无效-校园订单,
                //8.无效-企业订单,9.无效-团购订单,11.无效-乡村推广员下单,13.无效-违规订单,14.无效-来源与备案网址不符,
                //15.待付款,16.已付款,17.已完成（购买用户确认收货）,20.无效-此复购订单对应的首购订单无效,21.无效-云店订单',
                'status'           => $order['validCode'],
                //商家信息
                'shop_id'          => $order['goodsInfo']['shopId'],
                //订单生成时间
                'create_time'      => $order['orderTime'] ? $order['orderTime'] : 0,  //下单时间
                'finish_time'      => $order['finishTime'] ? $order['finishTime'] : 0,//完成时间
                'modify_time'      => $order['modifyTime'] ? $order['modifyTime'] : 0,//更新时间
                'sub_union_id'     => $order['subUnionId'],                           //订单关联推广位ID
                //佣金比例
                'commission_share' => $order['finalRate'],                            //最终分佣比例
                //实际佣金
                'commission'       => $order['estimateFee'],
                'bill_status'      => $billStatus,        //平台是否结算
                'type'             => 2
            ];
        }
        return $formatLists;
    }

    //将拼多多订单列表中的订单写入第三方平台订单表
    public function operatePinOrder($orderLists)
    {
        $orderThird = app()->make(UserThirdRepository::class);
        foreach ($orderLists as $k => $order) {
            if (empty($order)) continue;
            //判断数据库有无此订单
            $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());
        }

    }


}
