<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 滴灌通订单详情数据
 *
 * @icon fa fa-circle-o
 */
class Dgtdetaildata extends Backend
{

    /**
     * Dgtdetaildata模型对象
     * @var \app\admin\model\Dgtdetaildata
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Dgtdetaildata;

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['car'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('car')->visible(['chepaihao']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 订单详情数据上报
     */
    public function sendout(){

        $id = input('id',0);
        $info = Db::name('dgt_detail_data')->where('id',$id)->find();
        $money = $info['money'];
        $addtime = $info['datatime'];

        //车辆信息
        $car_info = Db::name('car')->where('id',$info['car_id'])->find();
        $chepaihao = $car_info['chepaihao'];

        //gps信息
        $gps_json = '';
        $gps_info = $this->getgpsinfo($car_info['chepaihao'],$car_info['chepaicolor']);
        if(is_array($gps_info) && isset($gps_info['Longitude']) && isset($gps_info['Latitude'])){
            $gps_json = json_encode([
                'Longitude' => $gps_info['Longitude'],
                'Latitude' => $gps_info['Latitude'],
            ]);
        }

        // 设置一个公钥(key)和私钥(secret)，公钥用于区分用户，私钥加密数据，不能公开
        $key = "44D1010BC0D8403D94AA35F014C0974D";
        $secret = "022BDF69C0A641008E5D70EB4E63BBCE";
        $mchId = 'BS202401243529022486';
        $store_id = 'b9f1b72b2cad493887cf';

        // 待发送的数据包

        $nowtime = $addtime;
        $batchNo = date('YmdHis',$nowtime) . $mchId;

        $data = [
            'batchNo' => $batchNo,
            'mchId' => $mchId,
            'batchDatetime' => date('Y-m-d H:i:s',$nowtime),
            'totalCount' => 1,
            'totalTurnover' => $money,
            'totalActualAmount' => $money,
            'businessDate' => date('Y-m-d',$nowtime),
            'orderDetails' => [
                [
                    'storeId' => $store_id,
                    'orderNo' => createUniqueNo('D'),
//                    'originalOrderNo' => '',
                    'completedAt' => date('Y-m-d H:i:s',$nowtime),
                    'orderType' => '00',
                    'turnover' => $money,
                    'actualAmount' => $money,
                    'tradeDetails' => [
                        [
                            'tradeName' => $chepaihao,
                            'tradeCount' => $money,
                        ]
                    ],
                    'extContentJson' => $gps_json,
                ]/*,
                [
                    'storeId' => '12506389',
                    'orderNo' => '20220981223312',
//                    'originalOrderNo' => '20220981223312',
                    'completedAt' => '2022-08-22 14:22:34',
                    'orderType' => '00',
                    'turnover' => 30,
                    'actualAmount' => 30,
                    'tradeDetails' => [
                        [
                            'tradeName' => '鲁Q123456',
                            'tradeCount' => 100,
                        ],
                    ],
                ],
                [
                    'storeId' => '12506389',
                    'orderNo' => '20220981223312',
//                    'originalOrderNo' => '20220981223312',
                    'completedAt' => '2022-08-22 14:22:34',
                    'orderType' => '00',
                    'turnover' => 40,
                    'actualAmount' => 40,
                    'tradeDetails' => [
                        [
                            'tradeName' => '鲁Q123456',
                            'tradeCount' => 100,
                        ],
                    ],
                ],*/

            ]
        ];


        $data_json =  json_encode($data,JSON_UNESCAPED_UNICODE);

        $time = $this->getMillisecond();
        $paramStr = $this->buildSignStr($data);

        $needSignStr  = $paramStr . '&key=' . $secret . '&timestamp=' . $time;

        $signStr  = base64_encode(hash_hmac('md5', $needSignStr, $secret,true));
        //dump($signStr);
//        echo 'needSignStr = [' . $needSignStr . ']' . ',sign=' .$signStr;
        $customHeader = array();
        $customHeader[] = 'Content-Type: application/json;charset=utf-8';
        $customHeader[] = 'appKey:' . $key      ;
        $customHeader[] = 'timestamp:' . $time  ;
        $customHeader[] = 'sign:' . $signStr    ;
        $customHeader[] = 'verify:HmacMd5'      ;
        $result = $this->send_post('https://sandbox.mcisaas.com/api/dock/nouser/api/oms/order/daily/order-details', $data_json,$customHeader);

        $update = [
            'times' => $info['times'] + 1,
            'sendtime' => time(),
            'content' => $data_json,
        ];
        Db::name('dgt_detail_data')->where('id',$id)->update($update);

        $this->success($result);
    }

