123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507 |
- <?php
- class WxApiAction extends Action {
-
-
- private function getHumenTime( $timeInterval ){
- if ($timeInterval < 60){
- $formatime = $timeInterval.'秒';
- }elseif($timeInterval < 60 * 60){
- $min = floor($timeInterval/60);
- $formatime = $min.'分钟';
- }elseif($timeInterval < 60 * 60 * 24){
- $h = floor($timeInterval/(60*60));
- $formatime = $h.'小时';
- }elseif($timeInterval < 60 * 60 * 24 * 30){
- $d = floor($timeInterval/(60*60*24));
- $formatime = $d.'天';
- }elseif($timeInterval < 60 * 60 * 24 * 30 * 12){
- $m = floor($timeInterval/(60*60*24*30));
- $formatime = $m.'月';
- }else{
- $y = floor($timeInterval/(60*60*24*30*12));
- $formatime = $y.'年';
- }
-
-
- return $formatime;
- }
-
-
- public function register( ){
- header('Access-Control-Allow-Origin: *');
-
- // 通过手机号和短信验证码注册
- $data = json_decode( file_get_contents("php://input") ,true);
-
- // 用户类型:个人(personal)、团体(group)
- $userType = $data['userType'];
- // 设备类型:卡牌(card)、徽章(badge)
- $deviceType = $data['deviceType'];
-
- // 团体卡牌用户(group_card_user) 不可注册
- // 个人用户(personal),团体徽章用户(group_badge_user) 可注册
- if ($userType == 'personal') { // 个人用户
- $identify = 'personal';
- } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户
- $identify = 'group_badge_user';
- } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户
- // $identify = 'group_card_user';
- json_fail('团体卡牌用户无需注册,请联系发卡人询问账号!');
- } else {
- json_fail('未知用户类型');
- }
-
- if(!$data['phone']){
- json_fail('手机号码不能为空');
- }
- if(!$data['smsCode']){
- json_fail('短信验证码不能为空');
- }
- if(! $data['password']){
- json_fail('密码不能为空');
- }
- if(! $data['confirmPassword']){
- json_fail('请输入确认密码');
- }
- if ($data['password'] != $data['confirmPassword']) {
- json_fail('两次密码不一致');
- }
-
- /*
- $cond = array(
- 'username'=>$data['phone']
- );
- $user_info = M('users')->where($cond)->join('user_has_roles ON users.id = user_has_roles.uid')->find();
- if($user_info){
- //存在用户则判断
- $role_identify=M('roles')->where(array('id'=>$user_info['role_id']))->getField('identify');
- if($role_identify==$identify){
- json_fail('该类型用户已经存在,请前往登陆');
- }
-
- }*/
- // 获取角色id
- $roleId = M('roles')->where(['identify' => $identify])->getField('id');
- if (!$roleId) {
- json_fail('未知角色类型');
- }
- // 判断角色、号码是否已注册
- $userinfo = M('users')->alias('a')->where(['username'=>$data['phone']])->join("INNER JOIN user_has_roles b ON a.id = b.uid AND b.role_id = {$roleId}")->find();
- if ($userinfo) {
- json_fail('该号码已注册');
- }
- // 验证码有效性
- $res = $this->isValidSmsCode($data['phone'], $data['smsCode']);
- if (!$res['success']) {
- json_fail($res['message']);
- }
- //if($user_info['password'] != password_hash($data['password'],PASSWORD_DEFAULT) ){
- $savePwd = password_hash($data['password'],PASSWORD_DEFAULT);
-
- $saveData = [
- 'username' => $data['phone'],
- 'realname' => '用户'.$data['phone'],
- 'password' => $savePwd,
- 'phone' => $data['phone'],
- 'created_at' => time(),
- ];
- // 个人用户给定默认部门
- if ($identify == 'personal') {
- $where = [
- 'type' => 'basic_config',
- 'field' => 'department_id',
- ];
- $department_id = M('sys_config')->where($where)->getField('fieldValue');
- if ($department_id) {
- $saveData['department_id'] = $department_id;
- }
- }
- M()->startTrans();
-
- $userid = M('users')->add($saveData);
- if(!$userid){
- M()->rollback();
- json_fail('注册失败');
- }
- $hasRoleData = [
- 'uid' => $userid,
- 'role_id' => $roleId
- ];
- $userHasRoleRes = M('user_has_roles')->add($hasRoleData);
- if(!$userHasRoleRes){
- M()->rollback();
- json_fail('注册失败');
- }
- M()->commit();
- json_success('注册成功',$userid);
-
- }
-
-
- public function login( ){
- header('Access-Control-Allow-Origin: *');
- //json_fail('登录失败');
- $openid = I('get.openid');
- if(!$openid){
- json_fail('未授权,请关闭当前页面重新进入');
- }
-
- $data = json_decode( file_get_contents("php://input") ,true);
-
-
- $identify = 'chezhu';
-
-
- $role_id = M('roles')->where(array('identify'=>$identify))->getField('id');
-
- if (!$role_id) {
- json_fail('未知用户类型');
- }
- $cond = array(
- 'username' => $data['username'],
- );
- $user_info = M('users')->alias('u')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$role_id}")->find();
- if(!$user_info){
- json_fail('账号错误');
- }
- if(!password_verify($data['password'], $user_info['password'])){
- json_fail('密码错误');
- }
- $where = array(
- 'wx_open_id' => $openid,
- 'id' => ['NEQ', $user_info['uid']],
- );
- //$result = M('users')->createSave($where,['wx_open_id'=>'']);
- $result = M('users')->where($where)->save(['wx_open_id'=>'']);
-
- if($result===false){
- json_fail('登陆失败');
- }
-
- if($user_info['wx_open_id'] != $openid){
- $update = array(
- 'wx_open_id' => $openid,
- 'last_login_ip' => $_SERVER['REMOTE_ADDR'],
- 'last_login_time' => time(),
- );
- $result = M('users')->createSave(array('id'=>$user_info['uid']),$update);
- if(!$result){
- json_fail('登陆失败');
- }
- }
- //如果当前openid与其他账号openid相同,清空其他表中openid
-
-
-
-
- $res = array(
- 'id'=>$user_info['uid'],
- 'realname'=>$user_info['realname'],
- 'avatar' => $user_info['avatar'],
- 'phone'=>$user_info['phone'],
- );
- json_success('登录成功', $res);
- }
-
-
- public function getLastPositionMulti( ){
- header('Access-Control-Allow-Origin: *');
- $userid = I('get.userid');
-
- if(!$userid){
- json_fail('未检测到用户标识');
- }
-
- $vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true);
-
- $devices=M('devices')->where(['bind_id' =>array('in',$vehiclesIds) ])->select();
- if(!$devices){
- json_fail('名下查询不到任何设备');
- }
-
-
- $resp = [];
- foreach($devices as &$locationInfo){
-
- //wifi_online_time
- //wifi_longitude
- //wifi_latitude
- //addr
- $locationInfo['isAlarm'] = $locationInfo['alarm_status'];
- $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;
-
-
- $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time'];
- $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude'];
- $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude'];
-
-
- $locationInfo['address'] = $locationInfo['address'];
-
-
-
-
-
-
- if(!$locationInfo['time']){
- $locationInfo['awayTime'] = '从未在线';
- }else{
- $timeInterval = time() - (int)$locationInfo['time'];
- $locationInfo['awayTime'] = $this->getHumenTime($timeInterval);
- }
- $lngLatAlter = new \Jms\Algo\Geometry();
-
-
- if(!$locationInfo['lat'] || !$locationInfo['lng']){
- continue;
- }
-
- $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']);
- $locationInfo['lat'] = $latLng['lat'];
- $locationInfo['lng'] = $latLng['lng'];
-
-
-
- $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']);
- array_push($resp, $locationInfo);
-
- }
- if(!$resp){
- json_fail('暂无任何设备上报过数据哦!');
- }
-
-
-
- json_success('查询成功', $resp);
- }
-
-
- private function checkLoginState( $openid, $userid ){
- $wx_open_id=M('users')->where(array('id'=>$userid))->getField('wx_open_id');
- if($wx_open_id === 'test_openid'){
- return array('status'=>true,'message'=>'');
- }
- if($wx_open_id!=$openid){
- //已被他人登录
- return array('status'=>false,'message'=>'账号可能在其他设备登录,请重新登录');
- }
- return array('status'=>true,'message'=>'');
-
- }
-
-
- public function getMyDevices( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
-
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
-
- //$vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true);
-
- //$devices=M('devices')->where(['bind_id' =>array('in',$vehiclesIds) ])->select();
-
- $list=M('vehicles')->where(array('user_id'=>$userid))->select();
-
- $type_id=M('sys_dict_type')->where(['code'=>'DeviceType'])->getField('id');
-
- foreach($list as &$val){
-
- $val['device_info']=M('devices')->where(['bind_id' =>$val['id']])->find();
- $val['department_name']=M('departments')->where(['id'=>$val['department_id']])->getField('department_name');
- $val['creator']=M('users')->where(['id'=>$val['creator_id']])->getField('username');
-
- }
- if(!$list){
- json_fail('暂无车辆');
- }
- json_success('查询成功',$list);
-
- }
-
-
- public function getAlarmList( ){
- header('Access-Control-Allow-Origin: *');
- $userid = I('get.userid');
- if(!$userid || $userid == 'undefined' || $userid == 'null'){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
- $openid = I('get.openid');
-
- //检测登录状态
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
-
-
- $imeiArr=M('devices')->where(['user_id' => $userid])->getField('imei',true);
- $page = I('get.page') ? I('get.page') : 1;
- $pageSize = 10;
- $start = ($page - 1) * $pageSize;
-
-
- $cond = [];
- $alarmType = I('get.alarmType');
- $imei = I('get.imei');
- if(!$imei){
- $cond['device_number'] = array('in',$imeiArr);
- }else{
- $cond['device_number'] = $imei;
- }
- if($alarmType){
- $cond['alarm_type'] = $alarmType;
- }
-
-
- $list = M('alarm_report')->where($cond)->limit( $start, $pageSize)->order('created_at desc')->select();
- $type_id=M('sys_dict_type')->where(array('code'=>'AlarmType'))->getField('id');
- foreach($list as &$val){
- $val['alarm_type_str']=M('sys_dict_data')->where(array('type_id'=>$type_id,'code'=>$val['alarm_type']))->getField('value');
- $val['created_at_str'] = date('Y-m-d H:i:s', $val['created_at']);
- }
- $total = M('alarm_report')->where($cond)->count() ?: 0;
-
- $resp = [
- 'list' => $list ?:[],
- 'total' => $total,
- 'pageSize' => $pageSize
- ];
- json_success('获取成功', $resp);
- }
-
-
- public function getSignaturEtc( ){
- header('Access-Control-Allow-Origin: *');
- $url = I('get.url');
- if(!$url){
- json_fail('no url');
- }
- $url = urldecode($url);
-
- $accessToken = $this->getWeixinAccessToken();
- if (!$accessToken) {
- json_fail('获取 access token 失败');
- }
- $apiTiket = $this->getJsapiTikcet($accessToken);
-
- if(is_array($apiTiket)){
- json_fail($apiTiket['errcode'].':'.$apiTiket['errmsg']);
- }
-
- $noncestr = substr(md5(time()), 0, 16);
- $timestamp = time();
- //jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value
-
- $str = 'jsapi_ticket='.$apiTiket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url;
-
- $signature = sha1($str);
-
- $data = [
- 'appId' => C('WECHAT_APPID'),
- 'timeStamp' => $timestamp,
- 'nonceStr' => $noncestr,
- 'signature' => $signature,
- 'url' => $url,
-
- 'jsapi_ticket' =>S('wx_jsapi_ticket'),
- 'accessToken' => $accessToken,
- ];
-
- json_success('get success', $data);
-
-
-
-
-
-
- }
-
-
- private function getJsapiTikcet( $accessToken ){
- $jsapiTicket = S('wx_jsapi_ticket');
-
- if(!$jsapiTicket){
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$accessToken .'&type=jsapi');
-
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
- $output = json_decode(curl_exec($ch), true);
-
- curl_close($ch);
-
- if($output['errcode'] != 0){
- return $output;
- }
- S('wx_jsapi_ticket', $output['ticket'], '7100');
- return $output['ticket'];
-
- }else{
- return $jsapiTicket;
- }
- }
-
-
- public function getGpsRoutes( ){
- header('Access-Control-Allow-Origin: *');
- $imei = I('get.imei');
- $startTime = I('get.startTime');
- $endTime = I('get.endTime');
- if(!$imei){
- json_fail('获取不到设备号');
- }
- if(!$startTime){
- json_fail('无起始时间');
- }
- if(!$endTime){
- json_fail('无结束时间');
- }
-
-
- //end_time
- //start_time
- //student_id
- //queyRouteListByStudentId
- $routeInfo = [];
- $lngLatAlter = new \Jms\Algo\Geometry();
-
- $routeInfo = queyGpsRouteListByimei($imei, $startTime, $endTime);
-
- //$routeInfo = analyzeRouteInfoGaodeBatch($routeInfo);
- $routeInfo = analyzeRouteInfoWayzBatch($routeInfo);
- $arr = [];
- foreach($routeInfo as &$v){
- $v['lat'] = $v['Latitude'];
- $v['lng'] = $v['Longitude'];
- if($v['lat']){
- array_push($arr, $v);
- }
- }
- $routeInfo =$arr;
- //$routeInfo =bmapFilterOutliers($arr);
-
-
-
-
-
- json_success('success', $routeInfo);
- }
-
-
- private function analyzeRouteInfo( $list ){
-
-
- if(!$list){
- return array();
- }
- $arr= [];
- foreach($list as $k=> $v){
- if(isset($v['WifiMacs']) && $v['WifiMacs'] !=''){
- $wifiRes =$this->requestWifiLBS($v);
- if($wifiRes['success']){
- if($wifiRes['data']['lon'] == '' || is_null($wifiRes['data']['lat'])){
- continue;
- }
- $list[$k]['Latitude'] = $wifiRes['data']['lat'];
- $list[$k]['Longitude'] = $wifiRes['data']['lon'];
- $list[$k]['SignalType'] = 'WiFi';
- $list[$k]['WifiAddress'] = $wifiRes['data']['address'];
-
- array_push($arr, $list[$k]);
- }else{
- // array_splice($list,$k,1);
- continue;
- }
- }else{
-
- $list[$k]['SignalType'] = 'GPS';
- array_push($arr, $list[$k]);
- }
- }
-
- return $arr;
- }
-
-
- private function requestWifiLBS( $routeInfo ){
-
- if(!$routeInfo){
- return array(
- 'success' => false,
- 'msg' => '空数据'
- );
- }
- if(!isset( $routeInfo['WifiMacs']) ){
- return array(
- 'success' => false,
- 'msg' => '无wifi信息'
- );
- }
-
- $WifiMacs = $routeInfo['WifiMacs'];
- $userKey = '';
- if(!$userKey){
- $userKey = 'f107b0b3a513e6e37c6fb0424bed6633';
- }
- //$url = 'http://api.cellocation.com:81/loc/?wl=' . $WifiMacs .'&output=json&coord=gcj02';
- $url = 'http://apilocate.amap.com/position?accesstype=1&imei=' . $routeInfo['DeviceNumber'] . '&macs=' . $WifiMacs . '&key=' . $userKey;
- $curl = curl_init($url);
-
- curl_setopt($curl, CURLOPT_TIMEOUT, 3);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- $response = curl_exec($curl);
-
- if (curl_errno($curl)) {
- $errmsg = curl_error($curl);
- curl_close($curl);
- return array(
- 'success' => false,
- 'msg' => $errmsg
- );
- }
-
- curl_close($curl);
- $response = json_decode($response, true);
-
- if($response['info'] != 'OK' || count($response['result']) <2 ){
- return array(
- 'success' => false,
- 'msg' => $response['info']
- );
- }
-
- $result = $response['result'];
- $location = $response['result']['location'];
- $location = explode(',', $location);
- $response = array(
- 'lon' => $location[0],
- 'lat' => $location[1],
- 'address' => $result['desc']
- );
-
-
- return array(
- 'success' => true,
- 'data' => $response
- );
-
- }
-
-
- private function registerDevice2third( $deviceImei ){
-
-
-
- $tokenInfo = $this->getThirdTokenInfo();
- if(!$tokenInfo){
- return false;
- }
-
- $postData = [
- "deviceImei" => $deviceImei,
- "phone" => "",
- "userId" => $tokenInfo['holder']
- ];
- var_dump($postData);
-
-
-
- $url = "http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/device";
- $headers[] = "Content-Type: application/json";
- $headers[] = "Authorization: ". $tokenInfo['token'];
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
- curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($postData) );
- $output = curl_exec($ch);
- curl_close($ch);
-
- if($output === false){
- $this->push_log('thirdapi_register_device_curl_error',curl_error($curl));
- return false;
- }
-
- $deviceRes = json_decode($output, ture) ;
-
- if($deviceRes['error'] || $deviceRes['code']){
- $this->push_log('thirdapi_register_device_response_error',$deviceRes);
- return false;
- }
- $this->push_log('thirdapi_register_device_response_success',$deviceRes);
- return true;
-
-
-
-
- }
-
-
- private function getThirdRoutes( $imei, $option ){
- /*
- {
- "page": 0,
- "size": 6000,
- "total": 8,
- "content": [{
- "collectDt": "2021-07-07 10:33:39",
- "receiveAt": "2021-07-07 10:33:39",
- "lat": "40.02577751048506",
- "lon": "116.35762812669113",
- "battery": 91,
- "positionType": 2,
- "imei": "71041607133",
- "isOnline": null
- }]
- }
- */
- if (!$imei) {
- $this->push_log('thirdapi_devicelocation_curl_error', 'imei 为空');
- return false;
- }
-
- $tokenInfo = $this->getThirdTokenInfo();
-
- if(!$tokenInfo){
- return false;
- }
- $pageNo = $option['pageNo'] ? $option['pageNo'] : 0;
- $pageSize = $option['pageSize'] ?$option['pageSize']: 6000;
- $startTime = isset($option['startTime']) ? $option['startTime'] * 1000 : '';
- $endTime = isset($option['endTime']) ? $option['endTime'] * 1000 : '';
- $positionTypes = $option['positionTypes'] ? $option['positionTypes']: '';
-
- $headers[] = "Content-Type: application/json";
- $headers[] = "Authorization: ". $tokenInfo['token'];
- $url = 'http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/devicedata/location/filter?imei='.$imei.'&pageNo='.$pageNo.'&pageSize='.$pageSize.'&startTime='.$startTime.'&endTime='.$endTime.'&positionTypes='.$positionTypes;
- //var_dump($url);
- $response = $this->http_get($url, $headers);
- if (!$response) {
- $this->push_log('thirdapi_devicelocation_curl_error', $response);
- return false;
- }
-
- return json_decode($response, true);
- }
-
-
- private function getThirdLocation( $imei ){
-
- if (!$imei) {
- $this->push_log('third_newlocation_curl_error', 'imei 为空');
- return false;
- }
-
- $tokenInfo = $this->getThirdTokenInfo();
-
- if(!$tokenInfo){
- return false;
- }
-
- $headers[] = "Content-Type: application/json";
- $headers[] = "Authorization: ". $tokenInfo['token'];
- $url = 'http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/devicedata/location/'.$imei;
-
- $response = $this->http_get($url, $headers);
-
- if (!$response) {
- $this->push_log('third_lastLocation_error', $response);
- return false;
- }
-
- return json_decode($response, true);
- }
-
-
- private function http_get( $url, $headers ){
- $oCurl = curl_init();
- if(!$headers){
- $headers = [];
- }
- if(stripos($url,"https://")!==FALSE){
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
- }
- curl_setopt($oCurl, CURLOPT_URL, $url);
- curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers );
- curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
- $sContent = curl_exec($oCurl);
- $aStatus = curl_getinfo($oCurl);
-
-
- if(intval($aStatus["http_code"])==200){
- curl_close($oCurl);
- return $sContent;
- }else{
- $this->push_log('thirdapi_token_curl_error',curl_error($oCurl));
- curl_close($oCurl);
- return false;
- }
- }
-
-
- public function sendSmsCode( ){
- header('Access-Control-Allow-Origin: *');
-
- $postData = json_decode(file_get_contents('php://input'), true) ?:[];
-
- if (!$postData['phone']) {
- json_fail('手机号码不能为空');
- }
- if (!preg_match('/^1[3456789]\d{9}$/', $postData['phone'])) {
- json_fail('手机号码格式不正确');
- }
-
- // 是否重置密码
- $isReset = $postData['isReset'];
-
- if ($postData['userType'] == 'personal') { // 个人用户
- $identify = 'personal';
- } elseif ($postData['userType'] == 'group' && $postData['deviceType'] == 'badge') { // 团体徽章用户
- $identify = 'group_badge_user';
- } elseif ($postData['userType'] == 'group' && $postData['deviceType'] == 'card') { // 团体卡牌用户
- $identify = 'group_card_user';
- } else {
- json_fail('暂不支持的用户类型');
- }
- // 注册时检测
- if (!$isReset && $identify == 'group_card_user') {
- json_fail('暂不支持的注册用户类型');
- }
-
- // 获取角色id
- $roleId = M('roles')->where(['identify' => $identify])->getField('id');
- // 判断角色、号码是否已注册
- $userinfo = M('users')->alias('a')->where(['username'=>$postData['phone']])->join("INNER JOIN user_has_roles b ON a.id = b.uid AND b.role_id = {$roleId}")->find();
- // 重置密码时
- if ($isReset && empty($userinfo)) {
- json_fail('该号码未注册');
- } elseif (!$isReset && $userinfo) {
- json_fail('该号码已注册');
- }
- $sms_code_mode = M('sms_verification_code'); // 短信验证码模型
- // 防盗刷IP地址检测
- $todayTime = strtotime(date('Y-m-d'));
- $where = ['access_ip' => $_SERVER['REMOTE_ADDR'], 'created_at' => ['GT', $todayTime]];
- $count = $sms_code_mode->where($where)->count();
- if ($count >= 10) {
- json_fail('已达到当日获取次数上限');
- }
-
- // 获取短信配置
- $rlyunId = M('sms_config')->where(['name' => 'rlyun'])->getField('id');
- $smsConfig = M('sms_config')->where(['pid' => $rlyunId])->getField('key,value');
- if (empty($smsConfig)) {
- json_fail('获取短信配置失败');
- }
- // 获取短信验证码模板信息
- $where = ['operator' => 'rlyun', 'code' => 'verification_code'];
- $tmpInfo = M('sms_template')->where($where)->find();
- if (empty($tmpInfo)) {
- json_fail('获取短信验证码模板信息失败');
- }
- // 生成验证码
- $code = rand(0, 9999);
- $code = str_pad($code, 4, '0',STR_PAD_LEFT);
- // 保存验证码
- $time = time();
- $saveData = [
- 'mobile' => $postData['phone'],
- 'code' => $code,
- 'access_ip' => $_SERVER['REMOTE_ADDR'],
- 'created_at' => $time,
- 'updated_at' => $time,
- ];
- M()->startTrans(); // 开启事务
- $res = $sms_code_mode->createAdd($saveData);
- if ($res === false) {
- M()->rollback();
- json_fail('发送失败,请稍后重试');
- }
-
-
- //M()->commit();
- //json_success('测试,不发短信,看数据库');
-
-
- // 发送短信验证码
- $content = str_replace('{1}', $code, $tmpInfo['content']);
- $content = str_replace('{2}', '5分钟', $content);
- $contentData = [
- 'tplno' => $tmpInfo['identify'],
- 'tpldata' => [ $code, '5分钟' ],
- //'tpldata' => $content, // error test
- 'info' => $content,
- ];
- //$res = (new \Jms\Sms\RlyuntxV100)->send($postData['phone'], $contentData, $smsConfig);
- $res = send_sms_with_config($postData['phone'], $contentData, $smsConfig);
- if (!$res['success']) {
- M()->rollback();
- $res = M('sms_send_log')->add($res['data']);
- json_fail($res['message'] ?: '发送失败');
- }
- M()->commit();
- json_success($res['message']);
- }
-
-
- public function getAlarmTypeOptions( ){
- header('Access-Control-Allow-Origin: *');
-
- $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id');
- $options = M('sys_dict_data')->field('id, value as text, code as value')->where(['type_id' => $typeid])->select();
-
-
- if(!$options){
- json_fail('获取告警选项失败');
- }
- json_success('获取选项成功', $options);
- //AlarmType
- }
-
-
- private function isValidSmsCode( $mobile, $code ){
- if (!$mobile) {
- return ['success' => false, 'message' => '手机号码不存在'];
- }
- if (!$code) {
- return ['success' => false, 'message' => '验证码不存在'];
- }
- // 根据手机号码和验证码查询最后一次验证码
- $sms_verification_code_model = M('sms_verification_code');
- $cond = [ 'mobile' => $mobile, 'code' => $code ];
- $info = $sms_verification_code_model->where($cond)->order('created_at', 'desc')->find();
- // 不存在
- if (empty($info)) {
- return ['success' => false, 'message' => '验证失败,请确保手机号码和验证码输入无误'];
- }
- // 超过时间(暂定5分钟)
- $valid_time = 60 * 5;
- if (time() - $info['created_at'] > $valid_time) {
- return ['success' => false, 'message' => '验证码已失效'];
- }
- // 超过使用次数(暂定3次)
- if ($info['use_times'] >= 3) {
- return ['success' => false, 'message' => '验证码已失效'];
- }
- // 可以使用,使用次数+1
- $cond = ['id' => $info['id']];
- $res = $sms_verification_code_model->where($cond)->setInc('use_times');
- if ($res === false) {
- return ['success' => false, 'message' => '操作失败,请重试'];
- }
- return ['success' => true, 'message' => '验证码有效'];
- }
-
-
- public function userBindDevice( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- // 通过手机号和短信验证码注册
- $data = json_decode( file_get_contents("php://input") ,true);
-
-
- // 用户类型:个人(personal)、团体(group)
- $userType = $data['userType'];
- // 设备类型:卡牌(card)、徽章(badge)
- $deviceType = $data['deviceType'];
-
- // 团体卡牌用户(group_card_user) 不可注册
- // 个人用户(personal),团体徽章用户(group_badge_user) 可注册
- if ($userType == 'personal') { // 个人用户
- $identify = 'personal';
- } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户
- $identify = 'group_badge_user';
- } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户
- $identify = 'group_card_user';
- } else {
- json_fail('未知用户类型');
- }
-
- if ($identify == 'group_card_user') {
- json_fail('无绑定设备权限');
- }
-
- //$data['imei'],$data['user_no'],$data['username']
- if(!$data['imei'] ){
- json_fail('缺少IMEI参数');
- }
- //先查询设备信息 看是否被绑定
- $where = array('imei'=>$data['imei']);
- $device_info=M('devices')->where($where)->find();
- if(!$device_info){
- json_fail('设备不存在,请确认输入无误');
- }
- if($device_info['user_id']){
- json_fail('设备已被绑定');
- }
- if ($identify == 'group_badge_user' && $device_info['device_type'] != 1 ) {
- json_fail('无法绑定该类型的设备');
- }
-
- $userType = $data['userType'];
- $device_name = '';
- if ($data['device_name']) {
- $device_name = $data['device_name'];
- } elseif ($data['username']) {
- $device_name = $data['username'];
- } else {
- $device_name = '用户'. substr($data['imei'], -4);
- }
-
- $save_data=array(
- 'device_name' => $device_name,
- 'user_id'=>$userid,
- 'use_state'=>1,
- );
- M()->startTrans();
-
- if ($identify == 'group_badge_user'){
- //团体用户 绑定设备 并绑定用户信息
- if( !$data['user_no'] || !$data['username'] ){
- json_fail('用户姓名和编号不能为空');
- }
- // 第一次绑定:将 badgeuser 中的 department_id 赋给 users 的 department_id,之后将只能绑定该部门下的设备
- // badge_cond
- $badge_cond = ['user_no'=>$data['user_no'], 'username'=>$data['username']];
- $userinfo = M('users')->where(['id'=>$userid])->find();
- if ($userinfo['department_id']) {
- $badge_cond['department_id'] = $userinfo['department_id'];
- }
- $badge_info = M('badgeuser')->where($badge_cond)->find();
- if(!$badge_info){
- json_fail('绑定用户不存在');
- }
- if ($badge_info['is_used']) {
- json_fail('该用户已绑定');
- }
- // 检测设备与用户是否在同一部门
- if ($device_info['department_id'] != $badge_info['department_id']) {
- json_fail('用户与设备所属部门不一致');
- }
- $update_data=array('is_used'=>1);
- //$badgeRes=M('badgeuser')->createSave(array('id'=>$badge_info['uid']),$update_data);
- // 修改徽章用户状态
- $badgeRes = M('badgeuser')->where(array('id'=>$badge_info['id']))->setField($update_data);
- if(!$badgeRes){
- M()->rollback();
- json_fail('绑定用户失败');
- }
- $save_data['badge_user_id']=$badge_info['id'];
- // 设置登录用户部门
- if (!$userinfo['department_id']) {
- $res = M('users')->where(['id'=>$userid])->setField(['department_id'=>$badge_info['department_id']]);
- if($res === false){
- M()->rollback();
- json_fail('设置用户部门失败');
- }
- }
- }
-
- $devRes=M('devices')->createSave(array('id'=>$device_info['id']),$save_data);
- if(!$devRes){
- M()->rollback();
- json_fail('绑定设备失败');
- }
- //未同步设备需要先同步
- if($device_info['sync_status']!=1){
- $result=$this->addToVoiceCenter($device_info['imei']);
- if(!$result['success']){
- create_log($device_info['imei'].'绑定时同步失败 message: '.$result['messaget'], 'AddVoiceCenter');
- M()->rollback();
- json_fail('绑定设备失败');
- }
- }
-
- M()->commit();
- json_success('绑定成功',$userid);
-
- }
-
-
- public function getUserFences( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
- $userid =intval(I('get.userid'));
- if(!$userid){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
-
- $field = 'id, name, fence_shape as shape, creator_id as userid, is_check_in as inFenceAlarm, is_check_out as outFenceAlarm, fence_info as fenceInfo, sent_interval';
- $res = M('fences')->field($field)->where(['creator_id' => $userid, 'fence_type' => 1])->select();
-
- if(!$res){
- json_fail('查询不到用户围栏');
- }
- foreach($res as &$v){
- $v['inFenceAlarm'] = (bool)($v['inFenceAlarm']);
- $v['outFenceAlarm'] = (bool)($v['outFenceAlarm']);
- $v['fenceInfo'] = json_decode($v['fenceInfo'], true);
- $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($v['fenceInfo']['center']['lat'], $v['fenceInfo']['center']['lng']);
- $v['fenceInfo']['center']['lat'] = $convPoint['lat'];
- $v['fenceInfo']['center']['lng'] = $convPoint['lng'];
- }
-
-
-
-
- json_success('查询成功', $res);
-
-
-
-
- }
-
-
- public function changeUserFenceAlarmStatus( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
-
- $post_data = file_get_contents('php://input');
- $post_data = json_decode($post_data, true);
-
- $fenceId = $post_data['id'];
- if(!$fenceId){
- json_fail('获取不到围栏标识,请刷新下');
- }
- $alarmType = $post_data['alarmType'];
- $value = $post_data['value'];
- if(is_null($value) ){
- json_fail('获取不到告警标识值');
- }
- $saveData = [];
- if($alarmType == 'in'){
- $saveData['is_check_in'] = $value;
- }else{
- $saveData['is_check_out'] = $value;
- }
-
- $res = M('fences')->where(['id' => $fenceId])->save($saveData);
-
- if(!res){
- json_fail('修改告警状态失败');
- }
- json_success('修改告警状态成功');
- }
-
-
- public function updateDeviceInfo( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
-
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
- $data = json_decode( file_get_contents("php://input") ,true);
- $device_id=$data['device_id'];
- if(!$device_id){
- json_fail('缺少设备ID');
- }
- $device_name=$data['device_name'];
- if(!$device_name){
- json_fail('缺少修改信息');
- }
- $cond=array('id'=>$device_id);
- $res=M('devices')->createSave($cond,array('device_name'=>$device_name));
- if(!$res){
- json_fail('修改失败');
- }
- json_success('修改成功',$list);
-
- }
-
-
- public function getSystemFences( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
- $userid =intval(I('get.userid'));
-
- if(!$userid){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
-
- $userBelongDep = M('users')->where(['id' => $userid ])->getField('department_id');
- if(!$userBelongDep){
- json_fail('查询不到用户归属组织');
- }
- $departIds = M('departments')->where(['id' => $userBelongDep ])->getField('level');
-
- if($departIds){
- $departIds = explode('-', $departIds);
- }else{
- $departIds =[];
- }
- array_push($departIds, $userBelongDep);
-
-
-
- $typeid = M('sys_dict_type')->where(['code' =>'FenceType'])->getField('id');
-
- $fenceTypeAssoc = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value');
-
-
- $fenceCond = [
- 'fence_type' => ['in', [0, 2]],
- 'departments' => ['in', $departIds]
- ];
-
- $field = 'fences.id, name, fence_shape as shape,fences.creator_id as userid, is_check_in as inFenceAlarm,fence_type, is_check_out as outFenceAlarm, fence_info as fenceInfo, departments.department_name';
-
- $res = M('fences')->field($field)
- ->join('departments on fences.departments = departments.id')
- ->where($fenceCond)
- ->select();
-
-
-
- if(!$res){
- json_fail('查询不到系统围栏');
- }
- foreach($res as &$v){
- $v['inFenceAlarm'] = (bool)($v['inFenceAlarm']);
- $v['outFenceAlarm'] = (bool)($v['inFenceAlarm']);
- $v['fence_type_text'] = $fenceTypeAssoc[$v['fence_type']];
- }
-
-
- json_success('查询成功', $res);
-
-
-
-
- }
-
-
- public function userUnbindDevice( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
- // 通过手机号和短信验证码注册
- $data = json_decode( file_get_contents("php://input") ,true);
- //$data['imei'],$data['user_no'],$data['username']
- //先查询设备信息 看是否被绑定
- if(!$data['device_id']){
- json_fail('缺少设备ID参数');
- }
- $device_info=M('devices')->where(array('id'=>$data['device_id']))->find();
- if(!$device_info){
- json_fail('设备不存在,请确认输入无误');
- }
- $save_data=array(
- 'user_id'=>'',
- 'badge_user_id'=>'',
- 'use_state'=>0,
- );
-
- M()->startTrans();
- if($device_info['badge_user_id']){
- $badRes=M('badgeuser')->createSave(array('id'=>$device_info['badge_user_id']),array('is_used'=>0));
- if(!$badRes){
- json_fail('解绑失败');
- }
- }
-
- $devRes=M('devices')->createSave(array('id'=>$device_info['id']),$save_data);
- if(!$devRes){
- M()->rollback();
- json_fail('解绑失败');
- }
- // 如果没有设备了,置空 department_id
- if (!M('devices')->where(['user_id'=>$userid])->count()) {
- $res = M('users')->where(['id'=>$userid])->setField(['department_id'=>'']);
- if($res === false){
- M()->rollback();
- json_fail('解绑失败2');
- }
- }
- M()->commit();
- json_success('解绑成功',$userid);
-
- }
-
-
- public function addUserFence( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
- $data = json_decode( file_get_contents("php://input") ,true);
- $userid =intval($data['userid']);
- if(!$userid){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
- $fenceName = $data['fenceName'];
- if(!$fenceName){
- json_fail('获取不到围栏名');
- }
-
- $fenceInfo = $data['fenceInfo'];
-
-
- if(!$fenceInfo){
- json_fail('获取不到围栏信息');
- }
- $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($fenceInfo['center']['lat'], $fenceInfo['center']['lng']);
- $fenceInfo['center']['lat'] = $convPoint['lat'];
- $fenceInfo['center']['lng'] = $convPoint['lng'];
-
- $saveData = [
- 'creator_id' => $userid,
- 'name' => $fenceName,
- 'push_users' => json_encode([$userid]),
- 'fence_shape' => 'circle',
- 'fence_type' => 1,
- 'fence_info' => json_encode($fenceInfo),
- 'created_at' => time(),
- 'created_at' => time()
- ];
-
- $res = M('fences')->add($saveData);
- if(!$res){
- json_fail('保存入库失败');
- }
- json_success('保存入库成功');
-
-
-
-
- }
-
-
- private function getWeixinAccessToken( ){
- $token = (new \Jiaruan\WxTmp())->getAccessToken();
-
- return $token;
- /*
- $appid= C('WECHAT_APPID');
- $appSecret = C('WECHAT_APPSECRET');
- $accessToken = S('wx_pub_accessToken');
- if(!$accessToken){
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appSecret);
-
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
- $output = json_decode(curl_exec($ch), true);
-
- curl_close($ch);
-
- if($output['errcode']){
- return $output;
- }
- S('wx_pub_accessToken', $output['access_token'], '7100');
- return $output['access_token'];
-
- }else{
- return $accessToken;
- }
- */
-
-
- }
-
-
- public function getAlarmRecords( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
- $openid = $post_data['openid'];
- $userid = $post_data['userid'];
-
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- // 获取登录账号部门下所有告警状态的学生数据
- $user_model = M('users');
- $where = ['id' => $userid];
- $userinfo = $user_model->field('id,department_id')->where($where)->find();
-
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取数据失败');
- }
-
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- // 告警记录条件
- // 初始化条件
- $cond = [];
- $reason = I('get.reason');
- $state = I('get.state');
- $result = I('get.result');
- if ($reason) {
- if ($reason == 'fence') {
- $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out']];
- } else {
- $cond['alarm_reason'] = $reason;
- }
- } else {
- // 默认只显示 SOS 和围栏告警记录
- $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out', 'press']];
- }
- if ($state) {
- $cond['state'] = $state;
- }
- if ($result !== '' && is_numeric($result)) {
- $cond['result'] = $result;
- }
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- // 查出总数量
- $list = [];
- $total = M('alarm_records')->where($cond)->count();
- if ($total) {
- if ($state == 'start' || $state == 'end') {
- $order = "{$state}_time desc";
- } else {
- $order = 'id desc';
- }
- $fields = 'id,device_number,alarm_reason,handler_id,start_time,end_time,state,comment,result';
- $list = M('alarm_records')->field($fields)->where($cond)->limit($limit)->page($page)->order($order)->select() ?: [];
- if (!empty($list)) {
- // alarm_reason,handler_id,result
- // 获取告警类型
- $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id');
- $reason_arr = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value');
- // 处理结果
- $result_arr = [
- 0 => '待处理',
- 1 => '已处理',
- 2 => '误报',
- ];
- // 中文转换
- foreach ($list as &$alarm) {
- $alarm['start_time'] = $alarm['start_time'] ? date('Y-m-d H:i:s', $alarm['start_time']) : '';
- $alarm['end_time'] = $alarm['end_time'] ? date('Y-m-d H:i:s', $alarm['end_time']) : '';
- if (is_array($reason_arr)) {
- $alarm['alarm_reason'] = $reason_arr[$alarm['alarm_reason']];
- }
- if (is_numeric($alarm['result'])) {
- $alarm['result'] = $result_arr[$alarm['result']];
- }
- }
- }
- }
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $list,
- ];
- json_success('获取成功', $data);
- }
-
-
- public function getAlarmDetail( ){
- header('Access-Control-Allow-Origin: *');
-
- $openid = I('get.openid');
- $userid = I('get.userid');
- if(!$userid || $userid == 'undefined' || $userid == 'null'){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- $alarm_id = I('get.id');
- if (!$alarm_id) {
- json_fail('获取告警信息失败1');
- }
- // 查出告警数据
- $where = ['id' => $alarm_id];
- $alarm_info = M('alarm_records')->where($where)->find();
- if (empty($alarm_info)) {
- json_fail('获取告警信息失败2');
- }
- $report_id = I('get.rid');
- if (!$report_id) {
- json_fail('获取告警信息失败3');
- }
- $where = ['id' => $report_id];
- $alarm_report = M('alarm_report')->where($where)->find();
- if (empty($alarm_report)) {
- json_fail('获取告警信息失败4');
- }
- $alarm_info['address']=$alarm_report['address'];
-
- // 查出设备信息
- $where = ['imei' => $alarm_info['device_number']];
- $device_info = M('devices')->where($where)->find();
- if (empty($alarm_info)) {
- json_fail('获取告警设备信息失败');
- }
- if ($device_info['online_time'] > $device_info['wifi_online_time']) {
- $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']);
- $device_info['last_location'] = $device_info['longitude'] .','. $device_info['latitude'];
- $res = bmap_geocoding($device_info['latitude'], $device_info['longitude']);
- if($res['success']){
- $device_info['address'] = $res['address'];
- }else{
- $device_info['address']='';
- }
- } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) {
- $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']);
- $device_info['last_location'] = $device_info['wifi_longitude'] .','. $device_info['wifi_latitude'];
- } else {
- $device_info['last_online_time'] = '0000-00-00 00:00:00';
- $device_info['last_location'] = '';
- $device_info['address']='';
- }
-
- // 查出设备用户
- if ($device_info['badge_user_id']) {
- $where = ['id' => $device_info['badge_user_id']];
- $user_info = M('badgeuser')->where($where)->find() ?: [];
- } else {
- $where = ['id' => $device_info['user_id']];
- $user_info = M('users')->where($where)->find() ?: [];
- }
- //if (empty($user_info)) {
- //json_fail('获取告警用户信息失败');
- //}
- // 获取紧急联系人
- $where = ['device_id' => $device_info['id']];
- $urgent_list = M('kq_urgent')->where($where)->select() ? : [];
- if (!empty($urgent_list)) {
- $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id');
- $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value');
- foreach ($urgent_list as $key => &$urgent) {
- $urgent['relationship_text'] = $ships[$urgent['relationship']];
- }
- }
- // 部门名称
- $alarm_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name');
- $alarm_info['user_info'] = $user_info;
- $alarm_info['urgent_list'] = $urgent_list;
- $alarm_info['device_info'] = $device_info;
- $alarm_info['device_info']['department_name'] = $alarm_info['department_name'];
-
- json_success('获取成功', $alarm_info);
- }
-
-
- public function handleAlarm( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
-
- $openid = I('get.openid');
- $userid = I('get.userid');
- if(!$userid || $userid == 'undefined' || $userid == 'null'){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- // result 1-出警,2-误报
- if (!$post_data['result']) {
- json_fail('处理结果不能为空');
- }
- if (!$post_data['comment']) {
- json_fail('处理原因不能为空');
- }
- if (!$post_data['id']) {
- json_fail('未获取到告警信息1');
- }
- $time = time();
-
- M()->startTrans();
-
- // 修改前,检测结果是否一致,如果一致不允许重复操作
- $records_model = M('alarm_records');
- $where = ['id' => $post_data['id']];
- $record_info = $records_model->where($where)->field('device_number,result')->find();
- if (empty($record_info)) {
- json_fail('未获取到告警信息2');
- }
- //if ($record_info['result'] > 0) {
- if ($record_info['result'] == $post_data['result']) {
- M()->rollback();
- json_fail('已处理,请勿重复操作');
- }
- $where = ['id' => $post_data['id']];
- $save_data = [
- 'comment' => $post_data['comment'],
- 'result' => $post_data['result'],
- 'handler_id' => $userid,
- 'state' => 'end',
- 'end_time' => $time,
- 'updated_at' => $time,
- ];
- $res = $records_model->createSave($where, $save_data);
- if ($res === false) {
- M()->rollback();
- json_fail('操作失败');
- }
- // 查出设备告警状态
- $where = ['imei' => $record_info['device_number']];
- $device_info = M('devices')->where($where)->field('id,alarm_state')->find();
- if ($device_info['alarm_state'] > 0) {
- // 修改设备状态
- $where = ['id' => $device_info['id']];
- $res = M('devices')->where($where)->setField('alarm_state', 0);
- if (!$res) {
- M()->rollback();
- json_fail('修改设备状态失败');
- }
- }
- M()->commit();
- json_success('操作成功');
- }
-
-
- public function editYysProfile( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- $data = json_decode( file_get_contents("php://input") ,true);
-
- $data = array_map(function($item){
- return trim($item);
- }, $data);
-
- if (!$data['nickName']) {
- json_fail('昵称不能为空');
- }
- if (!$data['phone']) {
- json_fail('手机号码不能为空');
- }
- if (!preg_match('/^[-_a-zA-Z0-9]{6,16}?$/', $data['phone'])) {
- json_fail('手机号码格式不正确');
- }
- // 修改密码
- if ($data['oldPwd']) {
- if (!$data['newPwd']) {
- json_fail('新密码不能为空');
- }
- if (!$data['confirmNewPwd']) {
- json_fail('确认密码不能为空');
- }
- if ($data['newPwd'] != $data['confirmNewPwd']) {
- json_fail('两次新密码不一致');
- }
- }
-
- $userCond = array( 'id' => $userid);
- $user_info = M('users')->where($userCond)->find();
- if(!$user_info){
- json_fail('获取用户信息失败');
- }
- if ($user_info['wx_open_id'] != $openid) {
- json_fail('账号可能被其他用户登录,请重新登录');
- }
- if ($data['oldPwd']) {
- if(!password_verify($data['oldPwd'], $user_info['password'])){
- json_fail('原密码不正确');
- }
- }
- $saveData = [
- 'realname' => $data['nickName'],
- 'phone' => $data['phone'],
- ];
- // 有原密码才能修改
- if ($data['oldPwd']) {
- $saveData['password'] = password_hash($data['newPwd'], PASSWORD_DEFAULT);
- }
- $result = M('users')->createSave($userCond, $saveData);
- if(!$result){
- json_fail('修改失败');
- }
- $respData = [
- 'id' => $user_info['id'],
- 'realname' => $data['nickName'],
- 'avatar' => $user_info['avatar'],
- 'phone' => $data['phone'],
- ];
- json_success('修改成功', $respData);
- }
-
-
- public function changeAuthorize( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
-
-
- $imei = I('get.imei');
- if(!$imei){
- json_fail('获取不到设备号');
- }
-
- $authorize = intval(I('get.authorize') );
- if($authorize !== 0 && $authorize !== 1){
- json_fail('授权状态值不合法');
- }
- $saveData = [
- 'authorize' => $authorize,
- 'updated_at' => time()
- ];
-
- $res = M('devices')->where(['imei' => $imei])->save($saveData);
- if(!res){
- json_fail('权限修改失败');
- }
- json_success('权限修改成功');
- }
-
-
- public function getDeviceInfoSingle( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
-
-
- $imei = I('get.imei');
- if(!$imei){
- json_fail('获取不到设备号');
- }
-
-
- $res = M('devices')->where(['imei' => $imei])->find();
- if(!res){
- json_fail('获取设备信息失败');
- }
- json_success('获取设备信息成功', $res);
- }
-
-
- public function getDevices( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- // 获取 POST 数据
- $post_data = json_decode(file_get_contents('php://input'), true);
-
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- $imei = $post_data['imei'];
- $list = [];
- $cond = [];
- $devices_model = M('devices');
-
- // 查出总数量
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- if ($imei) {
- $cond['imei'] = ['LIKE', "%{$imei}%"];
- }
- $total = $devices_model->where($cond)->count();
-
- if ($total) {
- $list = $devices_model->where($cond)->limit($limit)->page($page)->select() ?: [];
- }
-
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $list,
- ];
- json_success('获取成功', $data);
- }
-
-
- private function getYysLoginUserinfo( ){
- header('Access-Control-Allow-Origin: *');
-
- $openid = I('get.openid');
- if(!$openid){
- json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
- }
- // 微信运营角色
- $where = ['identify' => 'wxyy'];
- $role_id = M('roles')->where($where)->getField('id');
- if (!$role_id) {
- json_fail('未开放微信运营角色');
- }
- // 获取登录账号信息
- $userid = I('get.userid');
- $cond = [
- //'u.wx_open_id' => $openid,
- 'u.id' => $userid,
- ];
- //$userinfo = M('users')->field('id,department_id')->where($where)->find();
- $userinfo = M('users')->alias('u')->field('u.*')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$role_id}")->find();
- if (!$userinfo) {
- json_fail('获取用户信息失败,请重新登录');
- }
- if ($userinfo['wx_open_id'] != $openid) {
- json_fail('账号可能在其他设备登录,请重新登录');
- }
- return $userinfo;
- }
-
-
- public function getDeviceDetail( ){
- header('Access-Control-Allow-Origin: *');
- $userid = I('get.userid');
- if(!$userid || $userid == 'undefined' || $userid == 'null'){
- json_fail('未获取到用户标识,请重新登陆');
- }
-
- $id = I('get.id');
- if (!$id) {
- json_fail('获取设备信息失败');
- }
-
- $openid = I('get.openid');
- //检测登录状态
- $res = $this->checkLoginState($openid, $userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- // 检测是否在查询权限范围
-
- // 查出设备信息
- $where = ['id' => $id];
- $device_info = M('devices')->where($where)->find() ? : [];
- if (empty($device_info)) {
- json_fail('未获取到设备信息');
- }
-
- if ($device_info['online_time'] >= $device_info['wifi_online_time']) {
- $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']);
- $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($device_info['latitude'],$device_info['longitude']);
- $device_info['last_location'] = $convPoint['lng'] .','. $convPoint['lat'];
- } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) {
- $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']);
- $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($device_info['wifi_latitude'],$device_info['wifi_longitude']);
- $device_info['last_location'] = $convPoint['lng'] .','. $convPoint['lat'];
- } else {
- $device_info['last_online_time'] = '0000-00-00 00:00:00';
- $device_info['last_location'] = '';
- }
-
- // 查出设备用户
- if ($device_info['badge_user_id']) {
- $where = ['id' => $device_info['badge_user_id']];
- $user_info = M('badgeuser')->where($where)->find() ?: [];
- } else {
- $where = ['id' => $device_info['user_id']];
- $user_info = M('users')->where($where)->find() ?: [];
- }
- //if (empty($user_info)) {
- //json_fail('获取告警用户信息失败');
- //}
- // 获取紧急联系人
- $where = ['device_id' => $device_info['id']];
- $urgent_list = M('kq_urgent')->where($where)->select() ? : [];
- if (!empty($urgent_list)) {
- $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id');
- $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value');
- foreach ($urgent_list as $key => &$urgent) {
- $urgent['relationship_text'] = $ships[$urgent['relationship']];
- }
- }
- // 部门名称
- $device_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name');
- $device_info['user_info'] = $user_info;
- $device_info['urgent_list'] = $urgent_list;
-
- json_success('获取成功', $device_info);
- }
-
-
- public function getWaitHandleAlarmCounts( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
-
- $cond = [
- 'state' => 'start',
- ];
- // 查出总数量
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- $fields = 'alarm_reason, count(alarm_reason) as count';
- $list = M('alarm_records')->where($cond)->group('alarm_reason')->getField($fields) ?:[];
-
- json_success('获取成功', $list);
- }
-
-
- public function getDevicePositionList( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
-
- $cond = [
- 'use_state' => 1,
- ];
- // 查出总数量
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- $fields = 'imei,device_name,device_type,battery_level,loc_mode,loc_ploy,online_time,longitude,latitude,wifi_online_time,wifi_longitude,wifi_latitude,alarm_state';
- $list = M('devices')->field($fields)->where($cond)->select() ?: [];
-
- $resp = [];
- foreach($list as &$locationInfo){
- //new end
-
- //wifi_online_time
- //wifi_longitude
- //wifi_latitude
- //addr
- $locationInfo['isAlarm'] = $locationInfo['alarm_state'];
- $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;
-
-
- $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time'];
- $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude'];
- $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude'];
-
- if(!$locationInfo['time']){
- $locationInfo['awayTime'] = '从未在线';
- }else{
- $timeInterval = time() - (int)$locationInfo['time'];
- $locationInfo['awayTime'] = $this->getHumenTime($timeInterval);
- }
- $lngLatAlter = new \Jms\Algo\Geometry();
-
- if(!$locationInfo['lat'] || !$locationInfo['lng']){
- continue;
- }
-
- $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']);
- $locationInfo['lat'] = $latLng['lat'];
- $locationInfo['lng'] = $latLng['lng'];
- $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']);
- array_push($resp, $locationInfo);
- }
-
- json_success('获取成功', $resp);
- }
-
-
- public function getAllFences( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
- $userid =intval(I('get.userid'));
- if(!$userid){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
-
- $field = 'id, name, fence_shape as shape, creator_id as userid, is_check_in as inAlarm, is_check_out as outAlarm, fence_info as info';
- $cond = [
- 'fence_type' => 0,
- 'creator_id' => $userid,
- '_logic' => 'OR'
- ];
- $res = M('fences')->field($field)->where($cond)->select();
-
- if(!$res){
- json_fail('查询不到可见的围栏');
- }
- foreach($res as &$v){
- $v['inAlarm'] = (bool)($v['inAlarm']);
- $v['outAlarm'] = (bool)($v['outAlarm']);
- $v['info'] = json_decode($v['info'], true);
- }
-
-
- json_success('查询成功', $res);
-
-
-
-
- }
-
-
- public function editUserFence( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
- $data = json_decode( file_get_contents("php://input") ,true);
- $userid =intval($data['userid']);
- if(!$userid){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
- $fenceId = intval($data['fenceId']);
-
- $fenceName = $data['fenceName'];
- if(!$fenceName){
- json_fail('获取不到围栏名');
- }
-
- $fenceInfo = $data['fenceInfo'];
-
-
- if(!$fenceInfo){
- json_fail('获取不到围栏信息');
- }
- $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($fenceInfo['center']['lat'], $fenceInfo['center']['lng']);
- $fenceInfo['center']['lat'] = $convPoint['lat'];
- $fenceInfo['center']['lng'] = $convPoint['lng'];
-
- $saveData = [
- 'name' => $fenceName,
- 'fence_shape' => 'circle',
- 'fence_info' => json_encode($fenceInfo),
- 'updated_at' => time()
- ];
-
- $res = M('fences')->where(['id' => $fenceId])->save($saveData);
- if(!$res){
- json_fail('保存入库失败');
- }
- json_success('保存入库成功');
-
-
-
-
- }
-
-
- public function getRelationshipList( ){
- header('Access-Control-Allow-Origin: *');
- // 查出 Relationships id
- $where = array('code' => 'Relationships');
- $type_id = M('sys_dict_type')->where($where)->getField('id');
- if (empty($type_id)) {
- json_fail('获取失败');
- }
- $where = array('type_id' => $type_id);
- $list = M('sys_dict_data')->field('code as id, value as text')->where($where)->select();
- if (empty($list)) {
- json_fail('获取失败');
- }
- json_success('获取成功', $list);
- }
-
-
- public function editProfile( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- $data = json_decode( file_get_contents("php://input") ,true);
- $data = array_map(function($item){
- return trim($item);
- }, $data);
-
- if (!$data['nickName']) {
- json_fail('昵称不能为空');
- }
- if (!$data['phone']) {
- json_fail('手机号码不能为空');
- } else {
- if (!preg_match('/^[-_a-zA-Z0-9]{6,16}?$/', $data['phone'])) {
- json_fail('手机号码格式不正确');
- }
- }
- // 修改密码
- if ($data['oldPwd']) {
- if (!$data['newPwd']) {
- json_fail('新密码不能为空');
- }
- if (!$data['confirmNewPwd']) {
- json_fail('确认密码不能为空');
- }
- if ($data['newPwd'] != $data['confirmNewPwd']) {
- json_fail('两次新密码不一致');
- }
- }
-
- $userCond = array( 'id' => $userid);
- $user_info = M('users')->where($userCond)->find();
- if(!$user_info){
- json_fail('获取用户信息失败');
- }
- if ($user_info['wx_open_id'] != $openid) {
- json_fail('账号可能被其他用户登录,请重新登录');
- }
- if ($data['oldPwd']) {
- if(!password_verify($data['oldPwd'], $user_info['password'])){
- json_fail('原密码不正确');
- }
- }
- $saveData = [
- 'realname' => $data['nickName'],
- 'phone' => $data['phone'],
- ];
- // 有原密码才能修改
- if ($data['oldPwd']) {
- $saveData['password'] = password_hash($data['newPwd'], PASSWORD_DEFAULT);
- }
- $result = M('users')->createSave($userCond, $saveData);
-
- if(!$result){
- json_fail('修改失败');
- }
- $respData = [
- 'id' => $user_info['id'],
- 'realname' => $data['nickName'],
- 'avatar' => $user_info['avatar'],
- 'phone' => $data['phone'],
- ];
- json_success('修改成功', $respData);
- }
-
-
- public function getLastPositionSingle( ){
- header('Access-Control-Allow-Origin: *');
- $imei = I('get.imei');
-
- if(!$imei){
- json_fail('服务端未检测到设备编号');
- }
-
- $locationInfo = M('devices')->where(['imei' => $imei])->find();
-
-
- if(!$locationInfo){
- json_fail('查询不到该设备当前信息哦!');
- }
-
-
-
-
-
- //wifi_online_time
- //wifi_longitude
- //wifi_latitude
- //addr
- $locationInfo['isAlarm'] = $locationInfo['alarm_status'];
- $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;;
-
- $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time'];
- $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude'];
- $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude'];
-
-
- $locationInfo['address'] = $locationInfo['address'];
-
-
-
-
- //
-
- if(!$locationInfo['time']){
- $locationInfo['awayTime'] = '从未在线';
- }else{
- $timeInterval = time() - (int)$locationInfo['time'];
- $locationInfo['awayTime'] = $this->getHumenTime($timeInterval);
- }
- $lngLatAlter = new \Jms\Algo\Geometry();
-
- $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']);
- $locationInfo['lat'] = $latLng['lat'];
- $locationInfo['lng'] = $latLng['lng'];
-
- $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']);
-
-
-
-
- json_success('查询成功', $locationInfo);
- }
-
-
- public function yysLogin( ){
- header('Access-Control-Allow-Origin: *');
- //json_fail('登录失败');
- $openid = I('get.openid');
- if(!$openid){
- json_fail('未授权,请关闭当前页面重新进入');
- }
-
- $data = json_decode( file_get_contents("php://input") ,true);
- // 微信运营角色
- $where = ['identify' => 'wxyy'];
- $role_id = M('roles')->where($where)->getField('id');
- if (!$role_id) {
- json_fail('未开放微信运营角色');
- }
- $cond = array(
- 'username' => $data['username'],
- );
- $user_info = M('users')->alias('u')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$role_id}")->find();
- if(!$user_info){
- json_fail('无登录权限或账号、密码错误');
- }
- if(!password_verify($data['password'], $user_info['password'])){
- json_fail('账号或密码错误');
- }
-
- if($user_info['wx_open_id'] != $openid){
- $update = array(
- 'wx_open_id' => $openid,
- 'last_login_ip' => $_SERVER['REMOTE_ADDR'],
- 'last_login_time' => time(),
- );
- $result = M('users')->createSave(array('id'=>$user_info['uid']),$update);
- if(!$result){
- json_fail('登陆失败');
- }
- }
- //如果当前openid与其他账号openid相同,清空其他表中openid
- /*
- $where = array(
- 'wx_open_id' => $openid,
- 'id' => ['NEQ', $user_info['id']],
- );
- $result = M('users')->createSave($where,['wx_open_id'=>'']);
- if(!$result){
- json_fail('登陆失败');
- }
- */
- $res = array(
- 'id'=>$user_info['uid'],
- 'realname'=>$user_info['realname'],
- 'avatar' => $user_info['avatar'],
- 'phone'=>$user_info['phone'],
- );
- json_success('登录成功', $res);
- }
-
-
- public function getWaitHandleAlarmData( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
- $openid = $post_data['openid'];
- $userid = $post_data['userid'];
-
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- // 获取登录账号部门下所有告警状态的学生数据
- $user_model = M('users');
- $where = ['id' => $userid];
- $userinfo = $user_model->field('id,department_id')->where($where)->find();
-
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取数据失败');
- }
-
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- // 查出告警学生id
- $cond = [
- 'alarm_status' => 1,
- ];
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- // 查出总数量
- $student_list = [];
- $total = $user_model->where($cond)->count();
- if ($total) {
- $fields = 'id,avatar,realname,sex,age,active_rfid,student_no,online_time,last_station_mac,longitude,latitude';
- $student_list = $user_model->field($fields)->where($cond)->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
- }
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $student_list,
- ];
- json_success('获取成功', $data);
- }
-
-
- private function getRightCreatorIds( $userinfo ){
- $uid = $userinfo['id'];
- $dept_id = $userinfo['department_id'];
- // 非系统角色
- $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']];
- $devides_user_ids = M('roles')->where($where)->getField('id', true);
- // 查出拥有系统角色
- $where = [
- 'uid' => $uid,
- 'role_id' => ['NOT IN', $devides_user_ids],
- ];
- $role_ids = M('user_has_roles')->where($where)->getField('role_id', true);
- if (empty($role_ids)) {
- return false;
- }
-
- $user_ids = [];
- $is_all = false; // 全部数据
- // 查出角色拥有权限
- $where = ['id' => ['IN', $role_ids]];
- $range_list = M('roles')->distinct(true)->where($where)->getField('data_range', true);
- if (empty($range_list)) {
- return false;
- }
- // 根据角色权限查出
- $depart_model = M('departments');
- foreach($range_list as $range) {
- switch ($range) {
- case '1': // 全部数据
- $is_all = true;
- break;
- case '2': // 自定义数据
- case '3': // 本人数据
- $user_ids[] = $uid;
- break;
- case '4': // 部门数据
- $user_ids = array_merge($user_ids, $this->getUserIdsByDepartmentId([$dept_id]));
- break;
- case '5': // 部门及以下数据
- // 查一下下级部门
- // REGEXP '(^76$)|(^76-)'
- //$departmentIds = $depart_model->where(['parent_id' => $dept_id])->getField('id', true);
- $cond = ['level' => ['EXP',"REGEXP '(^{$dept_id}$)|(^{$dept_id}-)'"]];
- $departmentIds = $depart_model->where($cond)->getField('id', true) ?: [];
- $departmentIds[] = $dept_id;
- $user_ids = array_merge([$uid], $this->getUserIdsByDepartmentId($departmentIds));
- break;
- default:
- break;
- }
- // 如果有全部数据 直接跳出
- if ($is_all) {
- break;
- }
- }
- if ($is_all) {
- return true;
- }
- return array_unique(array_filter($user_ids));
- }
-
-
- private function getUserIdsByDepartmentId( $id ){
- // 取出非设备用户 (roles identify not in 'personal,group_badge_user,group_card_user')
- $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']];
- $devide_role_ids = M('roles')->where($where)->getField('id', true);
- $devide_role_ids = join(',', $devide_role_ids);
-
- $cond = [
- 'u.department_id' => ['IN', $id],
- ];
- $ids = M('users')->alias('u')
- ->field('u.id')
- ->where($cond)
- ->join("INNER JOIN user_has_roles r ON u.id=r.uid AND r.role_id NOT IN ({$devide_role_ids})")
- ->select() ? : [];
-
- return array_unique(array_column($ids, 'id'));
- }
-
-
- public function getConfirmAlarmData( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
- $openid = $post_data['openid'];
- if(!$openid){
- json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
- }
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- // 获取登录账号部门下所有告警状态的学生数据
- $where = ['wx_open_id' => $openid];
- $userinfo = M('users')->field('id,department_id')->where($where)->find();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- // 查出告警学生id
- $cond = [
- 'result' => 1,
- ];
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- // 查出总数量
- $record_list = [];
-
- $alarm_handle_records_model = M('alarm_handle_records');
- $total = $alarm_handle_records_model->where($cond)->count();
- if ($total) {
- $record_list = $alarm_handle_records_model->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
- }
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $record_list,
- ];
- json_success('获取成功', $data);
- }
-
-
- public function getCancelAlarmData( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
- $openid = $post_data['openid'];
- if(!$openid){
- json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
- }
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- // 获取登录账号部门下所有告警状态的学生数据
- $where = ['wx_open_id' => $openid];
- $userinfo = M('users')->field('id,department_id')->where($where)->find();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- // 查出告警学生id
- $cond = [
- 'result' => 2,
- ];
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- // 查出总数量
- $record_list = [];
-
- $alarm_handle_records_model = M('alarm_handle_records');
- $total = $alarm_handle_records_model->where($cond)->count();
- if ($total) {
- $record_list = $alarm_handle_records_model->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
- }
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $record_list,
- ];
- json_success('获取成功', $data);
- }
-
-
- public function getFenceAlarmData( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
- $openid = $post_data['openid'];
- if(!$openid){
- json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
- }
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- // 获取登录账号部门下所有告警状态的学生数据
- $where = ['wx_open_id' => $openid];
- $userinfo = M('users')->field('id,department_id')->where($where)->find();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- // 查出围栏
- $cond = [];
- if (!$post_data['type']) {
- $cond['alarm_type'] = ['IN',['fence_in','fence_out']];
- } elseif ($post_data['type'] == 'in') {
- $cond['alarm_type'] = 'fence_in';
- } elseif ($post_data['type'] == 'out') {
- $cond['alarm_type'] = 'fence_out';
- } else {
- json_fail('未知的围栏类型');
- }
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- // 查出总数量
- $list = [];
-
- $alarm_report = M('alarm_report');
- $total = $alarm_report->where($cond)->count();
- if ($total) {
- $list = $alarm_report->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
- }
-
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $list,
- ];
- json_success('获取成功', $data);
- }
-
-
- public function getYysFences( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- $fence_type = I('get.type');
- if (!$fence_type && $fence_type !== 0 && $fence_type !== '0') {
- json_fail('未获取到围栏类型');
- }
-
- $cond = [
- 'fence_type' => $fence_type,
- ];
- // 查出总数量
- if (is_array($creator_ids)) {
- $cond['creator_id'] = ['IN', $creator_ids];
- }
- $field = 'id, name, fence_shape as shape, creator_id as userid, is_check_in as inAlarm, is_check_out as outAlarm, fence_info as fenceInfo';
- $list = M('fences')->field($field)->where($cond)->select();
-
- if(!$list){
- json_fail('暂无围栏');
- }
-
- $geometry = new \Jms\Algo\Geometry();
- foreach($list as &$v){
- $v['inAlarm'] = (bool)($v['inAlarm']);
- $v['outAlarm'] = (bool)($v['outAlarm']);
- // 坐标转换:GCJ-02 -> BD-09
- $v['fenceInfo'] = json_decode($v['fenceInfo'], true) ?:[];
- $convPoint = $geometry->convertBd09ToGcj02($v['fenceInfo']['center']['lat'], $v['fenceInfo']['center']['lng']);
- $v['fenceInfo']['center']['lat'] = $convPoint['lat'];
- $v['fenceInfo']['center']['lng'] = $convPoint['lng'];
- }
-
- json_success('获取成功', $list);
- }
-
-
- private function getRecSignature( $url ){
- header('Access-Control-Allow-Origin: *');
- $url = urldecode($url);
-
- $accessToken = $this->getWeixinAccessToken();
- if (!$accessToken) {
- return [
- 'c' => 99,
- 'm' => '获取微信accesstoken失败'
- ];
- }
- $apiTiket = $this->getJsapiTikcet($accessToken);
-
- if(is_array($apiTiket)){
- json_fail($apiTiket['errcode'].':'.$apiTiket['errmsg']);
- return [
- 'c' => $apiTiket['errcode'],
- 'm' => $apiTiket['errmsg']
- ];
- }
-
- $noncestr = substr(md5(time()), 0, 16);
- $timestamp = time();
- //jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value
-
- $str = 'jsapi_ticket='.$apiTiket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url;
-
-
- $signature = sha1($str);
-
- return [
- 'c' => 0,
- 'm' => '',
- 'v' => [
- 'appid' => C('WECHAT_APPID'),
- 'timestamp' => $timestamp,
- 'noncestr' => $noncestr,
- 'signature' => $signature,
- ]
- ];
-
-
- }
-
-
- public function addEditFence( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
-
- $id = I('get.id');
- $data = json_decode( file_get_contents("php://input") ,true) ?: [];
-
- // 围栏类型
- $fenceTypeArr = [
- 'inout' => 0, // 机构安全围栏
- 'person_inout' => 1, // 个人安全围栏
- 'sos' => 2, // SOS围栏
- ];
- if ($data['name']) {
- $data['name'] = trim($data['name']);
- }
- if ($data['fence_info']) {
- // 坐标转换:GCJ-02 -> BD-09
- $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($data['fence_info']['center']['lat'], $data['fence_info']['center']['lng']);
- $data['fence_info']['center']['lat'] = $convPoint['lat'];
- $data['fence_info']['center']['lng'] = $convPoint['lng'];
- $data['fence_info'] = json_encode($data['fence_info']);
- }
- if ($data['in_fence_time_area'] && is_array($data['in_fence_time_area'])) {
- $data['in_fence_time_area'] = json_encode($data['in_fence_time_area']);
- }
- if ($data['out_fence_time_area'] && is_array($data['out_fence_time_area'])) {
- $data['out_fence_time_area'] = json_encode($data['out_fence_time_area']);
- }
- if ($data['push_users'] && is_array($data['push_users'])) {
- foreach($data['push_users'] as &$v){
- $v = intval($v);
- }
- $data['push_users'] = json_encode($data['push_users']);
- }
- // 新增
- if (!$id) {
- if($data['name'] === ''){
- json_fail('围栏名称不能为空');
- }
- if(!$data['fence_info']){
- json_fail('未获取到围栏信息');
- }
- if (!isset($fenceTypeArr[$data['fence_type']])) {
- json_fail('未知的围栏类型');
- }
- $data['fence_shape'] = $data['fence_shape'] ?: 'circle';
- $data['fence_type'] = $fenceTypeArr[$data['fence_type']];
- $data['creator_id'] = $userinfo['id'];
- $data['departments'] = $userinfo['department_id'];
- $data['created_at'] = time();
-
- $result = M('fences')->createAdd($data);
- if (!$result) {
- json_fail('添加失败');
- }
- json_success('添加成功', $result);
- }
- // 修改
- // 获取权限范围内的用户id
- $creatorIds = $this->getRightCreatorIds($userinfo);
- $info = M('fences')->where(['id'=>$id])->find();
- if (empty($info)) {
- json_fail('获取围栏信息失败');
- }
- if (!in_array($info['creator_id'], $creatorIds)) {
- //json_fail('无修改权限');
- }
-
- unset($data['fence_type']);
-
- $cond = ['id'=>$id];
- $result = M('fences')->createSave($cond, $data);
- if(!$result){
- json_fail('保存失败');
- }
- json_success('保存成功', $id);
- }
-
-
- public function deleteYysFences( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- $id = I('get.id');
- if (!$id) {
- json_fail('参数不合法');
- }
-
- $fence_info = M('fences')->where(['id'=>$id])->find();
- if (!$fence_info) {
- json_fail('围栏不存在');
- }
-
- if ($creator_ids !== true && !in_array($fence_info['creator_id'], $creator_ids)) {
- json_fail('无权限删除该围栏');
- }
-
- $res = M('fences')->where(['id'=>$id])->delete();
- if (!$res) {
- json_fail('删除失败');
- }
- json_success('删除成功');
- }
-
-
- public function getFenceInfo( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
-
- $id = I('get.id');
- if (!$id) {
- json_fail('缺少参数');
- }
-
- $info = M('fences')->where(['id'=>$id])->find();
-
- if(!$info){
- json_fail('获取失败');
- }
-
- // GCJ-02 -> BD-09
- $info['fence_info'] = json_decode($info['fence_info'], true) ?: [];
- $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($info['fence_info']['center']['lat'], $info['fence_info']['center']['lng']);
- $info['fence_info']['center']['lat'] = $convPoint['lat'];
- $info['fence_info']['center']['lng'] = $convPoint['lng'];
-
-
- $info['in_fence_time_area'] = json_decode($info['in_fence_time_area'], true) ?: [];
- $info['out_fence_time_area'] = json_decode($info['out_fence_time_area'], true) ?: [];
- $info['push_users'] = json_decode($info['push_users'], true) ?: [];
- json_success('获取成功', $info);
- }
-
-
- public function getFenceAlarmIntervals( ){
- header('Access-Control-Allow-Origin: *');
- $userid = I('get.userid');
- $openid = I('get.openid');
- if(!$userid || $userid == 'undefined' || $userid == 'null'){
- json_fail('未获取到用户标识,请重新登陆');
- }
- //检测登录状态
- $res = $this->checkLoginState($openid, $userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
- try {
- $typeid = M('sys_dict_type')->where(['code'=>'FenceSentInterval'])->getField('id');
- $list = M('sys_dict_data')->field('value as text,code as value')->where(['type_id'=>$typeid])->select() ? : [];
- } catch (\Exception $e) {
- json_fail($e->getMessage());
- }
- json_success('获取成功', $list);
- }
-
-
- public function getRightUsers( ){
- // 获取登录用户信息
- $userinfo = $this->getYysLoginUserinfo();
- // 获取权限范围内的用户id
- $creator_ids = $this->getRightCreatorIds($userinfo);
- if ($creator_ids === false) {
- json_fail('获取失败');
- }
- $cond = [
- 'username' => ['NOT IN', 'admin,manage']
- ];
- if (is_array($creator_ids)) {
- $cond['id'] = ['IN', $creator_ids];
- }
- if ($creator_ids === true) {
- $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']];
- $devide_user_ids = M('roles')->where($where)->getField('id', true);
- $device_ids = join(',', $devide_user_ids);
- $list = M('users')->alias('u')->field('u.id,u.realname,u.phone')
- ->where($cond)
- ->distinct(true)
- ->join("INNER JOIN user_has_roles r ON u.id=r.uid AND r.role_id NOT IN ({$device_ids})")
- ->select() ?:[];
- } else {
- $list = M('users')->field('id,realname,phone')->distinct(true)->where($cond)->select();
- }
-
- json_success('获取成功', $list);
- }
-
-
- public function getUserAlarmRecords( ){
- header('Access-Control-Allow-Origin: *');
-
- $post_data = json_decode(file_get_contents('php://input'), true);
- $openid = $post_data['openid'];
- $userid = $post_data['userid'];
-
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
- $page = isset($post_data['page']) ? $post_data['page'] : 1;
- // 告警记录条件
- $where = ['user_id' => $userid];
- $device_numbers = M('devices')->where($where)->getField('imei', true);
- if (empty($device_numbers)) {
- json_fail('暂无设备,请先绑定设备');
- }
- // 初始化条件
- $cond = [
- 'device_number' => ['IN', $device_numbers],
- ];
- $reason = I('get.reason');
- $state = I('get.state');
- $result = I('get.result');
- if ($reason) {
- if ($reason == 'fence') {
- $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out']];
- } else {
- $cond['alarm_reason'] = $reason;
- }
- } else {
- // 默认只显示 SOS
- $cond['alarm_reason'] = 'press';
- }
- if ($state) {
- $cond['state'] = $state;
- }
- if ($result !== '' && is_numeric($result)) {
- $cond['result'] = $result;
- }
- // 查出总数量
- $list = [];
- $total = M('alarm_records')->where($cond)->count();
- if ($total) {
- if ($state == 'start' || $state == 'end') {
- $order = "{$state}_time desc";
- } else {
- $order = 'id desc';
- }
- $fields = 'id,device_number,alarm_reason,handler_id,start_time,end_time,state,comment,result';
- $list = M('alarm_records')->field($fields)->where($cond)->limit($limit)->page($page)->order($order)->select() ?: [];
- if (!empty($list)) {
- // alarm_reason,handler_id,result
- // 获取告警类型
- $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id');
- $reason_arr = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value');
- // 处理结果
- $result_arr = [
- 0 => '待处理',
- 1 => '已处理',
- 2 => '误报',
- ];
- // 中文转换
- foreach ($list as &$alarm) {
- $alarm['start_time'] = $alarm['start_time'] ? date('Y-m-d H:i:s', $alarm['start_time']) : '';
- $alarm['end_time'] = $alarm['end_time'] ? date('Y-m-d H:i:s', $alarm['end_time']) : '';
- if (is_array($reason_arr)) {
- $alarm['alarm_reason'] = $reason_arr[$alarm['alarm_reason']];
- }
- if (is_numeric($alarm['result'])) {
- $alarm['result'] = $result_arr[$alarm['result']];
- }
- }
- }
- }
- // 返回
- $data = [
- 'total' => $total,
- 'limit' => $limit,
- 'page' => $page,
- 'list' => $list,
- ];
- json_success('获取成功', $data);
- }
-
-
- public function getUserAlarmDetail( ){
- header('Access-Control-Allow-Origin: *');
-
- $openid = I('get.openid');
- $userid = I('get.userid');
- if(!$userid || $userid == 'undefined' || $userid == 'null'){
- json_fail('获取不到你的用户标识,请重新登陆');
- }
- //检测登录状态
- $res = $this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- $alarm_id = I('get.id');
- if (!$alarm_id) {
- json_fail('获取告警信息失败1');
- }
- // 查出告警数据
- $where = ['id' => $alarm_id];
- $alarm_info = M('alarm_records')->where($where)->find();
- if (empty($alarm_info)) {
- json_fail('获取告警信息失败2');
- }
-
- $report_id = I('get.rid');
- if (!$report_id) {
- json_fail('获取告警信息失败3');
- }
- $where = ['id' => $report_id];
- $alarm_report = M('alarm_report')->where($where)->find();
- if (empty($alarm_report)) {
- json_fail('获取告警信息失败4');
- }
- $alarm_info['address']=$alarm_report['address'];
-
- // 查出设备信息
- $where = ['imei' => $alarm_info['device_number']];
- $device_info = M('devices')->where($where)->find();
- if (empty($alarm_info)) {
- json_fail('获取告警设备信息失败');
- }
- if ($device_info['online_time'] > $device_info['wifi_online_time']) {
- $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']);
- $device_info['last_location'] = $device_info['longitude'] .','. $device_info['latitude'];
- $res = bmap_geocoding($device_info['latitude'], $device_info['longitude']);
- if($res['success']){
- $device_info['address'] = $res['address'];
- }else{
- $device_info['address']='';
- }
- } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) {
- $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']);
- $device_info['last_location'] = $device_info['wifi_longitude'] .','. $device_info['wifi_latitude'];
- } else {
- $device_info['last_online_time'] = '0000-00-00 00:00:00';
- $device_info['last_location'] = '';
- $device_info['address']='';
- }
-
- // 查出设备用户
- if ($device_info['badge_user_id']) {
- $where = ['id' => $device_info['badge_user_id']];
- $user_info = M('badgeuser')->where($where)->find() ?: [];
- } else {
- $where = ['id' => $device_info['user_id']];
- $user_info = M('users')->where($where)->find() ?: [];
- }
- //if (empty($user_info)) {
- //json_fail('获取告警用户信息失败');
- //}
- // 获取紧急联系人
- $where = ['device_id' => $device_info['id']];
- $urgent_list = M('kq_urgent')->where($where)->select() ? : [];
- if (!empty($urgent_list)) {
- $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id');
- $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value');
- foreach ($urgent_list as $key => &$urgent) {
- $urgent['relationship_text'] = $ships[$urgent['relationship']];
- }
- }
- // 部门名称
- $alarm_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name');
- $alarm_info['user_info'] = $user_info;
- $alarm_info['urgent_list'] = $urgent_list;
- $alarm_info['device_info'] = $device_info;
- $alarm_info['device_info']['department_name'] = $alarm_info['department_name'];
-
- json_success('获取成功', $alarm_info);
- }
-
-
- public function setFenceAlarmInterval( ){
- //user_has_students
- header('Access-Control-Allow-Origin: *');
-
- $fenceId = I('get.fenceId');
- $interval = intval(I('get.interval') );
- if(!$fenceId){
- json_fail('获取不到围栏标识,请刷新下');
- }
- if(!$interval){
- json_fail('获取不到时间间隔,请重设重试');
- }
- if($interval < 1 || $interval > 720){
- json_fail('推送间隔目前只支持720分钟以内');
- }
-
- $saveData = [
- 'sent_interval' => $interval
- ];
- $saveData['sent_interval'] = $interval * 60;
-
- $res = M('fences')->where(['id' => $fenceId])->save($saveData);
-
- if($res === false){
- json_fail('修改推送间隔失败');
- }
- json_success('修改推送间隔成功');
- }
-
-
- public function resetPwd( ){
- header('Access-Control-Allow-Origin: *');
-
- // 通过手机号和短信验证码注册
- $data = json_decode( file_get_contents("php://input") ,true);
-
- // 用户类型:个人(personal)、团体(group)
- $userType = $data['userType'];
- // 设备类型:卡牌(card)、徽章(badge)
- $deviceType = $data['deviceType'];
-
- // 团体卡牌用户(group_card_user) 不可注册
- // 个人用户(personal),团体徽章用户(group_badge_user) 可注册
- if ($userType == 'personal') { // 个人用户
- $identify = 'personal';
- } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户
- $identify = 'group_badge_user';
- } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户
- $identify = 'group_card_user';
- } else {
- json_fail('未知用户类型');
- }
-
- if(!$data['phone']){
- json_fail('手机号码不能为空');
- }
- if(!$data['smsCode']){
- json_fail('短信验证码不能为空');
- }
- if(! $data['password']){
- json_fail('密码不能为空');
- }
- if(! $data['confirmPassword']){
- json_fail('确认密码不能为空');
- }
- if ($data['password'] != $data['confirmPassword']) {
- json_fail('两次密码不一致');
- }
-
- // 获取角色id
- $roleId = M('roles')->where(['identify' => $identify])->getField('id');
- if (!$roleId) {
- json_fail('未知角色类型');
- }
- // 判断角色、号码是否已注册
- $userinfo = M('users')->alias('a')->field('a.id')->where(['username'=>$data['phone']])->join("INNER JOIN user_has_roles b ON a.id = b.uid AND b.role_id = {$roleId}")->find();
- if (empty($userinfo)) {
- json_fail('该号码未注册');
- }
- // 验证码有效性
- $res = $this->isValidSmsCode($data['phone'], $data['smsCode']);
- if (!$res['success']) {
- json_fail($res['message']);
- }
- // 重置密码
- $savePwd = password_hash($data['password'], PASSWORD_DEFAULT);
-
- $cond = ['id' => $userinfo['id']];
- $res = M('users')->where($cond)->setField('password', $savePwd);
- if($res === false){
- json_fail('重置失败');
- }
- json_success('重置成功');
-
- }
-
-
- public function checkSingleLogin( ){
- header('Access-Control-Allow-Origin: *');
-
- $userid = I('get.userid');
- $openid = I('get.openid');
- $where = [
- 'id' => $userid,
- 'wx_open_id'=> $openid
- ];
- $flag = M('users')->where($where)->find();
-
- if($flag){
- json_success('goon');
- }
- json_fail('relogin');
-
- }
-
-
- private function getMaxDbm( $avFile, $start ){
- /*
- $string = file_get_contents($avFile);
-
- $bytes = array();
- for($i = 0; $i < strlen($string); $i++){
- $bytes[] = ord($string[$i]);
- }
-
-
-
- $counter = strlen($string);
- */
- $counter = 4;
- $bytes = [1,2,3,4];
- $absolute = 0;
- $maximum = 0;
- for ($i = $start; $i < $counter; $i++) {
- // $absolute = abs(getShort(new byte[] {vector[i], vector[i + 1]}, 0));
- $absolute = abs( $this->bytesToShort([$bytes[$i], $bytes[$i+1]], 0) ) ;
- if ($absolute > $maximum) {
- $maximum = $absolute;
- }
- $i++;
- }
- if ($maximum > 32767) {
- $maximum = 32767;
- }
- return (int)$maximum;
- }
-
-
- public function test_cus_function( ){
- $accessKeyId='LTAIOSQ4y09Jxbf3';
- $accessKeySecret='LQm05sOLBss87lFG6jx9iq4lzKCAqA';
- $config = new \Darabonba\OpenApi\Models\Config([
- "accessKeyId" => $accessKeyId,
- "accessKeySecret" => $accessKeySecret
- ]);
- // 访问的域名
- $config->endpoint = "dysmsapi.aliyuncs.com";
- $client= new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
- $params = [
- "signName" => "小友回收",
- "templateCode" => "SMS_245515027",
- "phoneNumbers" => 15706857065,
- "templateParam" => json_encode(['code' => '1234'])
- ];
- // $client = self::createClient( $accessKeyId, $accessKeySecret);
- $sendSmsRequest = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest($params);
- $runtime = new \AlibabaCloud\Tea\Utils\Utils\RuntimeOptions([]);
- $res=$client->sendSmsWithOptions($sendSmsRequest, $runtime);
- var_dump($res);
- }
-
-
- private function bytesToShort( $bytes, $position ){
- $val = 0;
- $val = $bytes[$position + 1] & 0xFF;
- $val = $val << 8;
- $val |= $bytes[$position] & 0xFF;
- return $val;
-
- }
-
-
- public function getDeviceAvatar( ){
- header('Access-Control-Allow-Origin: *');
-
- $imei = I('get.imei');
- if(!$imei){
- json_fail('获取不到设备标识');
- }
- $avatar = M('devices')->where(['imei' => $imei])->getField('avatar');
- if(!$avatar){
- json_fail('获取头像失败');
- }
- json_success('获取头像成功',$avatar);
-
-
- }
-
-
- public function getUserAvatar( ){
- header('Access-Control-Allow-Origin: *');
-
- $uid = I('get.uid');
- if(!$uid){
- json_fail('获取不到用户标识');
- }
- $avatar = M('users')->where(['id' => $uid])->getField('avatar');
- if(!$avatar){
- json_fail('获取头像失败');
- }
- json_success('获取头像成功',$avatar);
-
- }
-
-
- public function saveDeviceAvatar( ){
- header('Access-Control-Allow-Origin: *');
-
- $postData = json_decode( file_get_contents('php://input'), true);
- if(!$postData['imei']){
- json_fail('获取不到设备标识');
- }
- if(!$postData['avatar64content']){
- json_fail('获取不到头像信息');
- }
- $folder = realpath(__ROOT__).'/static/assets/avatar/'.date('Ymd').'/';
- if (!is_dir($folder)){
- $mres= mkdir($folder,0777,true);
- if($mres === false){
- json_fail('服务端创建目录权限不足');
- }
- }
-
- $fileName = 'avatar-device-imei'.$postData['imei'] .'-'. time();
- $saveFile = $this->base64_image_content($postData['avatar64content'], $folder, $fileName);
- if(!$saveFile){
- json_fail('服务端保存头像失败');
- }
-
- $res = M('devices')->where(['imei' => $postData['imei']])->save(['avatar' => $saveFile]);
- if($res === false){
- json_fail('保存头像地址失败');
- }
- json_success('保存成功');
- }
-
-
- public function saveUserAvatar( ){
- header('Access-Control-Allow-Origin: *');
-
- $postData = json_decode( file_get_contents('php://input'), true);
- if(!$postData['uid']){
- json_fail('获取不到用户标识');
- }
- if(!$postData['avatar64content']){
- json_fail('获取不到头像信息');
- }
- $folder = realpath(__ROOT__).'/static/assets/avatar/'.date('Ymd').'/';
- if (!is_dir($folder)){
- $mres= mkdir($folder,0777,true);
- if($mres === false){
- json_fail('服务端创建目录权限不足');
- }
- }
-
- $fileName = 'avatar-user-uid'.$postData['uid'] .'-'. time();
- $saveFile = $this->base64_image_content($postData['avatar64content'], $folder, $fileName);
- if(!$saveFile){
- json_fail('服务端保存头像失败');
- }
-
- $res = M('users')->where(['id' => $postData['uid']])->save(['avatar' => $saveFile]);
- if($res === false){
- json_fail('保存头像地址失败');
- }
- json_success('保存成功');
- }
-
-
- private function base64_image_content( $base64_image_content, $path, $name ){
- //匹配出图片的格式
- if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
- $type = $result[2];
- $new_file = $path.$name.".{$type}";
- $file = 'http://'.$_SERVER['HTTP_HOST'].'/static/assets/avatar/'.date('Ymd').'/'.$name.".{$type}";
-
- if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
- return $file;
- }else{
- return false;
- }
- }else{
- return false;
- }
- }
-
-
- public function setLocModel( ){
- /*
- 请求url上带上 openid userid
- post请求 参数: imei id(设备id) post_mode 定位模式 0-常规模式 1-追踪模式 2-定时模式
-
- 定时模式:需要设置 定位采样间隔(stopped_rtc_invl) 定位上报间隔(stopped_rpt_invl)
- */
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
-
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
- $data = json_decode( file_get_contents("php://input") ,true);
- $imei=$data['imei'];
- if(!$imei){
- json_fail('缺少设备imei号');
- }
- $config['pos_mode']=$data['pos_mode'];
- if(!isset($config['pos_mode']) || $config['pos_mode'] === ''){
- json_fail('缺少定位模式');
- }
- $dev_id=$data['id'];
- if(!$dev_id){
- json_fail('缺少设备id');
- }
- $redis = Redis('c61_gps_device_configs_'.$imei,"queue");
- //开启事务
- M()->startTrans();
- $config['msg_id'] = 0xAAAA0010;
- //判断是不是定时模式
- if ($config['pos_mode'] == 2) {
- if(!$data['stopped_rtc_invl']){
- json_fail('请设置定位采样间隔');
- }
- if(!$data['stopped_rpt_invl']){
- json_fail('请设置定位上报间隔');
- }
- $config_arr = array(
- 'stopped_rtc_invl' => intval($data['stopped_rtc_invl']),
- 'stopped_rpt_invl' => intval($data['stopped_rpt_invl']),
- 'msg_id' => 0xAAAA0007
- );
- //下发日志
- $log_data = array(
- 'send_contents' => json_encode($config_arr),
- 'type'=>'sensor',
- 'imei'=>$imei,
- 'created_at' => time(),
- 'creator_id' => $userid,
- 'device_id' => $dev_id
- );
- $lg_id = M('send_config_log')->createAdd($log_data);
- if (!$lg_id) {
- json_fail('下发日志添加失败');
- M()->rollback();
- }
- $config_arr['id'] = $lg_id;
- $redis->push(json_encode($config_arr));
- }else{//非定时模式 采样时间设为3000 上报间隔3600
- $config_arr = array(
- 'stopped_rtc_invl' => 3000,
- 'stopped_rpt_invl' => 3600,
- 'msg_id' => 0xAAAA0007
- );
- //下发日志
- $log_data = array(
- 'send_contents' => json_encode($config_arr),
- 'type'=>'sensor',
- 'imei'=>$imei,
- 'created_at' => time(),
- 'creator_id' => $userid,
- 'device_id' => $dev_id
- );
- $lg_id = M('send_config_log')->createAdd($log_data);
- if (!$lg_id) {
- json_fail('下发日志添加失败');
- M()->rollback();
- }
- $config_arr['id'] = $lg_id;
- $redis->push(json_encode($config_arr));
- }
- //下发日志
- $log_data = array(
- 'send_contents' => json_encode($config),
- 'type'=>'pos_mode',
- 'imei'=>$imei,
- 'created_at' => time(),
- 'creator_id' => $userid,
- 'device_id' => $dev_id
- );
- $config['id'] = M('send_config_log')->createAdd($log_data);
- if (!$config['id']) {
- json_fail('下发日志添加失败');
- M()->rollback();
- }
- $redis->push(json_encode($config));
- M()->commit();
- json_success('设置成功');
- }
-
-
- public function delUserFence( ){
- header('Access-Control-Allow-Origin: *');
-
- $userid = I('get.userid');
- if(!$userid){
- json_fail('获取不到用户标识,尝试重登');
- }
- $fenceId =I('get.fenceId');
-
- if(!$fenceId){
- json_fail('获取不到围栏标识,尝试刷新');
- }
-
- $res = M('fences')->where(['id' => $fenceId, 'creator_id' => $userid, 'fence_type' => 1] )->delete();
- if(!$res){
- json_fail('删除失败');
- }
- json_success('删除成功');
- }
-
-
- public function sendReverveNotice( ){
- header('Access-Control-Allow-Origin: *');
- $voice_template_id=C('WX_VOICE_TEMPLATE_ID');
- if(!$voice_template_id){
- debug_log('voice_notice','WX_VOICE_TEMPLATE_ID not exist');
- return false;
- }
-
- $data=$_POST;
- $this->wxMsg = new \Jiaruan\WxTmp();
-
- $access_token =$this->wxMsg->getAccessToken();
- $msgArray= array(
- "touser"=>$data['openid'],
- "msgtype"=>"text",
- "text"=>array(
- "content"=>urlencode("测试啥是")
- )
- );
- $json=urldecode(json_encode($msgArray));
- //var_dump($json);exit;
- #群发 文本消息
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- $res = json_decode(curl_exec($ch),true);
- curl_close($ch);
-
-
- json_success($res);
-
- }
-
-
- public function getMyInsureList( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
-
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
-
- $vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true);
-
- $list=M('insure_records')->where(['vehicle_id' =>array('in',$vehiclesIds) ])->select();
-
-
- foreach($list as &$val){
- $start_at=strtotime(date('Y-m-d 00:00:00',$val['start_at']));
- $end_at=strtotime(date('Y-m-d 23:59:59',$val['end_at']));
- if(time()<$start_at){
- $val['insure_state']=0;
- $val['insure_state_text']='待生效';
- }elseif(time()<=$end_at){
- $val['insure_state']=1;
- $val['insure_state_text']='生效中';
- }else{
- $val['insure_state']=2;
- $val['insure_state_text']='已失效';
- }
- $val['vehicle_info']=M('vehicles')->where(['id' =>$val['vehicle_id']])->find();
- $val['insure_info']=M('insurance')->where(['id' =>$val['insurance_id']])->find();
- $val['start_at']=date('Y-m-d 00:00:00',$val['start_at']);
- $val['end_at']=date('Y-m-d 23:59:59',$val['end_at']);
- }
- if(!$list){
- json_fail('暂无保险');
- }
- json_success('查询成功',$list);
-
- }
-
-
- public function getInsureOptions( ){
- header('Access-Control-Allow-Origin: *');
-
- $list=M('insurance')->where(['enable' =>1])->field('*,name as text,id as value')->select();
- foreach($list as &$val){
- $val['price']=$val['price']*100;
- }
- json_success('查询成功',$list);
-
- }
-
-
- public function userByInsure( ){
- header('Access-Control-Allow-Origin: *');
- $openid = I('get.openid');
- $userid = I('get.userid');
-
- //检测登录状态
- $res=$this->checkLoginState($openid,$userid);
- if(!$res['status']){
- json_fail($res['message']);
- }
-
- $data = json_decode( file_get_contents("php://input") ,true);
- $insurance_data=M('insurance')->where(['id'=>$data['insure_id']])->find();
- //添加保险记录信息
- $insurance = array(
- 'vehicle_id'=>$data['vehicle_id'],
- 'insurance_id'=>$data['insure_id'],
- 'start_at'=>strtotime(date('Y-m-d',strtotime('+1 day'))),
- 'end_at'=>strtotime(date('Y-m-d',strtotime('+'.$insurance_data['years'].' year')))+24*3600-1,
- 'creator_id'=>$userid,
- 'created_at'=>time(),
- 'updated_at'=>time()
- );
- if(!M('insure_records')->createAdd($insurance)){
- json_fail('添加保险失败');
- }
-
- json_success('购买成功',$userid);
-
- }
-
- }
|