<?php
namespace Home\Controller;
vendor('tencentsdk.TCloudAutoLoader');

use Think\Controller;
use SignedCookie;
use Zhida\OAuthHelperV3;
use Think\Upload\Driver\Qiniu\QiniuStorage;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Nlp\V20190408\NlpClient;
use TencentCloud\Nlp\V20190408\Models\SensitiveWordsRecognitionRequest;

use Think\Log;

class IndexController extends Controller
{
    private $auth_type = OAuthHelperV3::SCOPE_USERINFO;
    private $cookie_uid_key = 'skp-rotor-v1';
    private $debug = 1;
    private $today;
    use ControllerTrait;
    
    public function index()
    {
      $user = $this->get_user_info_from_cookie();
      // 如果没有获取到用户信息，引导用户授权
      if (!$user) {
          $this->request_auth($this->get_url());
          return;
      }
      $this->display();
    }

    public function detectSensitiveWords($text){
      // $text = $_GET['text'];
      $cred = new Credential("AKID9B4pPq5YBgz9Yo7qDRkspgOQK3c89PrD", "MXWK3DKNFzYgpvWwCKH4kKoma0O1Yu8A");
      $httpProfile = new HttpProfile();
      $httpProfile->setEndpoint("nlp.tencentcloudapi.com");
        
      $clientProfile = new ClientProfile();
      $clientProfile->setHttpProfile($httpProfile);
      $client = new NlpClient($cred, "ap-guangzhou", $clientProfile);
      $req = new SensitiveWordsRecognitionRequest();
      
      $params = '{"Text":"+'. $text .'+"}';
      $req->fromJsonString($params);
      $resp = $client->SensitiveWordsRecognition($req);
      $resp = $resp->toJsonString();
      return $resp;
    }
    public function checkWord() {
      $name = $_POST['name'];
      if($this->utf8_strlen($name) > 4 || empty($name))
      {
        $this->ajaxReturn(array(
          'status' => 0,
          'msg' => '非法',
          'step' => 3
        ));
        return;
      }
      $detectResult = json_decode($this->detectSensitiveWords($name),1);
      if($detectResult['SensitiveWords'] != null)
      {
        $this->ajaxReturn(array(
            'status' => -1,
            'msg' => '您提交的姓名包含敏感词',
            'step' => 3
        ));
        return;
      }
      else 
      {
        $this->ajaxReturn(array(
            'status' => 1,
            'msg' => '通过',
            'step' => 3
        ));
        return;
      }
    }

    public function upload()
    {
        $user = $this->get_user_info_from_cookie();
        if (!$user) {
            $this->ajaxReturn(array(
                'status' => 404,
                'msg' => '用户不存在'
            ));
            return;
        }
        if (!$_POST['image']) {
            $this->ajaxReturn(array(
                'status' => -1,
                'msg' => '请填写完整信息'
            ));
            return;
        }
        
        $url = $this->saveCommonImageToQiniu($_POST['image'], uniqid('pingan_marathon_'));
        if($_POST['source'] == 'poster')
        {
          M('User')->where(['id' => $user['id']])->save([
              'poster_url' => $url,
              'poster_times' => time()
          ]);
          $this->ajaxReturn(array(
              'status' => 1,
              'img_url' => $url,
              'msg' => '信息提交成功!'
          ));
          return;
        }
        else 
        {
          M('User')->where(['id' => $user['id']])->save([
              'headposter_url' => $url,
              'headposter_times' => time()
          ]);
          $this->ajaxReturn(array(
              'status' => 1,
              'img_url' => $url,
              'msg' => '信息提交成功!'
          ));
          return;
        }
        
    }
    private function saveCommonImageToQiniu($imgData, $fileNameWithoutExt)
    {
        $head = substr($imgData, 0, 20);
        $type = 'png';
        if (stripos($head, 'data:image/jpg;') !== false || stripos($head, 'data:image/jpeg;') !== false) {
            $type = 'jpg';
            $imgData = substr($imgData, strlen('data:image/jpeg;base64,'));
        } else {
            $imgData = substr($imgData, strlen('data:image/png;base64,'));
        }
        $imgData = str_replace(' ', '+', $imgData);
        $data = base64_decode($imgData);
        if (strlen($data) == 0) {
            return false;
        }
        $fileName = $fileNameWithoutExt . '.' . $type;
        $upfile = array(
            'name' => 'file',
            'fileName' => $fileName,
            'fileBody' => $data,
        );
        $config = C('UPLOAD_SITEIMG_QINIU')['driverConfig'];
        $qiniu = new QiniuStorage($config);
        $opt = array();
        $result = $qiniu->upload($opt, $upfile);
        $url = $qiniu->downlink($fileName);
        return $url;
    }

    // 计算中文字符串长度
    function utf8_strlen($string = null) {
      // 将字符串分解为单元
      preg_match_all("/./us", $string, $match);
      // 返回单元个数
      return count($match[0]);
    }
    
    public function cookie()
    {
        SignedCookie::set_cookie($this->cookie_uid_key, 'oVsrlt0zUWMLvMx2-KPGVmY2I-Xc', C('cookie_sign'), 86400 * 60);
    }
}