<?php
namespace app\shared\logic\platform;
use app\shared\model\House;
use app\shared\model\Store;
use app\shared\model\Electricity;
use app\shared\model\HouseOrder;
use app\shared\model\ElectricityLine;
use app\shared\model\LumiElectricityConfig;
use think\exception\ValidateException;
use app\BaseController;
class HouseForm extends  Base
{
    //获取数据
    public  function index(){
        $query=House::where(['acid'=>$this->acid,'is_delete'=>0]);
        if($store_id=input('store_id')){
            $query->where('store_id',$store_id);
        }else{
            $store_ids=Store::where(['acid'=>$this->acid,'is_delete'=>0])->column('id');
            $query->where('store_id','in',$store_ids);
        }
        $count=$query->count();
        $list=$query->page($this->page)->limit($this->limit)->order('sort ASC')->select();
        foreach ($list as $key => &$value) {
            $value['servicing_time']=json_decode($value['servicing_time'],1);
            $value['cover_url']=get_file_url($value['cover']);
            $value['banner_list']=get_file_urls($value['banner']);
            $value['line_config']=ElectricityLine::where([
              'acid'=>$value['acid'],
              'store_id'=>$value['store_id'],
              'mac'=>$value['electricityid'],
              'house_id'=>$value['id'],
              'is_delete'=>0
           ])->column('line,ahead_time,forward_time');
           $lumi_electricity_config=LumiElectricityConfig::where([
              'house_id'=>$value['id'],
              'is_delete'=>0
           ])->column('dev_did,dev_model,resource,ahead_time,forward_time,reset_time,remark');

           foreach ($lumi_electricity_config as &$vlm){
               $vlm['resource']=json_decode($vlm['resource'],1);
           }
           $value['lumi_electricity_config']=$lumi_electricity_config;
           $value['could_sound']=json_decode($value['could_sound'],1);
           if(empty($value['could_sound'])){
            $value['could_sound']=[
                'could_sound_id'=>0,
                'could_sound_token'=>"",
                'could_sound_version'=>"",
                'could_sound_repeat_content'=>'',
                'could_sound_finish_content'=>'',
            ];
           }
        }
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
    //编辑
    public function edit(){
        try {
          $data=request()->post();
          $rule = [
               'id|ID' => 'require',
               'store_id|商户ID'=>'require',
               'area_id|区域ID' => 'require',
               'name|名称' => 'require',
               'cover|封面' => 'require',
               'banner|轮播' => 'require',
               'servicing_time|服务时间' => 'require',
               'facility_servicing|设施服务' => 'require',
               'is_recommend|是否推荐' => 'require',
               'address|地址' => 'require',
               'lat|纬度' => 'require',
               'lng|经度' => 'require',
               'status|姓名'=>'require',
               'price|价格'=>'require',
               'sort|排序'=>'require',
               'lockid|智能锁设备ID'=>'require',
               'electricityid|智能电设备ID'=>'require',
               'booktime|起订时间'=>'require|float',
               'peoplenum|建议人数'=>'require',
               'is_network|锁是否联网'=>'require|in:0,1',
           ];
           $this->validate($data,$rule);
       }catch (ValidateException $e){
           return fetchJson([],$e->getError(),1);
       }
       $form=House::where(['id'=>$data['id'],'store_id'=>$data['store_id']])->find();
       $price=0;
       if(!$form){
            $form=new House();
            $form->acid=$this->acid;
            $form->store_id=$data['store_id'];
            $price_list=self::priceList($data['price']);
       }else{
          if($data['price']!=$form->price){
             $price=$data['price'];
          }
          $price_list=input('price_list')?self::changePriceList(input('price_list'),$price):self::priceList($data['price']);
       }
       $form->electricty_line_config=input('electricty_line_config');
       $form->could_sound=json_encode([
        'could_sound_id'=>input('could_sound_id'),
        'could_sound_token'=>input('could_sound_token'),
        'could_sound_version'=>input('could_sound_version'),
        'could_sound_repeat_content'=>input('could_sound_repeat_content'),
        'could_sound_finish_content'=>input('could_sound_finish_content')
       ]);
       $form->save([
            'area_id'=>$data['area_id'],
            'name'=>$data['name'],
            'cover'=>$data['cover'],
            'banner'=>$data['banner'],
            'servicing_time'=>$data['servicing_time'],
            'facility_servicing'=>$data['facility_servicing'],
            'is_recommend'=>$data['is_recommend'],
            'address'=>$data['address'],
            'lat'=>$data['lat'],
            'lng'=>$data['lng'],
            'status'=>$data['status'],
            'price'=>$data['price'],
            'sort'=>$data['sort'],
            'lockid'=>$data['lockid'],
            'electricityid'=>$data['electricityid'],
            'booktime'=>$data['booktime'],
            'peoplenum'=>$data['peoplenum'],
            'is_network'=>$data['is_network'],
            'ahead_time'=>input('ahead_time'),
            'forward_time'=>input('forward_time'),
            'open_type'=>input('open_type')?input('open_type'):1,
            'gatelockid'=>input('gatelockid'),
            'price_list'=>$price_list,
            'book_types'=>input('book_types')?input('book_types'):'',
            'limit_time'=>input('limit_time')?input('limit_time'):5,
            'virtual_sales'=>input('virtual_sales')?input('virtual_sales'):0,
            'lvelectricty_line_config'=>input('lvelectricty_line_config'),
            'member_price'=>input('member_price'),
            'original_price'=>input('original_price'),
            'package_price'=>input('package_price')?input('package_price'):'',//套餐价格
            'cancel_time'=>input('cancel_time')?input('cancel_time'):30,
            'video_url'=>input('video_url')?input('video_url'):0,
       ]);
       $lineConfig=json_decode($data['line_config'],1);
       ElectricityLine::where([
          'acid'=>$this->acid,
          'store_id'=>$data['store_id'],
          'mac'=>$data['electricityid'],
          'house_id'=>$form->id,
       ])->update(['is_delete'=>1]);
       foreach ($lineConfig as $key => $value) {
            if(!isset($value['line'])){
               return fetchJson([],'线路不得为空',1);
            }
            if(!isset($value['ahead_time'])){
               return fetchJson([],'提前时间',1);
            }
            if(!isset($value['forward_time'])){
                 return fetchJson([],'延后时间',1);
            }
            $eleForm=ElectricityLine::where(['acid'=>$this->acid,'store_id'=>$data['store_id'],'mac'=>$data['electricityid'],'line'=>$value['line']])->find();
            if(!$eleForm){
                //没有的情况下
                (new ElectricityLine())->save([
                  'acid'=>$this->acid,
                  'store_id'=>$data['store_id'],
                  'mac'=>$data['electricityid'],
                  'line'=>$value['line'],
                  'house_id'=>$form->id, 
                  'ahead_time'=>$value['ahead_time'],
                  'forward_time'=>$value['forward_time'],
                ]);
            }else{
               $ele=ElectricityLine::where([
                  'acid'=>$this->acid,
                  'store_id'=>$data['store_id'],
                  'mac'=>$data['electricityid'],
                  'line'=>$value['line'],
                  'house_id'=>$form->id,
                ])->find();
                if(!$ele){
                    $ele=new ElectricityLine();
                    $ele->acid=$this->acid;
                    $ele->store_id=$data['store_id'];
                    $ele->mac=$data['electricityid'];
                    $ele->line=$value['line'];
                    $ele->house_id=$form->id;
                }
                $ele->ahead_time=$value['ahead_time'];
                $ele->forward_time=$value['forward_time'];
                $ele->is_delete=0;
                $ele->save();
            }
       }
       LumiElectricityConfig::where([
          'acid'=>$this->acid,
          'store_id'=>$data['store_id'],
          'house_id'=>$form->id,
       ])->update(['is_delete'=>1]);
       $lumiElectricityConfig=json_decode(input('lumi_electricity_config'),1);

       foreach ($lumiElectricityConfig as $lm=>$vl){
            if(!isset($vl['dev_did'])){
               return fetchJson([],'设备DID不得为空',1);
            }
            if(!isset($vl['ahead_time'])){
               return fetchJson([],'提前时间不得为空',1);
            }
            if(!isset($vl['forward_time'])){
                 return fetchJson([],'延后时间不得为空',1);
            }
            $eleForm=LumiElectricityConfig::where(['acid'=>$this->acid,'store_id'=>$form->store_id,'dev_did'=>$vl['dev_did']])->find();
            if(!$eleForm){
                //没有的情况下
                (new LumiElectricityConfig())->save([
                  'acid'=>$this->acid,
                  'store_id'=>$form->store_id,
                  'dev_model'=>$vl['dev_model'],
                  'dev_did'=>$vl['dev_did'],
                  'house_id'=>$form->id, 
                  'ahead_time'=>$vl['ahead_time'],
                  'forward_time'=>$vl['forward_time'],
                  'resource'=>json_encode($vl['resource'])
                ]);
            }else{
                $ele=LumiElectricityConfig::where([
                  'acid'=>$this->acid,
                  'store_id'=>$form->store_id,
                  'dev_did'=>$vl['dev_did'],
                  'resource'=>json_encode($vl['resource']),
                  'house_id'=>$form->id,
                ])->find();
                if(!$ele){
                    $ele=new LumiElectricityConfig();
                    $ele->acid=$this->acid;
                    $ele->store_id=$form->store_id;
                    $ele->dev_did=$vl['dev_did'];
                    $ele->house_id=$form->id;
                }
                $ele->dev_model=$vl['dev_model'];
                $ele->ahead_time=$vl['ahead_time'];
                $ele->forward_time=$vl['forward_time'];
                $ele->resource=json_encode($vl['resource']);
                $ele->is_delete=0;
                $ele->reset_time=isset($vl['reset_time'])?$vl['reset_time']:0;
                $ele->remark=isset($vl['remark'])?$vl['remark']:'';
                $ele->save();
            }
       }
       $form->save();
       $tea_price=House::where(['store_id'=>$data['store_id'],'is_delete'=>0])->min('price');
       Store::where('id',$data['store_id'])->update(['tea_price'=>$tea_price]);
       return fetchJson([],'保存成功');
    }
    //改价格表
    private function changePriceList($priceList=[],$price=0){
        $priceList=json_decode($priceList,1);
        $list=[];
        foreach ($priceList as $value){
           if($value['price']<0){
              $list[]=[
                'time'=>$value['time'],
                'price'=>0,
              ];
           }else{
              $list[]=[
                'time'=>$value['time'],
                'price'=>$price>0?$price:$value['price'],
              ];
           }
        }
        return json_encode($list);
    }
    //删除
    public function delete(){
        House::where(['id'=>input('id')])->update(['is_delete'=>1]);
        return fetchJson([],'删除成功');
    }
     //价格表
    private function priceList($price=0){
        $list=[];
        for($i=0;$i<24;$i++){
            $list[]=[
              'time'=>$i<10?'0'.$i:$i,
              'price'=>$price
            ];
        }
        return json_encode($list);
    }
    //取电记录
    public function takeElectricityRecord(){
        $query=Electricity::alias('e')->leftJoin([HouseOrder::getTable()=>'o'],'e.order_id=o.id')
        ->leftJoin([House::getTable()=>'h'],'o.house_id=h.id')
        ->leftJoin([Store::getTable()=>'s'],'o.store_id=s.id')
        ->where(['e.acid'=>$this->acid])->order('e.id DESC');
        if($house_id=input('house_id')){
            $query->where('o.house_id',$house_id);
        }
        $count=$query->field('e.id,e.start_time,e.end_time,e.mac,e.line,e.config,e.create_time,e.update_time,o.order_no,e.status,o.house_id,h.name,s.address,e.reset_time')->count();
        $list=$query->page($this->page)->limit($this->limit)->select();
        foreach ($list as &$value){
          $value['start_time']=date('Y-m-d H:i:s',$value['start_time']);
          $value['end_time']=date('Y-m-d H:i:s',$value['end_time']);
          $value['config']=json_decode($value['config'],1);
        }
        return fetchJson([
          'count'=>$count,
          'list'=>$list
        ]);
    }
    //音响测试
    public function soundTest(){
       $could_sound_id=input('could_sound_id');
       $could_sound_token=input('could_sound_token');
       $could_sound_version=input('could_sound_version');
       $could_sound_content=input('could_sound_content');
       $url="https://speaker.17laimai.cn/notify.php?id={$could_sound_id}&token={$could_sound_token}&version={$could_sound_version}&message={$could_sound_content}";
       $res=httpRequest($url);
       $res=json_decode($res,1);
       if($res['errcode']==0){
          return fetchJson([],"发送成功");
       }
       return fetchJson([],$res['errmsg'],1);
    }

}