<?php
namespace app\smartbc\controller\api\v1;
use app\smartbc\controller\api\Base;
use app\smartbc\model\SmartbcConfig;
use app\smartbc\model\SmartbcCouponUser;
use app\smartbc\model\SmartbcStore;
use app\smartbc\model\SmartbcStoreBill;
use app\smartbc\model\SmartbcStoreGroup;
use app\smartbc\model\SmartbcStoreUnion;
use filter\Filter;
use think\Db;

class Group extends Base{

   
    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }
    /**
     * 我的商圈
     * @return void
     */
    public function index(){
        $param['store_id']  = $this->request->param('store_id');  //如果有值查询指定商圈列表，如果没有值查询自己已加入商圈和已申请商圈
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],$rel['msg']);
        }
        $store = SmartbcStore::where(['member_miniapp_id' => $this->miniapp_id,'manage_uid' => $this->user->id])->find();
        if(empty($store) && empty($param['store_id'])){
            return enjson(204);
        }
        $flag = [];
        $list = SmartbcStoreGroup::whereIn('id',SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id'=> !empty($store) ? $store->id : $param['store_id'],'type' => 0])->column('group_id'))->select()->toArray();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['red']       = 0;
                $list[$key]['is_manage'] = 0; 
                if($value['uid'] == $this->user->id){
                    $list[$key]['is_manage'] = 1; 
                    $unionList = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $value['id'] ,'type' => 1])->select();
                    if(!$unionList->isEmpty()){
                        $list[$key]['red'] = count($unionList); //如果有值 代表你是圈主,有n个人待审核
                    }
                }
                $list[$key]['num'] = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $value['id'] ,'type' => 0])->count();
                $flag[] = $list[$key]['is_manage'];
            }
        }
        array_multisort($flag, SORT_DESC, $list);
        //申请待通过
        $apply = empty($store) ? [] : SmartbcStoreGroup::whereIn('id',SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id'=> $store->id ?? 0,'type' => 1])->column('group_id'))->select();
        return enjson(200,'success',['list' => $list,'apply' => $apply]);
    }

    //创建和更新商圈
    public function edit(){
        $param['title']     = $this->request->param('title/s');
        $param['content']   = $this->request->param('content/s');
        $param['face']      = $this->request->param('face/s','[]','htmlspecialchars_decode');
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $validate = $this->validate($param,'Group.edit');
        if(true !== $validate){
            return enjson(403,$validate);
        }
        $face  = Filter::filter_escape(json_decode($param['face'],true));
        $store = SmartbcStore::manageStore($this->user->id);
        if (!$store) {
            return enjson(403,'你不是商家,禁止创建商圈');
        }
        $result = SmartbcStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'uid' =>  $this->user->id])->find();
        if($result){
            $days = intval((time()-$result->update_time)/86400);
            if($days < 1){
                return enjson(403,'每天只能修改一次商圈信息');
            }
            $result->title       = $param['title'];
            $result->content     = $param['content'];
            $result->update_time = time();
            if(!empty($face)){
                $result->face = $face[0];
            }
            $result->save();
            return enjson(200,'商圈修改成功');
        }else{
            $data['member_miniapp_id'] = $this->miniapp_id;
            $data['uid']               = $this->user->id;
            $data['title']             = $param['title'];
            $data['content']           = $param['content'];
            if(!empty($face)){
                $data['face'] = $face[0];
            }
            $group = SmartbcStoreGroup::create($data);
            SmartbcStoreUnion::create(['member_miniapp_id' => $this->miniapp_id,'group_id' => $group->id,'store_id' => $store->id,'type' => 0,'create_time' => time(),'update_time' => time()]);
            return enjson(200,'成功创建商圈');
        }
    }
   
    //商圈详情
    public function groupInfo(){
        $param['id']        = $this->request->param('id');    //商圈id
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $info = SmartbcStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id']])->find();
        if (!$info) {
            return enjson(204);
        }
        $info->is_manage = $info->uid == $this->user->id?1:0;
        $info->red = 0;
        $info->num = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $info->id,'type' => 0])->count();
        if($info->is_manage){
            $info->red = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id'=> $info->id,'type' => 1])->count();
        } 
        //买单
        $order = SmartbcStoreBill::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('store_id',SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => 0])->column('store_id'))->sum('money');
        //次数
        $count = SmartbcCouponUser::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('store_id',SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => 0])->column('store_id'))->count();
        //互助
        $help = SmartbcCouponUser::where(['member_miniapp_id' => $this->miniapp_id,'is_end' => 1])->where('','EXP',Db::raw("FIND_IN_SET(".$param['id'].",group_ids)"))->count();
        return enjson(200,['group' => $info,'order' => $order,'count' => $count,'help' => $help]);
    }

    //商圈中的店铺
    public function groupStore(){
        $param['id']   = $this->request->param('id');    //商圈id
        $param['type'] = $this->request->param('type');  //0正常 1待审核 2拒绝 3退出 4踢出
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $list = SmartbcStore::where(['member_miniapp_id' => $this->miniapp_id])->whereIn('id',SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => $param['type']])->column('store_id'))->select();
        if ($list->isEmpty()) {
            return enjson(200);
        }
        return enjson(200,$list);
    }

    //申请加入商圈
    public function groupAdd(){
        $param['id'] = $this->request->param('id');  //商圈id
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $store = SmartbcStore::where(['member_miniapp_id' => $this->miniapp_id,'manage_uid' => $this->user->id])->find();
        if(empty($store)){
            return enjson(403);
        }
        $info = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'store_id' => $store->id,'type' => 0])->find();
        if($info){
            return enjson(403,'您已经加入该商圈');
        }
        $info = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'store_id' => $store->id,'type' => 1])->find();
        if($info){
            return enjson(403,'您已经申请过该商圈');
        }
        $config = SmartbcConfig::getConfig($this->miniapp_id);
        $list = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'type' => 0])->select();
        if(!empty($config->group_member) && count($list) >= $config->group_member){
            return enjson(403,'商圈只能有'.$config->group_member.'个成员');
        }
        $size = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'type' => 0])->select();
        if(!empty($config->group_join) && count($size) >= $config->group_join){
            return enjson(403,'只能加入'.$config->group_join.'个商圈');
        }
        $code = SmartbcStoreUnion::create(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['id'],'store_id' => $store->id,'type' => 1,'create_time' => time(),'update_time' => time()]);
        if ($code) {
            return enjson(200,'已提交申请加入该商圈');
        }
        return enjson(204,'未找到商圈');
    }

    //商圈操作 0同意 2拒绝 3退出 4踢出
    public function groupOperate(){
        $param['group_id']  = $this->request->param('group_id');    //商圈ID
        $param['store_id']  = $this->request->param('store_id',0);  //商店ID
        $param['type']      = $this->request->param('type',1);      //0同意 2拒绝 3退出 4踢出
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        //读取商店信息
        if($param['store_id']){
            $condition['id'] = $param['store_id'];
        }else{
            $condition['manage_uid'] = $this->user->id;
        }
        $store = SmartbcStore::where(['member_miniapp_id' => $this->miniapp_id])->where($condition)->find();
        if(empty($store)){
            return enjson(403,'你不是商家');
        }
        $info = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $param['group_id'],'store_id' => $store->id])->find();
        if(empty($info)){
            return enjson(403,'你不在当前商圈');
        }
        $group = SmartbcStoreGroup::where(['member_miniapp_id' => $this->miniapp_id,'id' => $info->group_id])->find();
        if(!empty($group) && $group->uid == $this->user->id && ($param['type'] == 0 || $param['type'] == 2 || $param['type'] == 4)){
            switch ($param['type']) {
                case 0:
                    //默认通过
                    $info->type = 0;
                    $msg = '已审核通过';
                    //判断权限
                    $config = SmartbcConfig::getConfig($this->miniapp_id);
                    $store_group_num   = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'group_id' => $info->group_id,'type' => 0])->count();
                    if(!empty($config->group_member) && $store_group_num >= $config->group_member){
                        $info->type = 2;
                        $msg = '你的商圈只能有'.$config->group_member.'个成员';
                    }
                    $size = SmartbcStoreUnion::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'type' => 0])->count();
                    if(!empty($config->group_join) && $size >= $config->group_join){
                        $info->type = 2;
                        $msg = '已加入'.$size.'个商圈,每个商家只能加入.'.$config->group_join.'个商圈';
                    }
                    break;
                case 2:
                    $info->type = 2;
                    $msg = '已拒绝加圈申请';
                    break;
                case 4:  
                    $info->type = 4;
                    $msg = '已成功踢出我的商圈';
                    break;
                default:
                    return enjson(403,'操作失败');
                    break;
            }
        }elseif($param['type'] == 3){
            $info->type = 3;
            $msg = '你成功退出商圈';
        }else{
            return enjson(403,'操作失败');
        }
        $info->save();
        return enjson(200,$msg);
    }
}