<?php
namespace app\shared\logic\user;
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 app\BaseController;
use wechatpay\WechatPay;
use think\exception\ValidateException;
use slock\Slock;
use slock\Xsj;
use slock\Ttlock;
use Electronic\Lvmi;

//保洁管理
class CleaningForm extends  UserForm
{   
    private $cleaningGroup;
    public function __construct()
    {
        parent::__construct();
        $cleaningGroup=StoreCleaning::where(['acid'=>$this->acid,'account'=>$this->user->account,'is_delete'=>0,'status'=>1])->column('id,store_id,username');
        if(!$cleaningGroup){
            die(json_encode(['code'=>-4,'data'=>[],'msg'=>'您不是保洁员']));
        }
        $this->cleaningGroup=$cleaningGroup;
    }
    //统计
    public function statistics(){
        $cleaningIds=array_column($this->cleaningGroup,'id');
        $type=1;
        $status=input('status');
        //1累计，2今日，3昨日，4 七日，5，三十日
        
        $query=StoreCleaningOrder::alias('co')
                    ->leftJoin([StoreCleaning::getTable()=>'v'],'co.cleaning_id=v.id')
                    ->leftJoin([HouseOrder::getTable()=>'o'],'co.order_id=o.id')
                    ->where(['co.acid'=>$this->acid,'co.is_delete'=>0,'type'=>$type])
                    ->where('co.cleaning_id','in',$cleaningIds);
        if($status==2){
            $query->whereDay('co.create_time',date('Y-m-d'));
        }elseif($status==3){
            $query->whereDay('co.create_time','yesterday');
        }elseif($status==4){
            $end_time=time();
            $start_time=time()-86400*6;
            $query->whereTime('co.create_time', '<=',$end_time)->whereTime('co.create_time', '>=',$start_time);
        }elseif($status==5){
            $end_time=time();
            $start_time=time()-86400*30;
            $query->whereTime('co.create_time', '<=',$end_time)->whereTime('co.create_time', '>=',$start_time);
        }else{
            
        }            
        return fetchJson([
            'sum_price'=>$query->sum('o.price'),
            'wx_subscibe_book_sweep'=>Option::get_data($this->acid,'platform','wx_subscibe_book_sweep'),
            'count'=>$query->count()
        ]);             
    }
    public function list(){
        $storeIds=array_column($this->cleaningGroup,'store_id');
        $status=input('status')?1:0;
        if($status==1){
            $cleaning_ids=array_column($this->cleaningGroup,'id');
            $list=StoreCleaningOrder::alias('co')->leftJoin([HouseOrder::getTable()=>'o'],'co.order_id=o.id')
                         ->where(['o.acid'=>$this->acid])
                         ->where('o.status','in','3')
                         ->where('co.cleaning_id','in',$cleaning_ids)
                         ->field('o.id,o.order_no,o.username,o.tel,o.price,o.pay_type,o.start_time,o.end_time,o.status,o.snapshoot,o.cleaning_completion_time,o.is_cleaning,co.cleaning_time,co.cleaning_id')
                         ->page($this->page)
                         ->limit(10)
                         ->order('o.id DESC')
                         ->select();
            foreach($list as &$value){
                if($value['cleaning_completion_time']>0){
                    $value['status']=4;
                }
            }             
        }else{
            $query=HouseOrder::where(['status'=>3,'acid'=>$this->acid,'is_cleaning'=>0])->where('end_time','>',time()-(86400*7));
            $list=$query->where('store_id','in',$storeIds)
                         ->field('id,order_no,username,tel,price,pay_type,start_time,end_time,snapshoot,status')
                         ->page($this->page)
                         ->limit(10)
                         ->order('id DESC')
                         ->select();
        }
        foreach ($list as &$value){
            $value['snapshoot']=json_decode($value['snapshoot'],1);
            $value['cleaning_time']=isset($value['cleaning_time'])?date('Y-m-d H:i:s',$value['cleaning_time']):0;
        }
        return fetchJson($list);
    }
    public function handle(){
        try {
          $data=request()->post();
          $rule = [
               'order_id|订单ID' => 'require',
               'type|类型'=>'require|number|in:1',
           ];
          $this->validate($data,$rule);
        }catch (ValidateException $e){
           return fetchJson([],$e->getError(),1);
        }
        $storeIds=array_column($this->cleaningGroup,'store_id');
        if($data['type']==1){
            $order=HouseOrder::where(['id'=>$data['order_id'],'status'=>3,'is_delete'=>0,'is_cleaning'=>0])->find();
            if($order){
                if(in_array($order->store_id,$storeIds)){
                    $cleaningIds=array_column($this->cleaningGroup,'id','store_id');
                    $order->is_cleaning=1;
                    $order->save();
                    if(StoreCleaningOrder::where([
                        'acid'=>$this->acid,
                        'type'=>$data['type'],
                        'order_id'=>$order->id,
                        'status'=>1
                    ])->count()){
                        return fetchJson([],'已被保洁过了');
                    }
                    $form=new StoreCleaningOrder();
                    $form->save([
                        'acid'=>$this->acid,
                        'type'=>$data['type'],
                        'cleaning_id'=>$cleaningIds[$order->store_id],
                        'order_id'=>$order->id,
                        'store_id'=>$order->store_id,
                        'cleaning_time'=>time(),
                        'status'=>1,
                    ]);
                    return fetchJson([],'抢单成功');
                }
                return fetchJson([],'您不是该商户的保洁人员',1);
            }
            return fetchJson([],'暂无订单',1);
        }
        return fetchJson([],'暂无保洁订单',1);
    }
    //控制门
    public function controllerOpenDoor(){
        $order_id=input('order_id');
        $order=HouseOrder::where(['id'=>$order_id,'status'=>3])->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $onclick=input('onclick');
        $store=Store::where('id',$order->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);
        $house=House::where('id',$order->house_id)->find();
        $ahead_time=$house['ahead_time']*60;
        $forward_time=$house['forward_time']*60;
        //曼顿取电
        $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);
        $order['open_door_bgm']=isset($storeConfig['open_door_bgm'])?$storeConfig['open_door_bgm']:'';
        $order['open_room_bgm']=isset($storeConfig['open_room_bgm'])?$storeConfig['open_room_bgm']:'';

