<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 赠品管理
 */
namespace app\allwin\controller;
use app\allwin\model\Card as CardModel;
use app\allwin\model\CardUser;
use app\allwin\model\CardUserOrder;
use app\allwin\model\AllwinStore;
use app\allwin\model\Coupon;
use think\facade\Request;
use think\helper\Time;

class Card extends Common{

    public function initialize(){
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'商家储值','url'=>url("card/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $types = 0){
        $condition   = [];
        $condition[] = ['member_miniapp_id','=',$this->member_miniapp_id];
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        $view['card_num']         = CardModel::where($condition)->count();
        $view['card_amount']      = CardModel::where($condition)->sum('price');
        $view['carduser_num']     = CardUser::where($condition)->count();
        $view['carduser_amount']  = CardUserOrder::where($condition)->where(['state' => 1])->sum('amount');
        $keyword = Request::param('keyword');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        $condition[] = ['is_lock','=',$types ? 1 : 0];
        $view['lists']      = CardModel::where($condition)->order('update_time desc')->paginate(10);
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['keyword']    = $keyword;
        return view()->assign($view);
    }

    //添加
    public function add(){
        if(request()->isAjax()){
            $data = [
                'store_id'          => Request::param('store_id/d'),
                'coupon_id'         => Request::param('coupon_id/d'),
                'name'              => Request::param('name/s'),
                'price'             => Request::param('price/f'),
                'coupon_num'        => Request::param('coupon_num/d',2),
                'tips'              => Request::param('tips/s'),
                'relation_l1'       => Request::param('relation_l1/d'),
                'relation_l2'       => Request::param('relation_l2/d'),
                'member_miniapp_id' => $this->member_miniapp_id,
            ];
            $data['locktime'] = empty($data['locktime']) ? 0 : strtotime($data['locktime']);
            $validate = $this->validate($data,'Card.apicreate');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $store = AllwinStore::where(['id' => $data['store_id']])->find();
            if(empty($store)){
                return enjson(0,'好店不存在');
            }
            $data['create_time'] = time();
            $data['update_time'] = time();
            $result = CardModel::create($data); 
            if($result){
                return enjson(200,'成功',['url'=>url('allwin/card/index')]);
            }else{
                return enjson(0,'操作失败');
            }
        }else{
            return view();
        }
    }   

    //编辑
    public function edit(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'id'                => Request::param('id/d'),
                'store_id'          => Request::param('store_id/d'),
                'coupon_id'         => Request::param('coupon_id/d'),
                'name'              => Request::param('name/s'),
                'price'             => Request::param('price/f'),
                'coupon_num'        => Request::param('coupon_num/d',2),
                'tips'              => Request::param('tips/s'),
                'relation_l1'       => Request::param('relation_l1/d'),
                'relation_l2'       => Request::param('relation_l2/d'),
            ];
            $validate = $this->validate($data,'Card.apiedit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $store = AllwinStore::where(['id' => $data['store_id']])->find();
            if(empty($store)){
                return enjson(0,'好店不存在');
            }
            $data['update_time'] = time();
            $result = CardModel::update($data);
            if($result){
                return enjson(200,'成功',['url'=>url('allwin/card/index')]);
            }else{
                return enjson(0,'操作失败');
            }
        }else{
            $id = $this->request->param('id/d');
            $view['info'] = CardModel::where($this->mini_program)->where(['id' => $id])->find();
            if(empty($view['info'])){
                $this->error('内容不存在');
            }
            return view()->assign($view);
        }
    }

    //删除
    public function delete(){
        $id = $this->request->param('id/d');
        $count = CardUser::where($this->mini_program)->where(['card_id' => $id])->count();
        if($count){
            return json(['code'=>403,'msg'=>'已有用户开通,禁止删除,建议锁定.']);
        }else{
            CardModel::where($this->mini_program)->where(['id' => $id])->delete();
            return json(['code'=>200,'msg'=>'操作成功']); 
        } 
    }


