<?php
/**
 * 微信消息管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author lss <lss@qq.com>
 */

namespace Admin\Controller;
class OauthMemberController extends BaseController{
    public function message(){
        /* 查询条件初始化 */
        $map = array();
        $postdata=I('param.');
        if($postdata['name']){
            $where = $wheres = array();
            $where['id']=array('like','%'.$postdata['name'].'%');
            $where['username']=array('like','%'.$postdata['name'].'%');
            $where['mobile']=array('like','%'.$postdata['name'].'%');
            $where['_logic'] = 'or';
            $wheres['_complex'] = $where;
            $uid = M('Member')->where($wheres)->field('id')->select();
            $arr = array();
            foreach ($uid as $k => $v) {
                $arr[] = $v['id'];
            }
            $map['uid'] = implode(',',$arr);
        }
        if($postdata['time_frame'] && $postdata['time_end']){
            $map['sendtime'] = array(array('gt',strtotime($postdata['time_frame'])),array('lt',strtotime($postdata['time_end'])));
        }
        if($postdata['is_success'] == 2){
            $map['is_success'] = 0;
        }else if($postdata['is_success'] == 1){
			$map['is_success'] = 1;
		}
        $list = $this->lists('WxMsg', $map);
        $this->assign($postdata);
        $this->assign('list', $list);
        $this->display();
    }
    //添加新推送
    public function add() {   
        $this->display('edit');   
    }
    // 推送信息
    public function wxmsgsend() {
        $getdata=I('param.');
        $result = array();
        if($getdata['uid']&&$getdata['id']&&$getdata['resend']){//重新发送  
            $data=M('WxMsg')->where('id='.$getdata['id'])->field('content,openid')->find();
            $weixin = new \Common\Vendor\WeixinChat;
            $result=$weixin->sendMsg($data['content'], $data['openid'], 'text');
            $admininfo=session('admin_info');
            if($result['errcode']==0){
                $data['updatetime'] = NOW_TIME;
                $data['is_success'] = 1;
                $data['result']=$result['errmsg'];
                $data['adminid']=isset($admininfo['id'])?$admininfo['id']:0;
            }else{
                $data['result']=$result['errmsg'];
                $data['updatetime'] = NOW_TIME;
            }
            M('WxMsg')->where('id='.$getdata['id'])->save($data);
        }
        if($result['errcode']==0){
            $this->success('发送成功');
        }else{
            $this->error('发送失败');
        }
       
    }
    public function remove(){
        $ids=I('id');
        empty($ids) && $this->error('参数错误！');
        if(is_array($ids)){
            $map['id'] = array('in', $ids);
        }elseif (is_numeric($ids)){
            $map['id'] = $ids;
        }
        $res = M('WxMsg')->where($map)->delete();
        if($res !== false){
            $this->success('删除成功！');
        }else {
            $this->error('删除失败！');
        }
    }
    public function send(){
        $MemberRank = M('MemberRank')->where('status=1')->field('id,name')->select();
        foreach ($MemberRank as $k => $v) {
           $groupData[$v['id']] = $v['name'];
        }
        $this->assign('groupData', $groupData);
        $this->get_type(0,'add');
        $this->send_type();
        $this->display();
    }

