<?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\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)
    {
        $data = [
            'stomach' => [
                'title' => '肠胃不适反应有哪些（必选）',
                'key1' => '没有不适',
                'key2' => '恶心',
                'key3' => '胃部反酸',
                'key4' => '胃部疼痛',
                'key5' => '便秘',
                'key6' => '腹胀',
                'key7' => '大便带血',
                'key8' => '腹泻',
                'key9' => '其它',
            ],
            'heart' => [
                'title' => '心脏不适有哪些（必选）',
                'key1' => '没有不适',
                'key2' => '心慌,心悸',
                'key3' => '心率异常',
                'key4' => '胸闷',
                'key5' => '呼吸急促',
                'key6' => '头晕',
                'key7' => '打鼾',
                'key8' => '其它',
            ],
            'sleep' => [
                'title' => '睡眠相关不适反应有哪些（必选）',
                'key1' => '没有不适',
                'key2' => '失眠',
                'key3' => '入睡困难',
                'key4' => '浅度睡眠',
                'key5' => '视觉疲劳',
                'key6' => '反应迟钝',
                'key7' => '记忆力衰退',
                'key8' => '焦虑',
                'key9' => '困倦疲惫',
                'key10' => '其它',
            ],
            'man' => [
                'title' => '目前男科问题有哪些（必选）',
                'key1' => '没有不适',
                'key2' => '不孕不育',
                'key3' => '尿频尿急',
                'key4' => '小腹胀痛',
                'key5' => '其它',
            ],
            'other' => [
                'title' => '其它不适有哪些（必选）',
                'key1' => '没有不适',
                'key2' => '呼吸系统不好',
                'key3' => '鼻炎',
                'key4' => '腰酸背痛',
                'key5' => '肌肉酸痛',
                'key6' => '容易感冒',
                'key7' => '虚弱无力',
                'key8' => '无食欲',
                'key9' => '容易感染',
                'key10' => '皮肤问题',
                'key11' => '哮踹',
                'key12' => '耳鸣',
                'key13' => '咳嗽',
                'key14' => '水肿',
                'key15' => '反应迟钝',
                'key16' => '其它',
            ],
            'dietary' => [
                'title' => '您的饮食习惯（必选）',
                'key1' => '一日三餐规律饮食',
                'key2' => '饿了就吃',
                'key3' => '偏好主食',
                'key4' => '偏好蔬菜水果',
                'key5' => '偏好肉类',
                'key6' => '偏好甜食',
                'key7' => '高盐高油',
                'key8' => '其它',
                'key9' => "一日一餐",
                "key10" => "一日两餐",
                "key11" => "一日四餐以上",
            ],
            'living' => [
                'title' => '您的生活习惯（必选）',
                'key1' => '抽烟',
                'key2' => '喝酒',
                'key3' => '规律睡眠',
                'key4' => '经常熬夜',
                'key5' => '经常运动',
                'key6' => '偶尔运动',
                'key7' => '几乎不运动',
                'key8' => '其它',
            ],
            'mental' => [
                'title' => '您目前精神心理状态有哪些（必选）',
                'key1' => '经常感到职场压力',
                'key2' => '经常感到夫妻关系压力',
                'key3' => '经常感到父母关系压力',
                'key4' => '经常感到亲子关系压力',
                'key5' => '经常感到焦虑',
                'key6' => '经常无故冲动',
                'key7' => '经常处于心平气和的状态',
                'key8' => '面对问题，能够快速的找到解决的办法',
                'key9' => '开心愉悦',
                'key10' => '其它',
            ],
            'family' => [
                'title' => '您目前家庭关系有哪些（必选）',
                'key1' => '夫妻关系和睦',
                'key2' => '亲子关系和睦',
                'key3' => '我与父母关系和睦',
                'key4' => '夫妻关系不和睦',
                'key5' => '亲子关系不和睦',
                'key6' => '我与父母关系不和睦',
                'key7' => '其它',
            ],
            'family_member' => [
                'title' => '您家庭成员有哪些（必选）',
                'key1' => '一个孩子',
                'key2' => '两个孩子',
                'key3' => '三个孩子及以上',
                'key4' => '父亲',
                'key5' => '母亲',
                'key6' => '丈夫',
                'key7' => '妻子',
                'key8' => '其它',
            ],
            'personal' => [
                'title' => '个人情况（必选）',
                'key1' => '已婚',
                'key2' => '未婚',
                'key3' => '离异',
                'key4' => '丧偶',
                'key5' => '财务方面压力较大',
                'key6' => '财务方面压力较小',
                'key7' => '财务方面毫无压力',
                'key8' => '其它',
            ],
            'woman' => [
                'title' => '目前妇科问题有哪些（必选）',
                'key1' => '没有不适',
                'key2' => '月经不规律',
                'key3' => '月经紊乱',
                'key4' => '已绝经',
                'key5' => '白带增多异常',
                'key6' => '尿频尿急',
                'key7' => '不孕不育',
                'key8' => '小腹胀痛',
                'key9' => '子宫肌瘤',
                'key10' => '其它',
            ],
            'know' => [
                'title' => '您是否知悉、充分理解并自愿承担方案过程中因自身疾病问题而出现或可能出现的不可抗力或者并发症（如癫痫、抽搐、痉挛、病情加重等），除非经有权司法机关裁决事故系由本公司故意或重大过失引起的，否则本公司不承担任何法律责任（必选）',
                'key1' => '完全知悉',
                'key2' => '不知悉、不理解'
            ],
            'understand' => [
                'title' => '您是否充分理解本公司的健康学习方案原则，并同意严格按本公司的指导方法进行学习，并愿意承担方案过程中可能产生的任何不良反应（必选）',
                'key1' => '充分理解',
                'key2' => '不理解'
            ],
            'really' => [
                'title' => '您反映的身体症状，以及提供的医院的病例及检验数据（如有）,是否真实、准确、完整?（必选）',
                'key1' => '是',
                'key2' => '否'
            ],
            'duty' => [
                'title' => '您是否自愿承担健康学习方案过程中突发性生命危险或病情加重的后果,并不以任何形式追究本公司的任何责任?（必选）',
                'key1' => '是',
                'key2' => '否'
            ],
            'health_server' => [
                'title' => '在未来的健康服务中，您更希望获得哪些类型的服务？（必选）',
                'key1' => '服务人员具备专业的健康知识',
                'key2' => '服务人员可以随时解答您的问题',
                'key3' => '服务人员通过语音提供服务',
                'key4' => '服务人员通过文字提供服务',
                'key5' => '服务人员经常与您互动',
                'key6' => '除非必要，请不要与我联系',
                'key7' => '其它',
            ],
            'desc' => [
                'title' => "其它不适,请填写描述（必填）"
            ]
        ];
        dd(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    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");
    }




}
