<?php
/**
 * 新版本活动配置
 */
defined('IN_WEB') or die('Include Error!');
include_once dirname(__FILE__) . "/Base.php";
class Activitynew extends Base
{
    /**
     * Notes:获取活动列表或详情
     * User: wsc
     * Time: 2020/7/17 12:10
     * @param $param
     * @return false|string
     */
    public function getActivity($param){
        $tb = otable::activityConf();
        if(isset($param['id'])&&!empty($param['id'])){
            $ret = oo::commonOprModel('activitynew')->getActivity($param['id'],true);
            $ret['reward_info'] = json_encode(oo::commonOprModel('activitynew')->getActReward($param['id'],true)['reward']);
            $ret['extra_reward'] = json_encode(oo::commonOprModel('activitynew')->getActReward($param['id'],true)['extra_reward']);
        }else{
            $ret['list'] = oo::commonOprModel('activitynew')->getActivityList($param['w']);
            $ret['conf'] = oo::commonOprModel('activitynew')->getActCommonCfg();
            $ret['act_type'] = oo::commonOprModel('activitynew')->act_type;
        }
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    /**
     * Notes:获取分类配置
     * User: wsc
     * Time: 2020/7/16 15:28
     * @return false|string
     */
    public function getTypeConf(){
        $ret['act_type'] = oo::commonOprModel('activitynew')->act_type;
        $ret['reward_type'] = oo::cfg('props');
        $ret['skips'] = oo::cfg('skip');
        $ret['actProps'] = oo::commonOprModel('activitynew')->specialActTypeList;
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    /**
     * Notes:保存活动
     * User: wsc
     * Time: 2020/7/17 12:09
     * @param $param
     * @return mixed
     */
    public function saveActivity($param){
        if(!isset($param['is_online'])){
            if(empty($param['uniqidKey']))
                return json_encode(["code"=>0,"msg"=>"操作失败,参数异常"],256);
            $uniqid = $param['uniqidKey'];
            $param = oo::commonOprRedis('statistics')->hGetAll($uniqid);
            oo::commonOprRedis('statistics')->delete($uniqid);
            unset($param['uniqidKey']);
        }

        $data = funs::adminDateAllow($param);
//        oo::logs()->debug3($data,'activity.txt');
        $data2['reward'] = $data['reward_info'];
        $data2['extra_reward'] =$data['extra_reward']?$data['extra_reward']:'';
        unset($data['reward_info']);
        unset($data['extra_reward']);
        $data1 =$data;
        if(intval($data['id'])>0){
            $data2['aid'] = $data1['id'] = intval($data['id']);
        }
//        $vainfo = $this->verifyActTime($data);
//        if($vainfo){
//            return $vainfo;
//        }
        $aid = oo::commonOprModel('activitynew')->saveActicity($data1);
        if($aid>0&&(!empty($data2['reward'])||!empty($data2['extra_reward']))){
            if(!$data2['reward']) unset($data2['reward']);
            if(!$data2['extra_reward']) unset($data2['extra_reward']);
//            oo::logs()->debug3($data2,'reward.txt');
            $data2['aid']  = $aid;
            $data2['type'] = $data['type'];
            oo::commonOprModel('activitynew')->saveActReward($data2);
        }
        if($aid<=0){
            return json_encode(["code"=>0,"msg"=>"操作失败"],256);
        }
        return json_encode(["code"=>1,"msg"=>"操作成功","data"=>["id"=>$aid]],256);
    }

    public function setActCommonCfg($param){
        $data = funs::adminDateAllow($param);
        $res = oo::commonOprModel('activitynew')->saveActCommonCfg($data);
        return $res?json_encode(["code"=>1,"msg"=>"操作成功","data"=>["type"=>$res]],256):json_encode(["code"=>0,"msg"=>"操作失败"],256);
    }

    /**
     * Notes:活动上下线
     * User: wsc
     * Time: 2020/9/4 9:55
     * @param $param
     * @return false|string
     */
    public function onlineOrNo($param){
        $data = funs::adminDateAllow($param);
//        $vainfo = $this->verifyActOnline($data);
//        if($vainfo){
//            return $vainfo;
//        }
        $aid = oo::commonOprModel('activitynew')->saveActicity($data);
        if($aid<=0){
            return json_encode(["code"=>0,"msg"=>"操作失败"],256);
        }
        return json_encode(["code"=>1,"msg"=>"操作成功","data"=>["id"=>$aid]],256);
    }

    /**
     * Notes:删除活动
     * User: wsc
     * Time: 2020/9/4 9:55
     * @param $param
     * @return false|string
     */
    public function delActivity($param){
        $data = funs::adminDateAllow($param);
        $ainfo = oo::commonOprModel('activitynew')->getActivity($data['id']);
        if($ainfo['is_online']==1){
            return json_encode(["code"=>0,"msg"=>"操作失败,活动在上线中"],256);
        }
        $res = oo::commonOprModel('activitynew')->delActivity($data['id']);
        if(!$res){
            return json_encode(["code"=>0,"msg"=>"操作失败"],256);
        }else{
            return json_encode(["code"=>0,"msg"=>"删除成功"],256);
        }
    }
    /**
     * Notes:验证上线是否冲突
     * User: wsc
     * Time: 2020/8/12 16:48
     * @param $data
     * @return bool|false|string
     */
    public function verifyActOnline($data){
        if(isset($data['is_online'])&&$data['is_online']==1){//活动上线验证
            $actinfo = oo::commonOprModel('activitynew')->getActivity($data['id']);
            if(in_array($actinfo['type'],["rank","super_collect","rank2"])){//不能同时上线多个同类型活动
                $aids =  oo::commonOprModel('activitynew')->getAllOnlineActivityByType($actinfo['type']);
                if(!in_array($data['id'],$aids)){
                    return json_encode(["code"=>0,"msg"=>"已存在上线的该类型活动"],256);
                }
            }
        }
        return false;
    }
    /**
     * Notes:验证排期时间是否冲突
     * User: wsc
     * Time: 2020/8/12 15:58
     * @param $data
     * @return bool
     */
    public function verifyActTime($data){
        $st =$data['start_time'];
        $en =$data['end_time'];
        $type= $data['type'];
        if(in_array($type,["super_collect","rank","rank2"])){
            $tb = otable::activityConf();
            $w ="type={$type}'";
            $w .=" and (start_time between {$st} and {$en}) or (end_time between {$st} and {$en}) limit 1";
            $sql = "SELECT * FROM {$tb} WHERE $w";
            $res = oo::commonOprDb('common')->getOne($sql,1);
            if($res){
                if($data['id']&&$res['id']!=$data['id']){//更新
                    return json_encode(["code"=>0,"msg"=>"操作失败,活动排期时间与活动>>{$res['id']}:{$res['name']}<<冲突"],256);;
                }else{//写入
                    return json_encode(["code"=>0,"msg"=>"写入失败,活动排期时间与活动>>{$res['id']}:{$res['name']}<<冲突"],256);;
                }
            }
        }
        return false;
    }


    /**
     * Notes:设置用户通行证数据
     * User: xwy
     * Time: 2020/10/08 17:05
     * @param $data
     * @return bool
     */
    public function operateUserTrafficPermit($data)
    {
        if (empty($data['uid'])) {
            return json_encode(["code" => 0, "msg" => "参数异常"], 256);
        }
        $uid = $data['uid'];
        $actInfo = oo::commonOprModel('activitynew')->activityLock($uid, "traffic_permit", true);
        if (!empty($actInfo)) {
            $aid = $actInfo['activityData']['aid'];
            $end = $actInfo['activityData']['end'];
            $key = okeys::GamePassInfo($aid, $uid);

            if (!oo::commonOprRedis('activity')->exists($key)) {
                $initData = ["exp" => 0, "buy" => 0, "receive_normal" => "[]", "receive_special" => "[]"];
                oo::commonOprRedis('activity')->hMset($key, $initData);
                oo::commonOprRedis('activity')->expireAt($key, $end + 86400 * 2);
            }

            switch ($data['option']) {
                case 1:#获取用户通行证状态
                    $data = [
                        'status' => oo::commonOprRedis('activity')->hGet($key, "buy")
                    ];
                    break;
                case 2:#激活通行证
                    $trafficStatus = 0;
                    switch ($data['type']) {
                        case "normal":
                            $trafficStatus = 1;
                            break;
                        case "special":
                            $trafficStatus = 2;
                            break;
                    }

                    if (empty($data['type']) || empty($trafficStatus)) {
                        return json_encode(["code" => 0, "msg" => "参数 type 异常:" . $data['type']], 256);
                    }

                    $data['status'] = oo::commonOprRedis('activity')->hSet($key, "buy", $trafficStatus);

                    $reward_conf = ModelActivitynew::findPassRewardConfByLvRange($uid, $aid)['permitRewards'] ?? [];
                    $typeRewards = $reward_conf[$data['type']]['rewards'] ?? [];
                    oo::logs()->debug3(['msg' => $reward_conf], 'trafficRewards.log');
                    foreach ($typeRewards as $reward) {
                        switch ($reward['type']) {
//                            case 1 : break;//通行证专属名字颜色
                            case 2 :
                                $res = oo::commonOprModel('user')->sendUserAvatar($uid, $reward['value']);
                                break;//通行证专属头像框
                            case 3 :
                                $res = oo::commonOprModel('activitynew')->buyTrafficPermitLevelByPay($uid, $reward['value']);
                                break;//赠送N个通行证等级
                            default:
                                break;
                        }
                        oo::logs()->debug3(['msg' => $reward, 'res' => $res], 'trafficRewards.log');
                    }
                    break;
                case 3:
                    $lv = intval($data['lv']);
                    if (empty($lv)) return json_encode(["code" => 0, "msg" => "参数异常,缺少升级等级数"], 256);
                    $data = oo::commonOprModel('activitynew')->buyTrafficPermitLevelByPay($uid, $lv);
                    break;
                default:
                    return json_encode(["code" => 0, "msg" => "参数异常"], 256);
            }
            $data['code'] = 1;
            $data['msg'] = '操作成功';
            return json_encode($data);
        }
        return json_encode(["code" => 0, "msg" => "活动不存在"], 256);
    }
}