    /**
     * 得到消息类型并传到页面
     * @param $type
     * @param $t    如果是发送消息,$t='add'
     */
    public function get_type($type,$t='')
    {
        $type_array=array();
        $type_array['1']='会员';
        $type_array['2']='店铺';
        $type_array['3']='供货商';
        $this->assign('type_array', $type_array);
        if(empty($t)) {
            $select_type = '';
            foreach ($type_array as $k => $v) {
                $select_type .= '<option value="' . $k . '"';
                if ($type == $k) $select_type .= 'selected="selected"';
                $select_type .= '>' . $v . '</option>';
            }
            $this->assign('select_type', $select_type);
        }
    }
    /**
      *得到发送类型
      */
    private function send_type(){
        $map['pid']=2;
        $map['status']=1;
        $send_list=M('Type')->where($map)->field('id,name')->select();
        $send_type = array();
        if (!empty($send_list)) {
            foreach ($send_list as $v) {
                $send_type[$v['id']] = $v['name'];
            }
        }
        $this->assign('send_type', $send_type);
    }
    public function insert()
    {
        $postdata = I('post.');
        // 会员筛选
        $uids = array();
        if($postdata['act_rang_ext']){
            $ordergoods = M('OrderGoods')->alias('og')->where('og.goods_id='.$postdata['act_rang_ext'])->field('oi.uid')->JOIN('LEFT JOIN __ORDER_INFO__ oi ON oi.id=og.order_id')->distinct('oi.uid')->select();
            foreach ($ordergoods as $k => $v) {
                $uids[] = $v['uid'];
            }

        }
        if($postdata['begin_consume_time'] && $postdata['end_consume_time']){//上次消费时间
            $map = array();
            $map['addtime'] = array(array('gt',strtotime($postdata['begin_consume_time'])),array('lt',strtotime($postdata['end_consume_time'])));
            if($uids){
                $map['uid']=array('in',$uids);
            }
            $uids = M('OrderInfo')->where($map)->group('uid')->getField('uid',true);
        }
        $map=array();
        $map['status']=array('GT',0);
        $map['is_tmp'] = 0;
        if($uids){
//            $uid = implode(',',array_unique($uids));
            $map['id']=array('in',$uids);
        }
        if(!empty($postdata['rank_id'])){
           $map['rank_id']=$postdata['rank_id'];
        }
        if($postdata['mobile']){
            $map['mobile']=$postdata['mobile'];
        }
        if($postdata['begin_usepoints'] || $postdata['end_usepoints']){
            $map['usepoints'] = array(array('gt',$postdata['begin_usepoints']),array('lt',$postdata['end_usepoints']));
        }
        if($postdata['begin_money'] || $postdata['end_money']){
            $map['money'] = array(array('gt',$postdata['begin_money']),array('lt',$postdata['end_money']));
        }
        if($postdata['begin_reg_time'] && $postdata['end_reg_time']){
            $map['card_time'] = array(array('gt',strtotime($postdata['begin_reg_time'])),array('lt',strtotime($postdata['end_reg_time'])));
        }
        $map['wxid'] = array('neq','');
        $data = M('Member')->where($map)->field('id')->select();
        foreach ($data as $k => $v) {
            $postdata['rank_select_right'][] = $v['id'];
        }
        $uidarr=$postdata['rank_select_right'];
        if(!$uidarr)$this->error('请选择收信人！');
        if(empty($postdata['send_type'])) $this->error('请选择通知类型');
        $postdata['rank_select_right'] = implode(',',$postdata['rank_select_right']);
        $postdata['send_type'] = implode(',',$postdata['send_type']);
        $postdata['count'] = count($data);
        $this->assign($postdata);
        $this->display();
    }
    // 发送信息
    public function send_information(){
        $postdata = I('post.');
        // $post['fromuid'] = $postdata['fromuid'];
        $post['type'] = 1;
        $post['send_type'] = explode(',',$postdata['send_type']);
        $post['title'] = $postdata['title'];
        $post['content'] = $postdata['content'];
        $post['rank_select'] = $postdata['rank_select'];
        $post['rank_select_right'] = explode(',',$postdata['rank_select_right']);     
        $post['id'] = $postdata['id'];
        $post['addtime'] = $postdata['addtime'];
        
        $model = D(CONTROLLER_NAME);
        $uidarr=$post['rank_select_right'];
        if(!$uidarr)$this->error('请选择收信人！');
        // $basedata['from'] = $post['fromuid'];
        $basedata['title'] = $post['title'];
        // $basedata['content'] = $post['content'];
        $basedata['type'] = $post['type'];
        $basedata['addtime'] = $post['addtime'];

        if(empty($post['send_type'])) $this->error('请选择通知类型');
        foreach ($uidarr as $key => $v) {
//            $map = array();
//            $map['id'] = $v;
            $username = show_user_name($v);
            $rep_arr=array('[会员名称]'=>$username);
            $adddata[$key] = $basedata;
            $adddata[$key]['content']=strtr($post['content'],$rep_arr);
            $adddata[$key]['user_name']=$username;
            $adddata[$key]['touid']=$v;
            $adddata[$key]['time']=date('Y-m-d H:i:s',NOW_TIME);
            $adddata[$key]['remark']=strtr($post['content'],$rep_arr);

            $map = array();
            $map['code'] = 'MEMBER_NEWS';
            $sms_theme = M('SmsTheme')->where($map)->field('theme_id,theme_remark,theme_data')->find();
            $adddata[$key]['theme_id'] = $sms_theme['theme_id'];
            $adddata[$key]['theme_remark'] = $sms_theme['theme_remark'];
            $adddata[$key]['theme_data'] = strtoarray($sms_theme['theme_data']);

            foreach ($post['send_type'] as $val) {
                 //
               if($val==1){
                    if($post['type']==3){
                        $adddata[$key]['to'] = idtoname($v,'Suppliers','email');
                    }else {
                        $adddata[$key]['to'] = idtoname($v,'Member','email');
                    }
                    $result=send_method($val,$adddata[$key]);
                }elseif($val==2){
                    if($post['type']==2){
                        $map = array();
                        $map['shop_id'] = $v;
                        $map['pid'] = 0;
                        $adddata[$key]['to'] = M('ShopsAccount')->where($map)->getField('mobile');
                    }else if($post['type']==3){
                        $adddata[$key]['to'] = idtoname($v,'Suppliers','phone');
                    }else {
                        $adddata[$key]['to'] = idtoname($v,'Member','mobile');
                    }

                    $result=send_method($val,$adddata[$key]);
                }else{
                    $adddata[$key]['to'] = $v;
                    $result=send_method($val,$adddata[$key]);
                    $ret[] = $result;
                }
            }
        }
        
        if (!empty($result)) {
            if ($_POST['isajax']) $this->assign('dialog', '1');
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/message');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            $this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }
}
?>