<?php

namespace App\Admin\Controllers\Platform;

use App\Admin\Actions\LinkCreateAddress;
use Carbon\Carbon;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use Modules\User\Http\Controllers\Admin\Actions\AddUserRemark;
use Modules\User\Http\Controllers\Admin\Actions\JoinIdentity;
use Modules\User\Http\Controllers\Admin\Actions\UserStatusInit;
use Modules\User\Http\Controllers\Admin\Actions\UserStatusRefund;
use Modules\User\Models\Identity;
use Modules\User\Models\IdentityLog;
use Modules\User\Models\IdentityMiddle;
use Modules\User\Models\User;
use Modules\User\Models\UserChannel;
use Modules\User\Renderable\UserLog;

class VipController extends AdminController
{

    protected $title = '会员管理';

    /**
     * Notes   : 用户管理列表
     *
     * @Date   : 2021/3/11 1:59 下午
     * @Author : <Jason.C>
     * @return Grid
     */
    public function grid(): Grid
    {
        $grid = new Grid(new User());

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableEdit();
            $actions->disableDelete();
            $actions->disableView();
            if ($actions->row->status == User::STATUS_INIT) {
                $actions->add(new UserStatusRefund());
            }
            if ($actions->row->status == User::STATUS_REFUND) {
                $actions->add(new UserStatusInit());
            }
            
            $actions->add(new JoinIdentity());
            $actions->add(new AddUserRemark());
            $actions->add(new LinkCreateAddress());

        });

        $grid->quickSearch('username')->placeholder('快速搜索用户名');

        $grid->filter(function (Grid\Filter $filter) {
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('username', '用户名');
                $filter->equal('channel_id', '渠道')->select(UserChannel::pluck('name', 'id'));
            });

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('info.nickname', '用户昵称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('identities.id', '身份')
                    ->select(Identity::query()->where('id', '>', 1)->pluck('name', 'id'));
            });
        });

        $grid->model()
            ->whereHas('identities', function ($q) {
                $q->where('id', '>', 1);
            })
            ->withCount(['addresses', 'logs'])
            ->with(['info', 'parent', 'identities', 'addresses', 'vipOrders', 'userStock', 'logs']);

        //序号 姓名  手机号 会员类型  会员编号 缴费金额 加入时间  状态(正常，退费)  用箱数 提货箱数 剩余箱数
        $grid->column('id', '序号');
        $grid->column('username', '手机号');
        $grid->column('identities', '会员类型')
            ->display(function () {
                $data = [];
                foreach ($this->identities as $identity) {
                    $data[] = $identity->name;
                }
                return $data;
            })
            ->label();
        $grid->column('serial', '会员编号')
            ->display(function () {
                $data = [];
                foreach ($this->identities as $identity) {
                    $data[] = $identity->serial_prefix.$identity->getOriginal('pivot_serial');
                }
                return $data;
            })
            ->label();

        $grid->column('price', '缴费金额')
            ->display(function () {
                return $this->getOpenVipPrices();
            })
            ->label();

        $grid->column('created_at', '加入时间');
        $grid->column('status', '状态')
            ->using(User::STATUS)
            ->label();
        $grid->column('userStock.stock', '总箱数');
        $grid->column('userStock.hold', '提货箱数');
        $grid->column('userStock.residue', '剩余箱数');
        $grid->column('addresses_count', '收货地址')
            ->link(function () {
                return route('admin.mall.addresses.index', ['user_id' => $this->id]);
            }, '_self');
        $grid->column('logs_count', '备注')
            ->modal('备注信息', UserLog::class);

        $grid->disableExport(false);
        $grid->export(function ($export) {
            $export->column('identities', function ($value, $original) {
                return strip_tags($value);
            });
            $export->column('serial', function ($value, $original) {
                return strip_tags($value);
            });
            $export->column('price', function ($value, $original) {
                return strip_tags($value);
            });
            $export->column('status', function ($value, $original) {
                return strip_tags($value);
            });

//            $export->column('use_way', function ($value, $original) {
//                return strip_tags($value);
//            });
//            $export->column('所属用户', function ($value, $original) {
//                return iconv('gb2312//ignore', 'utf-8',
//                    iconv('utf-8', 'gb2312//ignore', strip_tags(str_replace("&nbsp;", " ", $value))));
//            });
//
//            $export->column('couponGrant.code', function ($value, $original) {
//                return $value."\n";
//            });

            $export->except(['addresses_count', 'logs_count']);

            $export->filename($this->title.date("YmdHis"));
        });

        return $grid;
    }

    /**
     * Notes   : 编辑表单
     *
     * @Date   : 2021/7/15 5:09 下午
     * @Author : <Jason.C>
     * @return Form
     * @throws Exception
     */
    public function form(): Form
    {
//        if (! config('user.create_user_by_admin')) {
//            throw new Exception('不运允许操作用户');
//        }

        Admin::script(" $(document.body).append(`<script src='/vendor/js/setStock.js'>`); ");
        $form = new Form(new User());

        //姓名  手机号 身份  编号 (数字从1开始) 缴费金额 加入日期(当天)  总箱数
        $form->text('info.nickname', '姓名')->required();
        $form->text('username', '手机号')
            ->required()
            ->rules(['phone:CN,mobile', 'unique:users,username,{{id}}'], [
                'phone' => '手机号格式错误'
            ]);
        $form->select('join_identity_id', '加入身份')
            ->options(Identity::where('order', '>', 2)->pluck('name', 'id'))
            ->required();
        $form->text('serial', '编号')->value($form->model()->getNewSerial(8))->required();
        $form->number('price', '缴费金额')
            ->default(1)
            ->required();

        $form->date('join_at', '加入时间')->default(now())->required();
        $form->number('stock', '总箱数')
            ->default(0)
            ->setLabelClass(['identity_stock'])
            ->required();

        $form->ignore(['join_at', 'price', 'serial', 'stock', 'join_identity_id']);

        $form->saving(function (Form $form) {
            $exists = IdentityMiddle::query()->where('serial', $form->serial)->first();
            if ($exists) {
                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => '编号已经存在',
                ]);

                return back()->withInput()->with(compact('error'));
            }
        });

        $form->saved(function (Form $form) {
            $user = $form->model();
            $user->update([
                'created_at' => Carbon::parse(request()->jion_at)->startOfDay()
            ]);
            $user->createOrder(request()->join_identity_id, 1, request()->price, request()->stock, [
                'serial'  => request()->serial,
                'channel' => IdentityLog::CHANNEL_SYSTEM,
            ]);//创建订单
        });
        return $form;
    }

    /**
     * Notes   : User 列表选择, 这里没有判断，用户是否已经有店铺了，如果判断的情况，可能导致当前用户 无法被选中
     *
     * @Date   : 2021/5/6 4:35 下午
     * @Author : <Jason.C>
     */
    public function ajax(Request $request)
    {
        $q = $request->get('q');

        return User::leftJoin('user_infos as info', 'users.id', '=', 'info.user_id')
            ->where('username', 'like', "%$q%")
            ->orWhere('info.nickname', 'like', "%$q%")
            ->select('id', DB::raw('CONCAT(username, " [", info.nickname, "]") as text'))
            ->paginate();
    }

    /**
     * Notes: 获取库存
     *
     * @Author: 玄尘
     * @Date: 2022/9/7 15:23
     * @param  Request  $request
     * @return mixed
     */
    public function stock(Request $request)
    {
        $q        = $request->get('q');
        $identity = Identity::find($q);
        return ['status_code' => 200, 'value' => $identity->stock];
    }

}
