<?php

namespace app\api\controller\activity;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\Weixin;
use app\common\model\QRcode;

class Activity extends Base
{
    protected $noNeedLogin = ['info','getList'];
    protected $noNeedRight = ['*'];

    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Activity;
    }
    
    public function getList(){
        $page = max(1,$this->param("page/d"));
        $limit = 10;

        $where = ['uniacid'=>UNIACID,'status'=>1,'sh_status'=>1,'is_public'=>1,'endtime'=>['>',time()]];

        $list = Db::name("bbfx_activity_list")->where($where)->field("id,title,image,type,is_public,starttime,endtime,baoming_total,address,detail_address,lat,lng")->order("starttime asc")->limit(($page-1)*$limit,$limit)->select();
        
        foreach ($list as $key => &$val){
            $val['starttime'] = date("Y.m.d H:i",$val['starttime']);
            $val['endtime'] = date("Y.m.d H:i",$val['endtime']);
            $baoming_num = Db::name("bbfx_activity_baoming")->where(['uniacid'=>UNIACID,'activity_id'=>$val['id'],'is_pay'=>1])->count();
            $val['baoming_num'] = $baoming_num;
            $val['image'] = cdnurl($val['image']);
            $val['advert_image'] = cdnurl($val['advert_image']);
        }
        unset($val);
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function getMyBaomingList(){
        $platform = $this->param("platform/s");

        $where = ['a.uniacid'=>UNIACID,'a.user_id'=>$this->user['id'],'a.is_pay'=>1,'b.status'=>1];

        $list = Db::name("bbfx_activity_baoming")->alias("a")->join("bbfx_activity_list b","a.activity_id=b.id","LEFT")->where($where)->field("a.*,b.title,b.starttime,b.endtime,b.is_hexiao")->order("a.id desc")->select();
        
        
        foreach ($list as $key => &$val){
            $val['starttime'] = date("Y.m.d H:i",$val['starttime']);
            $val['endtime'] = date("Y.m.d H:i",$val['endtime']);
            $val['paytime'] = date("Y.m.d H:i",$val['paytime']);
            $val['info'] = iunserializer($val['info']);
            if($val['info']){
                $val['info']['image'] = cdnurl($val['info']['image']);
                $val['info']['advert_image'] = cdnurl($val['info']['advert_image']);
            }

            if($val['is_hexiao'] == 1){
                $page = "plugin/activity/signup-list?activity_id=".$val['activity_id']."&code=".$val['hexiao_code'];
                $qrcode = "";
                if($platform == 'wxapp'){
                    $result = Weixin::getUnlimitedQRCode($page, "activity_hexiao_wxacode_".$val['id'],1);
                    if($result['code'] == 1){
                        $qrcode = cdnurl($result['data']['url']); 
                    }
                    
                }
                else{
                    $page .= "&i=".$val['uniacid'];
                    $url = request()->domain()."/mobile/#/".$page;
                    $result = QRcode::create($url, "activity_hexiao_qrcode_".$val['id']);
                    if($result['code'] == 1){
                        $qrcode = cdnurl($result['data']['url']); 
                    }
                    
                }
                $val['qrcode'] = $qrcode;
            }
            
        }
        unset($val);
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function info(){
        $id = $this->param("id/d");
        $platform = $this->param("platform/s");
        $user = $this->user;
        $info = Db::name("bbfx_activity_list")->where(['uniacid'=>UNIACID,'status'=>1,'sh_status'=>1,'id'=>$id])->find();
        if(empty($info)){
            __error("活动不存在");
        }
        
        // $store = \app\common\model\bbfxshop\Store::getInfo($info['store_id']);
        
        $info['slide_images'] = cdnurls(iunserializer($info['slide_images']));
        $info['slide_videos'] = cdnurls(iunserializer($info['slide_videos']));
        $info['detail_images'] = cdnurls(iunserializer($info['detail_images']));
        $info['goods_ids'] = iunserializer($info['goods_ids']);
        $info['advert_image'] = cdnurl($info['advert_image']);
        $info['image'] = cdnurl($info['image']);
        $info['music'] = cdnurl($info['music']);
        
        
        if($info['starttime'] > time()){
            $info['activity_status'] = 0;
        }
        else if($info['endtime'] > time() && $info['starttime'] < time()){
            $info['activity_status'] = 1;
        }
        else{
            $info['activity_status'] = 2;
        }
        
        $downtime = 0;
        if($info['activity_status'] == 0){
            $downtime = $info['starttime'] - time();
        }
        else if($info['activity_status'] == 1){
            $downtime = $info['endtime'] - time();
        }
        $info['downtime'] = $downtime;
        
        $info['starttime'] = date("Y-m-d H:i:s",$info['starttime']);
        $info['endtime'] = date("Y-m-d H:i:s",$info['endtime']);

        /*
        $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>['in',$info['goods_ids']],'status'=>1])->field("id,title,thumb,stock,price,o_price")->select();
        if(empty($goods)) $goods = [];
        foreach ($goods as $k => &$v){
            $v['thumb'] = cdnurl($v['thumb']);
        }
        unset($v);
        $info['goods'] = $goods;
        */
        
        $where = ['a.uniacid'=>UNIACID,'a.is_pay'=>1,'a.activity_id'=>$info['id']];
        $baoming = Db::name("bbfx_activity_baoming")->alias("a")->join("bbfx_user b","a.user_id=b.id","left")->where($where)->field("a.*,b.avatar,b.nickname")->order("a.id desc")->select();
        if(empty($baoming)) $baoming = [];
        foreach ($baoming as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
        }
        unset($val);
        $info['baoming'] = $baoming;
        
        $info['baoming_num'] = count($baoming);
        
        
        $baoming = Db::name("bbfx_activity_baoming")->where(['activity_id'=>$info['id'],'user_id'=>$this->user['id'],'is_pay'=>1])->find();
        $is_baoming = 0;
        if(!empty($baoming)){
            $is_baoming = 1;
        }
        
        Db::name("bbfx_activity_list")->where(['id'=>$info['id']])->setInc("browse",1);
        
        $path = "plugin/activity/activity?id={$info['id']}";
        if(!empty($user)){
            $path .= "&sup_uid=".$user['id'];
        }
        
        if($platform == 'wxapp'){
            
            $filename = "activity_{$info['id']}";
            if(!empty($user)){
                $filename = "activity_{$info['id']}_{$user['id']}";
            }
            
            $result = Weixin::getUnlimitedQRCode($path, $filename);
            if($result['code'] == 1){
                $info['activity_qrcode'] = cdnurl($result['data']['url'])."?t=".time();
            }
        }
        else{
            $text = request()->domain()."/mobile/#/".$path."&i=".$info['uniacid'];
            $filename = "activity_{$info['id']}";
            if(!empty($user)){
                $filename = "activity_qrcode_{$info['id']}_{$user['id']}";
            }
            $result = QRcode::create($text,$filename);
            if($result['code'] == 1){
                $info['activity_qrcode'] = cdnurl($result['data']['url'])."?t=".time();
            }
        }
        
        $poster_image = cdnurl($info['poster_image']);
        
        if(!empty($poster_image) && !strstr($poster_image, request()->domain())){
            
            $s = explode(".",$poster_image);
            $suffix = $s[count($s)-1];
            $remoteImage = fopen($poster_image, 'rb');
            $filename = "/data/poster_wxapp/a_{$info['id']}.".$suffix;
            $localPath = ROOT_PATH."public".$filename;
            $result = file_put_contents($localPath, $remoteImage);
            fclose($remoteImage);
            
            $poster_image = cdnurl($filename);
        }
        
        $info['poster_image'] = $poster_image;
        
        __success("操作成功",['info'=>$info,'is_baoming'=>$is_baoming]);
    }
    
    public function baoming(){
        $id = $this->param("id/d");
        $params = $this->param(['mobile/s','realname/s','sex/d']);

        $set = $this->model->getSet();
        if($set['status'] != 1){
            __error("未开启活动");
        }

        $info = Db::name("bbfx_activity_list")->where(['uniacid'=>UNIACID,'status'=>1,'sh_status'=>1,'id'=>$id])->find();
        
        if(empty($info)){
            __error("活动不存在");
        }
        
        if($info['starttime'] > time()){
            // __error("活动未开始");
        }
        
        if($info['bm_stime'] > 0 && $info['bm_etime'] > 0){
            if($info['bm_stime'] > time()){
                __error("未到活动报名开始时间");
            }
            if($info['bm_etime'] < time()){
                __error("活动报名时间已结束");
            }
        }
        else{
            if($info['starttime'] < time()){
                __error("请在活动开始前报名");
            }
        }
        if($info['endtime'] < time()){
            __error("活动已结束");
        }
        
        if(empty($params['realname'])){
            __error("请填写姓名");
        }
        if(empty($params['mobile'])){
            __error("请填写电话");
        }
        if(!in_array($params['sex'],[1,2])){
            __error("请选择性别");
        }
        
        $baoming = Db::name("bbfx_activity_baoming")->where(['activity_id'=>$info['id'],'is_pay'=>0,'user_id'=>$this->user['id']])->find();
        if(!empty($baoming) && $baoming['is_pay'] == 1){
            // __error("已报名");
        }
        
        $baoming_num = Db::name("bbfx_activity_baoming")->where(['activity_id'=>$info['id'],'is_pay'=>1])->count();
        if($baoming_num >= $info['baoming_total']){
            __error("报名人数已满");
        }
        
        $order_no = date('YmdHis').random(8,true);  
        $hexiao_code = random(8,true);
        
        $data = [
            "uniacid"=>UNIACID,
            "order_no"=>$order_no,
            "hexiao_code"=>$hexiao_code,
            "user_id"=>$this->user['id'],
            "activity_id"=>$info['id'],
            "mobile"=>$params['mobile'],
            "realname"=>$params['realname'],
            "sex"=>$params['sex'],
            "baoming_fee"=>round($info['baoming_fee'],2),
            "info"=>iserializer($info),
            "is_pay"=>0
        ];
        
        if($data['baoming_fee'] <= 0){
            $data['is_pay'] = 1;
            $data['paytype'] = 1;
            $data['paytime'] = time();
            $data['jiesuan_status'] = 1;
            $data['jiesuan_time'] = time();
        }
        
        if(!empty($baoming)){
            $res = Db::name("bbfx_activity_baoming")->where(['id'=>$baoming['id']])->update($data);
        }
        else{
            $data['createtime'] = time();
            $res = Db::name("bbfx_activity_baoming")->insert($data);
        }
        if($res){
            __success("报名成功",['is_pay'=>$data['is_pay'],'order_no'=>$order_no]);
        }
        else{
            __error("报名失败");
        }
    }
}