<?php
namespace app\shared\logic\platform;
use app\shared\model\Store;
use app\shared\model\House;
use app\shared\model\Area;
use app\shared\model\ApplyBecomeStore;
use think\exception\ValidateException;
use Electronic\Lvmi;
use app\BaseController;
class StoreForm extends  Base
{
    //获取数据
    public  function index(){
        $keyword=input('keyword');
        $field=input('field');
        $query=Store::where(['acid'=>$this->acid,'is_delete'=>0]);
        if($keyword){
            if($field){
                $fieldArray=['id','name','account'];
                $searchField=$field;
                if(!in_array($field,$fieldArray)){
                    $searchField='id|name|account';
                }
            }else{
                $searchField='id|name|account';
            }
            $query=$query->where($searchField,'like',"%{$keyword}%");
        }
        $count=$query->count();
        $list=$query
        ->page($this->page)
        ->limit($this->limit)
        ->withoutField('password')
        ->select()
        ->toArray();
        foreach ($list as $key => &$value) {
           $value['logo_url']=get_file_url($value['logo']);
           $value['banner_list']=get_file_urls($value['banner']);
           $smart_device=json_decode($value['smart_device'],1);
           $value['smart_device_appid']=isset($smart_device['appid'])?$smart_device['appid']:'';
           $value['smart_device_appkey']=isset($smart_device['appkey'])?$smart_device['appkey']:'';
           $value['smart_device_username']=isset($smart_device['username'])?$smart_device['username']:'';
           $value['smart_device_password']=isset($smart_device['password'])?$smart_device['password']:'';
           $value['electronic_mandun_apiUrl']=isset($smart_device['electronic_mandun_apiUrl'])?$smart_device['electronic_mandun_apiUrl']:'';
           $value['electronic_mandun_appKey']=isset($smart_device['electronic_mandun_appKey'])?$smart_device['electronic_mandun_appKey']:'';
           $value['electronic_mandun_appSecret']=isset($smart_device['electronic_mandun_appSecret'])?$smart_device['electronic_mandun_appSecret']:'';
           $value['electronic_mandun_uname']=isset($smart_device['electronic_mandun_uname'])?$smart_device['electronic_mandun_uname']:'';
           $value['electronic_mandun_passwd']=isset($smart_device['electronic_mandun_passwd'])?$smart_device['electronic_mandun_passwd']:'';
           $value['electronic_mandun_projectCode']=isset($smart_device['electronic_mandun_projectCode'])?$smart_device['electronic_mandun_projectCode']:'';
           $config=json_decode($value['config'],1);
           $value['open_door_bgm']=isset($config['open_door_bgm'])?$config['open_door_bgm']:'';
           $value['open_room_bgm']=isset($config['open_room_bgm'])?$config['open_room_bgm']:'';
           $value['xsj_app_key']=isset($config['xsjConfig']['app_key'])?$config['xsjConfig']['app_key']:'';
           $value['xsj_yard_sn']=isset($config['xsjConfig']['yard_sn'])?$config['xsjConfig']['yard_sn']:'';
           $value['tt_lock_username']=isset($config['xsjConfig']['tt_lock_username'])?$config['xsjConfig']['tt_lock_username']:'';
           $value['tt_lock_password']=isset($config['xsjConfig']['tt_lock_password'])?$config['xsjConfig']['tt_lock_password']:'';
           $value['wifi_username']=isset($config['wifi_config']['username'])?$config['wifi_config']['username']:'';
           $value['wifi_password']=isset($config['wifi_config']['password'])?$config['wifi_config']['password']:'';
           $icon_config=isset($config['icon_config']['home']['icon'])?$config['icon_config']:[];
           $value['lvmi_device']=json_decode($value['lvmi_device'],1);
           if(!$value['lvmi_device']){
              $value['lvmi_device']=[
                'accessToken'=>'',
                'expiresIn'=>'',
                'openId'=>'',
                'refreshToken'=>''
              ];
           }
           if(!$icon_config){
              $url=request()->domain().str_replace('index.php', '',request()->baseFile()).'static/shared/';
              $icon_config=[
                    'home'=>[
                      'title'=>'首页',
                      'status'=>1,
                      'icon'=>$url.'store_icon/home.png'
                    ],
                    'shop'=>[
                      'title'=>'茶城',
                      'status'=>1,
                      'icon'=>$url.'store_icon/shop.png'
                    ],
                    'kefu'=>[
                      'title'=>'客服',
                      'status'=>1,
                      'icon'=>$url.'store_icon/kefu.png'
                    ],
                    'wifi'=>[
                      'title'=>'WiFi',
                      'status'=>1,
                      'icon'=>$url.'store_icon/wifi.png'
                    ],
                    'code'=>[
                      'title'=>'商家码',
                      'status'=>1,
                      'icon'=>$url.'store_icon/code.png'
                    ],
                  ];
           }
           $value['icon_config']=$icon_config;
        }
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
    //编辑用户
    public function edit(){
    	$id=input('id');
        $form=Store::where(['id'=>$id])->find();
        try {
            $data=request()->post();
            $rule = [
               'account|账号'=>'require',
               'name|名称' => 'require',
               'logo|Logo' => 'require',
               'banner|图片' => 'require',
               'status|状态'=>'require',
               'tel|电话'=>'require',
               'tags|标签'=>'require',
               'address|地址'=>'require',
               'dec|概括'=>'require',
               'lat|纬度'=>'require',
               'lng|经度'=>'require',
               'policy|入住政策'=>'require',
               'fee|手续费比例'   => 'require',
           ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        if(!$form){
            $form=new Store();
            $form->acid=$this->acid;
            if(Store::where(['acid'=>$this->acid,'account'=>$data['account'],'is_delete'=>0])->count()){
            	return fetchJson([],'该账号已存在',1);
            }
        }else{
        	if(Store::where(['acid'=>$this->acid,'account'=>$data['account'],'is_delete'=>0])->where('id','<>',$form->id)->count()){
        		 return fetchJson([],'该账号已存在',1);
        	}
        }
        if($data['fee']>100||$data['fee']<0){
            return fetchJson([],'手续费比例请设置0-100内',1);
        }
        $form->account=$data['account'];
        if(!empty($data['password'])){
        	 $form->password=md5($data['password']);
        }
        $form->logo=$data['logo'];
        $form->area_id=$data['area_id'];
        $form->fee=$data['fee'];
        $form->name=$data['name'];
        $form->banner=$data['banner'];
        $form->status=$data['status'];
        $form->tel=$data['tel'];
        $form->tags=$data['tags'];
        $form->category=$data['category'];
        $form->address=$data['address'];
        $form->dec=$data['dec'];
        $form->openid=$data['openid'];
        $form->is_shop=empty(input('is_shop'))?0:input('is_shop');
        $form->lat=$data['lat'];
        $form->lng=$data['lng'];
        $form->policy=$data['policy'];
        $form->refund_rate=input('refund_rate');
        $form->local=input('local');
        $form->smart_device=json_encode([
           'appid'=>trim(input('smart_device_appid')),
           'appkey'=>trim(input('smart_device_appkey')),
           'username'=>trim(input('smart_device_username')),
           'password'=>trim(input('smart_device_password')),
           'electronic_mandun_apiUrl'=>trim(input('electronic_mandun_apiUrl')),
           'electronic_mandun_appKey'=>trim(input('electronic_mandun_appKey')),
           'electronic_mandun_appSecret'=>trim(input('electronic_mandun_appSecret')),
           'electronic_mandun_uname'=>trim(input('electronic_mandun_uname')),
           'electronic_mandun_passwd'=>trim(input('electronic_mandun_passwd')),
           'electronic_mandun_projectCode'=>trim(input('electronic_mandun_projectCode')),
        ]);
        $form->service_facilities=input('service_facilities');
        $form->facilities=input('facilities');
        $form->policy=input('policy');
        $form->video_url=input('video_url')?input('video_url'):0;
        $form->is_repeat_order_original=input('is_repeat_order_original')?input('is_repeat_order_original'):0;
        $form->config=json_encode([
          "open_door_bgm"=>input('open_door_bgm'),
          "open_room_bgm"=>input('open_room_bgm'),
          "xsjConfig"=>[
            'yard_sn'=>input('xsj_yard_sn'),
            'app_key'=>input('xsj_app_key'),
            'tt_lock_username'=>input('tt_lock_username'),
            'tt_lock_password'=>input('tt_lock_password')
          ],
          'wifi_config'=>[
            'username'=>input('wifi_username'),
            'password'=>input('wifi_password')
           ],
           'icon_config'=>json_decode(input('icon_config'),1)
        ]);
        $form->is_wallet=input('is_wallet')==1?1:0;
        $form->is_list_open=input('is_list_open')==1?1:0;
        $form->lvmi_device=json_encode(input('lvmi_device'));
        $form->store_manager=input('store_manager');
        $form->save();
        House::where('store_id',$form->id)->update(['address'=>$form->address,'lat'=>$form->lat,'lng'=>$form->lng]);
        return fetchJson([],'保存成功');
    }
    //快速编辑
    public function quickedit(){
        $id=input('id');
        $field=input('field');
        $edittext=input('edittext');
        $fieldArray=['name','status'];
        $form=Store::where(['acid'=>$this->acid,'id'=>$id])->find();
        if(!$form){
             return fetchJson([],'该数据未找到',1);
        }
        if(in_array($field,$fieldArray)){
            try {
               $form->save([
                   "{$field}"=>$edittext
               ]);
            } catch (ValidateException $e) {
                return fetchJson([],$e->getError(),1);
            } catch (\Exception $e) {
                return fetchJson([],$e->getMessage(),1);
            }
           return fetchJson([],'保存成功');
        }
        return fetchJson([],'该字段不能编辑',1);
    }
    public function delete(){
       $id=input('id');
       Store::where(['acid'=>$this->acid,'id'=>$id])->update(['is_delete'=>1]);
       return fetchJson([],'删除'); 
    }
    //申请列表
    public function applyList(){
        $query=ApplyBecomeStore::where(['acid'=>$this->acid,'is_delete'=>0]);
        $count=$query->count();
        $list=$query->page($this->page)->limit(10)->order('id DESC')->select();
        foreach ($list as $key => &$value) {
            $value['logo_url']=get_file_url($value['logo']);
            $value['banner_list']=get_file_urls($value['banner']);
            $value['area_name']=Area::where('id',$value['area_id'])->value('name');
        }
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
    //申请处理
    public function applyHandle(){
        try {
            $data=request()->post();
            $rule = [
                'id|ID'=>'require',
                'status|状态'=>'require|in:1,2',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        $form=ApplyBecomeStore::where(['acid'=>$this->acid,'id'=>$data['id'],'status'=>0])->find();
        if(!$form){
            return fetchJson([],'已处理',1);
        }
        $form->status=$data['status'];
        if($form->status==1){
            $account=input('account');
            $password=input('password')?input('password'):'123456';
            if(Store::where(['acid'=>$this->acid,'account'=>$account,'is_delete'=>0])->count()){
                return fetchJson([],'该账号，商户已存在',1);
            }
            $fee=input('fee');
            if($fee>=100||$fee<=0){
                 return fetchJson([],'手续费比例必须在0-100之间',1);
            }
            $store=new Store();
            $store->save([
                'acid'=>$this->acid,
                'account'=>$account,
                'password'=>md5($password),
                'logo'=>input('logo'),
                'name'=>$form['name'],
                'banner'=>input('banner'),
                'area_id'=>$form['area_id'],
                'address'=>input('address'),
                'lng'=>input('lng'),
                'lat'=>input('lat'),
                'status'=>0,
                'fee'=>$fee
            ]);
        }
        $form->save();
        return fetchJson([],'处理成功');
    }
    
        //获取绿米授权码
    public function getLvmiCode(){
        $account=input('account');
        $form=new Lvmi([
          'account'=>$account,
        ]);
        //获取验证码
        $res=$form->getAuthCode($account);
        if($res['code']==0){
          return fetchJson([],'获取成功');
        }
        return fetchJson([],$res['data'],1);
    }
     //绿米绑定
    public function lvmiDeviceBind(){
        $account=input('account');
        $code=input('code');
        $store_id=input('store_id');

        $form=new Lvmi([
          'account'=>$account,
          'id'=>$store_id,
          'code'=>$code,
        ]);
        //获取验证码
        $res=$form->positionCreate($code);
        if($res['code']==0){
             Store::where(['id'=>$store_id])->update([
              'lvmi_device'=>json_encode($res['data'])
             ]);
            return fetchJson($res['data'],'绑定成功');
        }
        return fetchJson([],'获取失败',1);
    }
    
}