     /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = CardModel::isLock($id, $this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 

    /**
     * 已开通商家的会员卡用户
     * @param integer $id  赠品ID
     * @param integer $uid 用户ID
     * @return void
     */
    public function user(){
        $condition   = [];
        $condition[] = ['member_miniapp_id','=',$this->member_miniapp_id];
        $store_id  = Request::param('store_id/d', 0);
        $time      = Request::param('time/d', 0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        $view['pathMaps'] = [['name' => '储值用户', 'url' => url("card/user")]];
        if (!empty($store_id)) {
            $condition[] = ['store_id', '=', $store_id];
        };
        $view['carduser_num']    = CardUser::where($condition)->count();
        $view['carduser_amount'] = CardUserOrder::where($condition)->where(['state' => 1])->sum('amount');
        $view['lists']           = CardUser::where($this->mini_program)->order('id asc')->paginate(20);
        $view['time']            = $time;
        $view['starttime']       = $starttime;
        $view['endtime']         = $endtime;
        $view['store_id']        = $store_id;
        return $this->fetch()->assign($view);
    }

    /**
     * 删除某个用户的会员卡
     * @return void
     */
    public function deleteUser(int $id){
        $result = CardUser::where($this->mini_program)->where(['id' => $id])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        }
    }

   /**
     * 选择好店
     */
    public function selectStore(){
        $condition  = [];
        $condition[] = ['is_lock','=',0];
        $keyword  = $this->request->param('keyword');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        $view['input']     = $this->request->param('input','store_id');
        $view['lists']     = AllwinStore::where($this->mini_program)->where($condition)->order('sort desc,id desc')->paginate(20,false,['query' => ['input' => $view['input'],'keyword'=>$keyword]]);
        $view['keyword']   = $keyword;
        return view()->assign($view);   
    }

    /**
     * 选择专属赠品（用户领取赠品主送）
     */
    public function selectConpon(int $store_id){
        $condition = [];
        $keyword = $this->request->param('keyword');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        $condition[] = ['member_miniapp_id','=',$this->member_miniapp_id];
        $condition[] = ['store_id','=',$store_id];
        $condition[] = ['is_platform','=',1];
        $condition[] = ['is_lock','=',0];
        $condition[] = ['is_check','=',0];
        $condition[] = ['is_shop','=',0];
        $condition[] = ['is_vip','=',0];
        $view['input']   = $this->request->param('input/s');
        $view['store_id']= $store_id;
        $view['lists']   = Coupon::where($condition)->order('sort desc,id desc')->paginate(20,false,['query' => ['input' => $view['input'],'store_id'=>$store_id,'keyword'=>$keyword]]);
        $view['keyword'] = $keyword;
        return view()->assign($view);
    }
    
    /**
     * 选择赠品
     */
    public function coupon(int $id){
        $condition = [];
        $vip = CardModel::where(['id' => $id])->where($condition)->field('coupon_ids')->find();
        if(empty($vip)){
            $this->error('没有找到对应会员类型');
        }
        $view['lists']  = Coupon::where($this->mini_program)->whereIn('id',$vip->coupon_ids)->order('sort desc,id desc')->paginate(20,false,['query' => ['id' => $id]]);
        $view['card_id'] = $id;
        return view()->assign($view);
    }

    /**
     * 弹出选择优惠券
     */
    public function winCoupon(int $card_id){
        if(request()->isAjax()){
            $ids = $this->request->param('ids');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的赠品']);
            }
            $result = CardModel::editCoupon($card_id,(array)ids($ids,true));
            if($result){
                return json(['code'=>302,'msg'=>'关联赠品成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'关联赠品失败']);
            }
        }else{
            $coupon     = CardModel::where($this->mini_program)->where(['id' => $card_id])->field('coupon_ids')->find();
            $condition  = [];
            if(!empty($coupon->coupon_ids)){
                $coupon_ids  = explode(',',$coupon->coupon_ids);
                $condition[] = ['id','notIn',$coupon_ids];
            }
            $keyword = $this->request->param('keyword');
            if(!empty($keyword)){
                $condition[] = ['name','like','%'.$keyword.'%'];
            }
            $condition[] = ['is_platform','=',0];
            $view['lists']   = Coupon::where($this->mini_program)->where($condition)->order('size desc,id desc')->paginate(20,false,['query' => ['card_id' => $card_id,'keyword'=>$keyword]]); 
            $view['card_id'] = $card_id;
            $view['keyword'] = $keyword;
            return view()->assign($view);
        }
    }

    //删除
    public function delCoupon(){
        $card_id   = $this->request->param('card_id/d');
        $coupon_id = $this->request->param('coupon_id/d');
        $info   = CardModel::where(['id' => $card_id])->find();
        if($info){
            $coupon_ids = ids(array_values_unset($coupon_id,explode(',',$info->coupon_ids)));
            $result = CardModel::where($this->mini_program)->where(['id' => $card_id])->update(['coupon_ids' => $coupon_ids]);
            if($result){
                return json(['code' =>200,'msg'=>'操作成功']);
            }
        }
        return json(['code' => 0,'msg'=>'操作失败']);
    }
}