<?php
namespace app\shared\logic\platform;
use app\shared\model\App;
use app\shared\model\Option;
use app\shared\model\SystemLog;
use think\exception\ValidateException;
use app\BaseController;
class SettingsForm extends  Base
{
    //获取数据
    public  function info(){
        $data=App::withoutField('password')->find($this->acid);
        $data['logo_url']=get_file_url($data['logo']);
        $data['wxapp_qrcode_url']=qrcodeUrl($this->acid,$wxappPath="pages/index/index",$dirname="platform_qr",$filename=$this->acid);
        $data['app_system_copyright']=Option::get_data($this->acid,'platform','app_system_copyright');
        $data['app_system_shortened']=Option::get_data($this->acid,'platform','app_system_shortened');
        $data['app_system_help_dec']=Option::get_data($this->acid,'platform','app_system_help_dec');
        $data['app_system_about_dec']=Option::get_data($this->acid,'platform','app_system_about_dec');
        $data['app_wechat_upload_key']=Option::get_data($this->acid,'platform','app_wechat_upload_key');
        $data['app_system_phones']=Option::where(['acid'=>$this->acid,'name'=>'app_system_phones'])->value('value');
        $data['app_thousands_tea_token']=Option::get_data($this->acid,'platform','app_thousands_tea_token');
        if(!$data['app_thousands_tea_token']){
            $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
            $app_thousands_tea_token=qy_encode(json_encode(['url'=>$root_url,'acid'=>$this->acid,'time'=>time()]));
            Option::set_data($this->acid,'platform','app_thousands_tea_token',$app_thousands_tea_token);
            $data['app_thousands_tea_token']=$app_thousands_tea_token;
        }
        return fetchJson($data);
    }
    public function edit(){
        $form=App::where(['id'=>$this->acid])->find();
        try {
            $data=request()->post();
            $rule = [
                'account|账号'   => 'require',
                'name|名称'=>'require',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        if(App::where(['account'=>$data['account']])->where('id','<>',$form->id)->count()){
            return fetchJson([],'该账号平台已存在',1);
        }
        $form->account=input('account');
        if(!empty(input('password'))){
             $form->password=md5(input('password'));
        }
        if(!$form->password){
            return fetchJson([],'请设置密码',1);
        }
        $form->logo=input('logo');
        $form->wx_app_id=input('wx_app_id');
        $form->wx_app_secret=input('wx_app_secret');
        $form->wxapp_app_id=input('wxapp_app_id');
        $form->wxapp_app_secret=input('wxapp_app_secret');
        $form->wx_mch_id=input('wx_mch_id');
        $form->wx_key=input('wx_key');
        $form->wx_cert_pem=input('wx_cert_pem');
        $form->wx_key_pem=input('wx_key_pem');
        $form->name=input('name');
        $form->save();
        Option::set_data($this->acid,'platform','app_system_shortened',input('app_system_shortened'));
        Option::set_data($this->acid,'platform','app_system_copyright',input('app_system_copyright'));
        Option::set_data($this->acid,'platform','app_system_help_dec',input('app_system_help_dec'));
        Option::set_data($this->acid,'platform','app_system_about_dec',input('app_system_about_dec'));
        Option::set_data($this->acid,'platform','app_wechat_upload_key',input('app_wechat_upload_key'));
        $op=Option::where(['acid'=>$this->acid,'name'=>'app_system_phones'])->find();
        if(!$op){
           $op=new Option();
        }
        $app_system_phones=input('app_system_phones');
        $op->save(['acid'=>$this->acid,'name'=>'app_system_phones','value'=>$app_system_phones?$app_system_phones:0]);
        if(input('app_thousands_tea_reset')==1){
            $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
            $app_thousands_tea_token=qy_encode(json_encode(['url'=>$root_url,'acid'=>$this->acid,'time'=>time()]));
            Option::set_data($this->acid,'platform','app_thousands_tea_token',$app_thousands_tea_token,1);
        }
        return fetchJson([],'保存成功');
    }
    public function navList(){
        if(input('is_edit')){
            Option::set_data($this->acid,'platform','app_nav_list',input('app_nav_list'));
            return fetchJson([],'保存成功');
        }else{
            $nav_list=Option::get_data($this->acid,'platform','app_nav_list');
            return fetchJson([
                'app_nav_list'=>json_decode($nav_list,1)
            ],'获取成功');
        }
    }
    //茶艺师设置
    public function teaSpecialistSetting(){
        if(input('is_edit')){
            Option::set_data($this->acid,'platform','app_tea_specialist_setting',input('app_tea_specialist_setting'));
            return fetchJson([],'保存成功');
        }else{
            $tea_specialist=Option::get_data($this->acid,'platform','app_tea_specialist_setting');
            return fetchJson([
                'app_tea_specialist_setting'=>json_decode($tea_specialist,1)
            ],'获取成功');
        }
    }
    //分销设置
    public function shareSetting(){
        if(input('is_edit')){
            Option::set_data($this->acid,'platform','app_share_setting',json_encode([
                'status'=>input('status'),
                'one'=>input('one'),
                'two'=>input('two')
            ]));
            Option::set_data($this->acid,'platform','app_share_rule',input('app_share_rule'));
            Option::set_data($this->acid,'platform','app_share_bg',input('app_share_bg'));

            return fetchJson([],'保存成功');
        }else{
            $share_setting=Option::get_data($this->acid,'platform','app_share_setting');
            return fetchJson([
                'app_share_setting'=>json_decode($share_setting,1),
                'app_share_rule'=>Option::get_data($this->acid,'platform','app_share_rule'),
                'app_share_bg'=>Option::get_data($this->acid,'platform','app_share_bg'),
            ],'获取成功');
        }
    }
    //美团店铺
    public function mtdianping(){
        $session=input('session');
        $session=json_decode(base64_decode($session),1);
        $getShopid=input('getShopid');
        $getShopid=json_decode(base64_decode($getShopid),1);
        if($session['code']==200&&$getShopid['code']==200){
            return fetchJson([
                'session'=>$session['access_token'],
                'bid'=>$session['bid'],
                'shop_list'=>$getShopid['data'],
                'alldata'=>$session,
                'create_time'=>time(),
            ]);
        }
        return fetchJson([],'绑定出错',1);
    }
    //美团店铺编辑
    public function mtdianpingEdit(){
        if(input('is_find')){
             $find=Option::get_data($this->acid,'platform','app_meituan_dianping');
             $find=json_decode($find,1);
            $find['meituan_url']="https://chashi.youdiy.cn/meituan.php?data=".base64_encode(json_encode(['url'=>request()->host(),'acid'=>$this->acid]));
             return fetchJson($find);
        }
        Option::set_data($this->acid,'platform','app_meituan_dianping',input('app_meituan_dianping'));
        return fetchJson([],'绑定成功',0);
    }
    //云片配置
    public function cloudSheetConfig(){
       if(input('is_find')){
            $config=Option::get_data($this->acid,'shared','cloudSheetConfig');
            if(!$config){
               $config=[
                  'title'=>'',
                  'apiKey'=>'',
               ];
            }else{
              $config=json_decode($config,1);
            }
            $tpl=Option::get_data($this->acid,'shared','cloudSheetConfigTplMsg');
            if(!$tpl){
                $config['ptu_arrive_tpl']="";
                $config['ptu_expire_tpl']="";
            }else{
                $tpl=json_decode($tpl,1);
                $config['ptu_arrive_tpl']=$tpl['ptu_arrive_tpl'];
                $config['ptu_expire_tpl']=$tpl['ptu_expire_tpl'];
            }
            return fetchJson($config);
       }
       Option::set_data($this->acid,'shared','cloudSheetConfig',json_encode([
         'title'=>input('title'),
         'apiKey'=>input('apiKey'),
       ]));
       Option::set_data($this->acid,'shared','cloudSheetConfigTplMsg',json_encode([
         'ptu_arrive_tpl'=>input('ptu_arrive_tpl'),
         'ptu_expire_tpl'=>input('ptu_expire_tpl'),
       ]));
       return fetchJson([],'保存成功');
   }
   //绿米配置
   public function lvmiConfig(){
       if(input('is_find')){
            $config=Option::where(['module'=>'shared','name'=>'lvmiSysTemConfig'])->value('value');
            $config=json_decode($config,1);
            if(!$config){
               $config=[
                  'appid'=>'',
                  'keyid'=>'',
                  'appKey'=>'',
               ];
            }
            return fetchJson($config);
       }
       try {
            $data=request()->post();
            $rule = [
                'appid'   => 'require',
                'keyid'   => 'require',
                'appKey'   => 'require',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        $config=Option::where(['module'=>'shared','name'=>'lvmiSysTemConfig'])->find();
        if(!$config){
            $config=new Option();
            $config->acid=-1;
            $config->module='shared';
            $config->name='lvmiSysTemConfig';
        }
        $config->save([
            'value'=>json_encode([
                 'appid'=>input('appid'),
                 'keyid'=>input('keyid'),
                 'appKey'=>input('appKey'),
            ])
        ]);
       return fetchJson([],'保存成功');
   }
   //微信上传小程序
   public function wxappUpload(){
        try {
            $data=request()->post();
            $rule = [
                'status|状态'   => 'require|in:1,2,3',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
       $url="http://wxapp.youdiy.cn/index.php?s=index/index/"; 
       $log=SystemLog::order('id DESC')->field('content,version')->find();
       if($data['status']==1){
           $domain=request()->domain().str_replace('index.php', '',request()->baseFile());
           $domain=str_replace('https://', '',$domain);
           $domain=str_replace('http://', '',$domain);
           $res=httpRequest($url.'setting','POST',[
            'appid'=>$this->admin->wxapp_app_id,
            'domain'=>$domain,
            'wxapp_key'=>Option::get_data($this->acid,'platform','app_wechat_upload_key'),
            'acid'=>$this->acid,
            'version'=>$log['version'],
          ]);
          $res=json_decode($res,1);
          return fetchJson($res['data'],$res['msg'],$res['code']);
       }else if($data['status']==2){
         $res=httpRequest($url.'preview','POST',[
            'appid'=>$this->admin->wxapp_app_id,
          ]);
          $res=json_decode($res,1);
          if($res['code']==0){
             $root_url=request()->domain().str_replace('index.php', '',request()->baseFile());
             file_put_contents(app()->getRootPath().'public/qrcode/'.$this->admin->wxapp_app_id.'qrcode.png',file_get_contents($res['data']['qrcode_url']));
             $res['data']['qrcode_url']=$root_url.'qrcode/'.$this->admin->wxapp_app_id.'qrcode.png?time='.time();
          }
          return fetchJson($res['data'],$res['msg'],$res['code']);
       }else if($data['status']==3){
          $res=httpRequest($url.'upload','POST',[
            'appid'=>$this->admin->wxapp_app_id,
            'version'=>$log['version'],
            'desc'=>$log['content'],
          ]);
          $res=json_decode($res,1);
          return fetchJson($res['data'],$res['msg'],$res['code']);
       }else{
           return fetchJson([],'系统错误',1);
       }
   }
}