        $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、大门金属二维码，包间通通锁
        $order['is_network']=$house['is_network'];
        $order['is_gatelock']=$house['gatelockid']==-1||$house['gatelockid']==0?0:1;
        $end_time=$order->end_time;
        $start_time=$order->start_time;
        $continueOrder=HouseOrderContinue::where(['order_id'=>$order->id])->where('status','>',0)->order('id DESC')->field('start_time,end_time')->find();
        if($continueOrder){
           if($continueOrder->end_time>time()&&$order->end_time<time()){
                $start_time=time();
            }
            $end_time=$continueOrder->end_time;
        }
        $order['snapshoot']=json_decode($order['snapshoot'],1);
        $order['store']=[
            'name'=>$store['name'],
            'tel'=>$store['tel'],
        ];
        $order['end_time']=$end_time;
        $mac=$house['electricityid'];
        //联网方式使用按钮开门
        if($house['is_network']==1){
            $onclick=input('onclick');
            //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($order,'大门开门成功');
                }
                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($order,'包厢开门成功');
                }
            }
            //优盯智能锁
            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){
                       return fetchJson($lock,'开大门失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开大门成功');
                }
                if($onclick==2){
                    $lockPost['keylockid']=$house['lockid'];
                    $lock=$slock->openRemoteDeviceLock($lockPost);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开包厢失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开包厢成功');
                }
               
            }
            //大门金属二维码---包厢优盯智能锁
            if($house['open_type']==4){
                if($onclick==1){
                    $slock=new Xsj($config);
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开大门失败,请联系管理员',1);
                    }
                    return fetchJson([],'开大门成功');
                }
                if($onclick==2){
                    $slock=new Slock($smart_device);
                    $lockPost['keylockid']=$house['lockid'];
                    $lock=$slock->openRemoteDeviceLock($lockPost);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开包厢失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开包厢成功');
                }
                return fetchJson($order,'开门错误',1);
            }
            //大门金属二维码---包厢金属二维码
            if($house['open_type']==5){
                $slock=new Xsj($config);
                if($onclick==1){
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开大门失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开大门成功');
                }
                if($onclick==2){
                    $lock=$slock->deviceRemote($house['lockid']);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开包厢失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开包厢门成功');
                }
            }
            //大门金属二维码---包厢通通锁
            if($house['open_type']==6){
                $slock=new Xsj($config);
                if($onclick==1){
                    $lock=$slock->deviceRemote($house['gatelockid']);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开大门失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开大门成功');
                }
                if($onclick==2){
                    $slock=new Ttlock($config);
                    $lock=$slock->unlock($house['lockid']);
                    if($lock['code']!=0){
                       return fetchJson($lock,'开包厢失败,请联系管理员',1);
                    }
                    return fetchJson($order,'开包厢门成功');
                }
            }
             //大门通通锁---包厢通通锁
            if($house['open_type']==7){
                if($onclick==1){
                    if(($start_time-$ahead_time)<time()&&($end_time+$forward_time)>time()){
                        $slock=new Ttlock($config);
                        $lock=$slock->unlock($house['gatelockid']);
                        if($lock['code']!=0){
                           return fetchJson($lock,'开大门失败,请联系管理员'.$lock['msg'],1);
                        }
                        self::electricityLine($house,$order,$config,$start_time,$end_time);
                    }else{
                        return fetchJson([],'不在服务时间范围内，无法开大门',1);
                    }
                    return fetchJson($order,'开大门成功');
                }
                if($onclick==2){
                    if(($start_time-$ahead_time)<time()&&($end_time+$forward_time)>time()){
                        self::electricityLine($house,$order,$config,$start_time,$end_time);
                        $slock=new Ttlock($config);
                        $lock=$slock->unlock($house['lockid']);
                        if($lock['code']!=0){
                           return fetchJson($lock,'开包厢失败,请联系管理员原因'.$lock['msg'],1);
                        }
                    }else{
                        return fetchJson([],'不在服务时间范围内，无法开包厢',1);
                    }
                    return fetchJson($order,'开包厢门成功');
                }
            }
            if($house['open_type']==8){
                if($onclick==1){
                    if(($start_time-$ahead_time)<time()&&($end_time+$forward_time)>time()){
                        $slock=new Xsj($config);
                        $lock=$slock->deviceRemote($house['gatelockid']);
                        if($lock['code']!=0){
                           return fetchJson($lock,'开大门失败,请联系管理员',1);
                        }
                        self::electricityLine($house,$order,$config,$start_time,$end_time);
                    }else{
                        return fetchJson([],'不在服务时间范围内，无法开大门',1);
                    }
                    return fetchJson($order,'开大门成功');
                }
                if($onclick==2){
                    if(($start_time-$ahead_time)<time()&&($end_time+$forward_time)>time()){
                        self::electricityLine($house,$order,$config,$start_time,$end_time);
                        $form=new \slock\Jwlock();
                        $lock=$form->qrcode($house['lockid'],($start_time-$ahead_time),($end_time+$forward_time));
                        if($lock['code']!=0){
                           return fetchJson($lock,'开包厢失败,请联系管理员',1);
                        }
                    }else{
                        return fetchJson([],'不在服务时间范围内，无法开包厢',1);
                    }
                    return fetchJson($order,'开包厢门成功');
                }
            }
            if($house['open_type']==9){
                if($onclick==1){
                    if(($start_time-$ahead_time)<time()&&($end_time+$forward_time)>time()){
                        $form=new \slock\Jwlock();
                        $lock=$form->oneKeyLock($house['gatelockid']);
                        if($lock['code']!=0){
                           return fetchJson($lock,',开大门失败,请联系管理员',1);
                        }
                        self::electricityLine($house,$order,$config,$start_time,$end_time);
                    }else{
                        return fetchJson([],'不在服务时间范围内，无法开大门',1);
                    }
                    return fetchJson($order,'开大门成功');                    
                }
                if($onclick==2){
                    if(($start_time-$ahead_time)<time()&&($end_time+$forward_time)>time()){
                        self::electricityLine($house,$order,$config,$start_time,$end_time);
                        $form=new \slock\Jwlock();
                        $lock=$form->oneKeyLock($house['lockid']);
                        if($lock['code']!=0){
                           return fetchJson($lock,'开包厢失败,请联系管理员',1);
                        }
                    }else{
                        return fetchJson([],'不在服务时间范围内，无法开包厢',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'=>$order->id]));
                return fetchJson($order,'开房成功');
            }
            //优盯智能锁
            if($house['open_type']==1){
                $lockPost['keylockid']=$house['lockid'];
                $lockPost['userid']=$smart_device['username'];
                $lockPost['enddate']=date('YmdHis',time()+300);
                $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);
                $lock_id=$house['gatelockid'].",".$house['lockid'];
                $lock=$slock->deviceQr($lock_id,time(),time()+300);
                if($lock['code']!=0){
                   return fetchJson($lock,'获取失败',1);
                }
               // $order['qrcode_url']="https://api.pwmqr.com/qrcode/create/?url=".$lock['data'];
                $order['qrcode_url']=generateQrCode($lock['data'],'house_id'.$house['id']);
                return fetchJson($order,'开门成功');
            }

        }
        return fetchJson($order);
    }
    //控制电
    public function controllerElectricity(){
        $order_id=input('order_id');
        $order=HouseOrder::where(['id'=>$order_id,'status'=>3,'cleaning_completion_time'=>0,'is_cleaning'=>1])->find();
        if(!$order){
            return fetchJson([],'暂无订单',1);
        }
        $status=input('status');
        $store=Store::where('id',$order->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'],
        ];
        $house=House::where('id',$order->house_id)->find();
        $storeConfig=json_decode($store['config'],1);
        $order['open_door_bgm']=isset($storeConfig['open_door_bgm'])?$storeConfig['open_door_bgm']:'';
        $order['open_room_bgm']=isset($storeConfig['open_room_bgm'])?$storeConfig['open_room_bgm']:'';

        $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){
            $order->is_cleaning=1;
            $order->cleaning_completion_time=time();
            $order->save();
            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'=>$this->acid,
            'store_id'=>$house['store_id'],
            'house_id'=>$house['id'],
            'is_delete'=>0
        ])->column('dev_did,dev_model,resource');
        $params=[];
        $accessToken=isset($lvmi_device['accessToken'])?$lvmi_device['accessToken']:'';
        foreach ($lumi_electricity_config as &$vlm){
            $resources=[];
            $resource=json_decode($vlm['resource'],1);
            foreach ($resource as $v){
              $resources[]=[
                'resourceId'=>$v['resuors'],
                'value'=>$status,
              ];
              $config=([
                [
                    'subjectId'=>$vlm['dev_did'],
                    'resources'=>$resources,
                ]
              ]);
              $form=new Lvmi();
              $res=$form->controllerDevice($accessToken,$config);
              sleep(1);
           }
        }
    } 
}