    private function getgpsinfo($chepaihao = '',$chepaicolor = '')
    {
        $url = 'http://140.210.193.143:8088/topgps/services/TopDataService.ashx';
        $url = 'http://ads.cetgps.com/topgps/services/TopDataService.ashx';

        $request = [
            'Action' => 'GetVehicleGpsInfo',
            'UserId' => 'dxqc',
            'Pwd' => strtoupper(md5('134679aA#')),
            'Vehicles' => [
                [
                    'PlateNum' => $chepaihao,
                    'ColorCode' => $chepaicolor,
                ],
            ],
            'NeedAddress' => '1',
        ];

        $curl_data = ['request'=>json_encode($request)];
        $result = curl_post($url,$curl_data);

        //$result = '{"Ret":0,"Msg":"","Data":[{"PlateNum":"川AA80498","ColorCode":"5","GpsTime":"2024/1/17 15:04:13","Mileage":"50805.90","Speed":"5.5","Longitude":"104.045393","Latitude":"30.646638","Address":"四川省成都市武侯区武侯祠大街231-2号 成都武侯祠博物馆南272米","Direction":"94","Altitude":"463","IsGpsValid":"1","AlarmInfo":"","StateInfo":"ACC开;定位;运营;","DriverLicense":"","DriverName":"","OrgName":"成都登欣汽车服务有限公司"}],"Datal":[]}';

        $data = [];


        $result = json_decode($result,true);
        if(is_array($result) && isset($result['Ret']) && $result['Ret'] == 0){

            if(isset($result['Data'][0])){
                $data0 = $result['Data'][0];
                unset($data0['DriverLicense']);
                unset($data0['DriverName']);
                unset($data0['OrgName']);


            }
        }

        //dump($data);
        return $data0;
    }


    private function buildSignStr($data) {

        $paramStr = '';
        $array = [];

        foreach ($data as $key => $value) {
            $array[] = $key;
        }

        sort($array);

        foreach ($array as $key) {

            $value = $data[$key];

            if ($key === 'sign' || is_null($value) || $value === '') {
                continue;
            }
            if(is_array($value)){
                $paramStr .=  $key;
                $paramStr .=  '=';
                $paramStr .= '[';
                $paramStr .= $this->buildArray($value);
                $paramStr .= ']';
            }else {
                $paramStr .= implode('=', [$key, $value]);
            }

            $paramStr .='&';
        }

        if($paramStr == ''){
            return '';
        }
        return substr($paramStr,0,strripos($paramStr,'&'));
    }


    private function buildArray($data){

        $paramStr = '';

        foreach($data as $item){
            $paramStr .= '{';
            foreach($item as $field => $val){
                if(is_array($val)){
//                    dump( __LINE__ );
                    $paramStr .=  $field;
                    $paramStr .=  '=';
                    $paramStr .= '[';
                    $paramStr .= $this->buildArray($val);
                    $paramStr .= '], ';
                }else{
//                    dump( __LINE__ );
                    $paramStr .= $field.'='.$val.', ';
                }
            }
            $paramStr = substr($paramStr,0,-2);
            $paramStr .= '}, ';
        }

        if($paramStr == ''){
            return '';
        }
        return substr($paramStr,0,strripos($paramStr,','));
    }

    private function buildobject($data){
        $paramStr = '';

        foreach($data as $field => $val){
            $paramStr .= $field.'='.$val.', ';
        }

        //$paramStr = substr($paramStr,0,-2);

        return substr($paramStr,0,strripos($paramStr,','));
    }

    private function send_post($url, $postdata,$header) {
        $rs = curl_post($url,$postdata,$header,900);
        return $rs;

        /* $options = array(
             'http' => array(
                 'method' => 'POST',
                 'header' =>  $header,
                 'content' => $postdata,
                 'timeout' => 15 * 60 // 超时时间（单位:s）
             )
         );
         $context = stream_context_create($options);
         return file_get_contents($url, false, $context);*/
    }
    /**
     * 获取时间戳到毫秒
     * @return bool|string
     */
    private function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime,0,13);
    }

    private function get_batch_no(){
        $batch_id = Db::name('dgt_batchid_log')->order('id desc')->value('batch_id');
        $batch_id += 1;

        if($batch_id > 999999){
            $batch_id = 1;
        }
        Db::name('dgt_batchid_log')->insertGetId(['batch_id'=>$batch_id]);

        $zero_arr = [
            1 => '00000',
            2 => '0000',
            3 => '000',
            4 => '00',
            5 => '0',
            6 => '',
        ];

        $xuliehao = $zero_arr[strlen($batch_id)].$batch_id;

        $mchId = 'BS202401243529022486';
        $batchNo = date('Ymd',time()) . $xuliehao . $mchId;

        return $batchNo;
    }



}
