<?php

namespace app\controller\api\store\product;

use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\user\UserRepository;
use app\common\repositories\user\UserThirdRepository;
use app\model\common\SuOrderModel;
use app\model\common\TbOrderModel;
use think\App;
use crmeb\basic\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use SuNing;
use think\facade\Log;
use app\controller\api\store\service\ThirdPartyCategory;

class Su extends BaseController
{
    public $appKey = '';
    public $secretKey = '';
    public $userThird;
    private $channel;

    public function __construct(App $app)
    {

        parent::__construct($app);
//        $this->appKey = '8349fdf89e7c46ff8ba28752093dfd09';
//        $this->secretKey = '7c386c01da509065febddde9f87d4821';
        $this->appKey = '7031e4de1179b326a904b9c2eec68eb1';
        $this->secretKey = 'bf0c498b244aaca811c19742602c2d4d';
        $this->channel = '';
        $this->userThird = app()->make(UserThirdRepository::class);
    }


    /*
    *
    * $apiName 服务名称
    * $method 方法名
    * $params  参数
    * $request  应用级参数
    * */
    public function getUrlResult($apiName, $request = [], $name)
    {
        if (empty($apiName)) {
            return false;
        }
        $request = $this->arrayToXml($request, $name);
        $sysParams["secret_key"] = $this->secretKey;
        $sysParams["method"] = $apiName;
        $sysParams["date"] = date('Y-m-d H:i:s');
        $sysParams["app_key"] = $this->appKey;
        $sysParams["api_version"] = "v1.2";
        $sysParams["post_field"] = base64_encode($request);
        $signHeader = $this->generateSignHeader($sysParams);

        unset($sysParams);

        $url = "https://open.suning.com/api/http/sopRequest/" . $apiName;
        //获取请求结果并返回
        return $this->curl($url, $request, $signHeader);

    }

    function generateSignHeader($params)
    {

        $signString = '';
        foreach ($params as $k => $v) {
            $signString .= $v;
        }
        $signString = md5($signString);
        // 组装头文件信息
        $signDataHeader = array(
            "Content-Type: text/xml; charset=utf-8",
            "AppMethod: " . $params['method'],
            "AppRequestTime: " . $params['date'],
            "Format: " . 'json',
            "signInfo: " . $signString,
            "AppKey: " . $params['app_key'],
            "VersionNo: " . $params['api_version'],
        );
        return $signDataHeader;
    }


    //通过curl发送post请求带body传参
    public function curl($url, $postFields = null, $header = array())
    {


        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        //body传参
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
        // 超时设置，以毫秒为单位
//        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        // 显示错误信息
        if (curl_error($curl)) {
            return curl_error($curl);
        } else {
            curl_close($curl);
            return json_decode($data, true);
        }
    }

