<?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\FengsuService;
use GuzzleHttp\Psr7\Request;
use app\common\model\ImportList;
use app\admin\service\JuShuiTanService;

use think\facade\Cache;

//抖音
class FengSu extends Command
{

    //抖音请求地址
    protected $url = 'https://fsdy2.fengsutb.com/amount/ship-list-new';

    //抖音请求头部
    protected $headers = [
        'Host' => 'fsdy2.fengsutb.com',
        'Accept' => 'application/json, text/plain, */*',
        'Authorization' => 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODYwNTQ1MTExNSIsImRhdGFfcGVybWlzc2lvbiI6InByb2R1Y3RDb3N0IiwibmlrZSI6IjE4NjA1NDUxMTE1IiwiY3JlYXRlZCI6MTc2NDEyNTQwMzQ0OSwiZHBJZCI6MTAwNjczLCJleHAiOjE3NjQ3MzAyMDMsImVuYWJsZWQiOnRydWUsImF1dGhvcml0aWVzIjpbInpodXlvbmdodSJdLCJkcEFjY291bnRJZCI6MTAwNjczfQ.ihv6NRfD2hzU1NQoqttTaZ-mPxqAEXIUICM8MuxVx2tVLEPW9j-uPhHoFz4T3-lH07wTt2ORf1k_SPOQP4PuQg',
        'Content-Type' => 'application/json',
        // 'platform' => 'dy',
    ];

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

    //根据shop_id
    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始同步订单');

