<?php

namespace App\Imports;

use App\Models\AgentOrder;
use App\Models\AgentOrderShare;
use App\Models\AgentUser;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;

class ImportAgentOrders implements ToCollection
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $collection)
    {
        foreach ($collection as $order)
        {
            if ($order[0] == "商品ID") continue;
            if ($order[10] == "伙伴") continue;
            $from_name = $order[10];
            //查找分享人
            $user = User::where("name", $from_name)->whereHas("officialWechat")->first();
            if (empty($user)) {
                $user = User::where("name", $from_name)->first();
            }
            if(empty($user)) {
                Log::info("ImportAgentOrders  订单手机号{$order[2]}  推荐人{$from_name} 没有找到账号");
                continue;
            }
            $order = AgentOrder::find($order[0]);
            if (empty($order)) {
                Log::info("ImportAgentOrders  订单手机号{$order[2]}  没有找到订单");
                continue;
            }
            AgentOrderShare::create([
                'user_id'=>$user->id,
                'order_id'=>$order->id,
                'trade_no'=>$order->trade_no,
                'amount'=>1560,
                'status'=>"APPLY",
            ]);
            $desc = "购买渣酒";
            AgentUser::changeLevel($order->user_id, AgentUser::AgentLevelBeing, $desc);
        }
    }
}
