<?php

namespace App\Http\Controllers;

use App\Exports\AgentUsersSimpleExport;
use App\Facades\CommonService;
use App\Facades\HttpService;
use App\Facades\TaskService;
use App\Facades\UserService;
use App\Facades\WechatService;
use App\Http\Response\ResponseJson;
use App\Imports\ActivityOrdersImport;
use App\Imports\AgentUsersImport;
use App\Imports\ApplyUserImport;
use App\Imports\ImportAgentOrders;
use App\Imports\ImportPackCode;
use App\Jobs\SendEasySms;
use App\Jobs\SendSubscribeMessage;
use App\Jobs\SendTemplateNotice;
use App\Jobs\SyncDailyStep;
use App\Jobs\SyncSaasUser;
use App\Jobs\TestJob;
use App\Models\ActivityIntroduceLog;
use App\Models\ActivityOrder;
use App\Models\AgentOrder;
use App\Models\AgentUser;
use App\Models\BandOriginSyn;
use App\Models\Collaborator;
use App\Models\DmaServiceUserRole;
use App\Models\ErrorLog;
use App\Models\Group;
use App\Models\GroupUser;
use App\Models\LotteryMember;
use App\Models\LottoCode;
use App\Models\MedicalReport;
use App\Models\OperateStockLog;
use App\Models\Order;
use App\Models\RegularActivity;
use App\Models\ServiceOrderStatus;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Wechat;
use App\Services\FatService;
use App\Services\ImService;
use App\Services\OfflineOrderService;
use cccdl\yunxin_sdk\Im\Team;
use GuzzleHttp\Client;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Maatwebsite\Excel\Facades\Excel;
use Tymon\JWTAuth\Facades\JWTAuth;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, ResponseJson;

    public function test(Request $request)
    {
        $userIds = [181, 177, 184];

        $userIds = ServiceOrderStatus::whereIn("user_id", $userIds)->where("order_status", 1)->pluck("user_id")->toArray();
        dd($userIds);
    }

    public function test2()
    {
        Log::info('test2');
        //        $app = WechatService::officialApp();
//        dd($app->getConfig());
        dd(session('wechat_user'));
    }

    public function wechatServer()
    {
        $response = WechatService::server();
        return $response;
    }

    public function errorLogs()
    {
        return $this->success('ok', ErrorLog::whereNotIn('status', [3, 4])->orderByDesc('id')->paginate());
    }


    public function sendAppError(Request $request)
    {
        $title = $request->input('title') ?: '友福同享安卓报错';
        $url = $request->input('url');
        $openids = ['oHGap6J6O_roaZH050uC7xGhbRqw', 'oHGap6EROqavcQxzoScKjpVUykzY'];
        foreach ($openids as $openid) {
            $param = [
                'template_id' => config('wechat.tpls.error_log_notice'),
                //            'template_id'=>'7Tj2vYAIGaYrPd2uyQwRp98MhzTCX7SL5LV97W9jn1A',
                'url' => $url,
                //            'miniprogram' => [
//                'appid' => config('wechat.mini_program.app_id'),
//                'pagepath' => 'pages/tabBar/serve',
//            ],
                'data' => [
                    'time2' => ['value' => date('Y-m-d H:i:s')],
                    'thing4' => ['value' => $title],
                ],
            ];
            $param['touser'] = $openid;
            //        $param['touser'] = "oHGap6LBV0CV893CYAwG7Pz7-hlY";
            SendTemplateNotice::dispatch($param)->onQueue('health');
        }

        return $this->success('ok');
    }


    public function errorLog(ErrorLog $log)
    {
        return view('errorMessage', ['message' => $log->message]);
    }

    public function web()
    {
        if (config('app.env') == 'production') {
            return redirect('https://ufutx.com');
        }
        return view('welcome');
    }

    /**
     * 导入批发商活动订单
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function testAgentActivityOrder()
    {
        $orders = DB::table('oa_agent_activity_order as ao')
            ->leftJoin('oa_agent_user as au', 'au.id', '=', 'ao.user_id')
            ->where('ao.pay_status', 'PAID')
            ->get();
        foreach ($orders as $order) {
            DB::beginTransaction();
            //用户
            $user_id = Wechat::where('openid', $order->openid)->value('user_id');
            if (!$user_id) {
                $user_id = User::where("mobile", $order->mobile)->value('id');
            }
            if (empty($user_id)) {
                $user = User::create(['name' => $order->name, 'mobile' => $order->mobile]);
                Wechat::create(['user_id' => $user->id, 'type' => 'official', 'openid' => $order->openid]);
                $user_id = $user->id;
            }
            //订单
            $agent_order = ActivityOrder::updateOrCreate(['trade_no' => $order->trade_no], ['activity_id' => 18, 'user_id' => $user_id, 'sku' => "批发商大会门票", 'is_pay' => 1, "num" => 1, 'sex' => 0, 'ara_code' => null, 'name' => $order->name, 'mobile' => $order->mobile, 'amount' => $order->price, 'residue_amount' => $order->price, 'created_at' => date("Y-m-d H:i:s", $order->created_at), 'updated_at' => date("Y-m-d H:i:s", $order->updated_at)]);

            //批发商
            $agent_user = AgentUser::where(['user_id' => $user_id])->first();
            if (!$agent_user || $agent_user->level == 0) {
                AgentUser::updateOrCreate(['user_id' => $user_id], ['level' => 2]);
            }
            DB::commit();
        }
        return $this->success('ok');
    }

    public function addLotteryMember(Request $request, $lottery_id)
    {
        $data = $request->only(['mobile', 'name', 'codes']);
        $user = User::where("mobile", $data['mobile'])->first();
        if (empty($user)) {
            $user = User::create($data);
        }
        foreach ($data['codes'] as $code) {
            LotteryMember::updateOrCreate(['user_id' => $user->id, 'code' => $code, 'lottery_id' => $lottery_id], [
                'lottery_id' => $lottery_id,
                'name' => $data['name'],
                'mobile' => $data['mobile'],
                'code' => $code
            ]);
        }
        return $this->success('ok');
    }



    public function addOfflineAgentOrder(Request $request)
    {
        $code = $request->input('code');
        if ($code != "009527")
            return $this->failure("请输入code");
        //生成用户
        $mobile = $request->input('mobile');
        if (empty($mobile))
            return $this->failure("请输入手机号");
        $name = $request->input('name');
        if (empty($name))
            return $this->failure("请输入姓名");
        $num = $request->input('num');
        if (empty($num) || !is_numeric($num))
            return $this->failure("请输入数量");
        $user_id = User::where("mobile", $mobile)->value('id');
        if (empty($user_id)) {
            $user = User::create(['name' => $name, 'mobile' => $mobile]);
            $user_id = $user->id;
        } else {
            User::where("mobile", $mobile)->update(['name' => $name]);
        }
        //生成订单
        $data['user_id'] = $user_id;
        $data['name'] = $name;
        $data['mobile'] = $mobile;
        $data['trade_no'] = CommonService::getTradeNo();
        $data['origin_price'] = $data['price'] = 3120 * $num;
        $data['is_online'] = 0;
        $data['pay_type'] = "free";
        $data['pay_status'] = 'PAID';
        $data['shop_id'] = 1;
        $data['sku_id'] = 1;
        $data['shop_info'] = null;
        $data['num'] = $num;
        $data['from_user_id'] = $request->input('from_user_id');
        //生成未支付订单
        $order = AgentOrder::create($data);
        //酒码
        for ($index = 0; $index < $num; $index++) {
            $code = time() . CommonService::random(6, 1) . strtoupper(CommonService::random(1));
            //生成抽奖码
            $order->lottoCode()->create(['user_id' => $order->user_id, 'code' => $code]);
        }
        //批发商
        AgentUser::updateOrCreate(['user_id' => $user_id], ['level' => 1]);
    }


    public function syncActivityOrders()
    {
        $love_activity_id = 2451;
        $dma_activity_id = 17;
        $url = config('app.shop_url') . "activities/{$love_activity_id}/orders?nopage=1";
        $response = HttpService::getData($url);
        $orders = $response['data'];
        foreach ($orders as $order) {
            //查询用户
            $user = User::whereHas("officialWechat")->where("mobile", $order['mobile'])->first();
            if (empty($user)) {
                $user = User::where("mobile", $order['mobile'])->first();
            }
            if (empty($user)) {
                $user = User::create(['mobile' => $order['mobile'], 'name' => $order['name']]);
            }
            $user->update(['name' => $order['name']]);
            //创建订单
            $activity_order = ActivityOrder::where("activity_id", $dma_activity_id)->owner($user->id)->paid()->first();
            if (empty($activity_order)) {
                ActivityOrder::create([
                    'activity_id' => $dma_activity_id,
                    'user_id' => $user->id,
                    'trade_no' => CommonService::getTradeNo(),
                    'sku' => "早鸟票",
                    'is_pay' => 1,
                    'num' => 1,
                    'sex' => 0,
                    'ara_code' => "+86",
                    "mobile" => $order['mobile'],
                    "name" => $order["name"],
                    "amount" => $order['price'],
                    'residue_amount' => $order['price']
                ]);
            } else {
                $activity_order->update(['name' => $order["name"]]);
            }
        }
        return $this->success('ok');
    }

    public function importAgentOrders()
    {
        $file = storage_path("wine.xlsx");
        Excel::import(new ImportAgentOrders(), $file);
        return $this->success("ok");
    }




}
