<?php
/**
 * 微信配置
 * Date: 2017/6/21
 * Time: 15:32
 */

namespace app\admin\controller;


use app\mobile\controller\WechatApi;
use think\Lang;
use think\Request;
use think\Validate;

class Wechat extends AdminControl
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'admin/lang/zh-cn/wechat.lang.php');
    }


    //公众号配置
    public function setting()
    {
        if (!request()->isPost()) {
            //获取公众号配置信息
            $wx_config = db('wxconfig')->find();
            $this->assign('wx_config', $wx_config);
            //接口地址
            $wx_apiurl = 'http://' . $_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], 'index.php')) . 'Mobile/Wechat/index';
            $this->assign('wx_apiurl', $wx_apiurl);
            return $this->fetch();
        } else {
            $data = [
                'token' => input('post.wx_token'),
                'appid' => input('post.wx_appid'),
                'appsecret' => input('post.wx_AppSecret'),
                'wxname' => input('post.wx_name'),
            ];
            //公众号二维码图片待处理
            $id = input('param.wx_id');
            if (empty($id)) {
                $res = db('wxconfig')->insert($data);
            } else {
                $res = db('wxconfig')->where('id', $id)->update($data);
            }
            if ($res) {
                $this->success(lang('ds_common_op_succ'));
            } else {
                $this->error(lang('ds_common_op_fail'));
            }
        }
    }

    //公众号菜单
    public function menu()
    {
        //获取顶级菜单
        $p_menu = db('wxmenu')->where('pid', 0)->order('sort ASC')->select();
        //获取二级菜单
        $child_menu=array();
        foreach ($p_menu as $k => $v) {
            $child_list = db('wxmenu')->where('pid', $v['id'])->order('sort desc')->select();
            $child_menu[$v['id']] = $child_list;
        }
        $menu_type=array('view'=>lang('menu_type_1'),'click'=>lang('menu_type_2'),'view_limited'=>lang('menu_type_3'));
        $this->assign('menu_type',$menu_type);
        $this->assign('p_menu', $p_menu);
        $this->assign('c_menu', $child_menu);
        $this->setAdminCurItem('menu');
        return $this->fetch();
    }

    //菜单编辑
    public function menu_edit()
    {
        $menu_id = input('param.id');
        if (empty($menu_id)) {
            $this->error(lang('empty_error'));
        }
        if (!request()->isPost()) {
            $parents = db('wxmenu')->field('name,id')->where('pid', 0)->select();
            $this->assign('parents', $parents);
        $menu=db('wxmenu')->where('id',$menu_id)->find();
        $this->assign('menu',$menu);
            $this->setAdminCurItem('menu_add');
        return $this->fetch('menu_form');
    }else {
            $data = [
                'name' => input('post.menu_name'),
                'value' => input('post.menu_value'),
                'sort' => input('post.menu_sort'),
                'type' => input('post.menu_type'),
                'pid' => input('post.menu_pid'),
            ];
            //添加顶级菜单时判断是否超过限定数量
            if ($data['pid'] == '0'&& input('param.id')>0) {
                $num = db('wxmenu')->where('pid', 0)->count();
                if ($num > 3) {
                    $this->error('顶级菜单只能有三个');
                }
            }
            $rule = [
                ['sort', 'number', lang('sort_error')],
            ];
            $validate = new Validate();
            $res = $validate->check($data, $rule);
            if (!$res) {
                $this->error($validate->getError());
            }
            $res=db('wxmenu')->where('id',$menu_id)->update($data);
            if($res){
                $this->success(lang('ds_common_op_succ'));
            }else{
                $this->error(lang('ds_common_op_fail'));
            }
        }
    }

    //菜单添加
    public function menu_add()
    {
        if (!request()->isPost()) {
            $data = [
                'name' => '',
                'pid' => '',
                'value' => '',
                'sort' => '',
                'type' => '',
                'id' =>''
            ];
            $parents = db('wxmenu')->field('name,id')->where('pid', 0)->select();
            $this->assign('parents', $parents);
            $this->assign('menu', $data);
            $this->setAdminCurItem('menu_add');
            return $this->fetch('menu_form');
        } else {
            $data = [
                'name' => input('post.menu_name'),
                'value' => input('post.menu_value'),
                'sort' => input('post.menu_sort'),
                'type' => input('post.menu_type'),
                'pid' => input('post.menu_pid'),
            ];
            //添加顶级菜单时判断是否超过限定数量
            if($data['pid'] == '0'){
                $num=db('wxmenu')->where('pid',0)->count();
                if($num >2){
                    $this->error('顶级菜单只能有三个');
                }
            }
            $rule = [
                ['sort', 'number', lang('sort_error')],
            ];
            $validate = new Validate();
            $res=$validate->check($data,$rule);
            if(!$res){
                $this->error($validate->getError());
            }
            $result=db('wxmenu')->insert($data);
            if($result){
                $this->success(lang('ds_common_save_succ'),'admin/Wechat/menu');
            }else{
                $this->error(lang('ds_common_save_fail'));
            }

        }
    }

    //菜单删除
    public function menu_drop(){
        $menu_id = input('param.id');
        if (empty($menu_id)) {
            $this->error(lang('empty_error'));
        }
        $res=db('wxmenu')->where('id',$menu_id)->delete();
        if($res){
            $this->success(lang('ds_common_del_succ'));
        }else{
            $this->error(lang('ds_common_del_fail'));
        }
    }

    //更新公众号菜单
    public function pub_menu(){
        //获取菜单
        $config = model('wechat')->WxConfig();
        //获取父级菜单
        $p_menus = db('wxmenu')->where(array('pid'=>0))->order('id ASC')->select();
        $p_menus = ds_changeArraykey($p_menus,'id');

        $post_str = $this->convert_menu($p_menus);

        // http post请求
        if(!count($p_menus) > 0){
            $this->error('没有菜单可发布','Wechat/menu');
            exit;
        }
        //查看access_token是否过期
        $wechat=new WechatApi($config);
        $expire_time = $config['expires_in'];
        if($expire_time > time()){
            //有效期内
            $wechat->access_token_= $config['access_token'];
        }else{
            $access_token=$wechat->checkAuth();
            $web_expires = time() + 7000; // 提前200秒过期
            db('wxconfig')->where(array('id'=>$config['id']))->update(array('access_token'=>$access_token,'expires_in'=>$web_expires));
        }
        $return=$wechat->createMenu($post_str);

        if($return['errcode'] == 0){
            $this->success('菜单已成功生成','Wechat/menu');
        }else{
            echo "错误代码;".$wechat->errCode;
            exit;
        }
    }


    //菜单转换
    private function convert_menu($p_menus){

        $new_arr = array();
        $count = 0;
        foreach($p_menus as $k => $v){
            $new_arr[$count]['name'] = $v['name'];

            //获取子菜单
            $c_menus = db('wxmenu')->where(array('pid'=>$k))->select();

            if($c_menus){
                foreach($c_menus as $kk=>$vv){
                    $add = array();
                    $add['name'] = $vv['name'];
                    $add['type'] = $vv['type'];
                    // click类型
                    if($add['type'] == 'click'){
                        $add['key'] = $vv['value'];
                    }elseif($add['type'] == 'view'){
                        $add['url'] = $vv['value'];
                    }else{
                        $add['key'] = $vv['value'];
                    }
                    $add['sub_button'] = array();
                    if($add['name']){
                        $new_arr[$count]['sub_button'][] = $add;
                    }
                }
            }else{
                $new_arr[$count]['type'] = $v['type'];
                // click类型
                if($new_arr[$count]['type'] == 'click'){
                    $new_arr[$count]['key'] = $v['value'];
                }elseif($new_arr[$count]['type'] == 'view'){
                    //跳转URL类型
                    $new_arr[$count]['url'] = $v['value'];
                }else{
                    //其他事件类型
                    $new_arr[$count]['key'] = $v['value'];
                }
            }
            $count++;
        }

        return array('button'=>$new_arr);
    }

    /**
     * 关键字文本回复
     */
    public function k_text(){

        $wechat = model('wechat')->WxConfig();
        if(empty($wechat)){
            $this->error('请先在公众号配置添加公众号，才能进行文本回复管理', 'Admin/Wechat/setting');
        }
        $lists=db('wxkeyword')->alias('k')->join('__WXTEXT__ t','t.id=k.pid','LEFT')->where(array('type'=>'TEXT'))->field('k.id,k.keyword,t.text')->order('t.createtime DESC')->paginate(10,false,['query'=>request()->param()]);
        $this->assign('lists',$lists);
        $this->assign('show_page',$lists->render());
        return $this->fetch();
    }
    /*
     * 添加文本回复
     */
    public function text_form(){
        $wechat = db('wxconfig')->find();
        if(empty($wechat)){
            $this->error('请先在公众号配置添加公众号，才能添加文本回复', 'Admin/Wechat/setting');
        }
        if(\request()->isPost()){
            $kid = input('param.id');
            $add['keyword'] =  input('param.keyword');
            $add['text'] = input('param.text');
            if(empty($kid)){
                //添加模式
                $add['createtime'] = time();
                $add['pid'] = db('wxtext')->insertGetId($add);
                unset($add['text']);
                unset($add['createtime']);
                $add['type'] = 'TEXT';
                $row = db('wxkeyword')->insert($add);
            }else{
                //编辑模式
                $data = db('wxkeyword')->where(array('id'=>$kid))->find();
                if($data){
                    $update['keyword'] = $add['keyword'];
                    db('wxkeyword')->where(array('id'=>$kid))->update($update);
                    $row = db('wxtext')->where(array('id'=>$data['pid']))->update($add);

                }
            }
            $row ? $this->success("添加成功",'Admin/Wechat/k_text') : $this->error("添加失败",'Admin/Wechat/k_text');
            exit;
        }
        //编辑状态
        $id = input('param.id');
        if($id){
           $where="k.id={$id} AND k.type='TEXT'";
            $res=db('wxkeyword')->alias('k')->join('__WXTEXT__ t','t.id=k.id','LEFT')->where($where)->field('k.id,k.keyword,t.text')->find();
        }else{
            $res=array(
                'id'=>'',
                'keyword'=>'',
                'text'=>''

            );
        }
        $this->assign('key',$res);
        return $this->fetch();
    }

    /*
     * 删除文本回复
     */
    public function del_text(){
        $id = input('param.id');
        $row = db('wxkeyword')->where(array('id'=>$id))->find();
        if($row){
            db('wxkeyword')->where(array('id'=>$id))->delete();
            db('wxtext')->where(array('id'=>$row['pid']))->delete();
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    /**微信注册会员列表*/
    public function member(){
       $res = model('wechat')->member();
       $this->assign('show_page',model('wechat')->page_info->render());
       $this->assign('member',$res);
       return $this->fetch('member');
    }

    /**消息推送*/
    public function msend(){
        $touser=input('param.openid');
        $id=input('param.member_id');
        if(request()->isPost()) {
            $config = model('wechat')->WxConfig();
            $wechat = new WechatApi($config);
            $type = input('param.type');
            if ($type == 'text') {
                //发送文本消息
                $content = input('param.text');
                $send = array(
                    'touser' => $touser, 'msgtype' => 'text', 'text' => array('content' => $content)
                );
            }
            else {
                //发送图文消息
                $title = input('param.title');
                $description = input('param.description');
                $url = input('param.url');
                $picUrl = '';

                if (!empty($_FILES['s_pic']['name'])) {
                    $prefix = $id;
                    $file_path = BASE_UPLOAD_PATH . DS . DIR_ADMIN . DS . 'wechat';
                    $file_name = $prefix . '_' . date('YmdHis') . rand(10000, 99999);
                    $file = request()->file('s_pic');
                    $result = $file->validate(['ext' => 'jpg,png,gif,jpeg'])->move($file_path, $file_name);
                    if (!$result) {
                        $this->error($file->getError());
                    }
                    $filename = $result->getFilename();
                    $picUrl = UPLOAD_SITE_URL . DS . DIR_ADMIN . DS.'wechat' . DS . $filename;
                }
                $content = array(
                    array(
                    'title' => $title, 'description' => $description, 'url' => $url, 'picurl' => $picUrl
                    )
                );
                $send = array(
                    'touser' => $touser, 'msgtype' => 'news', 'news' => array('articles' => $content)
                );
            }

            $SendInfo = serialize($send);
            $data['member_id'] = $id;
            $data['content'] = $SendInfo;
            $data['createtime'] = time();
            $ret = $wechat->sendCustomMessage($send);
            if ($ret) {
                //添加至推送列表
                $data['issend'] = '1';
                model('wechat')->wxMsg($data);
                $this->success('发送成功', 'wechat/member');
            }
            $data['issend'] = '0';
            model('wechat')->wxMsg($data);
            $this->error('发送失败,错误代码:' . $wechat->errCode, 'wechat/member');
        }
        return $this->fetch();
    }

    /**消息推送列表*/
    public function SendList(){
        $list=model('wechat')->msgList();
       foreach ($list as $key=>$val){
           $info=unserialize($val['content']);
           $type=$info['msgtype'];
           $list[$key]['type']= $type=='text'? '文本':'图文';
           if($type=='text'){
               $list[$key]['content']=$info['text']['content'];
           }
           else{
               $content=$info['news']['articles']['0'];
               $content=json_encode($content);
               $list[$key]['content']="<a href='javascript:void(0);' class='news' content=''>查看图文消息</a>";
              /* $this->assign('title',$content['title']);
               $this->assign('description',$content['description']);
               $this->assign('url',$content['url']);
               echo $this->fetch('news');*/

           }
       }
        $this->assign('show_page',model('wechat')->page_info->render());
        $this->assign('lists',$list);
        return $this->fetch('list');
    }

    /**消息群发*/
    public function SendGroup(){
        if(request()->isPost()){
            $m_info=model('wechat')->member();
            $openid='';
            foreach ($m_info as $k=>$val){
                $openid.=$val['member_wxopenid'].',';
            }
            $openid=explode(',',$openid);
            $content=input('param.text');
            $send=array(
                'touser'=>$openid,
                'msgtype'=>'text',
                'text'=>array('content'=>$content)
            );
            $config = model('wechat')->WxConfig();
            $wechat=new WechatApi($config);
            $res=$wechat->massSend($send);
            if($res){
                $this->success('群发成功','wechat/SendList');
            }
            $this->error('发送失败,错误代码:'.$wechat->errCode,'wechat/SendList');
        }
        return $this->fetch('sendgroup');
    }

    protected function getAdminItemList()
    {
        $menu_array=array(
            array('name'=>'menu','text'=>'菜单','url'=>url('Wechat/menu')),
            array('name'=>'menu_add','text'=>'自定义菜单','url'=>url('Wechat/menu_add')),
        );
        return $menu_array;
    }
}