<?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\Manage;
use app\allwin\controller\Common;
use app\allwin\model\AllwinStore;
use app\allwin\model\AllwinGift;
use app\allwin\model\AllwinGiftData;
use app\allwin\model\AllwinGiftStore;
use think\facade\Request;
use think\helper\Time;

class Gift extends Common
{
    public function initialize()
    {
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'支付有礼','url' => url('manage.gift/index')]]);
    }


    /**
     * 列表
     */
    public function index(){
        $condition = [];
        $condition['member_miniapp_id'] = $this->member_miniapp_id;
        $view['lists'] = AllwinGift::where($condition)->order('id desc')->paginate(20); 
        return view()->assign($view);
    }

    /**
     * 活动预览
     */
    public function review(int $id){
        $condition = [];
        $view['info'] = AllwinGift::where($this->mini_program)->where(['id' => $id])->where($condition)->find();
        if(!$view['info']){
            $this->error("404 NOT FOUND");
        }
        $view['pay_num']    = AllwinGiftData::where(['gift_id' => $id])->where($condition)->sum('pay_num'); 
        $view['pay_amount'] = AllwinGiftData::where(['gift_id' => $id])->where($condition)->sum('pay_amount'); 
        $view['gite_num']   = AllwinGiftData::where(['gift_id' => $id])->where($condition)->count(); 
        $view['coupon_num'] = AllwinGiftData::where(['gift_id' => $id])->where($condition)->where('coupon_id','>',0)->count(); 
        $view['take_num']   = AllwinGiftData::where(['gift_id' => $id])->where($condition)->where(['is_take' => 1])->count(); 
        $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[] = ['update_time','>=',$start];
            $condition[] = ['update_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['update_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['update_time','<=',strtotime($endtime)];
            }
        }
        $types =Request::param('types/d',2);
        switch ($types) {
            case 1:
                $condition[] = ['coupon_id','=',0];
                break;
            case 2:
                $condition[] = ['coupon_id','>',0];
                break;
            case 3:
                $condition[] = ['coupon_id','>',0];
                $condition[] = ['is_take','=',0];
                break;
            case 4:
                $condition[] = ['coupon_id','>',0];
                $condition[] = ['is_take','=',1];
                break;
        }
        $view['list']       = AllwinGiftData::where(['gift_id' => $id])->where($condition)->order('id desc')->paginate(20); 
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['id']         = $id;
        return view()->assign($view);
    }

    /**
     * 添加
     */
    public function add(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'types'             => Request::param('types/d',0),
                'pay_num'           => Request::param('pay_num/d',0),
                'pay_amount'        => Request::param('pay_amount/f',0),
                'coupon_id'         => Request::param('coupon_id/d',0),
                'title'             => Request::param('title/s'),
                'share_img'         => Request::param('share_img/s'),
                'share_title'       => Request::param('share_title/s'),
                'share_text'        => Request::param('share_text/s'),
                'note'              => Request::param('note/s'),
                'start_time'        => Request::param('start_time/s'),
                'end_time'          => Request::param('end_time/s'),
            ];
            $validate = $this->validate($data,'Gift.add');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = AllwinGift::edit($data);
            if($result){
                return json(['code'=>200,'url'=>url('manage.gift/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            return view();
        }
    }


    //编辑
    public function edit(){
        if(request()->isAjax()){
            $data = [
                'id'                => Request::param('id/d'),
                'member_miniapp_id' => $this->member_miniapp_id,
                'types'             => Request::param('types/d',0),
                'pay_num'           => Request::param('pay_num/d',0),
                'pay_amount'        => Request::param('pay_amount/f',0),
                'coupon_id'         => Request::param('coupon_id/d',0),
                'title'             => Request::param('title/s'),
                'share_img'         => Request::param('share_img/s'),
                'share_title'       => Request::param('share_title/s'),
                'share_text'        => Request::param('share_text/s'),
                'note'              => Request::param('note/s'),
                'start_time'        => Request::param('start_time/s'),
                'end_time'          => Request::param('end_time/s'),
            ];
            $validate = $this->validate($data,'Gift.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = AllwinGift::edit($data);
            if($result){
                return json(['code'=>200,'url'=>url('manage.gift/index'),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $condition = [];
            $condition['id']                = Request::param('id');
            $condition['member_miniapp_id'] = $this->member_miniapp_id;
            $view['info'] = AllwinGift::where($condition)->find();
            if(!$view['info']){
                $this->error("404 NOT FOUND");
            }
            return view()->assign($view);
        }
    }

    //删除
    public function delete(int $id){
        $condition = [];
        $result = AllwinGiftAllwinStore::where($this->mini_program)->where($condition)->where(['store_id' => $id])->find();
        if($result){
            return json(['code'=>0,'msg'=>'禁止删除,请先删除关联商家']);
        }else{
            AllwinGift::where($this->mini_program)->where($condition)->where(['id' => $id])->delete();
            return json(['code'=>200,'msg'=>'操作成功']);
        } 
    }
    /**
     * 是否锁定和解锁活动
     * @param integer $id
     * @return json
     */
    public function isLock(int $id){
        $info = AllwinGift::where($this->mini_program)->where(['id' => $id])->find();
        if(!$info){
            return json(['code'=>0,'msg'=>'未找到活动']);
        }
        if($info->is_lock){
            $store_id = AllwinGiftAllwinStore::where($this->mini_program)->where(['gift_id' => $id,'is_lock' => 1])->column('store_id');
            $is_store = AllwinGiftAllwinStore::where($this->mini_program)->where(['is_lock' => 0,'store_id' => $store_id])->count();
            if($is_store){
                return json(['code'=>0,'msg'=>'禁止启用,请先删除其它活动中相同的好店']);
            }
        }
        $is_lock = $info->is_lock ? 0 : 1;
        $result = AllwinGift::where($this->mini_program)->where(['id' => $id])->update(['is_lock' => $is_lock]);
        if($result){
            AllwinGiftAllwinStore::where($this->mini_program)->where(['gift_id' => $id])->update(['is_lock' => $is_lock]);
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>0,'msg'=>'操作失败']);
        }
    }
    
    /**
     * 好店列表
     */
    public function store(int $id){
        $condition = [];
        $condition['id']                = $id;
        $condition['member_miniapp_id'] = $this->member_miniapp_id;
        $info = AllwinGift::where($condition)->find();
        if(!$info){
            $this->error("404 NOT FOUND");
        }
        $view['info']  = $info;
        $view['store'] = AllwinGiftAllwinStore::where(['gift_id' => $info->id])->order('id desc')->paginate(20,false,['query' => ['id' => $id]]); 
        return view()->assign($view);
    }
    
    /**
     * 选择并添加活动好店
     */
    public function selectStore(int $id){
        if(request()->isAjax()){
            $ids = input('post.ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的商家']);
            }
            $gift = AllwinGift::where($this->mini_program)->where(['id' => $id])->find();
            if(empty($gift)){
                return json(['code'=>0,'msg'=>'未找到活动']);
            }
            $ids = (array)ids($ids,true);
            $condition = [];
            $condition['is_lock']  = 0;
            $condition['store_id'] = $ids;
            $store_id = AllwinGiftAllwinStore::where($this->mini_program)->where($condition)->column('store_id');
            if(!empty($store_id)){
                return json(['code'=>0,'msg'=>'同一个好店禁止在多个活动中']);
            }
            $data = [];
            foreach ($ids as $key => $value) {
                $data[$key]['member_miniapp_id'] = $gift->member_miniapp_id;
                $data[$key]['gift_id']           = $gift->id;
                $data[$key]['store_id']          = $value;
            }
            AllwinGiftAllwinStore::insertAll($data);
            return json(['code'=>200,'msg'=>'操作成功','data' =>[]]);
        }else{
            $condition = [];
            $condition[] = ['is_lock','=',0];
            $store_id = AllwinGiftAllwinStore::where($this->mini_program)->where($condition)->column('store_id');
            $keyword  = Request::param('keyword','');
            if(!empty($keyword)){
                $condition[] = ['name','like','%'.$keyword.'%'];
            }
            $view['lists']     = AllwinStore::where($this->mini_program)->where($condition)->whereNotIn('id',$store_id)->order('is_top desc,sort desc,id desc')->paginate(20);
            $view['keyword']   = $keyword;
            $view['id']        = $id;
            return view()->assign($view);   
        }
    }
    
    //删除好店
    public function storeDelete(int $id){
        $result = AllwinGiftAllwinStore::where($this->mini_program)->where(['id' => $id])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>0,'msg'=>'删除失败']);
        } 
    }    
}