<?php
namespace app\common\controller;
use think\Controller;

use PHPExcel;
use PHPExcel_IOFactory;

class Common extends Controller
{
    protected $excelWidth = 20;// 默认excel宽度
    protected $excelHeight = 20;// 默认excel高度

    //跨域
    public function __construct()
    {
        parent::__construct();
        //header("Access-Control-Allow-Origin:*");
        //header('Access-Control-Allow-Methods:POST');
        //header('Access-Control-Allow-Headers:x-requested-with, content-type');
//        header('Access-Control-Allow-Origin:*');
//        header('Access-Control-Allow-Methods:*');
//        header('Access-Control-Allow-Headers:*');
//        header('Access-Control-Allow-Credentials:false');
    }
        /**创建日期
     * @return false|string
     */
    public static function getDate($str='Y-m-d H:i:s')
    {
        return date($str, time());
    }
    // 获取今日时间字符串
    public static function today_time_stamp()
    {
        return strtotime(self::getDate('Y-m-d'));
    }
    // 获取昨天时间戳
    public static function yesterday_time_stamp()
    {
        return strtotime("-1 day");
    }
    public static function getWallet($condition, $create=false)
    {
        $wallet = db('user_wallet')->where($condition)->find();
        if($create){
            $condition['add_time'] = self::getDate();
            $id = db('user_wallet')->insertGetId($condition);
            $wallet = db('user_wallet')->where(['id'=>$id])->find();
        }
        return $wallet;
    }
    public function params()
    {
        $params = $this->request->param();
        unset($params['token']);
        unset($params['path']);
        return $params;
    }   
    /**
     * 参数验证
     * @param array $opts
     * @param $scene
     */
    public static function verify($opts, $scene)
    {
        $validate = validate('Data');
        if ($validate->scene($scene)->check($opts) !== true) {
            echo json_encode(['code'=>2,'message'=>$validate->getError()]);
            exit;
        }
    }
    // 随机字符串
    public static function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    // 获取管理员ID
    public static function get_admin_id($token)
    {
        return db('admin')->where(['token'=>$token,'status'=>1])->value('id');
    }
    // 获取token值
    public static function get_token($id)
    {
        $str = md5(uniqid(md5(microtime(true)), true));
        $str = sha1($str . $id);
        return $str;
    }
    //返回JSON
    public static function json($code=0, $data=[], $message=null, $time=null) {
        if (is_array($code)){
            return json($code);
        }else{  
            return json(self::jsonArr($code, $data, $message, $time));
        }
    }

