<?php

namespace Modules\Project\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Modules\Base\Entities\User;
use SMG\Admin\Admin;
use SMG\Admin\Controllers\HasResourceActions;
use SMG\Admin\DefaultCsvExporter;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Invitation\InvitationService;
use SMG\Invitation\UserInvitation;
use SMG\Wallet\Wallet;

class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('用户管理')
            ->body($this->grid());
    }

    public function org2($user_id, Content $content)
    {
        $user = User::findOrFail($user_id);
        $data = [];

        $data[] = ['id' => $user_id, 'parentId' => null, 'Name' => $user->phone, 'Level' => $user->team_level_title, 'UID' => $user_id];

        $this->getChildren2($user, $data);

        $callback = 'let data = '.json_encode($data).';';

        $callback .= <<<EOF
$('#people').height($(window).height()-200);
 var orgchart = new getOrgChart(document.getElementById("people"), {
        primaryFields: ["UID", "Name", "Level", "id"],
        expandToLevel: 5,
        enableEdit: false,
        enableDetailsView: false,
        enableSearch: false,
        clickNodeEvent: clickHandler,   
        dataSource: data
    });
    
    function clickHandler(sender, args) {
           window.location.href="/admin/user/org/"+args.node.id;
          //alert("clecked node.id " + args.node.id);
        }
EOF;

        Admin::addCss('/css/getorgchart.css');
        Admin::addJs('/js/getorgchart.js', $callback);

        return $content->header('下级列表')
//            ->description('最多显示10级')
            ->body('<div id="people">&nbsp;</div>');
    }

    public function getChildren2($user, &$data, $level = 0)
    {

        //$invitation = $user->invitation;
        //if ($invitation) {
        $children = User::where('parent_id', $user->id)->get();
        if (!blank($children)) {
            foreach ($children as $child) {
                $data[] = ['id' => $child->id, 'parentId' => $child->parent_id, 'Name' => $child->phone, 'Level' => $child->team_level_title, 'UID' => $child->id];
                if ($level < 11) {
                    //$level++;
                    $this->getChildren2($child, $data, ($level + 1));
                }
            }
        }
        //}
    }

    public function org($user_id, Content $content)
    {
        $user = User::findOrFail($user_id);
        $data = [];

        $user_ids = $user->descendants()->pluck('id')->toArray();
        array_push($user_ids, $user->id);
        //$team_consumption = Wallet::whereIn('user_id', $user_ids)->sum('consumption');

        $data[] = ['id' => $user_id, 'parentId' => null, 'Name' => $user->phone, 'Level' => $user->level_title. ' '.$user->ad_level_title, 'UID' => $user_id];

        $invitation = $user->invitation;
        if ($invitation) {
            $this->getChildren($invitation, $data);
        }

        $callback = 'let data = '.json_encode($data).';';

        $callback .= <<<EOF
$('#people').height($(window).height()-200);
 var orgchart = new getOrgChart(document.getElementById("people"), {
        primaryFields: ["UID", "Name", "Level", "id"],
        expandToLevel: 5,
        enableEdit: false,
        enableDetailsView: false,
        enableSearch: false,
        clickNodeEvent: clickHandler,   
        dataSource: data
    });
    
    function clickHandler(sender, args) {
           window.location.href="/admin/user/org/"+args.node.id;
          //alert("clecked node.id " + args.node.id);
        }
EOF;

        Admin::addCss('/css/getorgchart.css');
        Admin::addJs('/js/getorgchart.js', $callback);

        return $content->header('推荐的人')
//            ->description('最多显示10级')
            ->body('<div id="people">&nbsp;</div>');
    }

    public function getChildren($invitation, &$data, $level = 0)
    {

        //$invitation = $user->invitation;
        //if ($invitation) {
        $children = $invitation->children()->with(['user' => function ($query) {
            $query->select('id', 'phone', 'level', 'ad_level');
        }])->get();
        if (!blank($children)) {
            foreach ($children as $child) {
                //$u = $child->user;

                //$user_ids = $u::descendants()->pluck('id')->toArray();
                //array_push($user_ids, $u->id);

                $data[] = ['id' => $child->user_id, 'parentId' => $child->parent_id, 'Name' => $child->user->phone, 'Level' => $child->user->level_title. ' '.$child->user->ad_level_title, 'UID' => $child->user_id];
                if ($level < 11) {
                    //$level++;
                    $this->getChildren($child, $data, ($level + 1));
                }
            }
        }
        //}
    }

    /**
     * Show interface.
     *
     * @param mixed   $id
     * @param Content $content
     *
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed   $id
     * @param Content $content
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑用户')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新增用户')
            ->description('')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);

        $grid->model()->with(['invitation.parent.user']);

        $grid->id('Id');
        $grid->name('用户名');
        $grid->phone('手机');

        //$grid->column('realName.real_name', '姓名');
        //$grid->sn('编号');

        $grid->level('等级')->display(function ($v) {
            $colors = [
                '#D1CBC4',
                '#98A76C',
                '#98A76C',
                '#E86BFF',
                '#EB7878',
                '#DD872F',
            ];

            return '<span class="badge" style="background-color: '.$colors[$v].'">LV '.$v.'&nbsp;&nbsp;&nbsp;'.User::$level_maps[$v].'</span>';
        });
        //$grid->column('is_member', '省钱卡会员')->bool();
//        $grid->ad_level('广告等级')->display(function ($v) {
//            $colors = [
//            '#D1CBC4',
//            '#98A76C',
//            '#98A76C',
//            '#E86BFF',
//            '#EB7878',
//            '#DD872F',
//        ];

//            return '<span class="badge" style="background-color: '.$colors[$v].'">LV '.$v.'&nbsp;&nbsp;&nbsp;'.User::$ad_level_maps[$v].'</span>';
//        });
//        $grid->column('membership_card_no', '养老卡号');

        $grid->column('parent', '推荐人')->display(function ($v) {
            if ($ui = $this->invitation && $p = $this->invitation->parent) {
                return '<a href="'.manage_url('user?&id='.$p->user_id).'">'.$p->user->phone.'</a>';
            }
        });

        //$grid->column('code', '邀请码');

        $grid->created_at('注册时间');

        $grid->model()->orderBy('id', 'DESC');

        //$grid->disableCreateButton();

        $grid->enableFilter();
        $grid->filter(function (Filter $filter) {
            //$filter->disableIdFilter();
            //$filter->equal('name', '姓名');
            //$filter->equal('level', '等级')->select(User::$levels);
            $filter->where(function ($query) {
                $query->whereRaw("users.name like '%{$this->input}%'");
            }, '用户名');
            $filter->where(function ($query) {
                $query->whereRaw("users.phone like '%{$this->input}%'");
            }, '手机号');

            //$filter->like('realName.real_name', '姓名');
            //$filter->equal('sn', '编号');
            //$filter->between('created_at', '注册时间')->datetime();
            //$filter->equal('level', '等级')->select(User::$level_maps);
            $filter->where(function ($query) {
                $parent = User::where('phone', $this->input)->first();
                if ($parent) {
                    $ids = $parent->childrenIds();
                } else {
                    $ids = [];
                }
                $query->whereIn('id', $ids);
            }, '推荐人手机号');
        });

        $grid->disableRowSelector();

        $grid->actions(function (Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->append('&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.manage_url('wallet?phone='.$actions->row->phone).'"><i class="fa fa-rmb"></i>资产</a>');
            $actions->append('&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.manage_url('user/org/'.$actions->getKey()).'"><i class="fa fa-users"></i>推荐的人</a>');
        });

        $grid->enableExport();
        $columns = ['ID' => 'id', '用户名' => 'name', '手机' => 'phone',
//            '姓名' => 'realName.real_name',
            //'等级' => function($row){return User::getLevelTitleArray($row->level);},
//            '养老卡号' => 'membership_card_no',
            '推荐人' => 'inviter_name',
//            '等级' => function ($row) {
//                return User::$level_maps[$row->level];
//            },
            /*
            '推荐人' => function ($row) {
                if ($ui = $row->invitation && $p = $row->invitation->parent) {
                    return $p->user->phone;
                }

                return '';
            },*/
            '注册时间' => 'created_at', ];
        $grid->exporter(new DefaultCsvExporter(null, $columns));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->id('Id');
        $show->name('Name');
        $show->phone('Phone');
        $show->email('Email');
        $show->password('Password');
        $show->remember_token('Remember token');
        $show->created_at('Created at');
        $show->updated_at('Updated at');
        $show->avatar('Avatar');
        $show->sex('Sex');
        $show->ext('Ext');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User);

        $id = request()->route('user');
        $phone_rule = $id ? 'unique:users,phone,'.$id.',id' : 'unique:users';

        $form->text('name', '用户名');
        $form->mobile('phone', '手机号')->rules($phone_rule);
        $form->password('password', '密码')->help('修改时为空则不修改');
        //$form->text('membership_card_no', '会员卡号');
        //$form->text('sn','编号')->rules('required');

        $form->select('level', '用户等级')->options(User::$level_maps);
        //$form->select('ad_level', '广告等级')->options(User::$ad_level_maps);

        if ($id) {
            $iv = UserInvitation::where('user_id', $id)->first();
            if(!$iv || !$iv->parent_id) {
                $form->hidden('update', 1)->value(1);
                $form->mobile('invite_code', '推荐人')->rules('invite_code_check2');
            } else {
                $form->html(optional(User::find($iv->parent_id))->phone, '推荐人');
            }
        } else {
            $form->mobile('invite_code', '推荐人')->rules('invite_code_check2');
        }
        $form->ignore(['invite_code', 'invitation_phone', 'update']);

        $form->saving(function (Form $form) {
            $model = $form->model();
            /*
            if (!$form->model()->id && empty($model->password)) {
                throw new \Exception('密码不能为空');
            }*/

            if (empty($form->input('password'))) {
                $form->input('password', $model->password);
            } elseif (strlen($form->input('password')) < 6) {
                $error = \Illuminate\Validation\ValidationException::withMessages([
                    'password' => ['密码长度不能小于6位'],
                ]);

                throw $error;
            } else {
                $form->input('password', \Hash::make($form->input('password')));
            }
        });

        $form->saved(function (Form $form) {
            $update = request('update', 0);
            if ($update == 1) {
                $model = $form->model();
                (new InvitationService())->created($model);
            }
        });

        return $form;
    }
}
