<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Log;
use think\Response;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取视频第一针
     */
    public function getVideo() {
        $video = $this->request->request('video'); // 视频文件
        if(!$video) {
            $this->error(__('视频文件缺失!'));
        }

        $cover = 'uploads/video_cover/'.date('Ymd').date('His').rand(1000,9999).'.png';
        getVideoCover($video,0.1,$cover);
        $full_cover = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"].'/'.$cover;

        if($full_cover) {
            $this->success("获取成功",$full_cover);
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        getVideoCover(config('project_path') . '/public/assets/123.mp4',3,'uploads/ffmpeg_test.png');
        $this->success('请求成功');
    }

    /**
     * 获取版本更新信息
     */
    public function getEdition() {
        // 获取二维码
        $is_force = config("site.is_force");
        $apkUrl = config("site.apkUrl");
        $apkName = config("site.apkName");
        $desc = config("site.desc");
        $versionCode = config("site.versionCode");
        $this->success("获取成功!",["versionCode"=>$versionCode,"isForceUpdate"=>$is_force,"apkUrl"=>$apkUrl,"apkName"=>$apkName,"desc"=>$desc]);
    }

    /**
     * 获取网站配置信息
     */
    public function getWebsiteInfo() {
        $params = $this->request->request("params"); //内容
        $this->success("获取成功!",config("site.".$params));
    }

    /**
     * 获取省数据
     */
    public function getProvince() {
        $res = \app\common\model\Area::field("id,pid,name,level")->where(["pid"=>0])->select();
        $this->success('请求成功',$res);
    }

    /**
     * 获取市数据
     */
    public function getCity() {
        $province = $this->request->request('province'); // 省
        if (!$province) $this->error('参数缺失!');

        $res = \app\common\model\Area::field("id,pid,name,level")->where(["pid"=>$province])->select();
        $this->success('请求成功',$res);
    }

    /**
     * 获取区数据
     */
    public function getArea() {
        $city = $this->request->request('city'); // 市
        if (!$city) $this->error('参数缺失!');

        $res = \app\common\model\Area::field("id,pid,name,level")->where(["pid"=>$city])->select();
        $this->success('请求成功',$res);
    }

    /**
     * 根据生日获取年龄和星座
     */
    public function getAgeByBirthday() {
        $birthday = $this->request->request('birthday'); // 生日 格式:2011-04-31
        $signs = array( array('20' => '水瓶座'), array('19' => '双鱼座'), array('21' => '白羊座'), array('20' => '金牛座'), array('21' => '双子座'), array('22' => '巨蟹座'), array('23' => '狮子座'), array('23' => '处女座'), array('23' => '天秤座'), array('24' => '天蝎座'), array('22' => '射手座'), array('22' => '摩羯座'));
        if (!empty($birthday)) {
            $age = strtotime($birthday);
            if ($age === false) {
                $this->error("参数缺失!");
            }

            list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));

            list($y2, $m2, $d2) = explode("-", date("Y-m-d"), time());

            $age = $y2 - $y1;
            //下面是判断月份大小,如果只是逄年份的可以去掉,如果算上月份的话,比如:2000年4月1日,那算出来是16算,要到了4月,算出来才是17岁
            if ((int)($m2 . $d2) < (int)($m1 . $d1)) {
                $age -= 1;
            }

            //星座
            $key = (int)$m1 - 1;
            $startSign = array_keys($signs[$key]);
            $signName = array_values($signs[$key])[0];

            if ($d1 < $startSign) {
                $key = $m1 - 2 < 0 ? $m1 = 11 : $m1 -= 2;
                $startSign = array_keys($signs[$key]);
                $signName = array_values($signs[$key])[0];
            }
            if($age < 0) {
                $this->error("出生日期不能大于当前时间!");
            }
            $data = [];
            $data['age'] = $age;
            $data['signName'] = $signName;
            $this->success("获取成功!",$data);
        } else {
            $this->error("参数缺失!");
        }
    }

    /**
     * 获取期望对象列表
     */
    public function getExpect() {
        $this->success("获取成功!",\app\admin\model\website\Expect::order("weight","desc")->select());
    }

    /**
     * 获取爱好列表
     */
    public function getHobby() {
        $this->success("获取成功!",\app\admin\model\website\Hobby::order("weight","desc")->select());
    }

    /**
     * 获取职业列表
     */
    public function getProfession() {
        $this->success("获取成功!",\app\admin\model\website\Profession::order("weight","desc")->select());
    }

    /**
     * 获取收入列表
     */
    public function getIncome() {
        $this->success("获取成功!",\app\admin\model\website\Income::order("weight","desc")->select());
    }

    /**
     * 获取会员举报类型
     */
    public function getReportType() {
        $this->success("获取成功!",\app\admin\model\website\ReportType::order("weight","desc")->select());
    }

    /**
     * 获取音乐列表信息
     */
    public function getMusicInfo() {
        $this->success("获取成功!",\app\admin\model\website\Music::order("weight","desc")->select());
    }

    /**
     * 获取标签列表信息
     */
    public function getTagInfo() {
        $this->success("获取成功!",\app\admin\model\website\Tag::order("weight","desc")->select());
    }

    /**
     * 获取客服列表
     */
    public function getCsList() {
        $this->success("获取成功!",\app\admin\model\website\Kefu::order("weight","desc")->select());
    }

    /**
     * 获取邀请图片
     */
    public function getInviteImg() {
        // 获取用户的邀请码
        $invitecode = \app\common\model\User::where(["id"=>$this->auth->id])->value("invite_no");

        // 文字图片合成
        $bigImgPath = httpurllocal('/assets/img/inviteimg.png');
        $img = imagecreatefrompng($bigImgPath);
        imagesavealpha($img, true);

        //字体文件
        $font = realpath('./assets/fonts/lato/lato-black.ttf');

        //字体颜色(RGB)
        $black = imagecolorallocate($img, 217, 76, 41);
        //字体大小
        $fontSize = 30;
        //旋转角度
        $circleSize = 0;
        //左边距
        $left = 383;
        //上边距
        $top = 680;
        imagefttext($img, $fontSize, $circleSize, $left, $top, $black, $font, $invitecode);
        $filename = date("YmdHis"). $this->auth->id . rand(10000, 99999) . ".jpeg";
        $path = "/uploads/qrcode/".$filename;
        $file = $_SERVER['DOCUMENT_ROOT'] . $path;//打开文件准备写入
        list($bgWidth, $bgHight, $bgType) = getimagesize($bigImgPath);
        switch ($bgType) {
            case 1://gif
                header('Content-Type:image/gif');
                imagegif($img,$file);
                break;
            case 2://jpg
                header('Content-Type:image/jpg');
                imagejpeg($img,$file);
                break;
            case 3://jpg
                header('Content-Type:image/png');
                imagepng($img,$file);
                break;
            default:
                break;
        }

        //销毁照片
        imagedestroy($img);

        // 图片和二维码合成
//        $qrcode = config("site.qrcode");
        $params['text'] = $_SERVER['HTTP_HOST'] . '/index/index/invite?code=' . $invitecode;
        $qrcode_service = \addons\qrcode\library\Service::qrcode($params);
        $mimetype = 'image/png';
        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        header('Content-Type: ' . $qrcode_service->getContentType());
        $response->content($qrcode_service->writeString());
        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath . md5(implode('', $params)) . '.png';
            $qrcode_service->writeFile($filePath);
        }

        $background = $file;
        $target = $filePath;//httpurl($qrcode);

