<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 滴灌通营业日结数据
 *
 * @icon fa fa-circle-o
 */
class Dgtdaysdata extends Backend
{

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

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

    }


    /**
     * 营业日结数据上报
     */
    public function sendout()
    {
        $id = input('id',0);
        $info = Db::name('dgt_days_data')->where('id',$id)->find();
        $money = $info['money'];
        $addtime = $info['datatime'];

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

        // 待发送的数据包
        $nowtime = $addtime;
//        $batchNo = $this->get_batch_no();
        $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,
            'dailyIncomeSummarys' => [
                [
                    'storeId' => $store_id,
                    'businessDate' => date('Y-m-d',$nowtime),
                    'storeStatus' => '1',
                    'turnover' => $money,
                    'actualAmount' => $money,
                ]/*,
                [
                    'storeId' => $store_id,
                    'businessDate' => '2021-10-30',
                    'storeStatus' => '1',
                    'turnover' => '-50.00',
                    'actualAmount' => '-50.00',
                ],
                [
                    'storeId' => $store_id,
                    'businessDate' => '2021-10-31',
                    'storeStatus' => '1',
                    'turnover' => '10855.50',
                    'actualAmount' => '9955.50',
                ],*/

            ],
        ];

        $data_json =  json_encode($data,JSON_UNESCAPED_UNICODE);
        $time = $this->getMillisecond();
        $paramStr = $this->buildSignStr($data);

        $needSignStr  = $paramStr . '&key=' . $secret . '&timestamp=' . $time;
        //dump($needSignStr);
        $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/financial-stat', $data_json,$customHeader);


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

        $this->success($result);
    }

    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;
    }


}