    public static function jsonArr($code=0, $data=[], $message=null, $time=null)
    {
        $event = request()->path();
        return ['code'=>$code, 'data'=>$data, 'message'=>$message, 'time'=>$time, 'event'=>$event];
    }
    // 保留两位小数
    public static function round($num, $r=2){
        return sprintf("%.".$r."f",$num);
    }
    // 上传图片
    public static function upload_img($config=[])
    {
        if(!is_array($config))$config = [];
        if(!isset($config['file'])) $config['file'] = 'file';
        if(!isset($config['exts'])) $config['exts'] = array('png', 'jpg', 'jpeg', 'gif', 'PNG', 'JPG', 'JPEG', 'GIF');
        if(!isset($config['size'])) $config['size'] = 1024 * 1024 * 5;
        if(!isset($config['fileClassify'])) $config['fileClassify'] = 'uploads';

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($config['file']);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $ds = '/';
        $info = $file->validate(['size'=>$config['size'], 'ext'=>join(',', $config['exts'])])->rule('uniqid')->move('.'. $ds . $config['fileClassify'],true,false);
        if($info){
            $filename = $info->getSaveName();
            $path = $ds.$config['fileClassify'].$ds.$filename;
            $url = request()->domain().$path;
            return self::jsonArr(0,['url'=>$url, 'path'=>$path]);
        }else{
            // 上传失败获取错误信息
          return self::jsonArr(1,null, $file->getError());
        }
    }
     /**
     * 生成excel表格数据
     * @param array $list
     * @param array $param ['id'=>['编号',20],'name'=>['姓名',20]] 标题+宽度
     * @param string $title excel 表格标题
     * @param array $del ['state'] 需要删除的字段
     * @param int $height
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function createExcel($list=[],$param=[],$title='',$del=[], $height=0,$path=false)
    {
        if(is_object($list)) $data = $list->toArray()['data'];
        else $data = $list;
        if(empty($param))$param = array_keys($data[0]);

        if(empty($height))$height = $this->excelHeight;

        // vendor('phpexcel.PHPExcel');//调用类库,路径是基于vendor文件夹的
        // vendor('phpexcel.PHPExcel.Worksheet.Drawing');
        // vendor('phpexcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
        if(!empty($data)){
            $objActSheet = $objExcel->getActiveSheet();
            $letter = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
            $i = 0;
            $arr = [];
            foreach ($param as $key=>$value){
                if(in_array($key,$del))continue;

                if(is_string($value)){
                    $param[$key] = [$value,$this->excelWidth];
                }else{
                    if(!isset($param[$key][0]))$param[$key][0] = $key;
                    if(!isset($param[$key][1]))$param[$key][1] = $this->excelWidth;
                }

                //设置表格宽度
                $objActSheet->getColumnDimension($letter[$i])->setWidth($param[$key][1]);
                //填充表头信息
                $objActSheet->setCellValue("$letter[$i]1",$param[$key][0]);

                $arr[$i] = $key;
                $i++;
            }

            //填充表格信息
            foreach($data as $index => $item) {
                $index += 2;
                $j=0;
                foreach ($arr as $a){
                    $objActSheet->setCellValueExplicit($letter[$j] . $index, $item[$a],\PHPExcel_Cell_DataType::TYPE_STRING);
                    $j++;
                }
                $objActSheet->getRowDimension($index)->setRowHeight($height);
            }
        }
        $outfile = $title.date('YmdHis', time()).rand(100,999).".xlsx";
        if($path){
            $objWriter->save('excel/'.$outfile);
            return request()->domain().'/excel/'.$outfile;
        }else{
            ob_end_clean();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="'.$outfile.'"');
            header("Content-Transfer-Encoding: binary");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            $objWriter->save('php://output');
        }
    }
  
      // 阿里云人脸识别
    public static function aliyun_face_recognition($image_url, $bool = true)
    {
        try{
            header("content-type:text/html;charset=utf-8");
            $akId = 'LTAIIBCxuCyW6qPZ';
            $akSecret = 'N951pDlM74O3o5JO6bViCZpfGIzEpF';
            //更新api信息
            //官方API   https://help.aliyun.com/knowledge_detail/53399.html
            $url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/detect";
            $rq_data['type']=0;
            $rq_data['image_url'] = $bool ? $image_url : 'http://imgsrc.baidu.com/imgad/pic/item/38dbb6fd5266d01671f6f0dc9d2bd40734fa3552.jpg';

            //$rq_data['type']=1;
            //$rq_data['content']='data:image/jpeg;base64, ';

            $options = array(
                'http' => array(
                    'header' => array(
                        'accept'=> "application/json",
                        'content-type'=> "application/json",
                        'date'=> gmdate("D, d M Y H:i:s \G\M\T"),
                        'authorization' => ''
                    ),
                    'method' => "POST", //可以是 GET, POST, DELETE, PUT
                    'content' => json_encode($rq_data) //如有数据，请用json_encode()进行编码
                )
            );
            $http = $options['http'];
            $header = $http['header'];
            $urlObj = parse_url($url);
            if(empty($urlObj["query"]))
                $path = $urlObj["path"];
            else
                $path = $urlObj["path"]."?".$urlObj["query"];
            $body = $http['content'];
            if(empty($body))
                $bodymd5 = $body;
            else
                $bodymd5 = base64_encode(md5($body,true));
            $stringToSign = $http['method']."\n".$header['accept']."\n".$bodymd5."\n".$header['content-type']."\n".$header['date']."\n".$path;
            $signature = base64_encode(
                hash_hmac(
                    "sha1",
                    $stringToSign,
                    $akSecret, true));
            $authHeader = "Dataplus "."$akId".":"."$signature";
            $options['http']['header']['authorization'] = $authHeader;
            $options['http']['header'] = implode(
                array_map(
                    function($key, $val){
                        return $key.":".$val."\r\n";
                    },
                    array_keys($options['http']['header']),
                    $options['http']['header']));
            $context = stream_context_create($options);
            $file = file_get_contents($url, false, $context );
            return self::jsonArr(0, json_decode($file, true));
        }catch(Exception $e){
            return self::jsonArr(1, $e->getMessage());
        }
    }
    // 发送短信验证码
    public static function send_sms($phone, $code){
        $aliyun = new AliyunSms();
        return $aliyun->aliyunSendSms($phone, $code);
    }
     /**
     * [idenDist 身份证识别，官网：https://market.aliyun.com/products/57124001/cmapi010401.html]
     * @param  [type] $host    [description]
     * @param  [type] $path    [description]
     * @param  [type] $method  [description]
     * @param  [type] $appcode [购买提供的code]
     * @return [array]          [查看网官返回结果]
     */
    public static function idenDist($imageSrc, $side)
    {
        if (!file_exists($imageSrc)) return ['code'=>false, 'message'=>'身份证图片文件不存在'];

        // 身份证识别
        $url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
        $appcode = "5cfdd1c9cabf45748be916b9e724020a";
        $file = $imageSrc;
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        $config = array(
            "side" => $side
        );
        if($fp = fopen($file, "rb", 0)) {
            $binary = fread($fp, filesize($file)); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        if($is_old_format == TRUE){
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );
            if(count($config) > 0){
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        }else{
            $request = array(
                "image" => "$base64"
            );
            if(count($config) > 0){
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$url, "https://")){
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);
        $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        if($httpCode == 200){
            if($is_old_format){
                $output = json_decode($rbody, true);
                $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
            }else{
                $result_str = $rbody;
            }
            $result = json_decode($result_str, true);
            return $result;
        }else{
            if($side != 'back'){
                return ['success'=>false, 'message'=>'正面未认识成功，请手动认证'];
            }else{
                return ['success'=>false, 'message'=>'反面未认识成功，请手动认证'];
            }
        }
    }
    /**
     * [idenAuth 身份证认证，官网：https://market.aliyun.com/products/57000002/cmapi028815.html#sku=yuncode2281500001]
     * @param  [type] $idCardNum [身份证件号]
     * @param  [type] $realName  [身份证姓名]
     * @param  [type] $appcode   [购买提供的code]
     * @return [type]            [查看网官返回结果]
     */
    public static function idenAuth($idCardNum, $realName)
    {
        $host = "https://simpleinfo.market.alicloudapi.com";
        $path = "/simple";
        $method = "POST";
        $appcode = "5cfdd1c9cabf45748be916b9e724020a";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "idCardNum=".$idCardNum."&realName=".$realName;
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        // 返回结果
        $result = curl_exec($curl);
        // 结果转对象 $result->code 获取
        $result = json_decode($result);
        return $result;
    }

    protected  function timeInit($starttime=null,$endtime=null)
    {
        if(empty($starttime)) $starttime = '2019-01-01 00:00:00';
        if(empty($endtime)) $endtime = '2099-01-01 00:00:00';

        if($starttime>$endtime){
            $temp = $starttime;
            $starttime = $endtime;
            $endtime = $temp;
        }
        if($starttime==$endtime){
            $starttime.= ' 00:00:00';
            $endtime.= ' 23:59:59';
        }
        if(strlen($starttime)<11)$starttime.=' 00:00:00';
        if(strlen($endtime)<11)$endtime .=' 23:59:59';
        return [$starttime,$endtime];
    }
    private function createInvitationCodeSourceString()
    {
        return 'uZpFh5QivwLiVSpua8F2giH2sa5mllwoBVZW5WvlTNiPZWrugmecNBqZyvKsk48u';
    }
    // id生成邀请码
    protected function create_invitation_code($user_id) {
        $source_string = $this->createInvitationCodeSourceString();
        $num = $user_id;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod].$code;
        }

