<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class YouController extends Controller
{
    //优惠券列表
    public function list()
    {
        $list = DB::table('admin_you') -> get();
        return view('Admin.you-list',['you' => $list]);
    }
    //优惠券状态
    public function status(Request $req)
    {
        if(!$req -> id){
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        $status = DB::table('admin_you') -> where('id',$req -> id) -> value('status');
        if($status){
            $is = DB::table('admin_you') -> where('id',$req -> id) -> update(['status'=>0]);
        }else{
            $is = DB::table('admin_you') -> where('id',$req -> id) -> update(['status'=>1]);
        }
        return $is ? ['code'=> '1000','msg'=>'操作完成'] : ['code'=> '1002','msg'=>'操作失败'];
    }
    //优惠券删除
    public function delete(Request $req)
    {
        if(!$req -> id){
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        $is = DB::table('admin_you') -> where('id',$req -> id) -> delete();
        return $is ? ['code'=> '1000','msg'=>'删除成功'] : ['code'=> '1002','msg'=>'删除失败'];
    }
    //查看优惠券
    public function look($id)
    {
        if(!$id) {
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        $user_you = DB::table('user_you') -> where('youhui_id',$id) -> get();
        $you = DB::table('admin_you') -> where('id',$id) -> first();
        return view('Admin.you-look',['you'=>$you,'uyou'=>$user_you]);
    }
    //撤回优惠券
    public function back(Request $req)
    {
        if(!$req -> id || !$req -> yhid){
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        //删除当前用户呃优惠券
        $user_yhid = DB::table('user_you') -> where('user_id',$req -> id) -> where('youhui_id',$req -> yhid) -> value('id');
        $is = $user_yhid ? DB::table('user_you') -> where('id',$user_yhid) -> delete() : '';
        //已领取减1
        if($is){
            $iss = DB::table('admin_you') -> where('id',$req -> yhid) -> decrement('use_num');
        }
        return $is && $iss ? ['code'=> '1000','msg'=>'删除成功'] : ['code'=> '1002','msg'=>'删除失败'];
    }
    //添加优惠券页面
    public function add()
    {
        //拿到所有商品信息
        $goods = DB::table('goods') -> where('status',1) -> orderBy('orders','asc') -> get();
        $all_goods = [];
        foreach($goods as $key => $val) {
            $all_goods[$key]['id'] = $val -> id;
            $all_goods[$key]['goods_name'] = $val -> goods_name;
        }
        $md = DB::table('md') -> where('status',1) -> get();
        return view('Admin.you-add',['goods'=>$goods,'md' => $md]);
    }
    //添加充值专享优惠券
    public function vipAdd()
    {
        //拿到所有商品信息
        $goods = DB::table('goods') -> where('status',1) -> orderBy('orders','asc') -> get();
        $all_goods = [];
        foreach($goods as $key => $val) {
            $all_goods[$key]['id'] = $val -> id;
            $all_goods[$key]['goods_name'] = $val -> goods_name;
        }
        $md = DB::table('md') -> where('status',1) -> get();
        //获取会员几倍
        $vip_level = DB::table('vip_level') -> where('status',1) -> get();
        return view('Admin.you-vipAdd',['goods'=>$goods,'md' => $md,'vip_level' => $vip_level]);
    }
    //处理添加会员优惠券
    public function vipDoadd(Request $req)
    {
        // if(strtotime($req -> end_date) < time()){
        //     return ['code'=> '1001','msg'=>'优惠券的截止有效期不能小于现在的时间'];
        // }
        $res['name'] = $req -> name;   //优惠券名称
        $res['type'] = $req -> type;   //直减  折扣
        $res['price'] = $req -> price;   //直减折扣 金额
        $res['use_height_type'] = $req -> use_height_type;   //优惠券使用门槛 1无门槛 2满减
        $res['use_height'] = 0;   //无门槛为0   4-2
        if($req -> use_height_type == 2) {
            $res['use_height'] = $req -> use_height;   //2满多少 减  
        }
        $res['send_num'] = $req -> send_num;   //发放数量限制  限制的数量
        $res['end_date'] = $req -> end_date;   //截止时间（自领取之日天数）
        $res['md'] = $req -> md;   //使用门店    0为全部门店   其他为门店id
        $res['use_type'] = $req -> use_type;   //使用范围  1全部可用  2以下可用  3以下不可用
        if($req -> use_type == 2) {
            $res['use_size'] = implode(',',$req -> use_size2);   //使用商品id
        }else if($req -> use_type == 3) {
            $res['use_size'] = implode(',',$req -> use_size3);   //使用商品id
        }else{
            $res['use_size'] = '';
        }
        
        $res['addtime'] = time();  //添加时间
        $res['send_user_type'] = $req -> user_type;  //发放的用户类型  1所有人  2指定类型 3指定的用户id
        $res['tips'] = $req -> tips;   //优惠券说明
        $res['vip'] = $req -> vip;   //发放的vip等级
        $is = DB::table('admin_you') -> insert($res);
        return $is ? ['code'=> '1000','msg'=>'发放成功']:['code' => '1001','msg' => '发放失败'];
    }
    //门店获取商品信息
    public function getGoods(Request $req)
    {   
        if($req -> md_id != 0){
            $goods = DB::table('goods') ->  whereIn('status',[1,2]) -> where('md_id',$req -> md_id) -> get();
            return $goods;
        }
        $goods = DB::table('goods') -> whereIn('status',[1,2]) -> get();
        return $goods;
    }
    //搜索单个用户信息
    public function search(Request $req)
    {
        if(!$req -> kw) {
            return ['code'=>'10001','msg'=>'搜索结果不能为空'];
        }
        $result = DB::table('user') -> where('nickname','like','%'.$req -> kw.'%') -> take(10) -> get();
        return ['code'=> '1000','msg'=>'OK','result' => $result];
    }
    //处理优惠券添加
    public function doadd(Request $req)
    {
        if(strtotime($req -> end_date) < time()){
            return ['code'=> '1001','msg'=>'优惠券的截止有效期不能小于现在的时间'];
        }
        $res['name'] = $req -> name;   //优惠券名称
        $res['type'] = $req -> type;   //直减  折扣
        $res['price'] = $req -> price;   //直减折扣 金额
        $res['use_height_type'] = $req -> use_height_type;   //优惠券使用门槛 1无门槛 2满减
        $res['use_height'] = 0;   //无门槛为0   4-2
        if($req -> use_height_type == 2) {
            $res['use_height'] = $req -> use_height;   //2满多少 减  
        }
        $res['send_type'] = $req -> send_type;   //发放数量限制  1无限制  2限制多少张
        if($req -> send_type == 2) {
            $res['send_num'] = $req -> send_num;   //发放数量限制  限制的数量
        }
        
        $res['end_date'] = strtotime($req -> end_date);   //截止时间
        $res['md'] = $req -> md;   //使用门店    0为全部门店   其他为门店id
        $res['use_type'] = $req -> use_type;   //使用范围  1全部可用  2以下可用  3以下不可用
        if($req -> use_type == 2) {
            $res['use_size'] = implode(',',$req -> use_size2);   //使用商品id
        }else if($req -> use_type == 3) {
            $res['use_size'] = implode(',',$req -> use_size3);   //使用商品id
        }else{
            $res['use_size'] = '';
        }
        
        $res['addtime'] = time();  //添加时间
        $res['send_user_type'] = $req -> user_type;  //发放的用户类型  1所有人  2指定类型 3指定的用户id
        if($req -> user_type == 2) {
            $res['send_user'] = implode(',',$req -> user_arr);   //user_type 为2时是用户类型  为3时时用户id
        }else if($req -> user_type == 3) {
            $res['send_user'] = implode(',',$req -> search_user);   //user_type 为2时是用户类型  为3时时用户id
        }
        $res['tips'] = $req -> tips;   //优惠券说明
        // return $res;
        // return $res;
        DB::beginTransaction();
        $is = DB::table('admin_you') -> insertGetId($res);
        if(!$is) {
            DB::rollBack();   //失败后回滚
            return ['code'=> '1002','msg'=>'发放失败'];
        }

        $user['youhui_id'] = $is;  //优惠券id
        $user['name'] = $res['name'];   //优惠券名称
        $user['type'] = $res['type'];   //优惠券  1直减  2折扣
        $user['price'] =  $res['price'];   //优惠券额度
        $user['use_height'] = $res['use_height'];    //满多少钱可用   无门槛为0
        $user['end_date'] = $res['end_date'];   //优惠券过期时间
        $user['md'] = $res['md'];    //使用门店限制   0为全部门店  其他为门店id 
        $user['use_type'] = $res['use_type'];   //商品使用范围  1全部 2以下可用  3以下不可用
        $user['use_size'] = $res['use_size'];    //指定商品id   指定商品不可用id   全部不需要id
        $user['tips'] = $res['tips'];              //优惠券说明
        $user['addtime'] = time();                  //领取时间
        $user['status'] = 0;                    //0未使用  1已使用
        //继续流程   发给用户
        // 1、发放数量   2、发放人群  3、领取截止时间
        if($res['end_date'] < time()){
            //超出时间，发放完成（没人能领取）；退出
            DB::commit();
            return ['code'=> '1000','msg'=>'发放成功'];
        }
        // if($res['send_type'] == 1) {   //无数量限制
            //获取领取的用户类型
            switch($res['send_user_type']) {
                case 1:
                    //所有人
                   
                    $insert_num = 0;
                    if($res['send_type'] == 2){   //有数量限制，进行随机发放
                        $send_num = $res['send_num'];  //发放的数量
                        $user_id = DB::table('user')
                        ->inRandomOrder()
                        ->take($send_num)
                        ->pluck('id');
                        if(!count($user_id)){  //极端情况，没有用户，发放成功，直接退出
                            DB::commit();
                            return ['code'=> '1000','msg'=>'1发放成功'];
                        }
                    }else{
                        $user_id = DB::table('user') -> pluck('id');
                        if(!count($user_id)){  //极端情况，没有用户，发放成功，直接退出
                            DB::commit();
                            return ['code'=> '1000','msg'=>'2发放成功'];
                        }
                    }
                    for($i=0;$i<count($user_id);$i++) {
                        $user['user_id'] = $user_id[$i];
                        $insert_num += DB::table('user_you') -> insert($user);
                    }
                    
                    if($insert_num != count($user_id)) {
                        DB::rollBack();
                        return ['code'=> '1002','msg'=>'发放失败'];
                    }

                    if(DB::table('admin_you') -> where('id',$is) -> update(['use_num' => $insert_num])){   //领取数量
                        DB::commit();
                        return ['code'=> '1000','msg'=>'3发放成功'];
                    }
                break;

                case 2:
                  //指定类型人
                  $user_type = explode(',',$res['send_user']);
                //   return $user_type;
                  $send_type = '';
                  $is_vip = 0;
                  $id_arr = [];
                  $handle = DB::table('user');
                  for($i=0;$i<count($user_type);$i++) {   //目前只有会员 非会员  新用户   所以是3
                    if($user_type[$i] == 1){
                       $handle -> where('level','!=',0);
                       $is_vip = 1;
                    }else if($user_type[$i] == 2) {
                       $handle -> orwhere('level',0);
                       $is_vip = 2;
                    }else{
                        $send_type = 'newUser';
                    }
                 }
                if($res['send_type'] == 2){   //有数量限制，进行随机发放
                    $send_num = $res['send_num'];  //发放的数量
                    if($is_vip){
                        $id_arr = $handle
                        ->inRandomOrder()
                        ->take($send_num)
                        ->pluck('id');
                    }
                    if(!count($id_arr)){  //极端情况，没有用户，发放成功，直接退出
                        //判断是否值发给新用户
                        if($send_type == 'newUser'){
                            //给改admin_you加标记
                            $if = DB::table('admin_you') -> where('id',$is) -> update(['newUser' => 1]);
                            if($if){
                                DB::commit();
                                return ['code'=> '1000','msg'=>'7发放成功'];
                            }else{
                                DB::rollBack();
                                return ['code'=> '1002','msg'=>'发放失败'];
                            }
                        }
                        DB::commit();
                        return ['code'=> '1000','msg'=>'4发放成功'];
                    }
                }else{   //无数量限制
                    if($is_vip){
                        $id_arr = $handle -> pluck('id');
                      }
                    if(!count($id_arr)){  //极端情况，没有用户，发放成功，直接退出
                        //判断是否值发给新用户
                        if($send_type == 'newUser'){
                            //给改admin_you加标记
                            $if = DB::table('admin_you') -> where('id',$is) -> update(['newUser' => 1]);
                            if($if){
                                DB::commit();
                                return ['code'=> '1000','msg'=>'7发放成功'];
                            }else{
                                DB::rollBack();
                                return ['code'=> '1002','msg'=>'发放失败'];
                            }
                        }
                        DB::commit();
                        return ['code'=> '1000','msg'=>'5发放成功'];
                    }
                }
                  $insert_num = 0;
                  for($i=0;$i<count($id_arr);$i++) {
                    $user['user_id'] = $id_arr[$i];
                    $insert_num += DB::table('user_you') -> insert($user);
                  }
                  if($insert_num != count($id_arr)) {
                        DB::rollBack();
                        return ['code'=> '1002','msg'=>'发放失败'];
                    }
                if($insert_num == 0){
                    if($send_type == 'newUser') {
                        //给改admin_you加标记
                        $if = DB::table('admin_you') -> where('id',$is) -> update(['newUser' => 1]);
                        if($if){
                            DB::commit();
                            return ['code'=> '1000','msg'=>'6发放成功'];
                        }else{
                            DB::rollBack();
                            return ['code'=> '1002','msg'=>'发放失败'];
                        }
                    }
                }else{
                    if(DB::table('admin_you') -> where('id',$is) -> update(['use_num' => $insert_num])){   //领取数量
                        //判断是否发放新用户
                            if($send_type == 'newUser') {
                                //给改admin_you加标记
                                $if = DB::table('admin_you') -> where('id',$is) -> update(['newUser' => 1]);
                                if($if){
                                    DB::commit();
                                    return ['code'=> '1000','msg'=>'7发放成功'];
                                }else{
                                    DB::rollBack();
                                    return ['code'=> '1002','msg'=>'发放失败'];
                                }
                            }else{
                                DB::commit();
                                return ['code'=> '1000','msg'=>'8发放成功'];
                            }
                        }
                }
                  break;
                case 3:
                //指定用户
                    $user_type = explode(',',$res['send_user']);
                    if($user_type) {
                        $insert_num = 0;
                        for($i=0;$i<count($user_type);$i++) {
                            $user['user_id'] = $user_type[$i];
                            $insert_num += DB::table('user_you') -> insert($user);
                        }
                        if($insert_num != count($user_type)) {
                            DB::rollBack();
                            return ['code'=> '1002','msg'=>'发放失败'];
                        }
                        if(DB::table('admin_you') -> where('id',$is) -> update(['use_num' => $insert_num])){   //领取数量
                            DB::commit();
                            return ['code'=> '1000','msg'=>'9发放成功'];
                        }
                    }else{
                        DB::commit();
                        return ['code'=> '1000','msg'=>'00发放成功'];
                    }
                  break;
            }
        // }else{
        //     //有数量限制

        // }
    }
}
