<?php

/**
 * ----------------------------------------------------------------------------
 * 行到水穷处，坐看云起时
 * 开发软件，找贵阳云起信息科技，官网地址:https://www.56q7.com/
 * ----------------------------------------------------------------------------
 * Author: 老成
 * email：85556713@qq.com
 */

declare(strict_types=1);

namespace app\admin\command;

use app\common\model\FengsuShip;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use GuzzleHttp\Client;
use app\common\model\CrontabLog;
use app\common\model\ImportSku;
use app\common\model\ShopList;
use app\common\model\ProductConfig;
use app\common\model\ShopDelivery;
use app\common\model\CustomerSpec;
use app\admin\service\JuShuiTanService;
use GuzzleHttp\Psr7\Request;
use app\common\model\ImportList;
use think\facade\Cache;
//抖音
class JuShuiTan extends Command
{

    //抖音请求地址
    protected $url = 'https://innerapi.scm121.com/api/inner/supOrder/getErpNormalOrders';

    //抖音请求头部
    protected $headers = [
        //'Host' => 'fsdy2.fengsutb.com',
        'Accept' => 'application/json, text/plain, */*',
        'Authorization' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiIyMTk0MzA5MSIsInJvbGVJZHMiOltdLCJ1c2VyX25hbWUiOiIxODE4MjY2OTkzNSIsImNvSWQiOiIxNDc5MjIyMiIsImV4cGlyYXRpb24iOjE3NjYyMTg0NDM1MzQsInVzZXIiOnsiY29JZCI6IjE0NzkyMjIyIiwiY29OYW1lIjoi5LqR5Y2X5LmQ55Wq55Sw5L6b5bqU6ZO-5pyJ6ZmQ5YWs5Y-4IiwibG9naW5OYW1lIjoiMTgxODI2Njk5MzUiLCJsb2dpbldheSI6IlVTRVJOQU1FIiwibmlja05hbWUiOiLmnY4iLCJyb2xlSWRzIjoiMTEsMTIsMTMsMTQsMTUsMTYsMTcsMTgsMjIsMjMsMjcsMjgsMjksMzAsMzEsMzIsMzMsMzQsMzUsMzYsMzksNDAsNDEsNTIsNTMsNTQsNjEsNjIsNjMsNjQsNjUsNjYsNjcsNzAsNzEsNzIsNzMsNzYsOTAsMTAxLDEwMiwxMDMsMTA0LDEwNSwxMDYsMTA3LDEwOCwxMDkiLCJ1aWQiOiIyMTk0MzA5MSJ9LCJhdXRob3JpdGllcyI6WyJKU1QtY2hhbm5lbCIsIm11bHRpTG9naW4iLCJKU1Qtc3VwcGxpZXIiXSwiY2xpZW50X2lkIjoicGMiLCJqdGkiOiIxYjNhZjA4OC04ZDhiLTRhNzMtYjcwNC1lYzhhY2QwNzU1ODUiLCJleHAiOjE3NjYyMTg0NDN9.fXIP-yUlJDIfd49QgxjTQXUlRka2gpw0NrfY7lB50sU',
        'Content-Type' => 'application/json',
        // 'platform' => 'dy',
    ];

    // 打单平台 1:风速  2：聚水潭
    protected $type_id = 2;
    // 指令配置
    protected function configure()
    {
        $this->setName('ju_shui_tan')->setDescription('the task command');
    }

