<?php namespace App\Jobs\Company\BatchDeliver;


use App\Servers\Wechat\OpenPlat;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

use App\Facades\Servers\Logs\Log;

use App\Models\Manager\Company as   CompanyModel;
use App\Models\Manager\Orders;
use App\Models\Manager\OrdersProduct;
use App\Models\Manager\Lottery\LiveRecord;
use App\Models\OpenPlat\Component;
use App\Models\Manager\CustomOpenid;
use App\Models\Manager\OrdersAddr;

use App\Servers\DB\DbService;
use Illuminate\Support\Facades\DB;


/**
 * 奖品发放
 */
class DeliverJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** 奖品数据 **/
    protected $data;

    /**
     * 任务可尝试的次数
     *
     * @var int
     */
    public $tries = 3;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data    = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 获取数据
        $ordersData                                = $this->data;
        $orderId                                   = $ordersData['order_id'];
        $companyId                                 = $ordersData['company_id'];
        $expressId                                 = $ordersData['express_id'];
        $expressNo                                 = $ordersData['express_no'];
        $logisticsType                             = $ordersData['logistics_type'];
        try {
            // 切换数据库
            (new DbService())->getConnectionNameByCompanyId($ordersData['company_id']);
            // 中奖记录
            $LiveRecord                         = (new LiveRecord);
            $OrdersProduct                      = (new OrdersProduct);
            $Orders                             = (new Orders);
            $CompanyModel                       = (new CompanyModel);
            $Component                          = (new Component);
            $CustomOpenid                       = (new CustomOpenid);
            $OrdersAddr                         = (new OrdersAddr);
            $orderInfo                          = $Orders->query()->where('id','=',$orderId)->first()->toArray();
            if (!$orderInfo)                    Log::info('job_error/deliver_jobs', '发货失败，订单不存在',$ordersData);
            //获取订单产品详情
            $orderProducts						= $OrdersProduct->query()->where('order_id','=',$orderId)->get()->toArray();
            if (!$orderProducts)                Log::info('job_error/deliver_jobs', '发货失败，订单产品不存在',$ordersData);
            $productNames						= array_column($orderProducts,'product_name');
            $item_desc						    = implode(';',$productNames);
            //查询商户是否开启同步发货
            $synchDelivery          = $CompanyModel->query()->where('id','=',$companyId)->value('synch_delivery');
            if($orderInfo['is_pay'] == 1 && $orderInfo['port_type'] == 0 && $synchDelivery == 0){
                $receiverContact                    = '';
                //查询商户小程序APPID
                $map                                = [
                    'company_id'                    => $companyId,
                    'auth_type'                     => 2,
                ];
                $appId                              = $Component->query()->where($map)->value('authorizer_appid');
                //查询地址
                if ($expressId == 'SF'){
                    $addressInfo                      = $OrdersAddr->query()->where(['order_id'=>$orderId])->first();
                    if (!$addressInfo){
                        Log::info('job_error/deliver_jobs', '发货失败，订单收货地址不存在',$ordersData);
                    }
                    if ($addressInfo['contact_phone']){
                        $receiverContact                = hide_phone($addressInfo['contact_phone']);
                    }
                }
                $openMap                              = [
                    'custom_uid'                    => $orderInfo['custom_uid'],
                    'type'                          => 0,
                ];
                //查询客户openid
                $customOpenId                       = $CustomOpenid->query()->where($openMap)->value('openid');
                if (!$customOpenId){
                    Log::info('job_error/deliver_jobs', '发货失败，缺少客户openid',$ordersData);
                }
                $deliverData						= [
                    'order_number_type'				=> 2,
                    'mchid'					        => config('wechatpay.mini.mchid'),
                    'transaction_id'				=> $orderInfo['transaction_id'],
                    'delivery_mode'					=> 1,
                    'tracking_no'					=> $expressNo,
                    "express_company"               => $expressId,
                    "item_desc"                     => $item_desc,
                    'consignor_contact'             => '',
                    'receiver_contact'              => $receiverContact,
                    'upload_time'                   => time(),
                    'openid'                        => $customOpenId,
                    'logistics_type'                => $logisticsType,
                ];
                //同步到微信
                $result								= (new OpenPlat())->deliver($appId,$deliverData);
                if( $result['code'] == 'error' ){
                    // 回退数据
                    Log::info('job_error/deliver_jobs', '发货失败', $result);
                }
            }
            // 返回结果
            return                              $result;
        } catch (Throwable $th) {
            Log::info('job_error/deliver_jobs', $th->getMessage(), $ordersData);
        }
    }
}
