<?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\smartbc\controller;
use app\smartbc\model\SmartbcConfig;
use app\smartbc\model\SmartbcCoupon;
use app\smartbc\model\SmartbcCouponUser;
use app\smartbc\model\SmartbcCard;
use app\common\facade\Inform;
use think\facade\Request;
use think\helper\Time;
use app\smartbc\model\SmartbcStore;

class Coupon extends Common{

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'优惠券管理','url'=>url("coupon/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $types = 0,int $page = 0){
        $condition = [];
        $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)];
            }
        }
        $store_id   = Request::param('store_id/d');
        $store_name = Request::param('store_name');
        if($store_id){
            $condition[] = ['store_id','=',$store_id];
        }
        $keyword = Request::param('keyword');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        //统计
        $view['coupon_count']          = SmartbcCoupon::where($this->mini_program)->where($condition)->where(['is_end' => 0,'is_lock' => 0])->count();
        $view['coupon_end_count']      = SmartbcCoupon::where($this->mini_program)->where($condition)->where(['is_end' => 1])->count();
        $view['coupon_user_count']     = SmartbcCouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 0])->count();
        $view['coupon_user_end_count'] = SmartbcCouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 1])->count();
        switch ($types) {
            case 1:
                $condition[] = ['is_lock','=',1];
                $condition[] = ['is_end','=',0];
                break;
            case 2:
                $condition[] = ['is_lock','=',0];
                $condition[] = ['is_end','=',0];
                break;
            case 4:
                $condition[] = ['is_end','=',1];
                break;
            default;
                $condition[] = ['is_end','=',0];
                break;
        }
        $view['lists']      = SmartbcCoupon::where($this->mini_program)->where($condition)->order('sort desc,is_lock desc,update_time desc')->paginate(10,false,['query' => ['types' => $types,'store_id' => $store_id,'store_name' => $store_name]]);
        $view['types']      = $types;
        $view['page']       = $page;
        $view['keyword']    = $keyword;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        return view()->assign($view);
    }

    //优惠券预览和统计
    public function review(int $id,int $types = 0){
        $info = SmartbcCoupon::where($this->mini_program)->where(['id' => $id])->find();
        if(empty($info)){
            $this->error('内容不存在');
        }
        $condition = [];
        $condition['is_end']      = $types ?? 0;
        $condition['coupon_id']   = $id;
        $view['lists']            = SmartbcCouponUser::where($this->mini_program)->where($condition)->order('id asc')->paginate(10,false,['query'=>['id' => $id,'types' => $types]]);
        $view['types']            = $types;
        $view['coupon_count']     = SmartbcCouponUser::where($this->mini_program)->where(['coupon_id' => $id])->count();
        $view['coupon_end_count'] = SmartbcCouponUser::where($this->mini_program)->where(['coupon_id' => $id,'is_end' => 1])->count();
        $view['info']             = $info;
        $config = SmartbcConfig::getConfig($this->member_miniapp_id);
        $view['end_time']         = $config->end_time * 60 * 60;
        return view()->assign($view);
    }

    //编辑
    public function edit(){
        $id   = Request::param('id/d');
        if(request()->isAjax()){
            $data = [
                'id'         => Request::param('id/d'),
                'name'       => Request::param('name/s'),
                'price'      => Request::param('price/f'),
                'discount'   => Request::param('discount/d',0),
                'howmuch'    => Request::param('howmuch/d',0),
                'tips'       => Request::param('tips/s'),
                'types'      => Request::param('types/d',0),
            ];
            $validate = $this->validate($data,'Coupon.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            if($data['types'] == 0){
                $data['discount']  = 0;
            }else{
                $data['price'] = 0;
            }
            if($id){
                $data['id'] = $id;
                $result = SmartbcCoupon::where($this->mini_program)->where(['id' => $data['id']])->update($data);
            }else{
                $store_id = Request::param('store_id/d',0);
                $store = SmartbcStore::where(['id' => $store_id])->find();
                if(empty($store)){
                    return json(['code'=>0,'msg'=>'商家必须选择']);
                }
                $data['member_miniapp_id'] = $this->member_miniapp_id;
                $data['create_time']       = time();
                $data['update_time']       = time();
                $data['store_id']          = $store_id;
                $data['cate_id']           = $store->cate_id;
                $data['cate_sid']          = $store->cate_sid;
                $data['is_top']            = 0;
                $result                    = SmartbcCoupon::create($data);
            }
            if($result){
                return json(['code'=>200,'url'=>url('coupon/index',['page' => input('get.page/d')]),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $info = SmartbcCoupon::where($this->mini_program)->where(['id' => $id])->find();
            $view['info'] = $info;
            $view['page'] = input('get.page/d');
            return view()->assign($view);
        }
    }

    //删除
    public function delete(int $id){
        $result = SmartbcCoupon::where($this->mini_program)->where(['id' => $id])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

    /**
     * 排序
     */
    public function sort(){
        if(request()->isAjax()){
            $data = [
                'sort' => input('post.sort/d'),
                'id'   => input('post.id/d'),
            ];
            $validate = $this->validate($data,'Coupon.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = SmartbcCoupon::where($this->mini_program)->where(['id' => $data['id']])->update(['sort'=>$data['sort']]);
            if($result){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }
    }
   
    /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $rel = SmartbcCoupon::where(['id' => $id])->field('is_top')->find();
        $rel->is_top = $rel->is_top ? 0 : 1;
        $rel->save();
        return json(['code'=>200,'msg'=>'操作成功']);
    } 

     /**
     * 审核和取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = SmartbcCoupon::where(['id' => $id])->field('is_lock,store_id')->find();
        $result->is_lock = $result->is_lock ? 0 : 1;
        $rel = $result->save();
        if($rel){
            if($result->is_lock == 0){
                $store = SmartbcStore::where('id','=',$result->store_id)->find();
                if($store){
                    Inform::sms($store->manage_uid,$this->member_miniapp_id,['title' =>'业务进展通知','type' => '优惠券申请','content' =>'您的优惠券申请已经通过审核','state' => '成功']);
                }
            }
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>0,'msg'=>'操作失败']);
        }
    } 
   
    /**
     * 用户已领优惠券管理
     *
     * @param integer $id  优惠券ID
     * @param integer $uid 用户ID
     * @return void
     */
    public function user(int $types = 0){
        $condition = [];
        $uid  = Request::param('uid/d');
        if($uid){
            $condition[] = ['uid','=',$uid];
        }
        $store_id   = Request::param('store_id/d');
        $store_name = Request::param('store_name/s');
        if($store_id){
            $condition[] = ['store_id','=',$store_id];
        }
        $time = Request::param('time/d',0);
        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];
        }
        $starttime = Request::param('starttime/s');
        $endtime = Request::param('endtime/s');
        if($starttime){
            $condition[] = ['create_time','>=',strtotime($starttime)];
        }
        if($endtime){
            $condition[] = ['create_time','<=',strtotime($endtime)];
        }
        $view['coupon_count']     = SmartbcCouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 0])->count();
        $view['coupon_end_count'] = SmartbcCouponUser::where($this->mini_program)->where($condition)->where(['is_end' => 1])->count();
        $view['lists']      = SmartbcCouponUser::where($this->mini_program)->where($condition)->where(['is_end'=>$types ? 1 : 0])->order('id desc')->paginate(20,false,['query'=>['uid' => $uid,'types' => $types,'starttime' => $starttime,'endtime' => $endtime,'time'=>$time]]);
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['uid']        = $uid;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['pathMaps']   = [['name'=>'已领优惠券','url'=>url("coupon/user")]];
        $config = SmartbcConfig::getConfig($this->member_miniapp_id);
        $view['end_time']         = $config->end_time * 60 * 60;
        return view()->assign($view);
    }

    /**
     * 查看用户优惠券信息
     * @param integer $id
     * @return void
     */
    public function userCoupon(int $id = 0){
        $view['info'] = SmartbcCouponUser::where($this->mini_program)->where(['id' => $id])->find();
        return view()->assign($view);
    }

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