//        $background_iamge = imagecreatefromstring(file_get_contents($background)); // 无透明度
        $background_iamge = imagecreatefrompng($background); // 保留背景的透明度
        imagesavealpha($background_iamge, true);

        $target_image = imagecreatefromstring(file_get_contents($target));
        list($target_width, $target_height, $target_type) = getimagesize($target);
        imagecopy($background_iamge , $target_image , 350, 850, 0, 0, $target_width, $target_height);
        list($background_width, $background_height, $background_type) = getimagesize($background);
        switch ($background_type) {
            case 1://gif
                header('Content-Type:image/gif');
                imagegif($background_iamge,$file);
                break;
            case 2://jpg
                header('Content-Type:image/jpg');
                imagejpeg($background_iamge,$file);
                break;
            case 3://jpg
                header('Content-Type:image/png');
                imagepng($background_iamge,$file);
                break;
            default:
                break;
        }
//        header("Content-type: image/png");
//        imagepng($background_iamge);exit;
        $savepath = httpurllocal($path);

        $this->success("获取成功!",$savepath);
    }

    /**
     * 获取邀请的用户
     */
    public function getInviteusers() {
        $user_list = \app\common\model\User::field('id,nickname,invite_time')->where(['pre_user_id'=>$this->auth->id])->select();
        if($user_list) {
            $user_profit_log = Db::name('user_profit_log');
            foreach($user_list as $k => &$v) {
                $user_list[$k]['invite_time'] = date('Y-m-d H:i:s',$v['invite_time']);
                $income = $user_profit_log->where(['user_id' => $v['id']])->order('id', 'desc')->value('after');
                $v['total_income'] = $income ? : "0.00";
            }
        }
        $this->success("获取成功!",$user_list);
    }
    /**
     * 获取累计邀请/邀请码等
     */
    public function getInviteCount() {
        $user_count = \app\common\model\User::where(['pre_user_id'=>$this->auth->id])->count("id");
        $invite_no = \app\common\model\User::where(['id'=>$this->auth->id])->value('invite_no');
        $this->success("获取成功!",['user_count'=>$user_count,'invite_no'=>$invite_no]);
    }

    //rsa公钥私钥加密测试
    public function test() {
        $data = '123456';
        $private_key = "-----BEGIN RSA PRIVATE KEY-----" .PHP_EOL.
            wordwrap(config('private_key'), 64, PHP_EOL, true) .
            PHP_EOL."-----END RSA PRIVATE KEY-----";

        $public_key = "-----BEGIN PUBLIC KEY-----" .PHP_EOL.
            wordwrap(config('public_key'), 64, PHP_EOL, true) .
            PHP_EOL."-----END PUBLIC KEY-----";

        $encrypted = $decrypted = "";
        openssl_private_encrypt($data, $encrypted, $private_key); // 使用私钥加密数据
        echo base64_encode($encrypted);
        openssl_public_decrypt($encrypted, $decrypted, $public_key);// 使用公钥进行解密
        echo $decrypted;
    }

}