<?php

    namespace plugin\admin\app\controller;

    use app\api\repositories\MoneyLogRepositories;
    use app\business\LoginBusiness;
    use app\business\StreamBusiness;
    use Illuminate\Support\Arr;
    use plugin\admin\app\model\BankCard;
    use plugin\admin\app\model\MyGood;
    use plugin\admin\app\model\Stream;
    use plugin\admin\app\model\UserIdentity;
    use Respect\Validation\Validator;
    use support\Db;
    use support\Request;
    use support\Response;
    use plugin\admin\app\model\User;
    use plugin\admin\app\controller\Crud;
    use support\exception\BusinessException;

    /**
     * 会员列表
     */
    class UserController extends Crud
    {

        /**
         * @var User
         */
        protected $model = null;

        /**
         * 构造函数
         * @return void
         */
        public function __construct()
        {
            $this->model = new User;
        }

        /**
         * 浏览
         * @return Response
         */
        public function index(): Response
        {
            return view('user/index');
        }

        /** 首页
         * @param Request $request
         * @return Response
         */
        public function select(Request $request): Response
        {
            $param  = $request->all();
            $teamId = admin('team_id');
            $data   = User::query()->where(function ($query) use ($param, $teamId) {
                if (is_numeric(Arr::get($param, 'money.1')) && is_numeric(Arr::get($param, 'money.0'))) {
                    $query->whereBetween('money', [$param['money'][0], $param['money'][1]]);
                } elseif (is_numeric(Arr::get($param, 'money.0'))) {
                    $query->where('money', '>=', $param['money'][0]);
                } elseif (is_numeric(Arr::get($param, 'money.1'))) {
                    $query->where('money', '<=', $param['money'][1]);
                }

                if (is_numeric(Arr::get($param, 'money_one.1')) && is_numeric(Arr::get($param, 'money_one.0'))) {
                    $query->whereBetween('money_one', [$param['money_one'][0], $param['money_one'][1]]);
                } elseif (is_numeric(Arr::get($param, 'money_one.0'))) {
                    $query->where('money_one', '>=', $param['money_one'][0]);
                } elseif (is_numeric(Arr::get($param, 'money_one.1'))) {
                    $query->where('money_one', '<=', $param['money_one'][1]);
                }

                if (is_numeric(Arr::get($param, 'money_two.1')) && is_numeric(Arr::get($param, 'money_two.0'))) {
                    $query->whereBetween('money_two', [$param['money_two'][0], $param['money_two'][1]]);
                } elseif (is_numeric(Arr::get($param, 'money_two.0'))) {
                    $query->where('money_two', '>=', $param['money_two'][0]);
                } elseif (is_numeric(Arr::get($param, 'integral.1'))) {
                    $query->where('money_two', '<=', $param['money_two'][1]);
                }


                if (Arr::get($param, 'created_at.0') && Arr::get($param, 'created_at.1')) {
                    $query->whereBetween('created_at', [$param['created_at'][0], $param['created_at'][1]]);
                } elseif (Arr::get($param, 'created_at.0')) {
                    $query->where('created_at', '>=', $param['created_at'][0]);
                } elseif (Arr::get($param, 'created_at.1')) {
                    $query->where('created_at', '<=', $param['created_at'][1]);
                }

                if (Arr::get($param, 'join_time.0') && Arr::get($param, 'join_time.1')) {
                    $query->whereBetween('join_time', [$param['join_time'][0], $param['join_time'][1]]);
                } elseif (Arr::get($param, 'join_time.0')) {
                    $query->where('join_time', '>=', $param['join_time'][0]);
                } elseif (Arr::get($param, 'join_time.1')) {
                    $query->where('join_time', '<=', $param['join_time'][1]);
                }

                if (is_numeric(Arr::get($param, 'status'))) {
                    $query->where('status', $param['status']);
                }

                if (Arr::get($param, 'name')) {
                    $query->where('name', $param['name']);
                }
                if (Arr::get($param, 'mobile')) {
                    $query->where('mobile', $param['mobile']);
                }
                if (Arr::get($param, 'is_autonym')) {
                    $query->where('is_autonym', $param['is_autonym']);
                }
                if (Arr::get($param, 'id')) {
                    $query->where('id', $param['id']);
                }
                if ($teamId) {
                    $query->where('team_id', $teamId);
                }
            })->with('pidData:id,name,mobile');
            if (Arr::get($param, 'field')) {
                $order = 'asc';
                if (Arr::get($param, 'order')) {
                    $order = $param['order'];
                }
                $data = $data->orderBy($param['field'], $order);
            }
            $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();


            return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['total']]);
        }

        /** 下级
         * @param Request $request
         * @return Response
         */
        public function subordinate(Request $request): Response
        {
            $param = $request->all();


            if ($request->isAjax()) {

                $data = User::query()->where(function ($query) use ($param) {
                    if (is_numeric(Arr::get($param, 'money.1')) && is_numeric(Arr::get($param, 'money.0'))) {
                        $query->whereBetween('money', [$param['money'][0], $param['money'][1]]);
                    } elseif (is_numeric(Arr::get($param, 'money.0'))) {
                        $query->where('money', '>=', $param['money'][0]);
                    } elseif (is_numeric(Arr::get($param, 'money.1'))) {
                        $query->where('money', '<=', $param['money'][1]);
                    }

                    if (Arr::get($param, 'created_at.0') && Arr::get($param, 'created_at.1')) {
                        $query->whereBetween('created_at', [$param['created_at'][0], $param['created_at'][1]]);
                    } elseif (Arr::get($param, 'created_at.0')) {
                        $query->where('created_at', '>=', $param['created_at'][0]);
                    } elseif (Arr::get($param, 'created_at.1')) {
                        $query->where('created_at', '<=', $param['created_at'][1]);
                    }

                    if (is_numeric(Arr::get($param, 'status'))) {
                        $query->where('status', $param['status']);
                    }

                    if (Arr::get($param, 'last_time.0') && Arr::get($param, 'last_time.1')) {
                        $query->whereBetween('last_time', [$param['last_time'][0], $param['last_time'][1]]);
                    } elseif (Arr::get($param, 'last_time.0')) {
                        $query->where('last_time', '>=', $param['last_time'][0]);
                    } elseif (Arr::get($param, 'last_time.1')) {
                        $query->where('last_time', '<=', $param['last_time'][1]);
                    }

                    if (Arr::get($param, 'join_time.0') && Arr::get($param, 'join_time.1')) {
                        $query->whereBetween('join_time', [$param['join_time'][0], $param['join_time'][1]]);
                    } elseif (Arr::get($param, 'join_time.0')) {
                        $query->where('join_time', '>=', $param['join_time'][0]);
                    } elseif (Arr::get($param, 'last_time.1')) {
                        $query->where('join_time', '<=', $param['join_time'][1]);
                    }

                    if (Arr::get($param, 'last_ip')) {
                        $query->where('last_ip', $param['last_ip']);
                    }

                    if (Arr::get($param, 'join_ip')) {
                        $query->where('join_ip', $param['join_ip']);
                    }

                    if (Arr::get($param, 'name')) {
                        $query->where('name', $param['name']);
                    }
                    if (Arr::get($param, 'mobile')) {
                        $query->where('mobile', $param['mobile']);
                    }


                    if (Arr::get($param, 'pid')) {

                        $query->where('pid', $param['pid']);
                    }
                });
                if (Arr::get($param, 'field')) {
                    $order = 'asc';
                    if (Arr::get($param, 'order')) {
                        $order = 'desc';
                    }
                    $data = $data->orderBy($param['field'], $order);
                }
                $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();


                return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['total']]);
            }
            return view('user/subordinate', $param);
        }

        /** 流水
         * @param Request $request
         * @return Response
         */
        public function stream(Request $request): Response
        {
            $param = $request->all();

            if ($request->isAjax()) {
                $param = $request->all();
                $data  = Stream::query()->where(function ($query) use ($param) {
                    if (is_numeric(Arr::get($param, 'money.1')) && is_numeric(Arr::get($param, 'money.0'))) {
                        $query->whereBetween('money', [$param['money'][0], $param['money'][1]]);
                    } elseif (is_numeric(Arr::get($param, 'money.0'))) {
                        $query->where('money', '>=', $param['money'][0]);
                    } elseif (is_numeric(Arr::get($param, 'money.1'))) {
                        $query->where('money', '<=', $param['money'][1]);
                    }

                    if (Arr::get($param, 'created_at.0') && Arr::get($param, 'created_at.1')) {
                        $query->whereBetween('created_at', [$param['created_at'][0], $param['created_at'][1]]);
                    } elseif (Arr::get($param, 'created_at.0')) {
                        $query->where('created_at', '>=', $param['created_at'][0]);
                    } elseif (Arr::get($param, 'created_at.1')) {
                        $query->where('created_at', '<=', $param['created_at'][1]);
                    }

                    if (Arr::get($param, 'type')) {
                        $query->where('type', $param['type']);
                    }
                    if (Arr::get($param, 'mold')) {
                        $query->where('mold', $param['mold']);
                    }
                    if (Arr::get($param, 'user_id')) {
                        $query->where('user_id', $param['user_id']);
                    }
                })->whereExists(function ($query) use ($param) {
                    $query->from('wa_users')->whereRaw('wa_users.id=wa_stream.user_id');
                    if (Arr::get($param, 'user_name')) {
                        $query->where('name', 'like', '%' . $param['user_name'] . '%');
                    }
                    if (Arr::get($param, 'mobile')) {
                        $query->where('mobile', 'like', '%' . $param['mobile'] . '%');
                    }
                })
                    ->with('userData:id,name,mobile');
                if (Arr::get($param, 'field')) {
                    $order = 'asc';
                    if (Arr::get($param, 'order')) {
                        $order = 'desc';
                    }
                    $data = $data->orderBy($param['field'], $order);
                } else {
                    $data = $data->orderByDesc('id');
                }
                $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();
                $arr  = [];
                foreach ($data['data'] as $k => $v) {
                    $arr[] = [
                        'user_name'   => $v['user_data']['name'],
                        'user_mobile' => $v['user_data']['mobile'],
                        'type_id'     => $v['type'],
                        'mold_id'     => $v['mold'],
                        'type'        => streamType($v['type']) . '--' . moldType($v['mold']),
                        'created_at'  => $v['created_at'],
                        'total_money' => $v['total_money'],
                        'money'       => $v['money']
                    ];
                }
                return json(['code' => 0, 'data' => $arr, 'msg' => 'ok', 'count' => $data['total']]);
            }
            return view('user/stream', $param);
        }

        /** 银行卡
         * @param Request $request
         * @return Response
         */
        public function bankcard(Request $request): Response
        {
            $param = $request->all();

            if ($request->isAjax()) {

                $data = BankCard::query()->where(function ($query) use ($param) {

                    if (Arr::get($param, 'id')) {

                        $query->where('uid', $param['id']);
                    }
                })->with('userData:id,name,mobile');
                if (Arr::get($param, 'field')) {
                    $order = 'asc';
                    if (Arr::get($param, 'order')) {
                        $order = 'desc';
                    }
                    $data = $data->orderBy($param['field'], $order);
                }
                $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();


                return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['total']]);
            }
            return view('user/bankcard', $param);
        }

        /** 身份证
         * @param Request $request
         * @return Response
         */
        public function identity(Request $request): Response
        {
            $param = $request->all();
            if ($request->isAjax()) {
                $data = UserIdentity::query()->where(function ($query) use ($param) {
                    if (Arr::get($param, 'id')) {
                        $query->where('uid', $param['id']);
                    }
                });
                if (Arr::get($param, 'field')) {
                    $order = 'asc';
                    if (Arr::get($param, 'order')) {
                        $order = 'desc';
                    }
                    $data = $data->orderBy($param['field'], $order);
                }
                $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();


                return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['total']]);
            }
            return view('user/identity', $param);
        }

        /** 更新身份证
         * @param Request $request
         * @return Response
         */
        public function identitysave(Request $request): Response
        {
            $param = $request->all();
            $param = Arr::only($param, ['id', 'name', 'number']);
            if ($request->isAjax()) {
                try {
                    $has = UserIdentity::query()->where('uid', $param['id'])->first();
                    if ($has) {
                        UserIdentity::query()->where('uid', $param['id'])->update([
                            'name'    => $param['name'],
                            'number'  => $param['number'],
                            'uid'     => $param['id'],
                            'oname'   => $has->name,
                            'onumber' => $has->number,
                        ]);
                    } else {
                        UserIdentity::query()->insert([
                            'uid'        => $param['id'],
                            'name'       => $param['name'],
                            'number'     => $param['number'],
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s'),
                        ]);
                    }
                    User::query()->where('id', $param['id'])->update([
                        'is_autonym' => 1,
                        'name'       => $param['name'],
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                } catch (\Throwable $exception) {
                    return $this->fail($exception->getMessage());
                }
                return $this->success();
            }
        }

        /**
         * 更新
         * @param Request $request
         * @return Response
         * @throws BusinessException
         */
        public function update(Request $request): Response
        {
            if ($request->method() === 'POST') {
                $param = $request->all();

                $param = Arr::only($param, ['id', 'password', 'status', 'pid_mobile', 'mobile']);
                Db::beginTransaction();
                try {
                    Validator::input($param, [
                        'id' => Validator::notEmpty()->setName('标识'),
                    ]);

                    $userModel = User::query();
                    $has       = (clone $userModel)->where('id', $param['id'])->first();
                    if (empty($has)) {
                        throw new \Exception('账号不存在!');
                    }
                    if (Arr::get($param, 'name')) {
                        $save['name'] = $param['name'];
                    }
                    if (Arr::get($param, 'password')) {
                        $save['password'] = md5($param['password']);
                    }
                    /** 修改手机号 */
                    if (Arr::get($param, 'mobile') && $has->mobile != Arr::get($param, 'mobile')) {
                        $hasMobile = (clone $userModel)->where('mobile', $param['mobile'])->exists();
                        if (empty($hasMobile)) {
                            $save['mobile'] = $param['mobile'];
                        } else {
                            throw new \Exception($param['mobile'] . '手机号已存在!');
                        }
                    }
                    if (Arr::get($param, 'pid_mobile')) {
                        $pid = (clone $userModel)->where('mobile', $param['pid_mobile'])->value('id');
                        if (!empty($pid)) {
                            $save['pid'] = $pid;
                            (clone $userModel)->where('pid', $has->id)->update(['ppid' => $pid]);
                            (clone $userModel)->where('ppid', $has->id)->update(['toppid' => $pid]);
                        } else {
                            throw new \Exception($param['pid_mobile'] . '未查询到您需要变更的上级信息,请确认手机号是否正确!');
                        }
                    }

                    if (is_numeric(Arr::get($param, 'status'))) {
                        $save['status'] = $param['status'];
                    }

                    (clone $userModel)->where('id', $param['id'])->update($save);

                } catch (\Throwable $exception) {
                    Db::rollBack();
                    return $this->fail($exception->getMessage());
                }
                Db::commit();
                return $this->success();
            }
            return view('user/update');
        }

        /**
         * 插入
         * @param Request $request
         * @return Response
         * @throws BusinessException
         */
        public function insert(Request $request): Response
        {
            if ($request->method() === 'POST') {
                $param = Arr::only($request->all(), ['mobile', 'password', 'invitation_code']);
                Db::beginTransaction();
                try {
                    Validator::input($param, [
                        'mobile'          => Validator::notEmpty()->intType()->setName('手机号'),
                        'password'        => Validator::notEmpty()->stringType()->Length(6, 15)->alnum()->setName('密码'),
                        'invitation_code' => Validator::notEmpty()->intType()->setName('邀请码'),
                    ]);
                    LoginBusiness::register($param);
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    return $this->fail($exception->getMessage());
                }
                Db::commit();
                return $this->success();

            }
            return view('user/insert');
        }

        /** 更新银行卡
         * @param Request $request
         * @return Response
         */
        public function bankcardsave(Request $request): Response
        {
            $param = $request->all();
            $param = Arr::only($param, ['id', 'affiliated_bank', 'account_holder', 'card_number']);
            if ($request->isAjax()) {
                try {
                    $has = BankCard::query()->where('uid', $param['id'])->first();
                    if ($has) {
                        BankCard::query()->where('uid', $param['id'])->update([
                            'affiliated_bank'   => $param['affiliated_bank'],
                            'account_holder'    => $param['account_holder'],
                            'card_number'       => $param['card_number'],
                            'o_account_holder'  => $has->account_holder,
                            'o_affiliated_bank' => $has->affiliated_bank,
                            'o_card_number'     => $has->card_number,
                        ]);
                    } else {
                        BankCard::query()->insert([
                            'uid'             => $param['id'],
                            'affiliated_bank' => $param['affiliated_bank'],
                            'account_holder'  => $param['account_holder'],
                            'card_number'     => $param['card_number'],
                        ]);
                    }
                } catch (\Throwable $exception) {
                    return $this->fail($exception->getMessage());
                }
                return $this->success();
            }
        }

        /** 会员产品
         * @param Request $request
         * @return Response
         */
        public function goods(Request $request): Response
        {
            $param = $request->all();
            if ($request->isAjax()) {
                $teamId = admin('team_id');
                $data   = MyGood::query()->where(function ($query) use ($param) {

                    if (Arr::get($param, 'id')) {
                        $query->where('user_id', $param['id']);
                    }


                })->whereExists(function ($query) use ($teamId) {
                    $query->from('wa_users')->whereRaw('wa_users.id=wa_my_goods.user_id');
                    if (!empty($teamId)) {

                        $query->where('team_id', $teamId);
                    }
                })->with('userData:id,name');
                if (Arr::get($param, 'field')) {
                    $order = 'asc';
                    if (Arr::get($param, 'order')) {
                        $order = 'desc';
                    }
                    $data = $data->orderBy($param['field'], $order);
                } else {
                    $data = $data->orderByDesc('id');
                }
                $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();


                return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['total']]);
            }
            return view('user/goods', $param);
        }

        /** 上下分
         * @param Request $request
         * @return Response
         */
        public function money(Request $request): Response
        {
            if ($request->method() === 'POST') {
                $param = $request->all();

                $param = Arr::only($param, ['id', 'type', 'buy', 'mold', 'operate_password']);
                Db::beginTransaction();
                try {
                    Validator::input($param, [
                        'id'               => Validator::notEmpty()->setName('标识'),
                        'type'             => Validator::notEmpty()->setName('操作类型'),
                        'buy'              => Validator::notEmpty()->setName('金额'),
                        'mold'             => Validator::notEmpty()->setName('钱包'),
//                        'operate_password' => Validator::notEmpty()->setName('密码'),
                    ]);

//                    $system = Db::table('wa_system')->first();
//                    if (md5($param['operate_password']) != $system->operate_password) {
//                        throw new \Exception('密码填写错误!');
//                    }

                    if (Arr::get($param, 'type') == 1) {
                        StreamBusiness::addStream($param['id'], $param['buy'], streamType7, $param['mold'], moldTypefild($param['mold']));

                    } elseif (Arr::get($param, 'type') == 2) {
                        StreamBusiness::delStream($param['id'], $param['buy'], streamType8, $param['mold'], moldTypefild($param['mold']));

                    }

                } catch (\Throwable $exception) {
                    Db::rollBack();
                    return $this->fail($exception->getMessage());
                }
                Db::commit();
                return $this->success();
            }
            return view('user/money');
        }

    }
