<?php

namespace app\api\controller;

use Limen\Redisun\Examples\HashModel;
use Limen\Redisun\Examples\StringModel;
use think\Db;
use think\Cache;
include_once '../vendor/aliyun/aliyun-php-sdk-core/Config.php';
use Mts\Request\V20140618 as Mts;

/**
 * 眼缘接口
 */
class Eyemargin extends Common
{
    protected $noNeedLogin = ['mpsvideo', 'getencoderesult'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 发布眼缘
     */
    public function addFate() {
        $eye_type = $this->request->request('eye_type'); // 动态类型
        $content = $this->request->request('content'); // 内容
        if (!in_array($eye_type,[1,2]) || !$content) {
            $this->error(__('Invalid parameters'));
        }
        $str_arr = sensitive($content);
        if($str_arr['count'] > 0) {
            $this->error(__('发布内容存在敏感词汇:'.$str_arr['sensitiveWord'].' 请重新编辑后发布!'));
        }
        // 判断当前用户是否实名认证
        $userAuthInfo = \app\common\model\UserAuth::userIsAuth($this->auth->id);
        if($userAuthInfo['status'] == 0) $this->error($userAuthInfo['msg']);

        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["eye_type"] = $eye_type;
        $data["content"] = $content;

        if($eye_type == 2) {
            $cover = $this->request->request('cover'); // 影集封面图
            $album = $this->request->request('album'); // 影集图片
            $music = $this->request->request('music'); // 背景音乐
            if(!$cover || !$album || !$music) {
                $this->error(__('Invalid parameters'));
            }
            $data['cover'] = $cover;
            $data['album'] = $album;
            $data['music'] = $music;

        } elseif($eye_type == 1) {
            $video = $this->request->request('video'); // 视频文件
            if(!$video) {
                $this->error(__('视频图片缺失!'));
            }
            $cover = $this->request->request('cover'); // 影集封面图
            $data['cover'] = $cover;

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

            $data['video'] = $video;
            //视频转码加logo
            $oss_input_object = substr($data['video'], strpos($data['video'], 'uploads'));
            $oss_output_object = str_replace('uploads', 'output', $oss_input_object);
            $result = $this->mpsvideo($oss_input_object, $oss_output_object);
            if (!$result) {
                $this->error('网络错误,请稍后重试');
            }
            $data['jobid'] = $result;
        }

        $eyemarginModel = new \app\common\model\Eyemargin();
        $data["createtime"] = time();
        // 判断是否是第一个视频
        $info = $eyemarginModel->where(['user_id'=>$this->auth->id,'status'=>['in',[0,1]]])->find();
        if(!$info) {
            $data['is_main'] = 1;
            $msg = "恭喜,视频已发布审核中!温馨提示:长按可以取消或者修改'推荐'短视频,推荐的视频会展示给同城好友哦";
        } else {
            $msg = "发布成功!请耐心等待审核!";
        }

        $res = $eyemarginModel->insertGetId($data);
        if($res) {
            $this->success($msg);
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }

    /**
     * 当数据为空时
     * @param $is_goddess
     * @param $is_new
     * @param $redis_ids
     * @param $field
     * @param $user_id
     * @return false|mixed|\PDOStatement|string|\think\Collection
     */
    private function getFateInfo($redis_ids,$field,$user_id,&$common_where) {
        $redis_ids && $common_where['a.id'] = ['notin',implode(',',$redis_ids)];

        // 按照距离排序
        $where = [];
        $where = array_merge($where,$common_where);
        $a = \app\common\model\Eyemargin::getDistanceList($this->auth->lng,$this->auth->lat,$field,$where,$user_id);

        return $a;
    }

    /**
     * 获取眼缘视频/影集
     */
    public function getFate() {
        $is_goddess = $this->request->request('is_goddess'); // 是否女神:1=是,0=否
        $is_new = $this->request->request('is_new'); // 是否新人:1=是,0=否
        $is_neal = $this->request->request('is_neal'); // 是否附近:1=是,0=否
        if (!in_array($is_goddess,[0,1]) && !in_array($is_new,[0,1]) && !in_array($is_neal,[0,1])) {
            $this->error(__('请选择展示tab!'));
        }
        $pageNum = $this->request->request('pageNum',10); // 每页显示条数

        $user_id = $this->auth->id;
        $user_id_redis = 'u_'.$user_id;
        $redis_ids = json_decode(Cache::get($user_id_redis),true);

        $time = time() - 30*86400;
        $common_where = [];
//        $common_where['u.avatar'] = ['like', 'https%'];
        $common_where['a.is_main'] = 1;
        $common_where['a.status'] = 1;
        $common_where['u.city'] = $this->auth->city;
        $is_goddess && $common_where['u.is_goddess'] = 1;
        $is_new && $common_where['u.createtime'] = ['gt',$time];
        $common_where['a.status'] = 1;

        $field = "a.*,u.avatar,u.city_name,u.district_name,u.nickname,u.is_goddess,u.is_auth,vipStatus(u.vip_duetime) as is_vip, 
        u.age,u.constellation,u.hobby_ids,u.profession,u.declaration,u.lng,u.lat,u.mobile,u.copy_mobile,u.wechat";
        $list = [];

        $a = $this->getFateInfo($redis_ids,$field,$user_id,$common_where);

        if(!$a) {
            Cache::rm($user_id_redis);
            unset($common_where['a.id']);
            $redis_ids = [];
            $a = $this->getFateInfo($redis_ids,$field,$user_id,$common_where);
        }
        // 女神
        $where = [];
        $where['u.is_goddess'] = 1;
        $where = array_merge($where,$common_where);
        $b = \app\common\model\Eyemargin::getDistanceList($this->auth->lng,$this->auth->lat,$field,$where,$user_id);
        // 喜好 期望对象
        $expect = $this->auth->expect_ids;
        $user_ids =\app\common\model\Expect::getTagsByExpect($expect);
        if($user_ids) {
            $where = [];
            $where['u.id'] = ['in',implode(',',$user_ids)];
            $where = array_merge($where,$common_where);
            $c = \app\common\model\Eyemargin::getDistanceList($this->auth->lng,$this->auth->lat,$field,$where,$user_id);
        } else {
            $c = [];
        }

        // 新人
        $where = [];
        $where['u.createtime'] = ['gt',$time];
        $where = array_merge($where,$common_where);
        $d = \app\common\model\Eyemargin::getDistanceList($this->auth->lng,$this->auth->lat,$field,$where,$user_id);
        // 剩余

        // 三数组合并
        $bcd = \app\common\model\Eyemargin::arrayMerge($b,$c,$d);

        $e = array_diff($a,$bcd);

        // 附近

        $num_a = floor(config("site.nearbyTheOne") * 0.01 * $pageNum);
        $num_bcd = floor(config("site.nearbyTheTwo") * 0.01 * $pageNum);
        $num_e = $pageNum - $num_a - $num_bcd;

        // 先做好去重
        $a = array_slice($a,0,$pageNum);
        $bcd = array_diff($bcd,$a);
        $e = array_diff($e,array_merge($bcd,$a));


        $count_a = count($a);
        $count_e = count($e);
        $count_bcd = count($bcd);
        if($count_a <= ($num_a+$num_bcd+$num_e)) {
            $list = $a;
        }

        if($count_a >= $num_a && $count_bcd >= $num_bcd && $count_e >= $num_e) {
            $list_a = array_slice($a,0,$num_a);
            $list_bcd = array_slice($bcd,0,$num_bcd);
            $list_e = array_slice($e,0,$num_e);
            $list = \app\common\model\Eyemargin::arrayMerge($list_a,$list_bcd,$list_e);
        }
        // 10 = 10 =
        if($count_a >= $num_a && $count_bcd >= $num_bcd && $count_e < $num_e) {

            $list_a = array_slice($a,0,$pageNum-$num_bcd - $count_e);
            $list_bcd = array_slice($bcd,0,$num_bcd);
            $list_e = $e;
            $list = \app\common\model\Eyemargin::arrayMerge($list_a,$list_bcd,$list_e);
        }
        if($count_a >= $num_a && $count_bcd < $num_bcd && $count_e < $num_e) {
            $list_a = array_slice($a,0,$pageNum-$count_bcd-$count_e);
            $list_bcd = $bcd;
            $list_e = $e;
            $list = \app\common\model\Eyemargin::arrayMerge($list_a,$list_bcd,$list_e);
        }
        if($count_a >= $num_a && $count_bcd < $num_bcd && $count_e >= $num_e) {
            $list_a = array_slice($a,0,$pageNum-$count_bcd-$num_e);
            $list_bcd = $bcd;
            $list_e = array_slice($e,0,$num_e);
            $list = \app\common\model\Eyemargin::arrayMerge($list_a,$list_bcd,$list_e);
        }


        if($list) {
            // 收集眼缘ID
            $ids = array_column($list, 'id');
            if($redis_ids) {
                $redis_ids = array_merge($redis_ids,$ids);
            } else {
                $redis_ids = $ids;
            }
            Cache::set($user_id_redis,json_encode($redis_ids));
        } else {
            Cache::rm($user_id_redis);
        }
        $this->success("获取成功!",$list);
    }

    /**
     * 判断当前用户是否已经把我加到黑名单
     */
    public function isBlackUser() {
        $user_id = $this->request->request('user_id'); // 用户ID
        if(!$user_id) $this->error("参数缺失!");
        $where = [];
        $where['user_id'] = $user_id;
        $where['black_user_id'] = $this->auth->id;
        $blackInfo = \app\common\model\UserBlacklist::where($where)->find();
        if($blackInfo) {
            $this->success("获取成功!",['is_black'=>1]);
        } else {
            $this->success("获取成功!",['is_black'=>0]);
        }
    }

    /**
     * 阿里云媒体处理视频
     * @param string $oss_input_object  输入文件(相对路径)
     * @param string $oss_output_object  输出文件(相对路径)
     * @throws \ClientException
     * @throws \ServerException
     */
    public function mpsvideo($oss_input_object = '', $oss_output_object = '')
    {
        $access_key_id = config('oss.secretId'); //AccessKey ID
        $access_key_secret = config('oss.secretKey'); //AccessKey Secret
        $mps_region_id = config('oss.mps_region_id');
        $pipeline_id = config('oss.pipeline_id'); //管道id
        $watermark_template_id = config('oss.watermark_template_id'); //水印模板id
        $template_id = config('oss.template_id');//'S00000001-200030'; //转码模板id
        $oss_location = config('oss.region');
        $oss_bucket = config('oss.bucket'); //bucket
//        $oss_input_object = 'uploads/xuanzhuan.mp4'; //输入文件
//        $oss_output_object = 'output/xuanzhuan.mp4'; //输出文件
        $image_watermark_object = 'logo.png'; //水印logo地址
//        $video_watermark_object = 'logo.mov';
# DefaultAcsClient
        $clientProfile = \DefaultProfile::getProfile(
            $mps_region_id,                   # Region ID
            $access_key_id,                   # AccessKey ID
            $access_key_secret                # AccessKey Secret
        );
        $client = new \DefaultAcsClient($clientProfile);
# request
        $request = new Mts\SubmitJobsRequest();
        $request->setAcceptFormat('JSON');
# Input
        $input = array('Location' => $oss_location,
            'Bucket' => $oss_bucket,
            'Object' => urlencode($oss_input_object));
        $request->setInput(json_encode($input));
# Output
        $output = array('OutputObject' => urlencode($oss_output_object));
# Ouput->TemplateId
        $output['TemplateId'] = $template_id;
## Image Watermark
        $image_watermark_input = array(
            'Location' => $oss_location,
            'Bucket' => $oss_bucket,
            'Object' => urlencode($image_watermark_object)
        );
        $image_watermark = array(
            'WaterMarkTemplateId' => $watermark_template_id,
            'Type' => 'Image',
            'InputFile' => $image_watermark_input,
//            'ReferPos' => 'TopRight',
//            'Width' => 0.05,
            'Dx' => 100,
            'Dy'=> 50
        );
## Text Watermark
        /* $text_config = array(
             'Content' => '5rWL6K+V5paH5a2X5rC05Y2w',
             'FontName' => 'SimSun',
             'FontSize' => 16,
             'FontColor' => 'Red',
             'FontAlpha' => 0.5,
             'Top' => 10,
             'Left' => 10
         );
         $text_watermark = array(
             'WaterMarkTemplateId' => $watermark_template_id,
             'Type' => 'Text',
             'TextWaterMark' => $text_config
         );*/
## Video Watermark
        /*$video_watermark_input = array (
            'Location' => $oss_location,
            'Bucket' => $oss_bucket,
            'Object' => urlencode($video_watermark_object)
        );
        $video_watermark = array(
            'WaterMarkTemplateId' => $watermark_template_id,
            'Type' => 'Image',
            'InputFile'=> $video_watermark_input,
            'ReferPos' => 'BottomLeft',
            'Height' => 240,
            'Dx' => 0,
            'Dy' => 0
        );*/
# Output->Watermarks
//        $watermarks = array($image_watermark, $text_watermark, $video_watermark);
        $watermarks = array($image_watermark);
        $output['WaterMarks'] = $watermarks;
# Outputs
        $outputs = array($output);
        $request->setOUtputs(json_encode($outputs));
        $request->setOutputBucket($oss_bucket);
        $request->setOutputLocation($oss_location);
# PipelineId
        $request->setPipelineId($pipeline_id);
# call api
        try {
            $response = $client->getAcsResponse($request);
//            print 'RequestId is:' . $response->{'RequestId'} . "\n";;
            if ($response->{'JobResultList'}->{'JobResult'}[0]->{'Success'}) {
                return $response->{'JobResultList'}->{'JobResult'}[0]->{'Job'}->{'JobId'};
//                print 'JobId is:' .
//                    $response->{'JobResultList'}->{'JobResult'}[0]->{'Job'}->{'JobId'} . "\n";
            } else {
                return false;
//                print 'SubmitJobs Failed code:' .
//                    $response->{'JobResultList'}->{'JobResult'}[0]->{'Code'} .
//                    ' message:' .
//                    $response->{'JobResultList'}->{'JobResult'}[0]->{'Message'} . "\n";
            }
        } catch(ServerException $e) {
            return false;
//            print 'Error: ' . $e->getErrorCode() . ' Message: ' . $e->getMessage() . "\n";
        } catch(ClientException $e) {
            return false;
//            print 'Error: ' . $e->getErrorCode() . ' Message: ' . $e->getMessage() . "\n";
        }
    }
    
    //阿里云查询视频转码结果
    public function getencoderesult()
    {
        set_time_limit(0);

        $where = array(
            'eye_type' => 1,
            'jobid' => ['neq', ''],
            'encode_status' => 0,
        );
        $eyemargin = Db::name('eyemargin');
        $list = $eyemargin->where($where)->limit(100)->select();

        if (!$list) {
            echo 'mei shu ju';
            die;
        }

        //构建转码查询数据
        $data['Format'] = 'JSON';
        $data['Version'] = '2014-06-18';
        $data['AccessKeyId'] = config('oss.secretId');
        $data['SignatureMethod'] = 'HMAC-SHA1';
        $data['SignatureVersion'] = '1.0';
        $data['Action'] = 'QueryJobList';

        foreach ($list as &$v) {
            $data['Timestamp'] = str_replace('+00:00', 'Z', gmdate('c', time()));
            $data['SignatureNonce'] = md5(uniqid(mt_rand(), true));
            $data['JobIds'] = $v['jobid'];
            $data['Signature'] = $this->computeSignature($data, config('oss.secretKey'));

            $url = 'http://mts.cn-hangzhou.aliyuncs.com/?';
            foreach ($data as $apiParamKey => $apiParamValue) {
                $url .= "$apiParamKey=" . urlencode($apiParamValue) . '&';
            }
            $url = substr($url, 0, -1);

            $result = file_get_contents($url);
            $result = json_decode($result, true);
            $_data = [];
            if ($result['JobList']['Job'][0]['Percent'] == 100 && $result['JobList']['Job'][0]['State'] == 'TranscodeSuccess') {
                $_data['video'] = str_replace('uploads', 'output', $v['video']);
                $_data['encode_status'] = 1;
                $eyemargin->where(['id' => $v['id'], 'encode_status' => 0])->setField($_data);
            } elseif ($result['JobList']['Job'][0]['State'] == 'TranscodeFail') {
                $_data['encode_status'] = 2;
                $eyemargin->where(['id' => $v['id'], 'encode_status' => 0])->setField($_data);
            }
        }

        echo 'wan bi';
        die;
    }

    /**
     * @param $parameters
     * @param $accessKeySecret
     * @param $iSigner
     *
     * @return mixed
     */
    protected function computeSignature($parameters, $accessKeySecret)
    {
        ksort($parameters);
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
        }
        $stringToBeSigned = 'GET&%2F&' . $this->percentEncode(substr($canonicalizedQueryString, 1));
        return $this->signString($stringToBeSigned, $accessKeySecret . '&');
    }

    /**
     * @param $str
     *
     * @return string|string[]|null
     */
    protected function percentEncode($str)
    {
        $res = urlencode($str);
        $res = str_replace(array('+', '*'), array('%20', '%2A'), $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    public function signString($source, $accessSecret)
    {
        return base64_encode(hash_hmac('sha1', $source, $accessSecret, true));
    }
}