<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2022/11/4
 * Time: 13:55
 */

namespace app\api\controller;


use app\admin\model\device\Chargedevice;
use app\common\controller\Api;
use app\lib\utils\Aes;
use app\admin\model\order\Order as OrderModel;
use think\Cache;
use think\Log;


class Charge extends Api{


    protected $noNeedLogin = ['gettoken','getchargeorders'];
    protected $noNeedRight = ['*'];
    private $OperatorID = "MCH000104";//平台标识
    private $OperatorSecret = "1234567890abcdef";//平台密钥
    private $commonUrl = 'http://charge.shenmachong.com';
    private $AccessToken = '';
    private $charge_header = array();


    public function _initialize(){
        parent::_initialize();
        $this->AccessToken = Cache::get('ChargeAccessToken');
        if(!$this->AccessToken){
            $this->AccessToken = $this->getToken();
        }
        $this->charge_header[] = 'Authorization:Bearer'.$this->AccessToken;
    }
    /**
     * 获取charge平台access_token
     */
    public function getToken(){
        $requestUrl = $this->commonUrl."/open/api/smcloud/v1/query_token";
        $data=[
            'OperatorID' =>$this->OperatorID,
            'OperatorSecret' =>$this->OperatorSecret,
        ];
        $strdata = json_encode($data,true);
        $strEncrypt = Aes::encrypt($strdata);//加密
        $sign_arr = [
            'OperatorID' =>$this->OperatorID,
            'Data' =>$strEncrypt,
            'TimeStamp' =>getMilliseconds(),
            'Seq' =>'0001',
        ];
        $sign_str = '';
        foreach ($sign_arr as $key => $val){
            $sign_str.=$val;
        }
        $sign = hash_hmac('md5', $sign_str, $this->OperatorSecret);//HMAC-MD5 算法
        /*$md5_key = (strlen($OperatorSecret) >64) ? pack('H32','md5') : str_pad($OperatorSecret,64,chr(0));
        $ipad = substr($md5_key,0,64)^str_repeat(chr(0x36),64);
        $opad = substr($md5_key,0,64)^str_repeat(chr(0x5C),64);
        $sign = md5($opad.pack('H32',md5($ipad.$sign_str)));*/
        $sign_arr['Sig'] =$sign;
        $header = array('Content-Type: application/json; charset=utf-8');
        $res = sendCurl($requestUrl,json_encode($sign_arr,true),$header);
        $result = json_decode($res,true);
        $result_data = Aes::decrypt($result['data']);
        $AccessToken_arr = json_decode($result_data,true);
        $AccessToken = Cache::get('ChargeAccessToken');
        if($AccessToken){
            Cache::rm('ChargeAccessToken');
        }
        Cache::set('ChargeAccessToken', $AccessToken_arr['AccessToken'], $AccessToken_arr['TokenAvailableTime']);//存入缓存
//        return $AccessToken_arr['AccessToken'];
        $this->success('获取成功',['AccessToken_arr' =>$AccessToken_arr]);
    }

    /**
     * 对接charge平台订单
     */
    public function getChargeOrders(){
        $endTime= date('Y-m-d H:i:s');
        $startTime = strtotime($endTime)-(3600*2);
        $startTime = date('Y-m-d H:i:s',$startTime);
        $params = [
            'current' =>1,
            'size' =>300,
            'startTime' =>$startTime,
            'endTime' =>$endTime,
            'timeFilter' =>'1',
            'code' =>'',
            'shellId' =>'',
            'status' =>'',
        ];
        $requestUrl = $this->commonUrl."/open/api/smcloud/v1/order/list?".http_build_query($params);
//        $header = array('Authorization:Bearer7f77f0a1268ccc653ed820ddba2b9bd6');
        $res = sendCurl($requestUrl,'',$this->charge_header);
        $res = json_decode($res,true);
        if($res['code'] === 0){
            if($res['data']['records']){
                foreach ($res['data']['records'] as $key => $val){
                    $orderinfo = OrderModel::where(['order_sn' =>$val['orderNumber']])->find();
                    if($orderinfo){
                        continue;//避免重复插入订单数据
                    }
                    if(!in_array($val['status'],[3,4,5])){
                        continue;
                    }
                    $Chargedevice = Chargedevice::where(['charge_device_sn' =>$val['shellId']])->find();
                    if(!$Chargedevice){
                        continue;
                    }
                    if(!$Chargedevice['user_id']){
                        continue;
                    }
                    $data=[
                        'order_sn' =>$val['orderNumber'],
                        'user_id' =>$Chargedevice['user_id'],
                        'mobile' =>$val['mobile'],
                        'total_price' =>$val['amount'],
                        'need_pay' =>$val['amount'],
                        'device_sign' =>$val['shellId'],
                        'order_type' =>$val['orderType'],
                        'status' =>$val['status'],
                        'createtime' =>strtotime($val['startTime']),
                        'endtime' =>strtotime($val['endTime']),
                        'billingType' =>$val['billingType'],
                        'chargingElec' =>$val['chargingElec'],
                        'chargingGroupName' =>$val['chargingGroupName'],
                        'chargingName' =>$val['chargingName'],
                        'chargingPower' =>$val['chargingPower'],
                        'chargingTime' =>$val['chargingTime'],
                        'consumeCount' =>$val['consumeCount'],
                        'consumeTime' =>$val['consumeTime'],
                        'socketCode' =>$val['socketCode'],
                        'code' =>$val['code'],
                    ];
                    OrderModel::create($data);
                    \app\admin\model\users\Users::where(['id' =>$Chargedevice['user_id']])->setInc('total_money',$val['amount']);//增加收益
                }
                Log::record(date('Y-m-d H:i:s').'ChargeOrders获取成功','debug');
                $this->success('获取成功',['data' =>$res['data']['records']]);
            }
        }else{
            Log::record(date('Y-m-d H:i:s').'ChargeOrders获取失败','debug');
            $this->error('获取失败');
        }

    }

    /**
     * 对接charge平台设备
     */



}