<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Support\Facades\DB;
use App\Laravue\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\DevicesController;
use Illuminate\Support\Facades\Config;
use App\Http\Controllers\Auth\SwooleCommandMeTcpController;
use App\Http\Controllers\SmsailiyunController;
use Illuminate\Support\Facades\Log;

class  ZehongTcpController extends Controller
{

    //获取 tcp 上传数据
    public function swooletcplist($data = '')
    {
        if ($data != '') {
            return $this->substrdata($data);
        }
    }

//    解开数据包
    protected function substrdata($data)
    {
        if (is_string($data) && strlen($data) == 26) {
            $deviceId = substr($data, 0, 15); // 设备编号
            $status = substr($data, 15, 1); // 状态
            $devicenp = substr($data, 16, 3); // 浓度
            $devicefamen = substr($data, 19, 1);
            $devicechongqi = substr($data, 20, 1);
            $devicezijian = substr($data, 21, 1);
            $devicecrc = substr($data, 22, 4);
            $isdata = substr($data, 0, 22);
//            return $this->jsonSuccessData([$this->getPrc($isdata),$devicecrc]);
            if ($this->getPrc($isdata) == $devicecrc) {
                $data = ['id' => $deviceId, 'status' => $status, 'np' => $devicenp, 'famen' => $devicefamen, 'chongqi' => $devicechongqi, 'zijian' => $devicezijian];
                $totcp = json_decode($this->mysqldb($data), true);
                if ($totcp == "No equipment") {
                    return $totcp;
                }
                $totcpdata = $totcp['devicenum'] . $totcp['device_control'] . $devicechongqi . $devicezijian;
                $crcdata = $this->getPrc($totcpdata);
                return $totcpdata . $crcdata;
            }
        } else {
            return "Data format error";
        }
    }

    //解出prc
    protected function getPrc($msg)
    {
        /**
         * If your input string is HEX-formatted you should comment #15 line
         * for example: $msg="0123" equals   to 0x0123 without leading 0x
         */

        //conversion input string to plain HEX string. See comment above
        $msg = bin2hex($msg);
        //pack HEX-formatted $msg to the pure HEX array
        $data = pack('H*', $msg);
        //initialize crc as start HEX value;
        $crc = 0xFFFF;
        //loop $data array of HEX bytes
        for ($i = 0; $i < strlen($data); $i++) {
            //xor bits in the first byte of HEX value
            $crc ^= ord($data[$i]);
            //loop to shift every of 8 bits
            for ($j = 8; $j != 0; $j--) {
                //shift bits to the right and xor with polynome
                if (($crc & 0x0001) != 0) {
                    $crc >>= 1;
                    $crc ^= 0xA001;
                } else $crc >>= 1;
            }
        }
        //return the result as HEX-formatted string
        $data = strrev(sprintf('%04X', $crc));
        $crc1 = strrev(substr($data, 0, 2));
        $crc2 = strrev(substr($data, 2, 2));
        return $crc1 . $crc2;
    }

    //获取上报数据从数据库查询
    public function mysqldb($data)
    {
        if ($data != []) {
            // 报警提醒
            $meTcp = new SwooleCommandMeTcpController();
            $alarmData = $data['id'] . '/' . $data['status'] . '/' . $data['np'];
            $meTcp->swooletcplist($alarmData);
            $this->smsphone($data);
            $datainfo = DB::table('device')
                ->where('devicenum', '=', $data['id'])
                ->update(['nd' => intval($data['np']), 'devicepolice' => $data['status'] == 0 ? '1' : $data['status'], 'update_time' => time(), 'shutoff_status' => $data['famen']]);
            $todata = DB::table('device')
                ->where('devicenum', '=', $data['id'])
                ->select('devicenum', 'nd', 'device_control', 'devicepolice')
                ->first();
            if ($todata) {
                return json_encode($todata);
            } else {
                return json_encode("No equipment");
            }

        }
    }

    // 发送手机报警信息
    public function smsphone($data)
    {
        if (Redis::get($data['id']) == '') {
            if ($data['status'] > 1) {
                $sms = new SmsailiyunController();
                $code1 = json_encode($sms->sendSms());
                $code = json_decode($code1,true);
                Log::channel('slack')->info('短信发送初始化 =>' . $code1 . '设备号=>' . $data['id']);
                if ($code['Message'] == 'OK' && $code['Code'] == 'OK') {
                    Redis::set($data['id'], $code1);
                    Log::channel('slack')->info('短信发送结束 =>' . $code1 . '设备号=>' . $data['id']);
                }
            }
        } else {
            if ($data['status'] == 1 || $data['status'] == 0) {
                Log::channel('slack')->info('设备正常 =>' . '' . '设备号=>' . $data['id']);
                Redis::del($data['id']);
            }
        }
    }
}