    function arrayToXml($arr, $name)
    {
        $xml = "<sn_request><sn_body><$name>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<$key>$val</$key>";
            } else
                $xml .= "<$key><![CDATA[$val]]></$key>";
        }
        $xml .= "</$name></sn_body></sn_request>";
        return $xml;
    }

    // public function su_get_category(){
    //     $apiName = 'suning.netalliance.commoditycategory.query';
    //     $name = "queryInverstmentcommodity";
    //     $request = [
    //         'commoditycategoryList' => [
    //             "saleCategoryId"=>1,
    //             "saleGrade"=>1
    //         ]
    //     ];
    //     $result = $this->getUrlResult($apiName, $request, $name);
    //     $result = $result['sn_responseContent']['sn_body']['queryInverstmentcommodity'] ?? [];
    //     Log::info($result);
    //     // return json_encode($result);
    // }

    public function su_cron()
    {
        try{
            $total = 0;
            for($i=1; $i <= 100; $i++) {
                $apiName = 'suning.netalliance.inverstmentcommodity.query';
                $name = "queryInverstmentcommodity";
                $request = [
                    'size' => 40,
                    'pageIndex' => $i,
                    'couponMark' => 1,
                ];
                $result = $this->getUrlResult($apiName, $request, $name);
                
                $result = $result['sn_responseContent']['sn_body']['queryInverstmentcommodity'] ?? [];
                $total += count($result);
                // Log::info("===============su_cron===================");
                // Log::info($result);
                foreach ($result as $k => $goods) {
                    
                    // $yanglaojin = app()->make(ProductRepository::class)->yanglaojin(0, $goods['commodityInfo']['commodityPrice'] * $goods['commodityInfo']['rate'] / 100 ?? '');
                    
                    $commission=$goods['commodityInfo']['commodityPrice'] * $goods['commodityInfo']['rate'] / 100; //佣金
//                    $pv=round($commission* 0.5,2);  //PV
//                    $yanglaojin=$pv; //新的养老金

                    $systemvalueObj= $goods_obj = Db::name('system_config_value')
                        -> where('config_key','sanfangfenpei')->find();;
                    $sanfangfenpei=json_decode($systemvalueObj['value'],true);
                    $pv=round($commission*$sanfangfenpei['pv'],2);  //PV
                    $yanglaojin=round($commission*$sanfangfenpei['yanglaojin'],2); //新的养老金


                    // if($yanglaojin < 0.1) {
                    //     continue;
                    // }

                    //记录分类id到本地数据库
                    $cid=$goods['categoryInfo']['firstSaleCategoryId'];
                    $c_name=$goods['categoryInfo']['firstSaleCategoryName'];
                    (new ThirdPartyCategory())->addOrUpdateCategory($cid,$c_name , 4);


                    $goods = [
                        'type' => 3,//苏宁商品
                        'id' => $goods['commodityInfo']['commodityCode'] ?? '', //id
                        'thumb' => $goods['commodityInfo']['pictureUrl'][0]['picUrl'] ?? '',//商品缩略图
                        'name' => $goods['commodityInfo']['commodityName'],//名称
                        
                        'pv' => $pv,//佣金
                        'gongxian'=>$pv, //贡献
                        'jifen'=>$pv, //积分
                        'yanglaojin' => $yanglaojin,//养老金


                        'commission' => $commission,//佣金

                        'commission_rate' => $goods['commodityInfo']['rate'] ?? '',//佣金比例
                        'sales' => $goods['commodityInfo']["monthSales"],
                        'coupon_money' => $goods['couponInfo'] ?? [],
                        'market_price' => $goods['commodityInfo']['snPrice'],//苏宁价
                        'price' => $goods['commodityInfo']['commodityPrice'] ?? '', //价格

                        'shopName'=>$goods['commodityInfo']['supplierName'], //店铺名称
                        'monthSales'=>$goods['commodityInfo']['monthSales']>0?$goods['commodityInfo']['monthSales']:mt_rand(100,10000) //月销量
                    ];

                    // Log::info([
                    //     'json' => json_encode($goods, JSON_UNESCAPED_UNICODE),
                    //     'type' => 4,
                    //     'pension' => $yanglaojin,
                    //     'cid'=>$cid //一级分类
                    // ]);

                    Db::name("third_party_goods")->insert([
                        'json' => json_encode($goods, JSON_UNESCAPED_UNICODE),
                        'type' => 4,
                        'pension' => $commission,
                        'cid'=>$cid //一级分类
                    ]);
                    
                    // Log::info($yanglaojin);
                }
            }
            Log::info('苏宁获取的商品总数：' . $total);
        } catch(\think\Exception $e){
            Log::error('苏宁定时获取商品失败：' . $e->getMessage());
        }
    }

    // 数据库查询列表
    public function GoodList(UserRepository $repository)
    {
        [$page, $limit] = $this->getPage();

        $_cid = $this->request->param('cid');
        $keyword = $this->request->param('keyword');

        // $goods_obj = Db::name('third_party_goods')->where('type', 4)->page($page, $limit)->select()->toArray();
        $goods_obj = Db::name('third_party_goods')->where('type', 4);
        if($keyword){
            $goods_obj=$goods_obj->where('json', 'like', '%' . $keyword . '%');
        }
        if($_cid){
            $goods_obj=$goods_obj->where('cid', $_cid);
        }

        $data=$goods_obj->page($page, $limit)
        ->select()->toArray();
        



        // 获取列表数据
        
        $goodslist = [];
        if(!empty($data)) {
            foreach ($data as $value) {
                $json=json_decode($value['json'], true);
                $json['market_price']=set_price_rtrim($json['market_price']);
                $json['price']=set_price_rtrim($json['price']);
                $json['commission']=set_price_rtrim($json['commission']);

                $json['pension'] = $json['pension']??'0';

                $json['pv'] = isset($json['pv'])?$json['pv']:0;
                $json['gongxian'] = isset($json['gongxian'])?$json['gongxian']:0;
                $json['jifen'] = isset($json['jifen'])?$json['jifen']:0;
                $json['yanglaojin'] =isset($json['yanglaojin'])?$json['yanglaojin']:0;

                $json['shopName'] = isset($json['shopName'])?$json['shopName']:"";
                $json['monthSales'] = isset($json['monthSales'])?$json['monthSales']:0;
                $json['cid'] = isset($value['cid'])?$value['cid']:0;
                $goodslist[] = $json;

            }
        }
        $uid = $uid ?? 0;
        $repository->sproductkeywordHistory($uid, $keyword, 4);
        return app('json')->success('获取苏宁商品列表成功', $goodslist);
    }

    /*苏宁商品列表高佣专区类目查询接口*/
    public function GoodList_del()
    {
        [$page, $limit] = $this->getPage();
        $apiName = 'suning.netalliance.inverstmentcommodity.query';
        $name = "queryInverstmentcommodity";
        $request = [
            'size' => $limit,
            'pageIndex' => $page,
            'couponMark' => 1,
        ];
        $result = $this->getUrlResult($apiName, $request, $name);
        $result = $result['sn_responseContent']['sn_body']['queryInverstmentcommodity'] ?? [];
        $goodsList = [];

        $apiNames = 'suning.netalliance.unioninfomation.get';
        $names = "getUnionInfomation";

        foreach ($result as $k => $goods) {


            $requests = ['goodsCode' => $goods['commodityInfo']['commodityCode'] ?? ''];
            $result = $this->getUrlResult($apiNames, $requests, $names);
            if(!empty($result['sn_responseContent']['sn_error']))continue;
            $goodsList[] = [
                'type' => 3,//苏宁商品
                'id' => $goods['commodityInfo']['commodityCode'] ?? '', //id
                'thumb' => $goods['commodityInfo']['pictureUrl'][0]['picUrl'] ?? '',//商品缩略图
                'name' => $goods['commodityInfo']['commodityName'],//名称
                'commission' => app()->make(ProductRepository::class)
                    ->yanglaojin(0, $goods['commodityInfo']['commodityPrice'] * $goods['commodityInfo']['rate'] / 100 ?? ''),//佣金
                'commission_rate' => $goods['commodityInfo']['rate'] ?? '',//佣金比例
                'sales' => $goods['commodityInfo']["monthSales"],
                'coupon_money' => $goods['couponInfo'] ?? [],
                'market_price' => $goods['commodityInfo']['snPrice'],//苏宁价
                'price' => $goods['commodityInfo']['commodityPrice'] ?? '', //价格
            ];
        }
        return app('json')->success('获取苏宁商品列表成功', $goodsList);
    }

    public function test()
    {
        $params = [
            'startTime' => '2021-03-01 00:00:00',
            'endTime' => '2021-03-01 23:59:59',
        ];
        $orderLists = [];
        $page = 1;
        $pageSize = 50;
        do {
            $apiName = 'suning.netalliance.order.query';
            $name = "queryOrder";
            $request = [
                'pageNo' => $page,
                'pageSize' => $pageSize,
                'startTime' => $params['startTime'],
                'endTime' => $params['endTime']
            ];
            $result = $this->getUrlResult($apiName, $request, $name);
            $lists = $result['sn_responseContent']['sn_body']['queryOrder'] ?? [];
            $countList = count($lists);
            if (!empty($countList)) {
                $orderLists = array_merge($orderLists, $lists);
            }
            $page++;
        } while ($countList == $pageSize);
        return $orderLists;
    }

    /*苏宁商品列表*/
    public function searchOld()
    {
        [$page, $limit] = $this->getPage();
        $keyword = $this->request->param(['keyword']);
        $apiName = 'suning.netalliance.searchcommodity.query';
        $name = "querySearchcommodity";
        $request = [
            'size' => 10,
            'pageIndex' => $page,
            'keyword' => $keyword['keyword'],
        ];
        $response = $this->getUrlResult($apiName, $request, $name);
        $result = $response['sn_responseContent']['sn_body']['querySearchcommodity'] ?? [];
        if (!$result) {
            return app('json')->success('未查询到商品', $response);
        }
        $goodsList = [];
        foreach ($result as $k => $goods) {
            $goodsList[] = [
                'type' => 3,//苏宁商品
                'id' => $goods['commodityInfo']['commodityCode'] ?? '', //id
                'thumb' => $goods['commodityInfo']['pictureUrl'][0]['picUrl'] ?? '',//商品缩略图
                'name' => $goods['commodityInfo']['commodityName'],//名称
                'commission' => app()->make(ProductRepository::class)
                    ->yanglaojin(0, $goods['commodityInfo']['commodityPrice'] * $goods['commodityInfo']['rate'] / 100 ?? ''),//佣金
                'commission_rate' => $goods['commodityInfo']['rate'] ?? '',//佣金比例
                'sales' => $goods['commodityInfo']["monthSales"],
                'coupon_money' => $goods['couponInfo'] ?? [],
                'lowestCouponPrice' => $goods['commodityInfo']['commodityPrice'] ?? '', //苏宁价
                'price' => $goods['commodityInfo']['snPrice'] ?? '', //价格
            ];
        }
        return app('json')->success('获取苏宁商品列表成功', $goodsList);
    }

    // 数据库搜索
    public function search()
    {
        [$page, $limit] = $this->getPage();
        $keyword = $this->request->param('keyword');
        $_cid = $this->request->param('cid');
        // dd($_cid);
        $userId = $this->request->uid();
        TaoKe::set_third_history($userId,$keyword);
        

        $goods_obj = Db::name('third_party_goods')
            ->where('type', 4);
        if($keyword){
            $goods_obj=$goods_obj->where('json', 'like', '%' . $keyword . '%');
        }
        if($_cid){
            $goods_obj=$goods_obj->where('cid', $_cid);
        }
        $goods=$goods_obj->page($page, $limit)
            ->select()->toArray();
        $goodsList = [];

        if(!empty($goods)) {
            foreach ($goods as $value) {
                $json = json_decode($value['json'], true);
                $json['pension'] = $json['pension']??'0';
                $json['pv'] = $json['pension']*0.5;

                $json['pv'] = isset($json['pv'])?$json['pv']:0;
                $json['gongxian'] = isset($json['gongxian'])?$json['gongxian']:0;
                $json['jifen'] = isset($json['jifen'])?$json['jifen']:0;
                $json['yanglaojin'] =isset($json['yanglaojin'])?$json['yanglaojin']:0;

                $json['shopName'] = isset($json['shopName'])?$json['shopName']:"";
                $json['monthSales'] = isset($json['monthSales'])?$json['monthSales']:0;
                $json['cid'] = isset($value['cid'])?$value['cid']:0;
                $goodsList[] = $json;
            }
        }
        return app('json')->success('搜索苏宁商品列表成功', $goodsList);
    }

    //苏宁商品搜索
    public function search_del()
    {
        [$page, $limit] = $this->getPage();
        $keyword = $this->request->param(['keyword']);
        $userId = $this->request->uid();
        TaoKe::set_third_history($userId,$keyword['keyword']);
        $apiName = 'suning.netalliance.searchcommodity.query';
        $name = "querySearchcommodity";
        $request = [
            'size' => 10,
            'pageIndex' => $page,
            'keyword' => $keyword['keyword'],
            'couponMark' => 1,
            'sortType'=>7
        ];
        $response = $this->getUrlResult($apiName, $request, $name);
        $result = $response['sn_responseContent']['sn_body']['querySearchcommodity'] ?? [];
        $goodsList = [];
        foreach ($result as $k => $goods) {
            if($goods['commodityInfo']['commodityPrice'] == null || $goods['commodityInfo']['commodityPrice'] <= 0){
                continue;
            }
            $goodsList[] = [
                'type' => 3,//苏宁商品
                'id' => $goods['commodityInfo']['commodityCode'] ?? '', //id
                'thumb' => $goods['commodityInfo']['pictureUrl'][0]['picUrl'] ?? '',//商品缩略图
                'name' => $goods['commodityInfo']['commodityName'],//名称
                'commission' => app()->make(ProductRepository::class)
                    ->yanglaojin(0, $goods['commodityInfo']['commodityPrice'] * $goods['commodityInfo']['rate'] / 100 ?? ''),//佣金
                'commission_rate' => $goods['commodityInfo']['rate'] ?? '',//佣金比例
                'sales' => $goods['commodityInfo']["monthSales"],
                'coupon_money' => $goods['couponInfo'] ?? [],
                'sn_price' => $goods['commodityInfo']['snPrice'],//易购价
                'commodity_price' => $goods['commodityInfo']['commodityPrice'],//商品价格
                'market_price' => $goods['commodityInfo']['snPrice'],
                'price' => $goods['commodityInfo']['commodityPrice'] ?? '', //苏宁价
            ];
        }
        return app('json')->success('搜索苏宁商品列表成功', $goodsList);
    }

    /*推广位(生成工具商PID接口,弃用)*/
    public function createPid($uid)
    {
        $apiName = 'suning.netalliance.toolseller.add';
        $name = "addToolseller";
        $request = [
            'mediaCustNum' => $uid,
            'channel' => $this->channel ? $this->channel : 24,
        ];
        $result = $this->getUrlResult($apiName, $request, $name);
        $result = $result['sn_responseContent']['sn_body']['addToolseller']['pid'];
        if ($result) {
            $data =
                [
                    'pid' => $result,
                    'pid_name' => $result,
                    'create_time' => date("Y-m-d H:i:s"),
                    'type' => 3,
                    'uid' => $uid,
                ];
        }
        $pdd_id = $this->userThird->createPid($data);
        return $pdd_id;
    }


    /*商品详情*/
    public function goodsDetail($id)
    {
        try{
            $uid = $this->request->uid();
        } catch (\Exception $e) {
            $uid=0;
        }
//        $pid = $this->userThird->getDetail(['uid'=>$uid,'type'=>3]);
//        //上线后这几行可屏蔽
//        if(!$pid){
//            $this->createPid($uid);
//            $pid = $this->userThird->getDetail(['uid'=>$uid,'type'=>3]);
//        }
        $pid = '';
        $url = $this->request->params(['couponUrl']);
        $is_mp = $this->request->param('is_mp',0);
        $apiName = 'suning.netalliance.unioninfomation.get';
        $name = "getUnionInfomation";
        $request = ['goodsCode' => $id];
        $result = $this->getUrlResult($apiName, $request, $name);
        if (isset($result['sn_responseContent']['sn_error']['error_msg']) && $result['sn_responseContent']['sn_error']['error_msg'] == '查询没结果')
            return app('json')->fail('商品下架不存在', null, 401);
        $result = $result['sn_responseContent']['sn_body']['getUnionInfomation'][0] ?? [];
        //获取商品的图文详情
        $detail = $this->goodImgDetail($result['mertCode'] ?? '', $result['goodsCode'] ?? '');


        $commission=$result['wapPrePayCommission'] ; //佣金(预估)
//        $commission=$result['commodityInfo']['commodityPrice'] * $result['commodityInfo']['rate'] / 100; //佣金
        log::info("===========commission=====$commission=============");
        log::info("===========res==================");
        log::info($result);
//        $pv=$commission* 0.5;  //PV
//        $yanglaojin=$pv; //新的养老金

        $systemvalueObj= $goods_obj = Db::name('system_config_value')
            -> where('config_key','sanfangfenpei')->find();;
        $sanfangfenpei=json_decode($systemvalueObj['value'],true);
        $pv=round($commission*$sanfangfenpei['pv'],2);  //PV
        $yanglaojin=round($commission*$sanfangfenpei['yanglaojin'],2); //新的养老金

        $gongxian=$pv; //新的养老金
        $jifen=$pv; //新的养老金
        

        $result['pv']=round($pv,2);
        $result['yanglaojin']=round($yanglaojin,2);
        $result['gongxian']=round($gongxian,2);
        $result['jifen']=round($jifen,2);

        // Log::info($result);
        $result['detail'] = $detail;
        //商品和券二合一
        if($is_mp == 1){
            $result['url'] = $this->toMpOneUrl($uid, $result['productUrl'], $url['couponUrl'] ?? '');
        }else{
            $result['url'] = $this->toOneUrl($uid, $result['productUrl'], $url['couponUrl'] ?? '');
        }
        return app('json')->success('获取苏宁商品详情成功', $result);
    }

    //获取商品详情
    public function h5GetDetail($goodsId, $userId = 0)
    {
        $is_mp = $this->request->param('is_mp',0);
        $apiName = 'suning.netalliance.unioninfomation.get';
        $name = "getUnionInfomation";
        $request = ['goodsCode' => $goodsId];
        $response = $this->getUrlResult($apiName, $request, $name);
        $result = $response['sn_responseContent']['sn_body']['getUnionInfomation'][0] ?? [];
        if (empty($result)) {
            return ['code' => 0, 'url' => '', 'raw' => $response];
        }
        $commission = $result['prePayCommission'] ?: 0;
        $yanglao = $commission ? app()->make(ProductRepository::class)
            ->yanglaojin(0, $commission) : 0;
        if($is_mp == 1){
            $changUrl = $this->toMpOneUrl($userId, $result['productUrl'], $result['couponUrl'] ?? '');
        }else{
            $changUrl = $this->toOneUrl($userId, $result['productUrl'], $result['couponUrl'] ?? '');
        }
        return ['code' => 1, 'yanglao' => $yanglao, 'url' => $changUrl];
    }


    //商品图文详情查询
    public function goodImgDetail($supplyId, $goodsId)
    {
        if (empty($supplyId) || empty($goodsId)) return [];
        $apiName = 'suning.netalliance.commodityimages.query';
        $name = "queryCommodityimages";
        $request = [
            'supplierCode' => $supplyId,
            'commodityCode' => $goodsId,
        ];
        $response = $this->getUrlResult($apiName, $request, $name);
        $result = $response['sn_responseContent']['sn_body']['queryCommodityimages']['images'] ?? [];
        return $result ? array_column($result, 'img') : [];
    }


    /*
     * 商品和券二合一转链接口
    $productUrl 商品url
    $couponUrl  优惠券url
    $pid  用户苏宁工具商pid
    */
    public function toOneUrl($userId, $productUrl, $couponUrl = '')
    {
        $apiName = 'suning.netalliance.extensionlink.get';
        $name = "getExtensionlink";
        $request = [
            'productUrl' => $productUrl,
            'subUser' => $userId,//子会员编号
        ];
        $couponUrl && $request['quanUrl'] = $couponUrl;
        $result = $this->getUrlResult($apiName, $request, $name);
        return $result['sn_responseContent']['sn_body']['getExtensionlink']['shortLink'] ?? '';
    }

    /*
     * 商品和券二合一转链接口(小程序)
    $productUrl 商品url
    $couponUrl  优惠券url
    $pid  用户苏宁工具商pid
    */
    public function toMpOneUrl($userId, $productUrl, $couponUrl = '')
    {
        $apiName = 'suning.netalliance.appletextensionlink.get';
        $name = "getAppletextensionlink";
        $request = [
            'productUrl' => $productUrl,
            'subUser' => $userId,//子会员编号
        ];
        $couponUrl && $request['quanUrl'] = $couponUrl;
        $result = $this->getUrlResult($apiName, $request, $name);
        return $result['sn_responseContent']['sn_body']['getAppletextensionlink']['appletExtendUrl'] ?? '';
    }


    /*城市编码*/
    public
    function cityCode()
    {
        $apiName = 'suning.custom.city.query';
        $name = "city";
        $request = [
            'nationCode' => 'CN',
        ];
        $result = $this->getUrlResult($apiName, $request, $name);
        var_dump($result);
    }

    /*转链*/
    public
    function changeLink($url, $uid = '')
    {

        if (!$uid) {
            return $url;
        }
        //$pid = $this->userThird->getDetail(['uid'=>$uid,'type'=>3]);
        $apiName = 'suning.netalliance.custompromotionurl.query';
        $name = "queryCustompromotionurl";
        $request = [
            'visitUrl' => $url,
            'pid' => ''
        ];
        $result = $this->getUrlResult($apiName, $request, $name);
        $result = $result['sn_responseContent']['sn_body']['queryCustompromotionurl']['extendUrl'] ?? '';
        return $result;
    }


    /*获取订单*/
    public function orderList()
    {
        /*
        $time = $this->request->params([
            'startTime',
            'endTime'
        ]);
        */
        $params = request()->param();
        //自定义时间 每20分钟执行一次查询前二十分钟的数据
        if (empty($params)) {
            $params = [
                'startTime' => date("Y-m-d H:i:00", strtotime("-20 minute")),
                'endTime' => date('Y-m-d H:i:s'),
            ];
        }
        try {
            $orderLists = [];
            $page = 1;
            $pageSize = 50;
            do {
                $apiName = 'suning.netalliance.order.query';
                $name = "queryOrder";
                $request = [
                    'pageNo' => $page,
                    'pageSize' => $pageSize,
                    'startTime' => $params['startTime'],
                    'endTime' => $params['endTime']
                ];
                $result = $this->getUrlResult($apiName, $request, $name);
                $lists = $result['sn_responseContent']['sn_body']['queryOrder'] ?? [];
                $countList = count($lists);
                if (!empty($countList)) {
                    $orderLists = array_merge($orderLists, $lists);
                }
                $page++;
            } while ($countList == $pageSize);
            if (!empty($orderLists)) {
                //格式化从苏宁拉取的订单列表并处理
                $formatLists = $this->formatOrderList($orderLists);
                $this->operateOtherOrder($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) {
            $orderCode = $order['orderCode'];
            $orderDetail = reset($order['orderDetail']);
            $orderStatus = $orderDetail['orderLineStatusDesc'];
            //苏宁订单关联单号
            $pid = $userId = $orderDetail['childAccountId'] ?? 0;
            $createTime = strtotime($orderDetail['orderSubmitTime']);
            $payTime = $orderDetail['payTime'] ? strtotime($orderDetail['payTime']) : 0;
            $changeTime = $orderDetail['orderLineStatusChangeTime'] ? strtotime($orderDetail['orderLineStatusChangeTime']) : 0;
            $billStatus = $orderStatus == '退款' ? 2 : 0;
            //平台可以进行佣金结算的时间(订单创建时间+后台配置的时间间隔)
            $billEndTime = $user->getSettleTime($createTime);
            $isReturnCommission = $orderDetail['returnCommission'];
            $commission = 0;
            $commissionRate = $orderDetail['commissionRatio'];
            if ($isReturnCommission == 1) {//订单有返佣
                $commission = sprintf('%.2f', $orderDetail['payAmount'] * $commissionRate);
            }
            $address = Db::name('user_address')->field('code_list,village_id')->where('uid',$userId)->where('is_default',1)->find();
            $formatLists[] = [
                'uid' => $userId,
                'order_sn' => $orderCode,//订单号
                'pid' => $pid,//苏宁通过子会员编号进行订单与app用户匹配
                'status' => $orderStatus,//状态: 支付完成；退款；确认收货
                'goods_id' => $orderDetail['goodsNum'],//商品id
                'goods_name' => $orderDetail['productName'],//商品名称
                'goods_thumb' => $orderDetail['pictureUrl'],//商品图片
                'goods_count' => $orderDetail['saleNum'],//数量
                'cust_no' => $orderDetail['custNo'] ?? '',//推广会员编码
                'order_time' => $createTime,//下单时间
                'pay_time' => $payTime,//支付时间
                'change_time' => $changeTime,//修改时间
                'pay_amount' => $orderDetail['payAmount'],//订单金额
                'pre_commission' => $orderDetail['prePayCommission'],//预估佣金
                'commission' => $commission,//佣金
                'commission_rate' => $commissionRate,//佣金比例
                'bill_status' => $billStatus,
                'bill_end_time' => $billEndTime,
                'create_time' => $orderDetail['orderSubmitTime'],
                'user_address_ids'=> !empty($address) ? $address['code_list'] . ',' . $address['village_id'] : ''
            ];
        }
        return $formatLists;
    }


    /*处理订单*/
    public function operateOtherOrder($orderLists)
    {
        $orderThird = app()->make(UserThirdRepository::class);
        foreach ($orderLists as $k => $order) {
            if (empty($order)) continue;
            //判断数据库有无此订单
            $localOrder = SuOrderModel::getInstance()->getOne(['order_sn' => $order['order_sn']]);
            if (empty($localOrder)) {
                //订单写入数据库,bill_end_time再格式化订单的时候已经加入,所以写入订单的时候就不需要在计算了
                $localOrder = SuOrderModel::create($order);
                //预估养老金
                $orderThird->yuguOrder(
                    $localOrder['order_su_id'],
                    $localOrder['commission'],
                    $localOrder['uid'],
                    $localOrder['order_sn'],
                    3,
                    'order_su');
                //预估积分
                $orderThird->yuguJifen(
                    $localOrder['order_su_id'],
                    $order['commission'],
                    $order['uid'],
                    $order['order_sn'],
                    3
                );
            } else {
                if($localOrder['status']!=$order['status']) {
                    $localOrder->save($order);//更新订单信息
                    //修改积分和贡献,yanglaojin值记录
                    $orderThird->updateJilu(
                        $localOrder['uid'],
                        $localOrder['order_su_id'],
                        3);
                }
            }

        }
    }

    /*苏宁返利*/
    public function SuMoney()
    {
        $baseWhere = ['bill_status' => 0, 'status' => '确认收货'];
        $orderList = Db::name('order_su')->where($baseWhere)
            ->where('bill_end_time', '<=', time())
            ->select();
        try {
            $orderThird = app()->make(UserThirdRepository::class);
            foreach ($orderList as $k => $order) {
                $orderThird->successOrder(
                    $order['order_su_id'],
                    $order['commission'],
                    $order['pid'],
                    $order['order_sn'],
                    3,
                    'order_su');
            }
            return app("json")->success("唯品会结算定时任务执行成功");
        } catch (\Exception $e) {
            return app("json")->fail($e->getMessage());
        }
    }

}
