<?php
declare (strict_types=1);

namespace app\controller;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use think\facade\Db;
use think\Request;

class User
{

    public function index()
    {

        $table = 'zxc_user';

        $count = Db::table($table)->select()->count();
        $list = Db::table($table)->paginate(20, $count)->toArray();
        $i = 0;
        foreach ($list['data'] as $ll) {
            $list['data'][$i]['account'] = round($list['data'][$i]['account'], 2);
            $i += 1;
        }
        return json($list);
    }


    public function user_all()
    {


        $count = Db::table('zxc_user')->select();
        return json($count);
    }


    public function read($message = '')
    {
        $count = Db::table('zxc_user')->select()->count();
        $list = Db::table('zxc_user')->where('phone|openid', 'like', '%' . $message . '%')->paginate(20, $count);

        return json($list);
    }

    public function UpdateDiscount($message)
    {
        $time = date("Y-m-d H:i:s");
        Db::table('discount')->where('id', 1)->update(['message' => $message, 'update_time' => $time]);
        return json(['code' => '更新成功']);
    }

    public function DiscountInfo()
    {
        $message = Db::table('discount')->where('id', 1)->value('message');
        return json(['code' => '200', 'message' => $message]);
    }


    public function UserEdit($openid, $username, $phone, $sex, $location_area, $address)
    {
        $table = 'zxc_user';
        $data = ['username' => $username,
            'phone' => $phone,
            'sex' => $sex,
            'address' => $address];

        $update = Db::table($table)->where('openid', $openid)->update($data);
        if ($update != 0) {
            return json(['code' => 200, 'message' => '更新成功']);
        } else {
            return json(['code' => 1, 'message' => '没有更新']);
        }

    }

    public function UserInfo($openid)
    {

        $table = 'zxc_user';
        $info = Db::table($table)->where('openid', $openid)->field('username,sex,phone,address')->find();
        $location_area = Db::table($table)->where('openid', $openid)->value('location_area');
        if (!empty($location_area)) {
            $location_area = explode('-', $location_area);
        }
        $info['location_area'] = $location_area;
        return json(['code' => 200, 'message' => '请求成功', 'data' => $info]);
    }


    public function area()
    {
        $area = Db::table('area')->select();
        return json($area);
    }

    public function StationPrice(Request $request)
    {
        $data = $request->param();
        $where = [];
        if (isset($data['station_number']) && !empty($data['station_number'])) {
            $where['charge_station_number'] = ['=', $data['station_number']];
        }


        $info = Db::table('charge_station')->where($where)->where('charge_station_id', 19)->field('*')->find();

        // if ($info['station_type'] == 0) {
        $station_type = '快充';
        // } else {
        $station_type = '慢充';
        // }
        $ElectricityFee = str_replace('电费:', '', $info['ElectricityFee']);
        $Elect = explode(',', $ElectricityFee);
        for ($index = 0; $index < count($Elect); $index++) {
            $kk['time_interval'] = substr($Elect[$index], 0, 11);
            $kk['univalence'] = explode(':', $Elect[$index])[3];
            $ss[] = $kk;
        }
        $ServiceFee = str_replace('服务费:', '', $info['ServiceFee']);
        $Server = explode(',', $ServiceFee);
        for ($index = 0; $index < count($Server); $index++) {
            $ll['time_interval'] = substr($Server[$index], 0, -5);
            $ll['univalence'] = substr($Server[$index], Strlen($Server[$index]) - 4);
            $mm[] = $ll;

        }
        $info2 = Db::table('charge_station')->select();
        return json(['code' => 2000, 'Station_Type' => $station_type, 'ElectricityFee' => $ss, 'ServiceFee' => $mm, 'yuan' => $info2]);
    }

    public function StationPriceUpdate($station_number, $time_interval, $univalence)
    {
        $time_interval = preg_replace("/\s|　/", "", $time_interval);;
        $univalence = preg_replace("/\s|　/", "", $univalence);;
        $time_interval = str_replace('[', '', $time_interval);
        $time_interval = str_replace("'", "", $time_interval);
        $time_interval = str_replace('"', '', $time_interval);
        $time_interval = str_replace(']', '', $time_interval);
        $univalence = str_replace('[', '', $univalence);
        $univalence = str_replace(']', '', $univalence);
        $univalence = str_replace("'", "", $univalence);
        $univalence = str_replace('"', '', $univalence);
        $time_interval = explode(",", $time_interval);
        $univalence = explode(",", $univalence);
        $z = array();
        $ss = '';
        $station_type = \app\model\ChargeStation::where('charge_station_number', $station_number)->value('station_type');
        for ($i = 0; $i < count($time_interval); $i++) {
            if ($station_type != 1) {
                $z[$i] = $time_interval[$i] . ':' . number_format((float)($univalence[$i]), 6);
                if ($i != 7) {
                    $ss .= $z[$i] . ',';
                } else {
                    $ss .= $z[$i];
                }
            } else {
                $z[$i] = $time_interval[$i] . ':' . number_format((float)$univalence[$i], 6);
                $ss .= $z[$i];
            }
        }
        $last = '电费:' . $ss;
        \app\model\ChargeStation::where('charge_station_number', $station_number)->update(['ElectricityFee' => $last]);
        return json(['code' => 200, 'message' => '修改成功']);

    }

    protected function getLen($num)
    {

        $pos = strrpos($num, '.');
        $ext = substr($num, $pos + 1);
        $len = strlen($ext);
        return $len;
    }

