<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\View;
use think\facade\Validate;
use app\common\model\WechatKeywords as WechatKeywordsModel;
use app\common\model\WechatTemplate as WechatTemplateModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\CompanyContent as CompanyContentModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\WechatTweetsTpl as WechatTweetsTplModel;
use app\bsadmin\model\ApiApp as ApiAppModel;
use app\common\controller\Posters as PostersController;
use app\common\controller\Vip as VipController;
use helper\URL;
use helper\Wechat as WechatHelper;
class Wechat extends Base
{
    public function menu()
    {
        $Data=config('xy_wechat_mp_menu');
        $D=[];
        if(!empty($Data['button'])){
            foreach ($Data['button'] as $k => $v) {
                if (empty($v['sub_button'])) {
                    $D[$k]=[
                        'title'     => $v['name'],
                        'type'      => $v['type'],
                        'data'      =>  [],
                    ];
                    switch ($v['type']) {
                        case 'key':
                            $D[$k]['content']=$v['key'];
                            break;
                        case 'click':
                            $D[$k]['content']=$v['key'];
                            break;
                        case 'miniprogram':
                            $D[$k]['content']='';
                            $D[$k]['url']=$v['url'];
                            $D[$k]['appid']=$v['appid'];
                            $D[$k]['pagepath']=$v['pagepath'];
                            break;
                        
                        default:
                            $D[$k]['content']=$v['url'];
                            break;
                    }
                }else{
                    $D[$k]=[
                        'title'     => $v['name'],
                        'type'      => 'view',
                        'content'   => 'sub',
                    ];
                    foreach ($v['sub_button'] as $ke => $va) {
                        $D[$k]['data'][$ke]=[
                            'title'     => $va['name'],
                            'type'      => $va['type'],
                            ];
                        switch ($va['type']) {
                            case 'key':
                                $D[$k]['data'][$ke]['content']=$va['key'];
                                break;
                            case 'click':
                                $D[$k]['data'][$ke]['content']=$va['key'];
                                break;
                            case 'miniprogram':
                                $D[$k]['data'][$ke]['content']='';
                                $D[$k]['data'][$ke]['url']=$va['url'];
                                $D[$k]['data'][$ke]['appid']=$va['appid'];
                                $D[$k]['data'][$ke]['pagepath']=$va['pagepath'];
                                break;
                            
                            default:
                                $D[$k]['data'][$ke]['content']=$va['url'];
                                break;
                        }
                    }
                }
            }
        }
        View::assign('wxmenu',$D);
		return View::fetch();
    }
    public function saveMenu()
    {
    	if (request()->isPost()) {
            $D=request()->post();
	        if(empty($D['menu']))return $this->ajaxReturn('菜单不能为空');
	        $RouteWrite="<?php\nreturn [\n'button'=>[";
	        $menus='';
	        foreach ($D['menu'] as $k => $v) {
	            if(empty($v['data'])){
	                switch ($v['type']) {
	                    case 'key':
	                        $content="'key'=>'".$v['content']."'";
	                        break;
                        case 'click':
                            $content="'key'=>'".$v['content']."'";
                            break;
	                    case 'miniprogram':
                            $content="'url'=>'".$v['url']."'";
                            $content.=",'appid'=>'".$v['appid']."'";
	                        $content.=",'pagepath'=>'".$v['pagepath']."'";
	                        break;
	                    
	                    default:
	                        $content="'url'=>'".$v['content']."'";
	                        break;
	                }
	                $menus.=$k."=>['name'=>'".$v['title']."','type'=>'".$v['type']."',".$content."],\n";
	            }else{
	                $menus.=$k."=>['name'=>'".$v['title']."','sub_button'=>[";
	                foreach ($v['data'] as $ke => $va) {
	                    switch ($va['type']) {
	                        case 'key':
	                            $content="'key'=>'".$va['content']."'";
	                            break;
	                        case 'click':
	                            $content="'key'=>'".$va['content']."'";
	                            break;
                            case 'miniprogram':
                                $content="'url'=>'".$v['url']."'";
                                $content.=",'appid'=>'".$v['appid']."'";
                                $content.=",'pagepath'=>'".$v['pagepath']."'";
                                break;
	                        
	                        default:
	                            $content="'url'=>'".$va['content']."'";
	                            break;
	                    }
	                    $menus.=$ke."=>['name'=>'".$va['title']."','type'=>'".$va['type']."',".$content."],\n";
	                }
	                $menus.="],],";

	            }
	        }
	        $RouteWrite.=$menus."]];";
	        $RoutePath=config_path()."xy_wechat_mp_menu.php";;
	        $RouteFile = fopen($RoutePath, "w") or die("Unable to open file!");
	        fwrite($RouteFile, $RouteWrite);
	        fclose($RouteFile);
	        return $this->ajaxReturn();
	    }
    }
    public function releaseMenu()
    {
        if(request()->isAjax()){
            $Data=config('xy_wechat_mp_menu');
	        // JSON转换并且中文不转换
	        $menus = json_encode($Data, JSON_UNESCAPED_UNICODE);
	        // 获取TOKEN
	        $token = WechatHelper::GetWeiXinToken();
	        if (empty($token))
	            return $this->ajaxReturn('非常抱歉，TOKEN获取失败',-100);
	        if (!empty($token['status']) && $token['status']){
                $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$token['access_token']}";
                // 创建菜单
                $status = json_decode(URL::post($url, $menus), true);
                if ($status['errcode'] == 0 && $status['errmsg'] == 'ok') {
                    return $this->ajaxReturn('发布微信菜单成功');
                }else{
                    return $this->ajaxReturn('发布微信菜单失败<br />错误码：' . $status['errcode']. '<br />错误信息：' . $status['errmsg'],-100);
                }
            }else{
                return $this->ajaxReturn('非常抱歉，TOKEN获取失败',-100);
            }
        }
    }
    public function keywords()
    {
        if (request()->isAjax()) {
            $Data=WechatKeywordsModel::order('id desc')->paginate(1000)->each(function($v){
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑套餐
     */
    public function editKeywords($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'keyword'       => 'require|max:20',
                'value'         => 'require',
            ];
            $msg  =   [
                'keyword.require'       => '关键词不能为空', 
                'keyword.max'           => '关键词不能超过20个字符',
                'value.require'         => '请输入或选择回复内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatKeywordsModel=WechatKeywordsModel::find($id);
            $WechatKeywordsModel->keyword       = $D['keyword'];
            $WechatKeywordsModel->value         = $D['value'];
            $WechatKeywordsModel->type          = $D['type'];
            $WechatKeywordsModel->status        = $D['status'];
            $WechatKeywordsModel->is_default    = $D['is_default'];
            if ($D['is_default'])
                $this->cancelKeywordsDefault();
            $this->setKeywordsCache($WechatKeywordsModel);
            if ($WechatKeywordsModel->save()) {
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=WechatKeywordsModel::where(['id'=>$id])->find();
            if (request()->isAjax())
                return $this->ajaxReturn('',0,$Find);
            View::assign('Find',$Find);
            return View::fetch('add_keywords');
        }
    }
    /**
     * 创建套餐
     */
    public function addKeywords()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'keyword'       => 'require|max:20',
                'value'         => 'require',
            ];
            $msg  =   [
                'keyword.require'       => '关键词不能为空', 
                'keyword.max'           => '关键词不能超过20个字符',
                'value.require'         => '请输入或选择回复内容',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatKeywordsModel=new WechatKeywordsModel;
            $WechatKeywordsModel->keyword       = $D['keyword'];
            $WechatKeywordsModel->value         = $D['value'];
            $WechatKeywordsModel->type          = $D['type'];
            $WechatKeywordsModel->status        = $D['status'];
            $WechatKeywordsModel->is_default    = $D['is_default'];
            if ($D['is_default'])
                $this->cancelKeywordsDefault();
            $this->setKeywordsCache($WechatKeywordsModel);
            if ($WechatKeywordsModel->save()) {
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setKeywordsStatus($id,$status)
    {
        $WechatKeywordsModel=WechatKeywordsModel::find($id);
        $WechatKeywordsModel->status=$status;
        $this->setKeywordsCache($WechatKeywordsModel);
        if ($WechatKeywordsModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 设置套餐状态
     */
    public function setKeywordsDefault($id,$default)
    {
        $WechatKeywordsModel=WechatKeywordsModel::find($id);
        $WechatKeywordsModel->is_default=$default;
        $this->cancelKeywordsDefault();
        if ($WechatKeywordsModel->save()) {
            $this->setKeywordsCache($WechatKeywordsModel);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function cancelKeywordsDefault()
    {
        $DefaultWechatKeywordsModel=WechatKeywordsModel::where(['is_default'=>1])->find();
        if ($DefaultWechatKeywordsModel) {
            $DefaultWechatKeywordsModel->is_default=0;
            $DefaultWechatKeywordsModel->save();
        }
    }
    public function setKeywordsCache($Model)
    {
        if ($Model->status) {
            if ($Model->is_default)
                Cache::set('Wechat.default.keywords',$Model->value);
            Cache::set('Wechat.keywords.'.$Model->keyword,$Model->value);
        }else{
            if ($Model->is_default)
                Cache::delete('Wechat.default.keywords');
            Cache::delete('Wechat.keywords.'.$Model->keyword);
        }
    }
    public function delKeywords($id)
    {
        $WechatKeywordsModel=WechatKeywordsModel::find($id);
        $WechatKeywordsModel->status=0;
        $WechatKeywordsModel->is_default=0;
        $this->setKeywordsCache($WechatKeywordsModel);
        if ($WechatKeywordsModel->delete()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function pushTpl()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if(!empty($G['action'])&&$G['action']=='cache'){
                $WechatTemplateModel=WechatTemplateModel::field('id')->select();
                foreach ($WechatTemplateModel as $v) {
                    $this->setPushTplCache($v->id);
                }
                return $this->ajaxReturn();
            }
            $Data=WechatTemplateModel::paginate(1000)->each(function($v){
                    $v->item_data=json_decode($v->item_data,true);
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑套餐
     */
    public function editPushTpl($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'alias'       => 'require|max:50|unique:wechat_template',
                'title'       => 'require|max:100',
                'tplid'       => 'require',
                'first'       => 'require',
                'remark'      => 'require',
            ];
            $msg  =   [
                'alias.require'       => 'Alias不能为空', 
                'alias.max'           => 'Alias不能超过50个字符',
                'alias.unique'        => 'Alias已存在',
                'title.require'       => '名称不能为空',
                'title.max'           => '名称不能超过100个字符',
                'tplid.require'       => '模板ID不能为空',
                'first.require'       => 'First不能为空',
                'remark.require'      => 'Remark不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatTemplateModel=WechatTemplateModel::find($id);
            $alias='';
            if($WechatTemplateModel->alias!=$D['alias'])
                $alias=$WechatTemplateModel->alias;
            $WechatTemplateModel->alias         = $D['alias'];
            $WechatTemplateModel->number        = $D['number'];
            $WechatTemplateModel->title         = $D['title'];
            $WechatTemplateModel->tplid         = $D['tplid'];
            $WechatTemplateModel->first         = $D['first'];
            $WechatTemplateModel->first_color   = empty($D['first_color'])?'#343434':$D['first_color'];
            $WechatTemplateModel->remark        = $D['remark'];
            $WechatTemplateModel->remark_color  = empty($D['remark_color'])?'#343434':$D['remark_color'];
            $WechatTemplateModel->item_data     = json_encode($D['item_data'],JSON_UNESCAPED_UNICODE);
            $WechatTemplateModel->url           = $D['url'];
            $WechatTemplateModel->status        = $D['status'];
            if ($WechatTemplateModel->save()) {
                if($alias)
                $this->delPushTplCache($alias);
        		$this->setPushTplCache($WechatTemplateModel->id);
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=WechatTemplateModel::where(['id'=>$id])->withAttr('item_data',function($v,$data){
                return json_decode($v,true);
            })->find();
            if (request()->isAjax())
                return $this->ajaxReturn('',0,$Find);
            View::assign('Find',$Find);
            return View::fetch('add_push_tpl');
        }
    }
    /**
     * 创建套餐
     */
    public function addPushTpl()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'alias'       => 'require|max:50|unique:wechat_template',
                'title'       => 'require|max:100',
                'tplid'       => 'require',
                'first'       => 'require',
                'remark'      => 'require',
            ];
            $msg  =   [
                'alias.require'       => 'Alias不能为空', 
                'alias.max'           => 'Alias不能超过50个字符',
                'alias.unique'        => 'Alias已存在',
                'title.require'       => '名称不能为空',
                'title.max'           => '名称不能超过100个字符',
                'tplid.require'       => '模板ID不能为空',
                'first.require'       => 'First不能为空',
                'remark.require'      => 'Remark不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $WechatTemplateModel=new WechatTemplateModel;
            $WechatTemplateModel->alias         = $D['alias'];
            $WechatTemplateModel->number        = $D['number'];
            $WechatTemplateModel->title         = $D['title'];
            $WechatTemplateModel->tplid         = $D['tplid'];
            $WechatTemplateModel->first         = $D['first'];
            $WechatTemplateModel->first_color   = empty($D['first_color'])?'#343434':$D['first_color'];
            $WechatTemplateModel->remark        = $D['remark'];
            $WechatTemplateModel->remark_color  = empty($D['remark_color'])?'#343434':$D['remark_color'];
            $WechatTemplateModel->item_data     = json_encode($D['item_data'],JSON_UNESCAPED_UNICODE);
            $WechatTemplateModel->url           = $D['url'];
            $WechatTemplateModel->status        = $D['status'];
            if ($WechatTemplateModel->save()) {
        		$this->setPushTplCache($WechatTemplateModel->id);
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setPushTplStatus($id,$status)
    {
        $WechatTemplateModel=WechatTemplateModel::find($id);
        $WechatTemplateModel->status=$status;
        if ($WechatTemplateModel->save()) {
        	$this->setPushTplCache($id);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function setPushTplCache($id)
    {
        $WechatTemplateModel=WechatTemplateModel::where(['id'=>$id])->withAttr('item_data',function($v){
            return json_decode($v,true);
        })->find();
        if ($WechatTemplateModel)
            Cache::set('WechatTemplate.'.$WechatTemplateModel->alias,$WechatTemplateModel->toArray());
    }
    /**
     * 设置套餐状态
     */
    public function delPushTpl($id)
    {
        $WechatTemplateModel=WechatTemplateModel::find($id);
        if ($WechatTemplateModel->delete()) {
            $this->delPushTplCache($WechatTemplateModel->alias);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function delPushTplCache($alias)
    {
        Cache::delete('WechatTemplate.'.$alias);
    }
}
