<?php
/**
 * Created by PhpStorm.
 * User: machengjun
 * Date: 2018/2/8
 * Time: 下午6:16
 */
namespace App\Http\Controllers\Api\Customers;

use App\Common\Enums\HtTab;
use App\Exceptions\Api\ApiException;
use App\Http\Controllers\Controller;

use App\Modules\Enums\ErrorCode;
use App\Modules\Enums\WebsocketType;
use App\Modules\Models\CouponOrder\CouponOrder;
use App\Modules\Models\Machine\Machine;
use App\Modules\Onenet\Facades\Onenet;
use App\Modules\Onenet\Message\CommandMessage;
use App\Modules\Onenet\OnenetApi;
use App\Modules\Util\PushUtil;
use App\Repositories\Customers\MachineRepository;
use App\Repositories\Customers\PowerRepository;
use App\Repositories\Customers\RentRepository;
use App\Repositories\Customers\WeChatRepository;
use App\Repositories\Customers\WeGuideRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Yansongda\LaravelPay\Facades\Pay;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Grimzy\LaravelMysqlSpatial\Types\Point;


/**
 * Class RentController
 * @package App\Http\Controllers\Api
 */
class TestController extends Controller
{

    protected $weChat;

    protected $weGuide;
    protected $rent;
    protected $machine;
    protected $power;


    public function __construct(PowerRepository $power,WeChatRepository $weChat, WeGuideRepository $weGuide, RentRepository $rent, MachineRepository $machine)
    {
        $this->weChat = $weChat;
        $this->weGuide = $weGuide;
        $this->rent = $rent;
        $this->power = $power;
        $this->machine = $machine;


    }

    public function openMultiple(Request $request){
        $data = $request->only('mac_no','hatch_no');
        $machine_obj = Machine::where('mac_no',$data['mac_no'])->first();
        Onenet::openMultiple($machine_obj, '99999999', $data['hatch_no']);
        $res['time'] = date('Y-m-d H:i:s');
        $this->responseSuccess($res);

    }


    //555
    function index(){
        echo date('Y-m-d H:i:s');
        echo phpinfo();exit;
        $app = App();
        dd($app);
//        $machine_obj = $this->machine->get(1);
//        $machine_obj->position = new Point('120.7460761070','31.2753965207');
//        $machine_obj->save();
//        exit;


//        $app = app('wechat.mini_program');
//        $res = $app->template_message->send([
//            'touser' => 'oyd8e0R1JijysXuCTzeYfcEG59wM',
//            'template_id' => 'ivyzt64NFH5t_0TJGq8s632yob7YPNHez-kApQNrLeg',
//            'form_id'=>'wx201803070942516a6cc692d40629646007',
//            'data' => [
//                'keyword1' => 'VALUE',
//                'keyword2' => 'VALUE2',
//                'keyword3' => 'VALUE2',
//                'keyword4' => 'VALUE2',
//                'keyword5' => 'VALUE2',
//                'keyword6' => 'VALUE2',
//                'keyword7' => 'VALUE2',
//            ],
//        ]);
//        dd($res);
//        exit('sent success');
//        $spot_id=1;
//        $customer_id =1;
//        $key = HtTab::GUIDE_PERMISSION . '_' . $spot_id . '_' . $customer_id;
//        echo Redis::del($key);
//        exit;
//        $coupon = $this->rent->getAvailableFullDiscountCoupon(1, 1)->toArray();
//        dd($coupon);
//exit;
        $machine_obj = $this->machine->get(1);
//        Onenet::open($machine_obj, 222, 5);

//        dd($machine_obj);
        Onenet::openMultiple($machine_obj, 55555, [4,5]);
//test ss
        echo date('Y-m-d H:i":s');
        exit;
exit;

        $time = 24 * 60 * 60 * 3;
        $re = Redis::get('GS_2_4');
        dd($re);
        Redis::setex('GS_2_4',$time,date('Y-m-d H:i:s'));
exit;


        $where = [
            ['customer_id','=',1],
            ['expire_time','>=',date('Y-m-d H:i:s')],
            ['discount','>=',90]

        ];

        $total = 150;
        $with_where = [
            'couponType' => function ($query) {
                $query->where('discount', '<=', 150);
            },
        ];
//        $cun = CouponOrder::where($where)->whereHas('couponType', function ($query) use ($total) {
//            $query->where('discount', '<=', $total);
//        })->with('couponType')->orderBy('discount_money','asc')->get()->toArray();

        $cun = CouponOrder::where($where)->rightjoin('coupon_type','coupon_order.coupon_type_id','=','coupon_type.id')->orderBy('discount_money','desc')->get()->toArray();





        dd($cun);


        $power_no = '07E106030A000001FB';
        $power_obj = $this->power->takeOutSuccess($power_no);
        $product_obj = $this->rent->takeOutSuccess($power_obj);
        $rent_obj = $product_obj->rent()->first();
        //通知websocket
        $data = [
            'type' => WebsocketType::POWER_TAKE_OUT,
            'power_no' => $product_obj->power_no,
            'hatch_no' => $product_obj->rent_hatch_no
        ];
        PushUtil::pushWebsocketMessage($rent_obj->customer_id,$data);
    }

