<?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\FengsuSku;
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;

//抖音
class TaskDy 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',
    ];

    // 指令配置
    protected function configure()
    {
        $this->setName('task:dy')->setDescription('the task command');
    }

    //根据shop_id
    protected function execute(Input $input, Output $output)
    {
        dump($this->url);
        $client = new Client([ 'verify' => false]);
        $last_time = CrontabLog::getLastRunTime(2);
        $body = '{
        "goodType": 2,
        "goodsFlag": 1,
        "current": 1,
        "size": 25,
        "startTime": "'.$last_time.'",
        "endTime": "'.date('Y-m-d H:i:s').'",
        "skuOuterIdExact": false,
        "skuPropExact": false,
        "sort": "CONSIGN_TIME",
        "sortAsc": false,
        "timeType": 2,
        "tradeStatus": 2
        }';
        //获取Token

        $this->headers['Authorization'] = site_config('addonsd.authorization_token');
        dump($this->headers['Authorization']);
        $request = new Request('POST', $this->url, $this->headers, $body);

        dump($request);


        $res = $client->sendAsync($request)->wait();
        if($res->getStatusCode() == 200) {
            $data = json_decode($res->getBody()->getContents(), true);  
            $list = $data['data']['list'];
            if(empty($list)) {
                $output->writeln('无数据');
                return;
            }
            $queue = [];
            $shopList = new ShopList();
            $fengsuSku = new FengsuSku();
            $productConfig = new ProductConfig();
            $shopDelivery = new ShopDelivery();
            $customerSpec = new CustomerSpec();
            foreach($list as $item) {
                $status = FengsuService::getAdditionalPrice( $shopList, $fengsuSku, $productConfig, $shopDelivery, $customerSpec, $item);
                $queue[] = [
                    'shop_id'       => $item['shopId'],
                    'trade_from'    => $item['tradeFrom'],
                    'province'      => $item['receiverProvince'],
                    'city'          => $item['receiverCity'],
                    'company_name'  => $item['tradeOrderPrintVos'][0]['companyName'],
                    'waybill_no'    => $item['waybillNo'],
                    'consign_time'  => $item['consignTime'],
                    'goods_id'      => $item['tradeOrderPrintVos'][0]['goodsId'],
                    'sku_id'        => $item['tradeOrderPrintVos'][0]['skuId'],
                    'num'           => $item['tradeOrderPrintVos'][0]['total'],
                    'goods_title'   => $item['tradeOrderPrintVos'][0]['goodsTitle'],
                    'weigh'         => $item['tradeOrderPrintVos'][0]['weight'],
                    'price'         => bcdiv((string)$item['payment'], '100', 2),
                    'status'        => $status,
                ];
            }
            
            // 保存到数据库
            (new FengsuShip())->saveAll($queue);
            // 更新最后执行时间
            CrontabLog::create(['type_id' => 2,'last_time' => date('Y-m-d H:i:s')]);
        }

        // 指令输出
        $output->writeln('ok');
    }
}