        if(empty($code[3]))
            $code = str_pad($code,4,'0',STR_PAD_LEFT);
        return $code;
    }
    // 邀请码反推ID
    protected function decode_invitation_code($code) {

        $source_string = $this->createInvitationCodeSourceString();

        if (strrpos($code, '0') !== false)

            $code = substr($code, strrpos($code, '0')+1);

        $len = strlen($code);

        $code = strrev($code);

        $num = 0;

        for ($i=0; $i < $len; $i++) {

            $num += strpos($source_string, $code[$i]) * pow(35, $i);

        }

        return $num;

    }

    // 获取用户合约总的折合
    protected function get_user_hy_total_zh($uid)
    {
        $ch = db('user_deal_lines_c_h')->where('type','in','1,2')->where(['user_id'=>$uid])->select();
        $zh = 0;
        foreach ($ch as $item){
            $price = $this->get_currency_jy_value($item['currency'], 2, 2, 'value');
            $zh += $item['position'] * $price / $item['multiple'];
        }
        return $zh;
    }
    // 用户合约总资产
    protected function get_user_hy_total_usdt($uid)
    {
        $user = db('user')->field('hy_usdt,hy_usdt_lock')->where(['id'=>$uid])->find();
        $zh = $this->get_user_hy_total_zh($uid);
        return $user['hy_usdt'] + $user['hy_usdt_lock'] + $zh;
    }
    // 获取用户合约总盈亏
    protected function get_user_hy_profit_loss($uid)
    {
        return db('user_deal_lines_c_h')->where(['user_id'=>$uid])->where('type','in','1,2')->sum('floating_pl');
    }
    // 持仓占用交易保证金
    protected function get_user_hy_margin($uid)
    {
        return db('user_deal_lines_c_h')->where(['user_id'=>$uid])->where('type','in','1,2')->sum('margin');
    }
    // 获取风险率
    protected function get_user_hazard_rate($uid)
    {
        // 风险率
        $margin = $this->get_user_hy_margin($uid);
        if($margin==0){
            return 0;
        }else{
            $total = $this->get_user_hy_total_usdt($uid); // 合约账户总资产
            $pl = $this->get_user_hy_profit_loss($uid); // 合约账户总亏损
            // 净值=（合约账户总资产+合约账户总亏损）
            // 风险率＝客户账户净值÷持仓占用交易保证金
            return round(($total + $pl) / $margin * 100, 4) .'%';
        }
    }
}