    /**
     * @param Request $request
     * @param MachineRepository $machine
     * @param PowerRepository $powerRepository
     * @return bool|mixed|string
     * @throws ApiException
     */
    public function manualTakeOut(Request $request, MachineRepository $machine, PowerRepository $powerRepository)
    {
        Log::info('[小程序弹出工具]: '.json_encode(['mac_no: '=>$request->input('mac_no'), 'hatch_no: '=>intval($request->input('hatch_no'))]));
        $machine = $machine->get($request->input('mac_no'), true);
        $hatch_no = intval($request->input('hatch_no'));
//        $power = $powerRepository->getPowerInfo($hatch_no, $machine->id);
        if($hatch_no<1 || $hatch_no > 60){
            return json_encode(['errno'=>ErrorCode::MANUAL_TAKE_OUT_INVALID_HATCHNO, 'msg'=>trans('maual_take_out_invalid_hatchno')]);
        }
//        if($power->status != 2){
//            return json_encode(['errno'=>ErrorCode::MANUAL_TAKE_OUT_INVALID_HATCHNO, 'msg'=>trans('maual_take_out_invalid_hatchno')]);
//        }
        $positions = array($hatch_no - 1);

        $command = '';

        $command .= 'F';

        $commandMessage = new CommandMessage($machine->he_cloud_device_id, $command, $positions);

        $onenetApi = new OnenetApi();

        $result = $onenetApi->send_data_to_edp($commandMessage->getDeviceId(), 1, 1, $commandMessage->pack());
        return $result;
    }

    public function nowTime()
    {
        return date('Y-m-d H:i:s');
    }

    public function testShell(Request $request)
    {
        for($i=1;$i <= 55; $i++){
            $res = $this->_doTestShell($request->mac_no,[$i]);
            if(!$res){
                break;
            }
            sleep(10);
        }
    }

    /**
     * 多租命令弹充电宝
     * @param Request $request
     * @return string
     */
    public function toolOpenMultiple(Request $request)
    {
        $res = $this->_doTestShell($request->mac_no,[$request->h_no]);
        if($res){
            return '成功';
        }else{
            return '失败';
        }
    }

    private function _doTestShell($mac_no, $positions)
    {
        $machine_obj = $this->machine->get( $mac_no, true);
        if(!$machine_obj){
            return false;
//            dd('无效的机柜号');
        }
        if(!$machine_obj->life){
            return false;
        }
        $command = 'Slt=';

        $count = count($positions);
        $command .= chr($count);

        foreach ($positions as $position)
        {
            $command .= chr($position);
        }

        $command .= '|';


        $hexTime = dechex(time() + 28800);

        for ($i =0 ; $i < 4; $i++)
        {
            $command .= chr(hexdec(substr($hexTime, 2 * $i, 2)));
        }
        $command .= '0000';

        $commandMessage = new CommandMessage($machine_obj->he_cloud_device_id, $command, []);

        $onenetApi = new OnenetApi();

        $result = $onenetApi->send_data_to_edp($commandMessage->getDeviceId(), 1, 0, $commandMessage->pack());

        if (empty($result) || !empty($result['errno'])) {
            return false;
        }

        return true;

    }

}