    public function WxLogin()
    {
        $code = input('code');
        $res = getWxMessage($code);

        $userInfo = Db::table('zxc_user')->where('openid', $res['openid'])->find();

        $time = date('Y-m-d H:i:s', time());
        if (!$userInfo) {

            $data = ['openid' => $res['openid'], 'createtime' => $time];
            $id = Db::table('zxc_user')->insertGetId($data);

        } else {
            $id = $userInfo['user_id'];
        }
        Db::table('zxc_user')->where('user_id', $id)->update(['logintime' => $time]);
        $token = signToken($id);
        return json(['code' => 200, 'message' => '登录成功', 'token' => $token, 'openid' => $res['openid']]);
    }

    public function WxGetArea($openid)
    {
        $area_three = Db::table('area_three')->column('area');
        $new = array_rand($area_three);
        $area = $area_three[$new];
        $userinfo = \app\model\User::where('openid', $openid)->value('area');
        if (empty($userinfo)) {
            $message = \app\model\User::where('openid', $openid)->value('area');
            if (empty($message)) {
                return json(['code' => 1, 'message' => '地区信息无效']);
            }
            $table_user = 'zxc_user';
            $createtime = date('Y-m-d H:i:s', time());
            $user = Db::table($table_user)->where('openid', $openid)->find();
            if (empty($user)) {
                $data = ['openid' => $openid, 'createtime' => $createtime, 'area' => $area];
                Db::table($table_user)->save($data);
                return json(['code' => 200, 'message' => '用户地区保存成功']);
            }
            return json(['code' => 200, 'message' => '用户地区保存成功']);
        } else {
            return json(['code' => 200, 'message' => '用户地区信息已存过']);
        }

    }


    public function checkToken($token)
    {
        $key = 'zbcazbc';
        $key = new Key($key, 'HS256');
        $status = array("code" => 1);
//        echo $token;
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, $key, array('HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $res['code'] = 200;
            $res['msg'] = 'OK';
            $res['data'] = $arr['data'];
            return json($res);
        } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            $status['msg'] = "签名不正确";
            return json($status);
        } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            $status['msg'] = "token失效";
            return json($status);
        } catch (\Firebase\JWT\ExpiredException $e) { // token过期
            $status['msg'] = "token失效";
            return json($status);
        } catch (Exception $e) { //其他错误
            $status['msg'] = "未知错误";
            return json($status);
        }
    }

    public function UserBalance($openid)
    {

        $table_user = 'zxc_user';

        $info = Db::table($table_user)->where('openid', $openid)->field('account,phone')->find();
        $balance = $info['account'];
        $balance = sprintf("%01.2f", $balance);
        $FrozenAccount = Db::table($table_user)->where('openid', $openid)->value('FrozenAccount');
        $FrozenAccount = sprintf("%01.2f", $FrozenAccount);
        $table = 'zxc_charge_order';
        $count = Db::table($table)->where('openid', $openid)->field('order_number,start_time,end_time,revenue,status')->count();
        $enterprise_accout = Db::table('enterprise_user')->where('phone', $info['phone'])->count();
        return json([
            'openid' => $openid,
            'balance' => $balance,
            'count' => $count,
            'FrozenAccount' => $FrozenAccount,
            'phone' => $info['phone'],
            'enterprise' => $enterprise_accout
        ]);
    }
    
    public function getMoneyLog(){
        $result = Db::table('zxc_user_money_log')->where('openid',input('openid'))->order('id desc')->select();
        return json($result);
        
    }

// 企业相关

    /**
     * 获取企业信息
     *
     */
    public function getEnterpriseInfo($phone)
    {

        $enterprise_user = Db::table('enterprise_user')->where('phone', $phone)->find();
        if ($enterprise_user) {
            $enterprise = Db::table('enterprise')->where('id', $enterprise_user['enterprise_id'])->find();
            $enterprise['is_account'] = $enterprise_user['group_id'] == 1 ? false : true;
            $enterprise['enterprise_user_id'] = $enterprise_user['id'];
            return json($enterprise);
        }
        return json([]);

    }

    // 充值记录
    public function getEnterpriseReangeLog()
    {
    }

    protected function generate_tuikuan($length)
    {
        $chars = '0123456789';
        $time = time();
        $password = 'DZZS' . $time . 'TK';
        for ($i = 0; $i < $length; $i++) {
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }


}

function signToken($uid)
{
    $key = 'zbcazbc';
    $token = array(
        "iss" => $key,        //签发者 可以为空
        "aud" => '',          //面象的用户，可以为空
        "iat" => time(),      //签发时间
        "nbf" => time() + 3,    //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
        "exp" => time() + 1296000, //token 过期时间
        "data" => [           //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
            'uid' => $uid,
        ]
    );
//    print_r($token);
//    $keyId = "keyId";
    $jwt = JWT::encode($token, $key, "HS256");  //根据参数生成了 token
    return $jwt;
}

function getCurl($url)
{
    $headerArray = array("Content-type:application/json;", "Accept:application/json");
    $ch = curl_init();//初始化CURL
    curl_setopt($ch, CURLOPT_URL, $url);//设置访问地址
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//HTTPS访问设置 关闭监视
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//HTTPS访问设置 关闭监视访问地址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);//设置访问头部信息
    $output = curl_exec($ch);//获取结果
    curl_close($ch);//关闭连接
    $output = json_decode($output, true);//json数据转换
    return $output;
}

function getWxMessage($code)
{
    //网址,appid,appsecret都封装至配置文件中,方便后期管理

    $url = sprintf(config('wx.url'), config('wx.AppID'), config('wx.AppSecret'), $code);
    //使用封装的CURL方法
    $res = getCurl($url);
    //返回结果
    return $res;
}

function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000;
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance / 1000, 2);
}






