<?php
namespace app\shared\logic\store;
use app\BaseController;
use app\shared\model\App;
use app\shared\model\HouseOrder;
use app\shared\model\HouseOrderContinue;
use app\shared\model\Store;
use app\shared\model\Bill;
use app\shared\model\User;
use app\shared\model\Option;
use app\shared\model\House;
use app\shared\model\StoreCleaning;
use app\shared\model\StoreCleaningOrder;
use app\shared\model\LumiElectricityConfig;
use app\shared\model\ElectricityLine;
use think\exception\ValidateException;
use slock\Slock;
use slock\Xsj;
use slock\Ttlock;
use Electronic\Lvmi;
class HouseDoorForm extends  Base
{
    //控制门
    public function openDoor(){

        $onclick=input('onclick');
        $house_id=input('house_id');
        $house=House::where('id',$house_id)->find();
        if(!$house){
            return fetchJson([],'暂无房间',1);
        }
        $store=Store::where('id',$house->store_id)->field('smart_device,config,tel,name,lvmi_device')->find();
        $smart_device=$store['smart_device'];
        if(empty($smart_device)){
           return fetchJson([],'开锁失败，请联系商家,暂无设备',1);
        }
        $smart_device=json_decode($smart_device,1);
        
        $ahead_time=$house['ahead_time']*60;
        $forward_time=$house['forward_time']*60;
        $openType=input('openType')?input('openType'):0;
        //曼顿取电
        $config=[
            'appKey'=>$smart_device['electronic_mandun_appKey'],
            'appSecret'=>$smart_device['electronic_mandun_appSecret'],
            'uname'=>$smart_device['electronic_mandun_uname'],
            'passwd'=>$smart_device['electronic_mandun_passwd'],
            'projectCode'=>$smart_device['electronic_mandun_projectCode'],
            'api_url'=>$smart_device['electronic_mandun_apiUrl'],
        ];
        $storeConfig=json_decode($store['config'],1);

        $config['xsj_app_key']=isset($storeConfig['xsjConfig']['app_key'])?$storeConfig['xsjConfig']['app_key']:'';
        $config['xsj_yard_sn']=isset($storeConfig['xsjConfig']['yard_sn'])?$storeConfig['xsjConfig']['yard_sn']:'';

        $config['tt_lock_username']=isset($storeConfig['xsjConfig']['tt_lock_username'])?$storeConfig['xsjConfig']['tt_lock_username']:'';
        $config['tt_lock_password']=isset($storeConfig['xsjConfig']['tt_lock_password'])?md5($storeConfig['xsjConfig']['tt_lock_password']):'';
        //开门方式
        //1、用户扫码开门，
        //2、核销开门，
        //3、13387开门方式，
        //4、大门金属二维码门禁，包间优盯锁，
        //5、大门金属二维码，包厢金属二维码门禁，
        //6、大门金属二维码，包间通通锁
        
        if($openType==2){
            $house['is_network']=0;
        }
        if($openType==1){
            $house['is_network']=1;
        }
        $order['is_network']=$house['is_network'];
        $order['is_gatelock']=$house['gatelockid']==-1||$house['gatelockid']==0?0:1;
        $mac=$house['electricityid'];
        //联网方式使用按钮开门
        if($house['is_network']==1||$openType==1){
            //13187电磁锁开门方案
            if($house['open_type']==3){
                if($onclick==1){
                    if($mac=="-1"||$mac=="0"||$mac==''){
                         //绿米配置开门
                         $lvelectricty_line_config=json_decode($house['lvelectricty_line_config'],1);
                         $electricty_line=$lvelectricty_line_config[0];
                         $lvmi_device=json_decode($store['lvmi_device'],1);
                         $accessToken=isset($lvmi_device['accessToken'])?$lvmi_device['accessToken']:'';
                         $task=new \app\shared\controller\Task();
                         $task->lvmihandleIntime($accessToken,$electricty_line);
                    }else{
                        $electricty_line_config=json_decode($house['electricty_line_config'],1);
                        $electricty_line=$electricty_line_config[0];
                        $task=new \app\shared\controller\Task();
                        $task->handleIntime($config,$mac,$electricty_line['line'],$electricty_line['status'],$electricty_line['minute']);
                    }
                    return fetchJson([],'大门开门成功');
                }
                if($onclick==2){
                      if($mac=="-1"||$mac=="0"||$mac==''){
                             //绿米配置开门
                            $lvelectricty_line_config=json_decode($house['lvelectricty_line_config'],1);
                            $electricty_line=$lvelectricty_line_config[1];
                            $lvmi_device=json_decode($store['lvmi_device'],1);
                            $accessToken=isset($lvmi_device['accessToken'])?$lvmi_device['accessToken']:'';
                            $task=new \app\shared\controller\Task();
                            $task->lvmihandleIntime($accessToken,$electricty_line);
                      }else{
                           $electricty_line_config=json_decode($house['electricty_line_config'],1);
                           $electricty_line=$electricty_line_config[1];
                           $task=new \app\shared\controller\Task();
                           $task->handleIntime($config,$mac,$electricty_line['line'],$electricty_line['status'],$electricty_line['minute']);//副设备
                          
                      }
                      //开包厢电Code
                      return fetchJson([],'包厢开门成功');
                }
            }
            //优盯智能锁
            if($house['open_type']==1){
                $slock=new Slock($smart_device);
                if($onclick==1){
                    $lockPost['keylockid']=$house['gatelockid'];
                    $lock=$slock->openRemoteDeviceLock($lockPost);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $lockPost['keylockid']=$house['lockid'];
                    $lock=$slock->openRemoteDeviceLock($lockPost);
                    if($lock['code']!=0){
                         $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢成功');
                }
               
            }
            //大门金属二维码---包厢优盯智能锁
            if($house['open_type']==4){
                if($onclick==1){
                    $slock=new Xsj($config);
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $slock=new Slock($smart_device);
                    $lockPost['keylockid']=$house['lockid'];
                    $lock=$slock->openRemoteDeviceLock($lockPost);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢成功');
                }
                return fetchJson([],'开门错误',1);
            }
            //大门金属二维码---包厢金属二维码
            if($house['open_type']==5){
                $slock=new Xsj($config);
                if($onclick==1){
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                       $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $lock=$slock->deviceRemote($house['lockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢门成功');
                }
            }
            //大门金属二维码---包厢通通锁
            if($house['open_type']==6){
                $slock=new Xsj($config);
                if($onclick==1){
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $slock=new Ttlock($config);
                    $lock=$slock->unlock($house['lockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢门成功');
                }
            }
             //大门通通锁---包厢通通锁
            if($house['open_type']==7){
                if($onclick==1){
                    $slock=new Ttlock($config);
                    $lock=$slock->unlock($house['gatelockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $slock=new Ttlock($config);
                    $lock=$slock->unlock($house['lockid']);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开包厢失败,请联系管理员',1);
                    }
                    return fetchJson([],'开包厢门成功');
                }
            }
            if($house['open_type']==8){
                if($onclick==1){
                    $slock=new Xsj($config);
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $form=new \slock\Jwlock();
                    $lock=$form->oneKeyLock($house['lockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢门成功');
                }
            }
            if($house['open_type']==9){
                if($onclick==1){
                    $form=new \slock\Jwlock();
                    $lock=$form->oneKeyLock($house['gatelockid']);
                    if($lock['code']!=0){
                       $lock['lock_id']=$house['gatelockid'];
                       return fetchJson($lock,'开大门失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $form=new \slock\Jwlock();
                    $lock=$form->oneKeyLock($house['lockid']);
                    if($lock['code']!=0){
                        $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢门成功');
                }
            }
            //大门绿米包间优盯智能锁
            if($house['open_type']==10){
                if($onclick==1){
                    if($mac=="-1"||$mac=="0"||$mac==''){
                         //绿米配置开门
                         $lvelectricty_line_config=json_decode($house['lvelectricty_line_config'],1);
                         $electricty_line=$lvelectricty_line_config[0];
                         $lvmi_device=json_decode($store['lvmi_device'],1);
                         $accessToken=isset($lvmi_device['accessToken'])?$lvmi_device['accessToken']:'';
                         $task=new \app\shared\controller\Task();
                         $task->lvmihandleIntime($accessToken,$electricty_line);
                    }else{
                        $electricty_line_config=json_decode($house['electricty_line_config'],1);
                        $electricty_line=$electricty_line_config[0];
                        $task=new \app\shared\controller\Task();
                        $task->handleIntime($config,$mac,$electricty_line['line'],$electricty_line['status'],$electricty_line['minute']);
                    }
                    return fetchJson([],'大门开门成功');
                }
                if($onclick==2){
                    $slock=new Slock($smart_device);
                    $lockPost['keylockid']=$house['lockid'];
                    $lock=$slock->openRemoteDeviceLock($lockPost);
                    if($lock['code']!=0){
                         $lock['lock_id']=$house['lockid'];
                       return fetchJson($lock,'开包厢失败'.$lock['msg'],1);
                    }
                    return fetchJson([],'开包厢成功');
                }
            }
        }else{
            //联网方式使用二维码开门
            //核销员开门方式
            if($house['open_type']==2){
                $order['qrcode_url']="https://api.pwmqr.com/qrcode/create/?url=".urlencode(json_encode(['type'=>1,'order_id'=>0]));
                return fetchJson($order,'开房成功');
            }
            //优盯智能锁
            if($house['open_type']==1){
                $lockPost['keylockid']=$house['lockid'];
                $lockPost['userid']=$smart_device['username'];
                $lockPost['enddate']=date('YmdHis',time()+1200);
                $lockPost['startdate']=date('YmdHis',time());//软件测试了二位会提前20-30分钟，所以需要减去时间秒数
                $lockPost['validminute']=5;
                $slock=new Slock($smart_device);
                $lock=$slock->getLockQRCode($lockPost);
                if($lock['code']!=0){
                   return fetchJson([],'开锁失败,请联系管理员',1);
                }
                $order['lock_password']='data:image/jpg;base64,'.$lock['data'];
                return fetchJson($order,'获取成功');
            }
            //大门金属二维码---包厢金属二维码
            if($house['open_type']==5){
                $slock=new Xsj($config);
                if($house['gatelockid']==-1||$house['gatelockid']==0){
                     $lock_id=$house['lockid'];
                }else{
                     $lock_id=$house['gatelockid'].",".$house['lockid'];
                }
                $lock=$slock->deviceQr($lock_id,time(),time()+1200);
                if($lock['code']!=0){
                   return fetchJson($lock,'获取失败',1);
                }
                $order['lock_password']=generateQrCode($lock['data'],'house_id'.$house['id']);
                return fetchJson($order,'开门成功');
            }
            //大门金属二维码---包厢金属二维码
            if($house['open_type']==9){
                $form=new \slock\Jwlock();
                $lock=$form->qrcode($house['lockid'],time(),time()+1200);
                if($lock['code']!=0){
                   return fetchJson($lock,'开包厢失败,请联系管理员',1);
                }
                $order['lock_password']=generateQrCode($lock['data'],'house_id'.$house['id']);
                return fetchJson($order,'开门成功');
            }
        }

        return fetchJson($order);
    }
    //控制电
    public function electricity(){
        $status=input('status');
        $house_id=input('house_id');
        $house=House::where('id',$house_id)->find();
        if(!$house){
            return fetchJson([],'暂无房间',1);
        }
        $store=Store::where('id',$house->store_id)->field('smart_device,config,tel,name,lvmi_device')->find();
        $smart_device=$store['smart_device'];
        $lvmi_device=$store['lvmi_device'];
        if(empty($smart_device)){
           return fetchJson([],'开锁失败，请联系商家,暂无设备',1);
        }
        $smart_device=json_decode($smart_device,1);
        $lvmi_device=json_decode($lvmi_device,1);
         //曼顿取电
        $config=[
            'appKey'=>$smart_device['electronic_mandun_appKey'],
            'appSecret'=>$smart_device['electronic_mandun_appSecret'],
            'uname'=>$smart_device['electronic_mandun_uname'],
            'passwd'=>$smart_device['electronic_mandun_passwd'],
            'projectCode'=>$smart_device['electronic_mandun_projectCode'],
            'api_url'=>$smart_device['electronic_mandun_apiUrl'],
        ];
        $storeConfig=json_decode($store['config'],1);
        $config['xsj_app_key']=isset($storeConfig['xsjConfig']['app_key'])?$storeConfig['xsjConfig']['app_key']:'';
        $config['xsj_yard_sn']=isset($storeConfig['xsjConfig']['yard_sn'])?$storeConfig['xsjConfig']['yard_sn']:'';
        $config['tt_lock_username']=isset($storeConfig['xsjConfig']['tt_lock_username'])?$storeConfig['xsjConfig']['tt_lock_username']:'';
        $config['tt_lock_password']=isset($storeConfig['xsjConfig']['tt_lock_password'])?md5($storeConfig['xsjConfig']['tt_lock_password']):'';
        if($house['electricityid']=="-1"||$house['electricityid']=="0"||$house['electricityid']==''){    
            self::lvmiele($house,$lvmi_device,$status);
        }else{
            $lineList=ElectricityLine::where([
                'acid'=>$house['acid'],
                'store_id'=>$house['store_id'],
                'mac'=>$house['electricityid'],
                'house_id'=>$house['id'],
                'is_delete'=>0
             ])->column('line,ahead_time,forward_time');
            foreach ($lineList as $key => $value) {
               self::mandunLine($config,$house['electricityid'],$value['line'],$status);
            }
        }
        if($status==0){
            return fetchJson([],'关电成功');
        }
        return fetchJson([],'取电成功');
    }
    //曼顿线路取电
    public function mandunLine($config,$mac,$line,$status=0){
        $form=new \Electronic\Mandun($config);
        $res=$form->sceneServicePuls($mac,$line,$status);//副设备
    }
    //绿米取电
    public function lvmiele($house,$lvmi_device,$status=0){
        $lumi_electricity_config=LumiElectricityConfig::where([
            'acid'=>$house['acid'],
            'store_id'=>$house['store_id'],
            'house_id'=>$house['id'],
            'is_delete'=>0
        ])->column('dev_did,dev_model,resource,reset_time');
        $params=[];
        $accessToken=isset($lvmi_device['accessToken'])?$lvmi_device['accessToken']:'';
        foreach ($lumi_electricity_config as &$vlm){
            if($vlm['reset_time']>0){
                continue;
            }
            $resources=[];
            $resource=json_decode($vlm['resource'],1);
            foreach ($resource as $v){
              if($status==0){
                 $v['status']=$v['status']==0?1:0;
              }
              $resources[]=[
                'resourceId'=>$v['resuors'],
                'value'=>$v['status'],
              ];
              $config[]=[
                'subjectId'=>$vlm['dev_did'],
                'resources'=>$resources,
              ];
           }
        }
        $form=new Lvmi();
        $res=$form->controllerDevice($accessToken,$config);
    } 
}