<?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\AisConfig;
use app\ais\model\AisOrder;
use app\ais\model\AisStoreGroup;
use app\ais\model\AisStore;
use app\ais\model\AisStoreUnion;
use think\Db;
use think\facade\Request;
use think\helper\Time;

class Group extends Common{

    /**
     * 列表
     */
    public function index(){
        $view['lists']    = AisStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id])->order('id desc')->paginate(20);
        $view['pathMaps'] = [['name'=>'商圏管理','url'=> url("group/index")]];
        return $this->fetch()->assign($view);
    }

    /**
     * 已绑定商圏列表
     */
    public function store(int $id){
        $view['quan_id']  = $id;
        $view['lists']    = AisStore::where($this->mini_program)->whereIn('id',AisStoreUnion::where($this->mini_program)->where(['group_id' => $id])->column('store_id'))->order('id desc')->paginate(20);
        $view['pathMaps'] = [['name'=>'商圏管理','url'=> url("group/index")],['name'=>'商圈商户','url'=> url("group/storeindex",['id' => $id])]];
        return $this->fetch()->assign($view);
    }

    /**
     * 商圏列表
     */
    public function selectStore(int $quan_id){
        $condition   = [];
        $condition[] = ['member_miniapp_id', '=', $this->member_miniapp_id];
        if(request()->isAjax()){
            $ids     = $this->request->param('ids');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要入住商圏的好店']);
            }
            $list = AisStore::where($condition)->whereIn('id',$ids)->whereNotIn('id',AisStoreUnion::where($this->mini_program)->where(['group_id'=>$quan_id,'type' => 0])->whereIn('store_id',$ids)->column('store_id'))->select();
            foreach ($list as $info){
                $config = AisConfig::getConfig($this->member_miniapp_id);
                $member = AisStoreUnion::where(['member_miniapp_id' => $this->member_miniapp_id,'group_id' => $quan_id,'type' => 0])->select();
                if(!empty($config->group_member) && count($member) >=$config->group_member){
                    return enjson(403,'商圈只能有'.$config->group_member.'个成员');
                }
                $size = AisStoreUnion::where(['member_miniapp_id' => $this->member_miniapp_id,'store_id' => $info->id,'type' => 0])->select();
                if(!empty($config->group_join) && count($size) >=$config->group_join){
                    return enjson(403,'只能加入'.$config->group_join.'个商圈');
                }
                $union = AisStoreUnion::where(['member_miniapp_id'=>$this->member_miniapp_id,'store_id' => $info->id,'group_id' => $quan_id,'type' => 1])->find();
                if($union){
                    $union->delete();
                }
                AisStoreUnion::create(['member_miniapp_id'=>$this->member_miniapp_id,'store_id' => $info->id,'group_id' => $quan_id,'type' => 0,'create_time' => time(),'update_time' => time()]);
            }
            return json(['code'=>200,'msg'=>'好店入住商圏成功','data' =>[]]);
        }else{
            $keyword  = $this->request->param('keyword');
            if(!empty($keyword)) {
                $condition[] = ['name', 'like', '%' . $keyword . '%'];
            }
            $view['lists']   = AisStore::where($condition)->whereNotIn('id',AisStoreUnion::where($this->mini_program)->where(['group_id'=>$quan_id,'type' => 0])->column('store_id'))->order('id desc')->paginate(20);
            $view['keyword'] = $keyword;
            $view['quan_id'] = $quan_id;
            return $this->fetch()->assign($view);
        }
    }

    //编辑
    public function edit(){
        if(request()->isAjax()){
            $param = [
                'id'      => $this->request->param('id/d', 0),
                'title'   => $this->request->param('title/s'),
                'face'    => $this->request->param('face/s'),
                'content' => $this->request->param('content/s'),
                'uid'     => $this->request->param('uid/d'),
            ];
            $validate = $this->validate($param,'Group.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result =  AisStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id,'id' =>  $param['id']])->find();
            if($result){
                $result->title   = $param['title'];
                $result->content = $param['content'];
                $result->uid     = $param['uid'];
                $result->face    = $param['face'];
                $result->save();
            }else{
                $info =  AisStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id,'uid' =>  $param['uid']])->find();
                if($info){
                    return json(['code'=>403,'msg'=>'只能管理一个商圈']);
                }
                $param['member_miniapp_id'] = $this->member_miniapp_id;
                AisStoreGroup::create($param);
            }
            return json(['code'=>200,'url'=>url('group/index'),'msg'=>'操作成功']);
        }else{
            $view['info']= AisStoreGroup::where(['id' => $this->request->param('id/d',0),'member_miniapp_id' => $this->member_miniapp_id])->find();
            return $this->fetch()->assign($view);
        }
    }

    //删除商圈
    public function delete(int $id){
        $store = AisStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id])->whereIn('id',AisStoreUnion::where($this->mini_program)->where(['group_id' => $id,'type' => 0])->column('group_id'))->find();
        if($store){
            return json(['code'=>403,'msg'=>'删除失败,商圏中还包含店铺']);
        }
        $result = AisStoreGroup::destroy($id);
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

    //从商圏中删除好店
    public function deleteStore(int $id,$quan_id){
        $result = AisStoreUnion::destroy(['store_id' => $id,'group_id' => $quan_id]);
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }
        return json(['code'=>403,'msg'=>'删除失败']);
    }

    /**
     * 商圏用户订单
     * @access public
     */
    public function order(int $state = 1,int $group_id){
        $condition   = [];
        $condition[] = ['member_miniapp_id', '=',$this->member_miniapp_id];
        $condition[] = ['group_id', '=', $group_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[] = ['paid_time','>=',$start];
            $condition[] = ['paid_time','<=',$end];
        }
        $starttime = Request::param('starttime/s');
        if($starttime){
            $condition[] = ['paid_time','>=',strtotime($starttime)];
        }
        $endtime   = Request::param('endtime/s');
        if($endtime){
            $condition[] = ['paid_time','<=',strtotime($endtime)];
        }
        $view['orders']          = AisOrder::where(['state' => $state ? 1 : 0])->whereIn('store_id',AisStoreUnion::where($condition)->column('store_id'))->order('id desc')->paginate(20, false, ['query' => ['time' => $time, 'starttime' => $starttime, 'endtime' => $endtime, 'group_id' => $group_id]]);
        $view['order_num']       = AisOrder::where(['state' => 1])->whereIn('store_id',AisStoreUnion::where($condition)->column('store_id'))->count();
        $view['user_amount']     = AisOrder::where(['state' => 1])->whereIn('store_id',AisStoreUnion::where($condition)->column('store_id'))->sum('amount');
        $view['order_amount']    = AisOrder::where(['state' => 1])->whereIn('store_id',AisStoreUnion::where($condition)->column('store_id'))->sum('price');
        $view['coupon_price']    = money($view['user_amount'] - $view['order_amount']);
        $view['time']            = $time;
        $view['starttime']       = $starttime;
        $view['endtime']         = $endtime;
        $view['group_id']        = $group_id;
        return view()->assign($view);
    }
}