        $resquet = $this->getOrderList('');
        if ($resquet['code'] == 0) {
            $fengsu=[];
            $fengsu=Cache::get('fengsu');

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

                $fengsu_pageNum=$fengsu['pageNum'];
                $fengsu_pageNum=$fengsu_pageNum+1;
                $fengsu=[
                    'startTime'=>$fengsu['startTime'],
                    'endTime'=>$fengsu['endTime'],
                    'pageNum'=>$fengsu_pageNum,
                    'next_time_space'=>$fengsu['next_time_space']
                ];
                Cache::set('fengsu',$fengsu);


                $list = $resquet['data']['list'];
                // dump($list);
                // return;
                $this->insertOrder($list);
                //dump($resquet);
            } else {

                $fengsu=[
                    'startTime'=>$fengsu['startTime']+$fengsu['next_time_space'],
                    'endTime'=>$fengsu['endTime']+$fengsu['next_time_space'],
                    'pageNum'=>1,
                    'next_time_space'=>$fengsu['next_time_space']
                ];
                Cache::set('fengsu',$fengsu);


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

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

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

        $headers = [
            'Accept' => ' application/json, text/plain, */*',
            'Authorization' => site_config("addonsd.authorization_token"),
            'Host' => ' fsdy2.fengsutb.com',
            'platform' => $platform,
            '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;

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

        $fengsu_cache_data=Cache::get('fengsu');
        
        if(empty($fengsu_cache_data)||$fengsu_cache_data==null){
            Cache::set('fengsu',$fengsu);
        }
        $fengsu=Cache::get('fengsu');
        
        $startTime = date('Y-m-d H:i:s', $fengsu['startTime']);
        $endTime = date('Y-m-d H:i:s', $fengsu['endTime']);
        $pageNum=(int)$fengsu['pageNum'];
        
        $body = [
            'startTime'    => $startTime,//时间区间
            'endTime'    => $endTime,
            'sort'         => 'CONSIGN_TIME',
            'sortAsc'      => false,
            'current'      => $pageNum,//页数
            'size'         => 50,//每页多少条
            'tradeStatus'  => 2,
            'fromAccountId' => [],
            'goodType'     => 2,
            'goodsFlag'    => 2
        ];
            // 'waybillNos'   => ['73589756512463']
        $body = json_encode($body);
        
        $request = new Request('POST', 'https://fsdy2.fengsutb.com/amount/ship-list-new', $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();
        $shopDelivery_list = [];

        foreach ($order_list as $item) {
            $goods_id = $item['tradeOrderPrintVos'][0]['goodsId'];
            $oid = $item['tradeOrderPrintVos'][0]['oid'];
            $sku_id = $item['tradeOrderPrintVos'][0]['skuId'];
            $waybill_no = $item['waybillNo'];
            if (empty($waybill_no)) continue;
            $add_status = JuShuiTanService::prevent_duplicate_additions($sku_id, $waybill_no);
            if ($add_status) continue;
            // $status = FengsuService::getAdditionalPrice( $shopList, $importSku, $productConfig, $shopDelivery, $customerSpec, $item);

            $res = FengsuService::getAdditionalPrice($shopList, $importSku, $productConfig, $shopDelivery, $customerSpec, $item);
            $status = $res['status'];
            $shopDelivery_list[] = $res['shopDelivery'];

            $weight = $item['tradeOrderPrintVos'][0]['weight'];
            $weight = strval($weight);
            $weight = bcdiv($weight, '500', 2);
            $weight = (float)$weight;
            $price = $item['tradeOrderPrintVos'][0]['payment'];
            $price = strval($price);
            $price = bcdiv($price, '100', 2);
            $price = (float)$price;

            $getPackSpecsFee = JuShuiTanService::getPackSpecsFee($importSku, $item['shopId'], $item['tradeOrderPrintVos'][0]['skuId'], $item['receiverProvince']);

            $queue[] = [
                'type_id'       => $this->type_id,
                'shop_id'       => $item['shopId'],
                'order_id'       => $oid,
                'trade_from'    => $item['tradeFrom'],
                'province'      => $item['receiverProvince'],
                'city'          => $item['receiverCity'],
                'company_name'  => $item['companyName'],
                'waybill_no'    => $waybill_no,
                'consign_time'  => $item['consignTime'],
                'goods_id'      => $goods_id,
                'sku_id'        => $item['tradeOrderPrintVos'][0]['skuId'],
                'num'           => $item['tradeOrderPrintVos'][0]['total'],
                'goods_title'   => $item['tradeOrderPrintVos'][0]['goodsTitle'],
                'goods_info'   => $item['tradeOrderPrintVos'][0]['skuProp'],
                'weight'         => $weight,
                'price'         => $price,
                '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['tradeOrderPrintVos'][0]['orderStatus']


            ];
        }
        // 保存到数据库
        $shopDelivery->saveAll($shopDelivery_list);
        (new ImportList())->saveAll($queue);
        // 更新最后执行时间
        CrontabLog::create(['type_id' => 2, 'last_time' => date('Y-m-d H:i:s')]);
    }
}
//风速接口返回格式
//            {
//                "shopId": "DY117939700",
//                "sysNum": "3908161982177974",
//                "groupId": "g3908162034664709",
//                "tradeFrom": "dy",
//                "tid": "6948414820472788426",
//                "fromAccountId": 0,
//                "createTime": "2025-11-26 21:27:53",
//                "payTime": "2025-11-26 21:27:55",
//                "inserTime": "2025-11-27 15:11:27",
//                "inventoryPrintTime": null,
//                "consignTime": "2025-11-27 15:11:27",
//                "refunding": 0,
//                "buyerId": "1@#MhctHqbGY6MptrPvaPcNSU6JEPT1RwM+zhPxvrsCvBSVf2u9/qsla+xb9Fu81aUBMmCH",
//                "buyerNick": null,
//                "buyerMessage": "",
//                "sellerFlag": 0,
//                "localFlag": 0,
//                "sellerMemo": null,
//                "localMemo": null,
//                "offlineMemo": null,
//                "offlineFlag": null,
//                "receiverProvince": "黑龙江省",
//                "receiverCity": "哈尔滨市",
//                "receiverDistrict": "依兰县",
//                "receiverTown": "依兰镇",
//                "desensitizationName": "昕*",
//                "desensitizationPhone": null,
//                "desensitizationAddress": "*******",
//                "desensitizationMobile": "1**********",
//                "modifyAddr": 0,
//                "invoiceType": null,
//                "invoiceTitle": null,
//                "invoiceTaxId": null,
//                "promiseShipTime": "2025-12-01 21:27:56",
//                "tradeStatus": "WAIT_CONFIRM",
//                "payment": 9440,
//                "receiptAmount": 9440,
//                "postFee": 0,
//                "splitType": 1,
//                "packageNum": 1,
//                "dpAccountId": 100673,
//                "bizDpAccountId": 100673,
//                "uid": "117939700",
//                "bizShopId": "DY117939700",
//                "companyName": "中通快递",
//                "waybillNo": null,
//                "companyId": 3,
//                "templateId": 145375,
//                "printSize": 1,
//                "mergeHash": "6BC35CF08C74762098670BB71B38F77C387FB374",
//                "mergeHash2": "AC9CEFB7FD89A32A1AA235A9E09BD69FE838D08D",
//                "mergeable": 0,
//                "handDeliverFlag": 0,
//                "tradeAttr": "{\"promise_type\":1,\"recommend_logistics_list\":\"[]\"}",
//                "localAttr": null,
//                "senderAddressEntity": null,
//                "outChannel": null,
//                "tradeFlag": null,
//                "link": "",
//                "roleFlg": true,
//                "shopFlg": true,
//                "saleFlg": true,
//                "picUrlFlag": true,
//                "preSale": 1,
//                "preSaleTime": null,
//                "splitFailReason": null,
//                "businessTag": 0,
//                "locked": 0,
//                "tradeOrderPrintVos": [
//                    {
//                        "distTime": null,
//                        "orderStatus": "WAIT_CONFIRM",
//                        "goodsTitle": "田与薯云南圆圆果·榴莲蜜薯软糯蜜甜新鲜高原黄心番薯地瓜粗粮",
//                        "goodsId": "3665081518029678296",
//                        "skuProp": "{\"65\":\"小糖豆（50g-150g）\",\"66\":\"5斤(精品装（带箱5斤）)\",\"67\":\"5天内发货\"}",
//                        "companyName": "中通快递",
//                        "waybillNo": "76767227765924",
//                        "outerId": null,
//                        "refundStatus": null,
//                        "picUrl": "https://p3-aio.ecombdimg.com/obj/ecom-shop-material/jpeg_m_e379a8d857f16246745a757892497184_sx_320989_www1668-1668",
//                        "total": 1,
//                        "price": 3980,
//                        "payment": 3780,
//                        "receiptAmount": null,
//                        "orderType": 0,
//                        "consignTime": "2025-11-27 15:11:27",
//                        "signTime": null,
//                        "weight": 0,
//                        "goodShortName": null,
//                        "skuShortName": null,
//                        "oid": "6948414820472788426",
//                        "packageNum": 1,
//                        "splitType": 1,
//                        "companyId": 3,
//                        "templateId": 145375,
//                        "outerSkuId": "LFT-LLSPK-4.5-SC-CX",
//                        "skuId": "3617103894193922",
//                        "printSize": 1,
//                        "printTime": "2025-11-27 15:11:22",
//                        "roleType": 1,
//                        "roleName": "田与薯官方旗舰店",
//                        "lastFactoryId": 100673,
//                        "inventoryPrintSize": 0,
//                        "inventoryPrintTime": null,
//                        "platCode": "ZJ",
//                        "purchaseAttr": null,
//                        "shelfPosition": "",
//                        "pushTime": null,
//                        "orderAttr": "{\"author_name\":\"田与薯官方旗舰店\",\"order_goods_type\":0,\"order_biz\":2,\"pre_sale_label\":\"全款预售\",\"compensate_for_rotten_platform_guarantee\":\"坏了包退官方保障\",\"quick_refund_label\":\"极速退\",\"unsupport_7days_refund\":\"不支持7天\",\"c_biz_self_sell\":\"小店自卖\",\"compass_source_not_ad_mark\":\"非广告\",\"compass_source_content_type_live\":\"直播\",\"afterSaleType\":\"refund\",\"source_platform\":\"\",\"period_purchase_info\":{},\"pack_id\":\"147242304405974025\"}",
//                        "freeze": 0,
//                        "freezeReason": null,
//                        "auditStatus": 2,
//                        "payStatus": null,
//                        "settleStatus": null,
//                        "settleRefundStatus": null,
//                        "settleAmount": null,
//                        "templateType": "1",
//                        "productSkuName": null,
//                        "productSkuCode": null
//                    }
//                ],
//                "tradePrintList": null,
//                "platCode": "ZJ",
//                "purchaseId": null,
//                "purchaseStatus": null,
//                "supplierName": null,
//                "supplierId": null,
//                "purchaseName": null,
//                "offerId": null,
//                "specId": null,
//                "tradeClassify": "NORMAL",
//                "payType": "NORMAL",
//                "expressType": "NORMAL",
//                "msgTradeAttr": null,
//                "logisticsNames": null,
//                "logisticsTag": 0,
//                "tradeSource": null,
//                "printBatch": null,
//                "printBatchSn": 0,
//                "assignDeliveryId": null,
//                "factoryId": 100673,
//                "prepareShipGroupId": null,
//                "prepareShipDeliverStatus": null,
//                "prepareShipErrorMsg": null,
//                "prepareShipStatus": 0,
//                "prepareShipCreateTime": null,
//                "prepareShipUpdateTime": null,
//                "waybillEntities": [
//                    {
//                        "id": 7671095,
//                        "dpAccountId": 100673,
//                        "relationId": 3909499998804122,
//                        "deliveryId": 3,
//                        "waybillNo": "76767227765924",
//                        "createdTime": "2025-11-27 15:11:27",
//                        "recycleFlag": 0
//                    }
//                ],
//                "relationId": 3909499998804122,
//                "optType": 0,
//                "obsStatus": 0,
//                "obsTime": null,
//                "obsReason": null,
//                "printFailReason": null
//            },