<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\MemberCreateRequest;
use App\Http\Requests\MemberUpdateRequest;
use App\Http\Requests\MemberUpdateMoneyRequest;
use App\Models\Member;
use App\Models\MoneyDetails;
use App\Models\MembersDetailed;
use App\Models;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class MemberController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
        return view('admin.member.index');
    }
    public function data(Request $request)
    {
        $model = Member::query();
        $model = $model
            ->select(['phone', 'name', 'members.created_at', 'identity', 'is_deleted', 'membersDetailed_cash', 'members_id', 'membersDetailed_delete'])
            ->join('membersDetailed', 'membersDetailed.members_id', 'members.id');
        if ($request->get('name')){
            $model = $model->where('name','like','%'.$request->get('name').'%');
        }
        if ($request->get('phone')){
            $model = $model->where('phone','like','%'.$request->get('phone').'%');
        }
        $res = $model
            ->orderBy('created_at','desc')
            ->paginate($request->get('limit',30))
            ->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }
    public function getDetailedInfo()
    {
        return view('admin.member.detailedInfo');
    }
    public function dataDetailedInfo(Request $request)
    {
        $model = MoneyDetails::query();
        $startTime = $request->get('startTime') ?? '1900-01-01 00:00:00';
        $endTime = $request->get('endTime') ?? '3000-12-12 00:00:00';
        $modelBetween = [$startTime, $endTime];
        $model = $model
            ->where(['members_id' => $request->get('members_id'), 'moneyDetails_status' => 1])
            -> whereBetween('moneyDetails_time', $modelBetween);
        if ($request->get('type')){
            $model = $model->where(['moneyDetails_type' => $request->get('type')]);
        }
        if ($request->get('describe')){
            $model = $model->where('moneyDetails_describe','like','%'.$request->get('describe').'%');
        }
        $res = $model
            ->orderBy('moneyDetails_time','desc')
            ->paginate($request->get('limit',30))
            ->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }
    public function resetPassword(Request $request)
    {
        $ids = $request->get('ids');
        $memberModel = new Member;
        $uuid = $memberModel->select('uuid')->where(['id'=>$ids[0]])->first();
        $user['password'] = createPasswd(trim('123456'), $uuid->uuid);
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择要重置密码的用户']);
        }
        if (Member::whereIn('id',$ids)->update($user)){
            return response()->json(['code'=>0,'msg'=>'密码重置成功']);
        }
        return response()->json(['code'=>1,'msg'=>'密码重置失败']);
    }
    public function editMoney($id)
    {
        $member = Member::findOrFail($id);
        return view('admin.member.editMoney',compact('member'));
    }
    public function updateMoney(MemberUpdateMoneyRequest $request, $id)
    {
        $model = MembersDetailed::query();
        $cash = $model->select('membersDetailed_cash')->where(['members_id'=>$id, 'membersDetailed_delete'=>0])->first();
        $money = $request->get('money');
        $type = $request->get('type');
        $nowMoney = 0;
        $msg = '';
        if ($type==1){
            $msg = '充值';
            $nowMoney = $cash->membersDetailed_cash + $money;
        } elseif ($type==2) {
            $msg = '扣款';
            $nowMoney = $cash->membersDetailed_cash - $money;
            if ($nowMoney<0) {
                return redirect()->to(route('admin.member'))->withErrors('用户余额不足');
            }
        }
        DB::beginTransaction();
        $updateMoney = $model->where('members_id',$id)->update(['membersDetailed_cash'=>$nowMoney]);
        // 添加记录
        $uuid = getUUID();
        $moneyDetailsModel = new Models\MoneyDetails;
        $describe = '后台' . $msg;
        $data = [
            'moneyDetails_identity' => $uuid,
            'members_id' => $id,
            'moneyDetails_money' => $money,
            'moneyDetails_time' => date('Y-m-d H:i:s'),
            'moneyDetails_type' => $type,
            'moneyDetails_cash' => $nowMoney,
            'moneyDetails_describe' => $describe,
            'moneyDetails_status' => 1,
        ];
        $add = $moneyDetailsModel->insert($data);
        if ($updateMoney && $add){
            DB::commit();
            $msg = $msg . '成功';
            return redirect()->to(route('admin.member'))->with(['status'=>$msg]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>1,'msg'=>'操作失败']);
        }
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.member.create');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(MemberCreateRequest $request)
    {
        $data = $request->all();
        // $data['password'] = bcrypt($data['password']);
        $data['uuid'] = \Faker\Provider\Uuid::uuid();
        $data['password'] = createPasswd(trim($data['password']),$data['uuid']);
        if (Member::create($data)){
            return redirect()->to(route('admin.member'))->with(['status'=>'添加账号成功']);
        }
        return redirect()->to(route('admin.member'))->withErrors('系统错误');
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $member = Member::findOrFail($id);
        return view('admin.member.edit',compact('member'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(MemberUpdateRequest $request, $id)
    {
        $member = Member::findOrFail($id);
        $data = $request->except('password');
        if ($request->get('password')){
            $data['password'] =createPasswd(trim($request->get('password')),$member['uuid']);
        }
        if ($member->update($data)){
            return redirect()->to(route('admin.member'))->with(['status'=>'更新用户成功']);
        }
        return redirect()->to(route('admin.member'))->withErrors('系统错误');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        $status = $request->get('status') == 0 ? 1 : 0;
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择更改状态项']);
        }
        if (Member::whereIn('id',$ids)->update(['is_deleted'=>$status])){
            return response()->json(['code'=>0,'msg'=>'更改状态成功']);
        }
        return response()->json(['code'=>1,'msg'=>'更改状态失败']);
    }
}
