<?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\ais\controller\store;
use app\ais\controller\Common;
use app\ais\model\AisCard;
use app\ais\model\AisCardUser;
use app\ais\model\AisCardOrder;
use app\ais\model\AisStore;
use app\ais\model\AisCoupon;
use think\facade\Request;
use think\helper\Time;

class Card extends Common{

    public function initialize(){
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'商家储值','url'=>url("store.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)];
            }
        }
        $keyword = Request::param('keyword');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        switch ($types) {
            case 1:
                $condition[] = ['is_lock','=',1];
                $condition[] = ['is_end','=',0];
                break;
            case 2:
                $condition[] = ['is_end','=',1];
                break;
            default:
                $condition[] = ['is_lock','=',0];
                $condition[] = ['is_end','=',0];
                break;
        }
        $view['lists']      = AisCard::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 edit(){
        if(request()->isAjax()){
            $param['id']       = $this->request->param('id/d',0);
            $param['store_id'] = $this->request->param('store_id');
            $param['name']     = $this->request->param('name');
            $param['price']    = $this->request->param('price/f',0);
            $param['amount']   = $this->request->param('amount/d',0);
            $param['howmuch']  = $this->request->param('howmuch/f',0);
            $param['num']      = $this->request->param('num/d');
            $param['locktime'] = $this->request->param('locktime/s');
            $param['tips']     = $this->request->param('tips/s');
            $param['content']  = $this->request->param('content/s');
            $validate = $this->validate($param,$param['id']?'Card.api':'Card.edit');
            if(true !== $validate){
                return enjson(403,$validate);
            }
            $card_rel = [];
            if(!empty($param['id'])){
                $card_rel = AisCard::where(['id' => $param['id']])->find();
            }
            $store_id = empty($card_rel) ? $param['store_id'] : $card_rel->store_id;
            $store   = AisStore::where(['id' => $store_id])->field('id,citycode')->find();
            //优惠券数据
            $coupon['types']             = 3;
            $coupon['is_lock']           = 1;
            $coupon['name']              = $param['name'];
            $coupon['amount']            = $param['amount'];
            $coupon['howmuch']           = $param['howmuch'];
            $coupon['tips']              = $param['tips'];
            $coupon['num']               = $param['num'];
            $coupon['member_miniapp_id'] = $this->member_miniapp_id;
            $coupon['update_time']       = time();
            $coupon['create_time']       = time();
            $coupon['store_id']          = $store_id;
            $coupon['citycode']         = $store->citycode;
            //判断是添加还是修改
            if(empty($card_rel)){
                $coupon_rel = AisCoupon::create($coupon);
                if(!$coupon_rel){
                    return enjson(403,'储值活动创建失败');
                }
                $coupon_id = $coupon_rel->id;
            }else{
                $coupon_id = $card_rel->coupon_id;
                $coupon_rel = AisCoupon::where(['id' => $card_rel->coupon_id])->update($coupon);
                if(!$coupon_rel){
                    return enjson(403,'未找到储值活动');
                }
            }
            //判断是修改储值还是增加
            $card['store_id']          = $store_id;
            $card['member_miniapp_id'] = $this->member_miniapp_id;
            $card['name']              = $param['name'];
            $card['price']             = $param['price'];
            $card['tips']              = $param['content'];
            $card['coupon_id']         = $coupon_id;
            $card['locktime']          = strtotime($param['locktime']);
            $card['update_time']       = time();
            $card['create_time']       = time();
            if(empty($card_rel)){
                $rel = AisCard::create($card);
            }else{
                $rel = AisCard::where(['id' => $card_rel->id])->update($card);
            } 
            if($rel){
                return enjson(200,'储值活动创建成功');
            }
            return enjson(403,'未找到储值活动');
        }else{
            $view['info'] = AisCard::where($this->mini_program)->where(['id' => $this->request->param('id/d')])->find();
            return view()->assign($view);
        }
    }

    //删除
    public function delete(int $id){
        $card =  AisCard::where($this->mini_program)->where(['id' => $id])->find();
        if(empty($card)){
            return enjson(0);
        }
        $card->is_end = 1;
        $card->save();
        AisCoupon::where(['id' => $card->coupon_id])->update(['is_end' => 1]);
        return enjson(200);
    }

     /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = AisCard::isLock($id, $this->member_miniapp_id);
        if($result){
            return enjson(200);
        }
        return enjson(0);
    } 


    /**
     * ######################################################
     * 选择赠品
     */
    public function coupon(int $id){
        $coupon           = AisCard::where($this->mini_program)->where(['id' => $id])->field('coupon_ids')->find();
        $view['lists']   = AisCoupon::where($this->mini_program)->whereIn('id',$coupon->coupon_ids)->order('sort desc,id desc')->select();
        $view['card_id'] = $id;
        return view()->assign($view);
    }

    /**
     * 弹出选择优惠券
     */
    public function selectCoupon(int $card_id){
        if(request()->isAjax()){
            $ids = $this->request->param('ids');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的赠品']);
            }
            $result = AisCard::editCoupon($card_id,(array)ids($ids,true));
            if($result){
                return json(['code'=>302,'msg'=>'关联赠品成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'关联赠品失败']);
            }
        }else{
            $coupon     = AisCard::where($this->mini_program)->where(['id' => $card_id])->field('coupon_ids')->find();
            $condition[] = ['is_end','=',0];
            $condition[] = ['types','<=',2];
            if(!empty($coupon->coupon_ids)){
                $condition[] = ['id','notIn',explode(',',$coupon->coupon_ids)];
            }
            $keyword = $this->request->param('keyword');
            if(!empty($keyword)){
                $condition[] = ['name','like','%'.$keyword.'%'];
            }
            $view['lists']   = AisCoupon::where($this->mini_program)->where($condition)->order('sort 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   = AisCard::where($this->mini_program)->where(['id' => $card_id])->find();
        if($info){
            $info->coupon_ids = ids(array_values_unset($coupon_id,explode(',',$info->coupon_ids)));
            $result = $info->save(); 
            if($result){
                return enjson(200);
            }
        }
        return enjson(0);
    }



    /**
     * 已开通商家的会员卡用户
     * @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']    = AisCardUser::where($condition)->count();
        $view['carduser_amount'] = AisCardOrder::where($condition)->where(['state' => 1])->sum('amount');
        $view['lists']           = AisCardUser::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 = AisCardUser::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']     = AisStore::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);
    }
}