<?php

namespace App\Http\Controllers\H5;

use App\Facades\CommonService;
use App\Facades\HttpService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Resources\AgentShopCollection;
use App\Http\Resources\AgentShopResource;
use App\Http\Resources\AgentShopResrouce;
use App\Http\Response\ResponseJson;
use App\Jobs\SendEasySms;
use App\Models\ActivityIntroduceLog;
use App\Models\ActivityOrder;
use App\Models\ActivityOrderLog;
use App\Models\ActivityShareRefund;
use App\Models\AgentOrder;
use App\Models\AgentShop;
use App\Models\AgentUser;
use App\Models\LotteryMember;
use App\Models\LottoCode;
use App\Models\Message;
use App\Models\OperateStockLog;
use App\Models\S2ShopOrder;
use App\Models\S2ShopSkuExtend;
use App\Models\Shop;
use App\Models\ShopCode;
use App\Models\ShopCodeLog;
use App\Models\ShopCodePreview;
use App\Models\User;
use App\Models\Wechat;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShopController extends Controller
{
    use ResponseJson;

    public function bindWineCode(Request $request)
    {
        $user_id = auth()->id();
        $wine_code = $request->input('wine_code');
        if (empty($wine_code)) throw new \Exception("缺少参数酒码");
        //手机号、验证码检测
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $code = $request->input('code');
        $res = Message::checkCode($mobile, $code);
        if (empty($res)) return $this->failure("验证码错误");
        $shop_code = ShopCode::where('code', $wine_code)->first();
        if (empty($shop_code)) return $this->failure("酒码无效");
        $res = ShopCodeLog::code($shop_code->id)->receive()->exists();
        if ($res) return $this->failure("酒码已被绑定");
        ShopCodeLog::create(['mobile'=>$mobile, 'name'=>$name, 'code_id'=>$shop_code->id, 'user_id'=>$user_id, 'receive'=>1]);
        return $this->success('ok');
    }

    public function bindPackCode(Request $request)
    {
        $user_id = auth()->id();
        $pack_code = $request->input('pack_code');
        if (empty($pack_code)) throw new \Exception("缺少参数包装码");
        //手机号、验证码检测
//        $name = $request->input('name');
//        $mobile = $request->input('mobile');
//        $code = $request->input('code');
//        $res = Message::checkCode($mobile, $code);
//        if (empty($res)) return $this->failure("验证码错误");
        $shop_codes = ShopCode::where('pack_code', $pack_code)->get();
        if ($shop_codes->count() < 6) return $this->failure("包装码无效");
        $verify_code = $request->input('verify_code');
        Log::info("verify_code: ".strtoupper($verify_code));
        Log::info("verify_code2: ".$shop_codes->first()->verify_code);
        if ($shop_codes->first()->verify_code != strtoupper($verify_code)) return $this->failure("防伪码错误");
        $res = ShopCodeLog::codes($shop_codes->pluck('id')->toArray())->receive()->count();
        if ($res >=6) return $this->failure("包装码已被绑定");
        $data = [];
        foreach ($shop_codes as $shop_code) {
            $data[] = ['user_id'=>$user_id, 'mobile'=>null, 'name'=>null, 'code_id'=>$shop_code->id, 'type'=>ShopCodeLog::PACKTYPE, 'receive'=>1];
        }
        ShopCodeLog::upsert($data, ['code_id'], ['code_id']);
        return $this->success('ok');
    }

    public function wineCodeStatus(Request $request)
    {
        $user = auth()->user();
        $wine_code = $request->input('wine_code');
        if (empty($wine_code)) throw new \Exception("缺少参数酒码");
        $shop_code = ShopCode::where('code', $wine_code)->first();
        if (empty($shop_code)) return $this->failure("酒码无效");
        //记录扫码记录
//        ShopCodePreview::create(['code'=>$wine_code, 'user_id'=>$user_id, 'type'=>ShopCodePreview::WINETYPE]);
        //酒码是否有效 1:无效，0：有效
//        $receive = ShopCodeLog::code($shop_code->id)->receive()->exists()?1:0;
        $log = ShopCodeLog::code($shop_code->id)->receive()->first();
        if (empty($log)) {
            $log = ShopCodeLog::create( ['user_id'=>$user->id, 'mobile'=>null,'name'=>null, 'code_id'=>$shop_code->id, 'type'=>ShopCodeLog::WINETYPE, 'receive'=>1]);
        }
        $receive = 0;
        //返回酒编号
        $number = $shop_code->number;
        //绑定时间
        $created_at = $log->created_at->toDateTimeString();
        //app下载码
//        $download_qrcode = User::downloadQrcode($request->device);
        $download_qrcode = "https://images.health.ufutx.com/202402/19/6db174f81a6f1272cb6b13d68308428c.jpeg";
        $res = WechatService::wechatUserByOfficialOpenid($user->officialWechat->openid);
        $is_subscribe = $res['subscribe'];
        //公众号二维码
        $official_qrcode = 'https://ufutx-health.oss-cn-hangzhou.aliyuncs.com/202312/13/showqrcode.png';
        return $this->success('ok',compact('receive', 'number', 'created_at', 'download_qrcode','is_subscribe','official_qrcode'));
    }

    public function packCodeStatus(Request $request)
    {
        $user = auth()->user();
        $pack_code = $request->input('pack_code');
        if (empty($pack_code)) throw new \Exception("缺少参数包装码");
        $shop_codes = ShopCode::with('log')->where('pack_code', $pack_code)->orderBy('number')->get();
        if ($shop_codes->count() < 6) return $this->failure("包装码无效");
        //记录扫码记录
//        ShopCodePreview::create(['code'=>$pack_code, 'user_id'=>$user_id, 'type'=>ShopCodePreview::PACKAGETYPE]);
        //酒码是否有效
        $log = ShopCodeLog::codes($shop_codes->pluck('id')->toArray())->pack()->receive()->first();
        $receive = $log?1:0;
        //返回酒编号
        $number = $shop_codes->first()->pack_number;
        //绑定时间
        $created_at = $log?$log->created_at->toDateTimeString():null;
        //app下载码
        $download_qrcode = User::downloadQrcode($request->device);
        //是否关注公众号
        $res = WechatService::wechatUserByOfficialOpenid($user->officialWechat->openid);
        $is_subscribe = $res['subscribe'];
        //公众号二维码
        $official_qrcode = 'https://ufutx-health.oss-cn-hangzhou.aliyuncs.com/202312/13/showqrcode.png';
        return $this->success('ok',compact('receive', 'number', 'created_at', 'download_qrcode', 'is_subscribe', 'official_qrcode'));
    }

    public function wineCodeLogs(Request $request)
    {
        $user = auth()->user();
        $logs = ShopCodeLog::with(['shopCode'=>function($sql) {
            $sql->orderBy('shop_codes.pack_number');
        }])->user($user->id)->receive()->simplePaginate();
        foreach ($logs as $log) {
            $log->shopCode->number = $log->shopCode->pack_number."-".$log->shopCode->number;
        }
        return $this->success('ok', $logs);
    }

    public function sendSmsCode(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = CommonService::random(6, 1);
        $data = [
            'code' => $code,
            'message' => '绑定酒码验证码：' . $code . '，十分钟有效【友福同享】',
        ];
        $area_code = $request->input('area_code', 86);
        SendEasySms::dispatch($mobile, $data,$area_code)->onQueue('send.code.sms');
        return $this->success('ok');
    }

    public function serverBindWineCode(Request $request){
        $package_code = $request->input('package_code');
        if(empty($package_code)) return $this->failure('包装码无效');
        Log::info("serverBindWineCode: $package_code");
        $wine_code = $request->input('wine_code');
        if(empty($wine_code) && count($wine_code) < 6) return $this->failure('酒码无效');
        Log::info("serverBindWineCode: ".json_encode($wine_code));
        $unique_array = array_unique($wine_code);

        if (count($wine_code) != count($unique_array)) {
            return $this->failure('酒码重复');
        }

        $exists = ShopCode::where('pack_code', $package_code)->exists();
        if(empty($exists)) return $this->failure('包装码不存在');

        $shop_codes = ShopCode::where('pack_code', $package_code)->where('code','')->get();
        if(empty($shop_codes)) return $this->failure('包装码无效');

        $package_status = 0;
        if ($shop_codes->count() < 6) $package_status = 1;

        $wine_shop_code = ShopCode::whereIn('code', $wine_code)->pluck('code')?->toArray();
        $wines = [];
        foreach ($wine_code as $key => $wine){
            $wines[$key]['code'] = $wine;
            $wines[$key]['status'] = 0;
            if(in_array($wine,$wine_shop_code)){
                $wines[$key]['status'] = 1;
            }
        }

        $shop_codes = $shop_codes->toArray();
        if(!$package_status || empty($wine_shop_code)){
            foreach ($shop_codes as $index => $item){
                if(!isset($wine_code[$index])){
                    continue;
                }
                $package_info = ShopCode::where('id', $item['id'])->first();
                $package_info->code = $wine_code[$index];
                $package_info->number = (int)date('Ymd').'0'.$index+1;
                $package_info->save();

                $wines[$index]['code'] = $wine;
                $wines[$index]['status'] = 0;
            }
        }
        return $this->success('ok',compact('package_status','wines'));
    }

    public function serverGetDetail(Request $request){
        $package_code = $request->input('package_code');
        if(empty($package_code)) return $this->failure('包装码无效');

        $shop_codes = ShopCode::where('pack_code', $package_code)->get();
        if(empty($shop_codes)) return $this->failure('包装码无效');

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

    public function serverGetPackList(Request $request){
        $shop_codes = ShopCode::where(function($sql) {
            $sql->whereNotNull('code')->where('code', '<>', '');
        })->groupBy('pack_code', 'pack_number')->select('pack_code', 'pack_number')->orderBy('pack_number')->paginate();
        if(empty($shop_codes)) return $this->failure('包装码无效');

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

    public function agentShops(Request $request)
    {
//        $accid = auth()->user()->accid();
//        $param = $request->all();
//        $param['accid'] = $accid;
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/shops?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $shops = Shop::with('shopAgent')->whereHas("shopAgent", function ($sql) {
            $sql->show()->orderByDesc("id");
        })->keyword()->paginate();
        $shops = new AgentShopCollection($shops);

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

    public function agentShop(Request $request, Shop $shop)
    {
        $shop = new AgentShopResource($shop);
        return $this->success('ok', $shop);
    }

    public function payAgentShop(Request $request, Shop $shop)
    {
        $data = $request->all();
        $sku_id = $request->input('sku_id');
        $name = $request->input('name');
        if (empty($name)) return $this->failure('请填写收货人');
        $mobile = $request->input('mobile');
        if (empty($mobile)) return $this->failure('请填写电话');
        $num = $request->input('num');
        if (empty($num)) return $this->failure('请选择数量');
        $user = auth()->user();
        $open_id = $user->officialWechat->openid;
        if (empty($open_id)) throw new \Exception('获取用户openid失败');
        //批发商等级
        $sku_arr = $shop->shopAgent->sku;
        $sku = null;
        if (is_array($sku_arr) && count($sku_arr)) {//含sku
            $sku = collect($sku_arr)->where('sku_id', $request->sku_id)->first();
            $price = $sku['price'];
        }else {
            $price = $shop->price;
        }

        if ($shop->id != Shop::ZongZiId) {
            /**
             * 批发商半价，
             * 准批发商第一个原价第二件及以后半价并且成为批发商
             * 非批发商原价
             */
            $level = $user->agentUser?$user->agentUser->level:0;
            if (!$level) {//非经销商
                $data['price'] = $price * $data['num'];
            }elseif ($level == 2) {//非经销商除第一件，其他半价
                $data['price'] = number_format($price + ($price / 2 * ($data['num'] - 1)), 2, '.', '');
            }elseif ($level == 1) {
                $data['price'] = number_format($price / 2 * $data['num'], 2, '.', '');
            }
        } else {
            $data['price'] = $price * $data['num'];
        }

        /**
         * 两件及以上包邮
         */
        if ($data['num'] > 1) {
            $data['freight'] = 0;
        }else {
            $data['freight'] = $shop->shopAgent->freight;
        }
        $data['price'] = number_format($data['price'] + $data['freight'], 2, '.', '');

        //计算会员
        $data['origin_price'] =  number_format($price * $data['num'], 2, '.', '');;
        if ($data['price'] < 0) throw new \Exception("订单计算错误");
        $data['pay_type'] = $data['price'] == 0?"free":"wechat";
        $data['trade_no'] = CommonService::getTradeNo();
        $data['shop_id'] = $shop->id;
        $data['sku_id'] = $sku?$sku['sku_id']:0;
        $data['user_id'] = $user->id;
        $data['desc'] = $shop->title."-".($sku?$sku['name']:'');
        $data['shop_info'] = ["id"=>$shop->id, 'title'=>$shop->title, 'pic'=>$shop->icon, 'sku'=>$sku];
        $data['pay_status'] = $data['price'] > 0?"UNPAID":"PAID";
        $data['from_user_id']= $request->input('from_user_id');
        //代理商品比例
//        $arr = ShopAgent::AGENT_SHOP;
//        $ratio = $arr['agent_sku_id'] == $data['sku_id']?$arr['ratio']:1;
        $ratio = 1;
        $data['stock'] = $data['remain_stock']= $data['num'] * $ratio;
        $data['sub_mch_id'] = "1663332225";
        DB::beginTransaction();
        //生成未支付订单
        $order = AgentOrder::create($data);
        $config = [];
        if ($data['pay_status'] == 'UNPAID') {
            //获取支付配置
            $callback = config('app.url')."/api/h5/agent/order/".$data['trade_no'].'/callback';
            $appId = config('wechat.official_account.default.app_id')?:'wx5174eb5ba45228a4';
            $config = WechatService::mpPay($data['trade_no'], $open_id, $data['price'], $data['desc'],$callback,$appId,$data['sub_mch_id']);
        }else {
            $this->markAgentOrder($order);
        }
        DB::commit();
        return $this->success('ok', compact('order', 'config'));
    }

    public function payAgentShopV2(Request $request, Shop $shop)
    {
        $data = $request->all();
        $sku_id = $request->input('sku_id');
//        $name = $request->input('name');
//        if (empty($name)) return $this->failure('请填写收货人');
//        $mobile = $request->input('mobile');
//        if (empty($mobile)) return $this->failure('请填写电话');
        $num = $request->input('num');
        if (empty($num)) return $this->failure('请选择数量');
        $user = auth()->user();
        $open_id = $user->officialWechat->openid;
        if (empty($open_id)) throw new \Exception('获取用户openid失败');
        //批发商等级
        $sku_arr = $shop->shopAgent->getSkus();
        $sku = null;
        if (is_array($sku_arr) && count($sku_arr)) {//含sku
            $sku = $user->getGoodsSku($sku_arr, $sku_id);
            $price = $sku['price'] * $num;
            $data['origin_price'] = $sku['origin_price'] * $num;

        }else {
            $price = $shop->price * $num;
            $data['origin_price']  = $shop->price * $num;
        }
        //首单
        $first_order = AgentOrder::owner($user->id)->where('shop_id', $shop->id)->paid()->exists()?0:1;

        //任何用户首单  第一件原价，后面每件半价
        //修改为 除VIP用户外的任何用户首单  第一件原价，后面每件半价， VIP用户始终使用vip价格
        $agent_user = $user->agentUser;
        if (!$agent_user || $agent_user->level != AgentUser::AgentVIP) {
            if($first_order) {
                if ($num == 1) {
                    $price = $sku['origin_price'];
                }else {
                    $over_num = $num - 1;
                    $over_pirce = $sku['agent_price'];
                    $price = number_format($sku['origin_price'] + $over_num * $over_pirce, 2, '.', '');
                }
            }
        }


        //当前角色
        // $agent_user = $user->agentUser;
        // if ($agent_user && ($agent_user->level == AgentUser::AgentLevelReady || $agent_user->level == AgentUser::AgentLevelBeing) && $first_order) {
        //     //准批发价格另算
        //     if ($num <= $sku['before_num']) {
        //         $price = number_format( $sku['before_price'] * $num, 2,'.','');
        //     }else {
        //         $over_num = number_format($num - $sku['before_num']);
        //         $price = number_format($sku['before_num'] * $sku['before_price'] + $over_num * $sku['over_price'], 2, '.','');
        //     }
        // }
        //快递费
        $ship_fee = 0;
        if($data['is_online'] == AgentOrder::ONLINETYPE) {
            $ship_fee = AgentShop::getGoodsShip($sku, $data['num']);
        }
        $data['price'] = number_format($price + $ship_fee, 2, '.', '');
        $data['freight'] = $ship_fee;
        if ($data['price'] < 0) throw new \Exception("订单计算错误");
        $data['pay_type'] = $data['price'] == 0?"free":"wechat";
        $data['trade_no'] = CommonService::getTradeNo();
        $data['shop_id'] = $shop->id;
        $data['sku_id'] = $sku?$sku['sku_id']:0;
        $data['user_id'] = $user->id;
        $data['name'] = $user->name;
        $data['mobile'] = $user->mobile;
        $data['desc'] = $shop->title."-".($sku?$sku['name']:'');
        $lotto_code = $shop->shopAgent()->select("id","shop_id", 'is_show', 'lotto_code')->value('lotto_code');
        $data['shop_info'] = ["id"=>$shop->id, 'title'=>$shop->title, 'pic'=>$shop->icon, 'sku'=>$sku, 'lotto_code'=>$lotto_code];
        $data['pay_status'] = $data['price'] > 0?"UNPAID":"PAID";
        $data['from_user_id']= $request->input('from_user_id');
        //代理商品比例
//        $arr = ShopAgent::AGENT_SHOP;
//        $ratio = $arr['agent_sku_id'] == $data['sku_id']?$arr['ratio']:1;
        $ratio = 1;
        $data['stock'] = $data['remain_stock']= $data['num'] * $ratio;
        if ($shop->id == 89) {
            $data['sub_mch_id'] = "1626601973";
        }else {
            $data['sub_mch_id'] = $shop->shopAgent->payment?$shop->shopAgent->payment->sub_mch_id:'1626601973';
//            $data['sub_mch_id'] = "1663332225";
        }
        DB::beginTransaction();
        //生成未支付订单
        $order = AgentOrder::create($data);
        $order->status()->create(['status'=>AgentOrder::UNPAIDSTATUS]);

        $config = [];
        if ($data['pay_status'] == 'UNPAID') {
            //获取支付配置
            $callback = config('app.url')."/api/h5/agent/order/".$data['trade_no'].'/callback';
            $appId = config('wechat.official_account.default.app_id')?:'wx5174eb5ba45228a4';
            $config = WechatService::mpPay($data['trade_no'], $open_id, $data['price'], $data['desc'],$callback,$appId,$data['sub_mch_id']);
        }else {
            $this->markAgentOrderV2($order);
        }
        DB::commit();
        return $this->success('ok', compact('order', 'config'));
    }


    public function callbackAgentOrder($trade_no)
    {
        $order = AgentOrder::where('trade_no', $trade_no)->first();
        if ($order->mobile == "") {
            $user = $order->user;
            $order->update(['name'=>$user->name, 'mobile'=>$user->mobile]);
        }
        if ($order->pay_status != "UNPAID") return;
        if ($order->pay_type == 'wechat') {
            $sub_mch_id = $order->sub_mch_id;
            if ($order->shop_id == 89) {
                $sub_mch_id = "1626601973";
            }
            $res = WechatService::mpPaid($trade_no, $sub_mch_id);
            if ($res) return;
//            $this->markAgentOrder($order);
            $this->markAgentOrderV2($order);
        }
    }

    public function markAgentOrderV2($order)
    {
        DB::beginTransaction();
        //修改订单状态
        $order->update(['pay_status'=> 'PAID']);
        $order->status()->create(['status'=>AgentOrder::PAIDSTATUS]);
        if (($order->shop_info)['lotto_code']) {//是否需要生成抽奖码
            for ($index =0; $index < $order->num; $index++) {
                $code = time().CommonService::random(6,1).strtoupper(CommonService::random(1));
                //生成抽奖码
                $order->lottoCode()->create(['user_id'=>$order->user_id, 'code'=>$code]);

                //加入抽奖池
                if ($order->shop_id == ((config('app.env') == "production")? AgentShop::WINEID : AgentShop::ALPHA_WINEID)) {
                    $lottery_id = (config('app.env') == "production")?AgentShop::LOTTERYID: AgentShop::ALPHA_LOTTERYID;
                    LotteryMember::create(['user_id'=>$order->user_id, 'lottery_id'=>$lottery_id, 'name'=>$order->name, 'mobile'=>$order->mobile, 'code'=>$code]);
                }
                //手环加入抽奖
                if ($order->shop_id == ((config('app.env') == "production")? AgentShop::BANDID : AgentShop::ALPHA_BANDID)) {
                    $lottery_id = (config('app.env') == "production")?AgentShop::BAND_LOTTERY_ID: AgentShop::ALPHA_BAND_LOTTERY_ID;
                    LotteryMember::create(['user_id'=>$order->user_id, 'lottery_id'=>$lottery_id, 'name'=>$order->name, 'mobile'=>$order->mobile, 'code'=>$code]);
                }
            }
        }
        //准批发商成为批发商
        if (($order->shop_info)['sku']['is_agent']) {
            AgentUser::changeLevel($order->user_id, AgentUser::AgentLevelBeing,"购买".($order->shop_info)['title']."-".($order->shop_info)['sku']['name']);
        }

        DB::commit();
    }

    public function storeLottoCode($trade_no)
    {
        $order = S2ShopOrder::where('trade_no', $trade_no)->first();
        if (empty($order)) return $this->failure("订单不存在");
        if ($order->status != 2) return $this->failure("订单状态不正确");
        $extend = S2ShopSkuExtend::where('sku_id', $order->sku_id)->first();
        if ($extend && $extend->open_lottery_code) {//是否需要生成抽奖码
            $num = $order->lottoCode()->where('order_type', S2ShopOrder::class)->count();
            for ($index =0; $index < $order->num - $num; $index++) {
                $code = time().CommonService::random(6,1).strtoupper(CommonService::random(1));
                //生成抽奖码
                $order->lottoCode()->create(['user_id'=>$order->user_id, 'code'=>$code, 'order_type'=>S2ShopOrder::class]);

//                //加入抽奖池
//                if ($order->shop_id == ((config('app.env') == "production")? AgentShop::WINEID : AgentShop::ALPHA_WINEID)) {
//                    $lottery_id = (config('app.env') == "production")?AgentShop::LOTTERYID: AgentShop::ALPHA_LOTTERYID;
//                    LotteryMember::create(['user_id'=>$order->user_id, 'lottery_id'=>$lottery_id, 'name'=>$order->name, 'mobile'=>$order->mobile, 'code'=>$code]);
//                }
//                //手环加入抽奖
//                if ($order->shop_id == ((config('app.env') == "production")? AgentShop::BANDID : AgentShop::ALPHA_BANDID)) {
//                    $lottery_id = (config('app.env') == "production")?AgentShop::BAND_LOTTERY_ID: AgentShop::ALPHA_BAND_LOTTERY_ID;
//                    LotteryMember::create(['user_id'=>$order->user_id, 'lottery_id'=>$lottery_id, 'name'=>$order->name, 'mobile'=>$order->mobile, 'code'=>$code]);
//                }
            }
        }
    }


    public function markAgentOrder($order)
    {
        $wine_id = config('app.env') == 'production'?AgentShop::WINEID:AgentShop::ALPHA_WINEID;
        DB::beginTransaction();
        //修改订单状态
        $order->update(['pay_status'=> 'PAID']);

        if ($order->shop_id == $wine_id) {
            for ($index =0; $index < $order->num; $index++) {
                $code = time().CommonService::random(6,1).strtoupper(CommonService::random(1));
                //生成抽奖码
                $order->lottoCode()->create(['user_id'=>$order->user_id, 'code'=>$code]);
            }
        }

        $num = $order->num;
        $order->shop->decrementShopStock($order->sku_id, $num, $type=Shop::AGENTSTOCKTYPE);
        //准批发商成为批发商
//        $agent_user = AgentUser::where(['user_id'=>$order->user_id])->first();
        if ($order->shop_id == $wine_id) {
            AgentUser::changeLevel($order->user_id, AgentUser::AgentLevelBeing,"购买渣酒");
        }
        DB::commit();
    }

    public function orderCallback(Request $request)
    {
        $trade_no = $request->get('trade_no');
        if(empty($trade_no))return $this->failure('订单号不为空');
        $user_id = $request->input('user_id');
        $user = User::find($user_id);
        $num = $request->input('num');
        $ratio = (User::AGENT_SHOP)['ratio'];
        $num = $num * $ratio;
        $goods_id = $request->input('goods_id');
        $goods_name = $request->input('goods_name');
        $sku_name = $request->input('sku_name');
        $sku_stock = $request->input('sku_stock');

        $map = [];
        $map['id'] = $goods_id;
        $map['name'] = $goods_name.'/'.$sku_name;
        $map['stock'] = $sku_stock;
        $map['num'] = $num;
        $map['after_num'] = $sku_stock-$num;
        $map['type'] = OperateStockLog::TYPE_AGENT;
        $map['remark'] = '经销商用户:'.$user->name.' 购买了商品:'.$goods_name.' 购买数量:'.$num.' 订单号:'.$trade_no;
        $map['operate_type'] = OperateStockLog::OPERATE_TYPE_OUT;
        $map['status'] = OperateStockLog::OPERATE_STATUS_PASS;
        OperateStockLog::addLog($user,$map);
        return $this->success('ok');
    }

    public function agentOrders(Request $request)
    {
        $user_id = auth()->id();
        $orders = AgentOrder::owner($user_id)->paid()->orderByDesc('id')->paginate();
        foreach ($orders as $order)
        {
            $order->remain_stock = $order->num;
        }
        return $this->success('ok', $orders);

    }

    public function agentOrder(Request $request,AgentOrder $order)
    {
//        $accid = auth()->user()->accid();
//        $param = $request->all();
//        $param['accid'] = $accid;
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/shop/orders/$order_id?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $order->remain_stock = $order->num;
        $order->status;
        return $this->success('ok', $order);
    }

    public function agentTradeOrder(Request $request, $trade_no)
    {
//        $param = $request->all();
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/shop/orders/no/$trade_no?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $res = explode('_', $trade_no);
        switch ($res[0]) {
            case "AG": //GO语言批发商商城订单

                config(['database.connections.mysql.prefix' => '']);
                $order = DB::table('oa_agent_goods_order')->where('trade_no', $trade_no)->first();
                if ($order) {
                    $order->shop_info = json_decode($order->shop_info);
                    $order->sku = json_decode($order->sku);
                    $order->shop_info->sku = $order->sku;
                    $order->order_type = 'oa_agent_shop';
                }
                break;
            default :
                $order = AgentOrder::where('trade_no', $trade_no)->first();
                $order->order_type = 'agent_shop';
        }
        return $this->success('ok', $order);
    }

    public function agentShares(Request $request)
    {
        $accid = auth()->user()->accid();
        $param = $request->all();
        $param['accid'] = $accid;
        $param =  http_build_query($param);
        $url = config('app.shop_url')."agent/shares?$param";
        $res = $this->getData($url);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        return $this->success('ok', $data);
    }

    public function agentLottoCodes(Request $request)
    {
        $user_id = auth()->id();
        $logs = LottoCode::with('order:id,shop_info', 'winMember.award')->user($user_id)->orderByDesc('id')->paginate();
        foreach ($logs as $log) {
            $log->award = $log->winMember->award->awards??null;
            unset($log->winMember);
        }
        return $this->success('ok', $logs);


    }

    public function getOutStock(Request $request, $order_id)
    {
        $data = $request->all();
        $data['accid'] = auth()->user()->accid();
        $url = config('app.shop_url')."agent/shop/orders/$order_id/stock";
        $res = $this->postData($url, $data);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        return $this->success('ok', $data);
    }

    public function getOutStockV2(Request $request, $shop_id)
    {
        $data = $request->only(['num','name','mobile','get_type','address']);
        $data['accid'] = auth()->user()->accid();
        $url = config('app.shop_url')."agent/shop/$shop_id/stock";
        $res = $this->postData($url, $data);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        return $this->success('ok', $data);
    }

    public function agentInfo(Request $request)
    {
//        $param = $request->all();
//        $param['accid'] = auth()->user()->accid();
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/info?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        $data['qrcode'] = auth()->user()->getShopAgentQrcode();
//        return $this->success('ok', $data);
        $user = auth()->user();
        $amount = $user->earning();
        $user->amount = $amount;
        //总库存
        $total_stock = $user->agentOrders()->where('pay_status', AgentOrder::PAIDSTATUS)->sum("num");
        //消耗库存
        $consume_stock = 0;
        $stock = number_format($total_stock - $consume_stock, 0 , '.','');
        $user->stock = $stock;
        $user->qrcode= $user->getShopAgentQrcode();
        return $this->success('ok', $user);
    }

    public function agentEarning(Request $request)
    {
//        $param = $request->all();
//        $param['accid'] = auth()->user()->accid();
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/earning?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $amount = auth()->user()->earning();
        return $this->success("ok", compact('amount'));
    }

    public function agentWithdraws(Request $request)
    {
//        $param = $request->all();
//        $param['accid'] = auth()->user()->accid();
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/withdraws?$param";
//        $res = $this->getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $withdraws = auth()->user()->agentWithdraws()->orderByDesc('id')->simplePaginate();
        return $this->success('ok', $withdraws);
    }

    public function agentWithdraw(Request $request)
    {
//        $param = $request->all();
//        $param['accid'] = auth()->user()->accid();
//        $url = config('app.shop_url')."agent/withdraw";
//        $res = $this->postData($url,$param);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $user = auth()->user();
        $amount = $user->earning();
        $data = $request->all();
//        if ($data['amount'] > $amount) return $this->failure("余额不足");
        $data['user_id'] = $user->id;
        $data['status'] = 'AUDIT';
        $user->agentWithdraws()->create($data);
        return $this->success('ok');
    }

    public function agentShopQrcode(Request $request, $shop_id)
    {
        $qrcode = auth()->user()->getShopAgentQrcode($shop_id);
        return $this->success('ok', compact('qrcode'));
    }

    /**
     * 提取get请求公共代码
     * @param $url
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getData($url){
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];
        $client = new Client();
        $response = $client->get($url, [
            'headers' => $headers,
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }
    /**
     * 提取post请求公共代码
     * @param $url
     * @param $params
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function postData($url,$params){
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->post($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    public function putData($url,$params){
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->put($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    public function deleteData($url,$params){
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->delete($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    public function shopShareQrcode(Request $request, $shop_id)
    {
        $qrcode = auth()->user()->getShopAgentQrcode($shop_id, 'H5');
        return $this->success('ok', ['qrcode'=>$qrcode]);
    }

    /**
     * 注册经销商
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function storeAgentUsers(Request $request)
    {
        DB::beginTransaction();
        $user = auth()->user();
        $data = $request->all();
        //验证手机号和验证码
        $res = Message::checkCode($data['mobile'], $data['code']);
        if (empty($res)) return $this->failure("验证码无效");
        //判断手机号是否在其他微信注册
        $mobile_user = User::whereHas("officialWechat")->where("mobile", $data['mobile'])->where("id", "<>", $user->id)->first();
        if ($mobile_user) {
            //是否是虚拟openid
            if (!Wechat::isVirtualOpenid($mobile_user->officialWechat->openid))return $this->failure("手机号已存在其他微信账号");
            $user->officialWechat->update(['user_id'=>$mobile_user->id]);
            $mobile_user->officialWechat->update(['user_id'=>null]);
            $user = $mobile_user;
        }
        $user->update($data);
        //同步活动订单用户
        AgentUser::changeLevel($user->id, AgentUser::AgentLevelNot, "注冊经销商",true);
        $activity_order_count = ActivityOrder::where("mobile", $data['mobile'])->paid()->count();
        if ($activity_order_count) {
            AgentUser::changeLevel($user->id, AgentUser::AgentLevelBeing, "系统检测含票活动订单", true);
            ActivityOrder::where("mobile", $data['mobile'])->paid()->update(['user_id'=>$user->id]);
        }
        //同步渣酒订单用户
        $agent_order_count = AgentOrder::where("mobile", $data['mobile'])->where('shop_id', 3)->paid()->count();
        if ($agent_order_count) {
            AgentUser::changeLevel($user->id, AgentUser::AgentLevelBeing, "系统检测含渣酒订单");
            AgentOrder::where("mobile", $data['mobile'])->paid()->update(['user_id'=>$user->id]);
            //同步抽奖码
            $agent_order_ids = AgentOrder::where("mobile", $data['mobile'])->paid()->pluck("id");
            LottoCode::whereIn('order_id', $agent_order_ids)->update(["user_id"=> $user->id]);
        }
        //同步抽奖信息
        LotteryMember::where('user_id', $user->id)->update(['name'=>$user->name, 'mobile'=>$user->mobile]);

        $user_ids = User::where("mobile", $data['mobile'])->where('id', '<>', $user->id)->pluck('id')->toArray();
        //手机号对应的是否有agentUser
        $level = AgentUser::AgentLevelNot;
        if (count($user_ids)) {
            $level = AgentUser::whereIn("user_id", $user_ids)->where('level', '>', 0)->orderBy("level", "asc")->value('level');
        }
        if ($level) {
            AgentUser::changeLevel($user->id, $level, "同步手机号账号");
        }
        DB::commit();
        return $this->success('ok');
    }

    public function updateAgentUserInfo(Request $request){
        try {
            $user = auth()->user();

            $name = $request->input('name');
            $avatar = $request->input('avatar');
            $mobile = $request->input('mobile');
            $user->name = $name;
            $user->avatar = $avatar;
            if ($mobile) {
                //判断手机号是否在其他微信注册
                $mobile_user = User::whereHas("officialWechat")->where("mobile", $mobile)->where("id", "<>", $user->id)->first();
                if ($mobile_user) return $this->failure("手机号已存在其他微信账号");
                $user->mobile = $mobile;
            }
            $user->save();
            //同步抽奖信息
            LotteryMember::where('user_id', $user->id)->update(['name'=>$name, 'mobile'=>$mobile]);
            return $this->success('ok');
        }catch (\Exception $e) {
            Log::error('updateAgentUserInfo:'.$e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 经销商注册验证码
     * @param Request $request
     */
    public function agentUserCode(Request $request)
    {
        $mobile = $request->input('mobile');
        if(empty($mobile)) throw new \Exception("缺少参数mobile");
        $code = CommonService::random(6, 1);
        $data = [
            'code' => $code,
            'message' => '手机号验证码：' . $code . '，十分钟有效【友福同享】',
        ];
        SendEasySms::dispatch($mobile, $data)->onQueue('health');
        return $this->success('ok');
    }

    /**
     * 经销商已购商品列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function userAgentShops(Request $request)
    {
//        $accid = auth()->user()->accid();
//        $param['accid'] = $accid;
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."user/agent/shops?$param";
//        $res = HttpService::getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $user_id = auth()->id();
        $shops = Shop::whereHas("agentOrders", function ($sql) use($user_id){
            $sql->where('user_id', $user_id);
        })->withCount(["agentOrders as stock"=>function($sql) use($user_id) {
            $sql->where('user_id', $user_id)->select(DB::raw("sum(num) as stock_sum"));
        }])->orderByDesc("stock")->paginate();
        return $this->success('ok', $shops);
    }

    public function userAgentShop(Request $request, $shop_id)
    {
//        $accid = auth()->user()->accid();
//        $param['accid'] = $accid;
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."user/agent/shops/{$shop_id}?$param";
//        $res = HttpService::getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);

        $shop = Shop::find($shop_id);
        $user = auth()->user();
        //总库存
        $total_stock = $user->agentOrders()->where('shop_id', $shop_id)->where('pay_status', AgentOrder::PAIDSTATUS)->sum("num");
        //已消耗庫存
        $consume_stock = 0;
        $stock = number_format($total_stock - $consume_stock, 0 , '.','');
        $shop->stock = $stock;
        return $this->success('ok', $shop);
    }

    public function agentShareInfo(Request $request)
    {
//        $from_user_id = $request->input('from_user_id');
//        $from_accid = $from_user_id?User::userAccid($from_user_id):null;
//        $param['from_accid'] = $from_accid;
//        $param['shop_id'] = $request->input('shop_id');
//        $param =  http_build_query($param);
//        $url = config('app.shop_url')."agent/share/info?$param";
//        $res = HttpService::getData($url);
//        if ($res['code'] == 1) return $this->failure($res['message']);
//        $data = $res['data'];
//        return $this->success('ok', $data);
        $shop_id = $request->input('shop_id');
        $shop = Shop::find($shop_id);
        $from_user_id = $request->input('from_user_id');
        $user = null;
        if ($from_user_id) {
            $user = User::find($from_user_id);
        }
        return $this->success('ok', compact('user', 'shop'));
    }

    public function signOrder(Request $request, AgentOrder $order)
    {
        if ($order->pay_status != AgentOrder::SENDSTATUS) return $this->failure("该订单状态暂不能签收");
        $order->update(['pay_status'=>AgentOrder::SIGNEDSTATUS]);
        $order->status()->create(['status'=>AgentOrder::SIGNEDSTATUS]);
        return $this->success('ok');
    }

    /**
     * 活动票明细
     * @param Request $request
     */
    public function residueAmount(Request $request)
    {
        $user = auth()->user();
        //可退余额
        $residue_amount = ActivityOrder::owner($user->id)->paid()->residue()->sum("residue_amount");
        //明细
        $logs = ActivityOrderLog::owner($user->id)->orderByDesc("id")->paginate();
        foreach ($logs as $log)
        {
            $log->status = 1;
            $log->reason = '';
            $refund = ActivityShareRefund::where('log_id', $log->id)->first();
            if ($refund) {
                $log->status = $refund->status;
                $log->reason = $refund->reason;
            }
        }
        return $this->success('ok', compact('residue_amount', 'logs'));
    }

    /**
     * 申请余额退款
     * @param Request $request
     */
    public function applyRefundAmount(Request $request)
    {
        DB::beginTransaction();
        $amount = $request->input('amount');
        if (empty($amount)) return $this->failure("请输入退款金额");
        $user = auth()->user();
        //可退余额
        $residue_amount = ActivityOrder::owner($user->id)->paid()->residue()->sum("residue_amount");
        if ($amount > $residue_amount) return $this->failure("可退款金额不足");
        //退款申请
        $orders = ActivityOrder::owner($user->id)->paid()->residue()->get();
        //剩余需要退金额
        $remain = $amount;
        foreach ($orders as $order) {
            if ($remain == 0) break;
            if ($order->residue_amount >= $remain) {
                $order_amount = $remain;
            }else {
                $order_amount = $order->residue_amount;
            }
            ActivityIntroduceLog::create(['order_id'=>$order->id, 'amount'=>$order_amount, 'introduce_order_id'=>$order->id, 'type'=>ActivityIntroduceLog::REFUNDTYPE]);
            $log = ActivityOrderLog::addActivityOrderLog($order->user_id,$order->id,-$order_amount, "用户申请退款", null, null, ActivityOrderLog::REFUND_TYPE);
            $order->decrement('residue_amount', $order_amount);
            ActivityShareRefund::create([
                'user_id'=>$order->user_id,
                'order_id'=>$order->id,
                'target_order_id'=>$order->id,
                'trade_no'=>$order->trade_no,
                'refund_trade_no'=>CommonService::getTradeNO(),
                'total_amount'=>$order->amount,
                'amount'=>$order_amount,
                'status'=>0,
                'sub_mch_id'=>$order->sub_mch_id,
                'type'=>ActivityShareRefund::ADMINTYPE,
                'admin_id'=>null,
                'check' => ActivityShareRefund::CHECK_TRUE,
                'log_id'=>$log->id,
            ]);
            $remain -= $order_amount;
        }
        DB::commit();;
        return $this->success('ok');
    }
}
