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

class Index extends Common{

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

    /**
     * 列表
     */
    public function index(int $types = 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.'%'];
        }
        switch ($types) {
            case 1:
                $condition[] = ['is_lock','=',1];
                $condition[] = ['is_end','=',0];
                break;
            case 2:
                $condition[] = ['is_end','=',1];
                break;
            default;
                $condition[] = ['is_end','=',0];
                break;
        }
        $view['lists']      = AisCoupon::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['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 = AisCoupon::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']            = AisCouponUser::where($this->mini_program)->where($condition)->order('id asc')->paginate(10,false,['query'=>['id' => $id,'types' => $types]]);
        $view['types']            = $types;
        $view['coupon_count']     = AisCouponUser::where($this->mini_program)->where(['coupon_id' => $id])->count();
        $view['coupon_end_count'] = AisCouponUser::where($this->mini_program)->where(['coupon_id' => $id,'is_end' => 1])->count();
        $view['info']             = $info;
        $config = AisConfig::getConfig($this->member_miniapp_id);
        $view['end_time']         = $config->coupon_longtime * 60 * 60;
        return view()->assign($view);
    }

    //编辑
    public function edit($id = 0){
        if(request()->isAjax()){
            $param = [
                'id'         => $this->request->param('id/d',0),
                'name'       => $this->request->param('name/s'),
                'price'      => $this->request->param('price/d'),
                'types'      => $this->request->param('types/d'),
                'discount'   => $this->request->param('discount/d',0),
                'howmuch'    => $this->request->param('howmuch/d',0),
                'amount'     => $this->request->param('amount/f',0),
                'tips'       => $this->request->param('tips/s'),
                'num'        => $this->request->param('num/d',0),
            ];
            $validate = $this->validate($param,'Coupon.edit');
            if(true !== $validate){
                return enjson(0,$validate);
            }
            $data['name']     = $param['name'];
            $data['price']    = $param['price'];
            $data['tips']     = $param['tips'];
            $data['num']      = $param['num'];
            $data['howmuch']  = $param['howmuch'];
            $data['types']    = $param['types'];;
            $data['price']    = 0;
            $data['amount']   = 0;
            $data['discount'] = 0;
            switch ($param['types'] ) {
                case 1: //折扣券
                    $data['discount'] = $param['discount'];
                    break;
                case 2: //兑换券
                    $data['amount']   = $param['amount'];
                    break;
                default: //代金券
                    $data['price']    = $param['price'];
                    break;
            }
            if($param['id']){
                $result = AisCoupon::where($this->mini_program)->where(['id' => $param['id']])->update($data);
            }else{
                $store_id = $this->request->param('store_id/d',0);
                $store    = AisStore::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['citycode']          = $store->citycode;
                $data['is_top']            = 0;
                $result                    = AisCoupon::create($data);
            }
            if($result){
                return enjson(200);
            }
            return enjson(0);
        }else{
            $view['info'] = AisCoupon::where($this->mini_program)->where(['id' => $id])->find();
            return view()->assign($view);
        }
    }

    //删除
    public function delete(int $id){
        if(AisCoupon::where($this->mini_program)->where(['id' => $id,'types' => 3])->find()){
            return enjson(0,'本券禁止删除');
        }
        $result = AisCoupon::where($this->mini_program)->where(['id' => $id])->delete();
        if($result){
            return enjson(200);
        }
        return enjson(0);
    }

    /**
     * 排序
     */
    public function sort(){
        if(request()->isAjax()){
            $data = [
                'sort' => $this->request->param('sort/d'),
                'id'   => $this->request->param('id/d'),
            ];
            $validate = $this->validate($data,'Category.sort');
            if(true !== $validate){
                return enjson(0,$validate);
            }
            $result = AisCoupon::where($this->mini_program)->where(['id' => $data['id']])->update(['sort'=>$data['sort']]);
            if($result){
                return enjson(200);
            }
            return enjson(0);
        }
    }
   
    /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $result = AisCoupon::where(['id' => $id])->where('types','<','3')->field('is_top')->find();
        if(empty($result)){
            return enjson(0,'本券禁止操作');
        }
        $result->is_top = $result->is_top ? 0 : 1;
        $rel = $result->save();
        if($rel){
            return enjson(200);
        }
        return enjson(0);
    } 

     /**
     * 审核和取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = AisCoupon::where(['id' => $id])->where('types','<','3')->field('is_lock,store_id')->find();
        if(empty($result)){
            return enjson(0,'本券禁止操作');
        }
        $result->is_lock = $result->is_lock ? 0 : 1;
        $rel = $result->save();
        if($rel){
            return enjson(200);
        }
        return enjson(0);
    } 


    /**
     * 优惠券选项
     */
    public function select(){
        $view['input']       = $this->request->param('input/s');
        $view['store_id']    = $this->request->param('store_id/d',0);
        $view['keyword']     = $this->request->param('keyword');
        $view['types']       = $this->request->param('types/d',0);
        $view['is_lock']     = $this->request->param('is_lock/d',0);
        $condition   = [];
        $condition[] = ['is_lock', '=',0];
        if($view['types']){
            $condition[] = ['types','=',$view['types']];
        }else{
            $condition[] = ['types','<=',1];
        }
        if($view['store_id']){
            $condition[] = ['store_id','=',$view['store_id']];
        }
        $view['lists'] = AisCoupon::where($this->mini_program)->withSearch(['name'],['name' => $view['keyword']])->where($condition)->order('is_top desc,sort desc,is_lock desc,update_time desc')->paginate(10,false,['query' => ['keyword' => $view['keyword'],'store_id' => $view['store_id'],'input' => $view['input']]]);
        return view()->assign($view);
    }
}