    //根据shop_id
    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始同步聚水潭订单');
        $resquet = $this->getOrderList('dy');
        if ($resquet['success']) {
            $jushuitan=[];
            $jushuitan=Cache::get('jushuitan');

            if (count($resquet['data']) > 0) {

                

                $jushuitan_pageNum=$jushuitan['pageNum'];
                $jushuitan_pageNum=$jushuitan_pageNum+1;
                $jushuitan=[
                    'startTime'=>$jushuitan['startTime'],
                    'endTime'=>$jushuitan['endTime'],
                    'pageNum'=>$jushuitan_pageNum,
                    'next_time_space'=>$jushuitan['next_time_space']
                ];
                Cache::set('jushuitan',$jushuitan);
                
                $list = $resquet['data'];
                // dump($list);
                // return;
                $this->insertOrder($list);
                //dump($resquet);
            } else {
                $jushuitan=[
                    'startTime'=>$jushuitan['startTime']+$jushuitan['next_time_space'],
                    'endTime'=>$jushuitan['endTime']+$jushuitan['next_time_space'],
                    'pageNum'=>1,
                    'next_time_space'=>$jushuitan['next_time_space']
                ];
                Cache::set('jushuitan',$jushuitan);

                $output->writeln('没有数据');
            }
        } else {
            $output->writeln('接口错误: ' . $resquet['message']);
        }

        $output->writeln('ok');
    }

    public function getOrderList($platform = 'dy')
    {
        $client = new \GuzzleHttp\Client([
            'verify' => false,
            // 或指定证书路径
            // 'verify' => '/path/to/cacert.pem'
        ]);

        $headers = [
            'Accept' => ' application/json, text/plain, */*',
            'Authorization' => site_config('addonsd.ju_shui_tan_authorization_toke'),
            'Content-Type' => ' application/json'
        ];
        
        //时间间隔
        $start_end_space_time=10*60;
        //下一次时间间隔
        $next_time_space=7*60;


        //将查询分为，"2026-01-05 00:00:00~2026-01-05 00:05:00",查询该区间的订单，但是该时间区间单独数量可能超过50条，为了性能又不能一次性查询太多，从而进行分页查询，
        //查询不到数据,就往下一个时间区间查询
        $todayTime = date("Y-m-d");

        $startTime_stamp = strtotime($todayTime . ' 00:00:00');
        // $startTime_stamp = strtotime($todayTime . ' 07:20:00');
        $endTime_stamp=$startTime_stamp+$start_end_space_time;
        $pageNum=1;

        $jushuitan=[
            'startTime'=>$startTime_stamp,
            'endTime'=>$endTime_stamp,
            'pageNum'=>$pageNum,
            'next_time_space'=>$next_time_space
        ];

        $jushuitan_cache_data=Cache::get('jushuitan');
        
        if(empty($jushuitan_cache_data)||$jushuitan_cache_data==null){
            Cache::set('jushuitan',$jushuitan);
        }
        $jushuitan=Cache::get('jushuitan');

        $startTime = date('Y-m-d H:i:s', $jushuitan['startTime']);
        $endTime = date('Y-m-d H:i:s', $jushuitan['endTime']);
        $pageNum=(int)$jushuitan['pageNum'];

        $body = [
            'startTime'     => $startTime,     // 动态时间变量
            'endTime'       => $endTime,       // 动态时间变量
            'dateQueryType' => 'DeliveryDate',
            'coId'          => '14792222',
            'uid'           => '21943091',
            'upSendFailed'  => false,          // 布尔值保持原始类型
            'isExceptAddress' => 'Except',
            'pageNum'       => (int)$pageNum,  //当前页数
            'pageSize'      => 50,//每页数据多少
            'searchType'    => 1,       
            'orderStatus'   => ['Sent'] 
        ];
        $body = json_encode($body);
        
        // "orderStatus": [
        //         "Sent"
        //     ]
        // "orderFrom":"PINDUODUO"
        //"trackNo":"@SF3278427215674"
        $request = new Request('POST', 'https://innerapi.scm121.com/api/inner/supOrder/getErpNormalOrders', $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $json = [];
        if ($res->getStatusCode() == 200) {
            $json = json_decode($res->getBody()->getContents(), true);
        } else {
            dump($res->getStatusCode(), '接口返回结果');
        }
        return $json;
    }
    public function insertOrder($order_list)
    {
        if (!(count($order_list) > 0)) {
            return false;
        }
        $queue = [];
        $shopList = new ShopList();
        $importSku = new ImportSku();
        $productConfig = new ProductConfig();
        $shopDelivery = new ShopDelivery();
        $customerSpec = new CustomerSpec();

        usort($order_list, function ($a, $b) {
            // 将create_time转换为时间戳比较（支持字符串时间戳）
            $timeA = strtotime($a['deliveryDate']);
            $timeB = strtotime($b['deliveryDate']);

            // 降序排序（从新到旧）
            // return $timeB - $timeA;

            // 升序排序（从旧到新）可改为：
            return $timeA - $timeB;
        });
        $shopDelivery_list=[];
        foreach ($order_list as $item) {
            if (substr($item['trackNo'], 0, 1) === '@') continue;//同风速的，带@直接跳过
            // dump($item['shopId'], '店铺id');
            // 防止重复记录，订单号+快递单号
            $goods_id = $item['disInnerOrderGoodsViewList'][0]['shopIid'];

            $oid = $item['oid'];
            $sku_id=$item['disInnerOrderGoodsViewList'][0]['shopSkuId'];
            // $waybill_no = ltrim($item['trackNo'], '@');
            $waybill_no=$item['trackNo'];
            if (empty($waybill_no)) continue;
            $add_status = JuShuiTanService::prevent_duplicate_additions($sku_id, $waybill_no);
            if ($add_status) continue;
            // $status = JuShuiTanService::getAdditionalPrice($shopList, $importSku, $productConfig, $shopDelivery, $customerSpec, $item);
            $res = JuShuiTanService::getAdditionalPrice($shopList, $importSku, $productConfig, $shopDelivery, $customerSpec, $item);
           
            $status=$res['status'];
            $shopDelivery_list[]=$res['shopDelivery'];

            $getPackSpecsFee = JuShuiTanService::getPackSpecsFee($importSku, $item['shopId'], $item['disInnerOrderGoodsViewList'][0]['shopSkuId'], $item['receiverState']);

            $queue[] = [
                'type_id'       => $this->type_id,
                'shop_id'       => $item['shopId'],
                'order_id'       => $oid,
                'trade_from'    => $item['orderFrom'],
                'province'      => $item['receiverState'],
                'city'          => $item['receiverCity'],
                'company_name'  => $item['expressCompany'],
                'waybill_no'    => $waybill_no,
                'consign_time'  => $item['deliveryDate'],
                'goods_id'      => $goods_id,
                'sku_id'        => $item['disInnerOrderGoodsViewList'][0]['shopSkuId'],
                'num'           => $item['disInnerOrderGoodsViewList'][0]['itemCount'],
                'goods_title'   => $item['disInnerOrderGoodsViewList'][0]['itemName'],
                'goods_info'   => $item['disInnerOrderGoodsViewList'][0]['properties'],
                'weight'         => $item['weight'],
                'price'         => bcdiv((string)$item['disInnerOrderGoodsViewList'][0]['price'], '1', 2),
                'status'        => $status,
                'specs_name'        => $getPackSpecsFee['data']['title'],
                'pack_specs_id'        => $getPackSpecsFee['data']['id'],
                'labor_cost_money'        => $getPackSpecsFee['data']['labor_cost_money'],
                'one_surcharge_money'        => $getPackSpecsFee['one_surcharge_money'],
                'two_surcharge_money'        => $getPackSpecsFee['two_surcharge_money'],
                'order_status'   => $item['disInnerOrderGoodsViewList'][0]['status'],
            ];
            
        }
        // 保存到数据库
        $shopDelivery->saveAll($shopDelivery_list);
        (new ImportList())->saveAll($queue);
        // 更新最后执行时间
        CrontabLog::create(['type_id' => 2, 'last_time' => date('Y-m-d H:i:s')]);
    }
}
