<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------


namespace app\mp\controller;

use app\common\model\MpFriends;
use think\facade\Cache;
use think\Db;
use think\facade\Request;

class Friends extends Base
{
    public $friendMode;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function index()
    {
        $where = [];
        $nickname = '';
        $times = '';
        $need = '';
        $sex = '';
        if (Request::isGet()) {
            $_data = input('get.');
            $nickname = isset($_data['nickname']) ? $_data['nickname'] : '';
            $where = [];
            if (isset($_data['nickname'])) {
                $where[] = ['nickname', 'like', "%{$_data['nickname']}%"];
            }
            if (isset($_data['times'])) {
                $times = explode('到', $_data['times']);
                if (count($times) == 2) {
                    $where[] = ['subscribe_time', 'between', [strtotime($times[0]), strtotime($times[1]) + 86400]];
                }
                $times = $_data['times'];
            }
            if (isset($_data['need']) && $_data['need'] == 1) {

                $where[] = ['last_time', '>', (time() - (86400 * 2))];
                $need = 1;
            }
            if (isset($_data['sex']) && $_data['sex'] != 0) {
                $sex = $_data['sex'] ? $_data['sex'] : '0';
                $where[] = ['sex', '=', $_data['sex']];
            }
        }
        $post['nickname'] = $nickname;
        $post['times'] = $times;
        $post['need'] = $need;
        $post['sex'] = $sex;
        $FriendList = MpFriends::where(['mpid' => $this->mid, 'subscribe' => 1])
            ->where($where)
            ->order('subscribe_time DESC')->paginate(20);
        $this->assign('friendList', $FriendList);
        $this->assign('post', $post);
        return view();
    }

    public function SynFriends()
    {
        ini_set('max_execution_time', '0');
        $this->assign('url', '');
        $this->assign('jdtCss', '');
        $page = input('page');
        $page = $page ? $page : 0;
        $IN = input();
        $next_openid = isset($IN['next_openid']) ? $IN['next_openid'] : null;
        $wechatObj = getWechatActiveObj();
        $table = config('database.prefix') . 'syn_openid';
        $sql = "DELETE FROM {$table} WHERE openid IN (SELECT * FROM(SELECT openid FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS b) AND id NOT IN (SELECT * FROM (SELECT MIN(id) FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS c)";
        Db::execute($sql);
        $opneidTotal = Db::name('syn_openid')->where('mpid', '=', $this->mid)
            ->distinct(true)
            ->field('openid')
            ->count();
        $friendTotal = session($this->mid . 'friendTotal');
        if ($opneidTotal >= $friendTotal  && $friendTotal >0) {
            $synOpenids = Db::name('syn_openid')->where('mpid', '=', $this->mid)
                ->distinct(true)
                ->field('openid')
                ->paginate(100);
            if (!empty($synOpenids->items())) {
                $openids['user_list'] = [];
                foreach ($synOpenids as $key => $val) {
                    $openids['user_list'][$key]['openid'] = $val['openid'];
                }
                $friends_array = $wechatObj->getUsersInfo($openids);
                if (isset($friends_array['user_info_list']) && is_array($friends_array['user_info_list'])) {
                    foreach ($friends_array['user_info_list'] as $value) {
                        $value['mpid'] = $this->mid;
                        $value['tagid_list'] = @json_encode($value['tagid_list'], true);
                        if (Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->field('id')->find()) {
                            Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->update($value);
                        } else {
                            Db::name('mp_friends')->insert($value);
                        }
                    }
                }
                $url = getHostDomain() . url('mp/Friends/SynFriends', ['page' => $page + 1]);
                $jdtCss = abs(ceil(((100 * $page / $friendTotal) * 100)));
                if ($jdtCss > 100) {
                    $jdtCss = 100;
                }
                $this->assign('text', $jdtCss . '%');
                $this->assign('jdtCss', $jdtCss . '%');
                $this->assign('url', $url);
            } else {
                $this->assign('jdtCss', '100%');
                $this->assign('text', '同步完成');
                Db::name('syn_openid')->where('mpid', '=', $this->mid)->delete();
            }
            return view('friend');
        }
        $friendList = $wechatObj->getUserList($next_openid);
        session($this->mid . 'friendTotal', $friendList['total']);
        if (!empty($friendList) && $friendList['count'] > 0) {
            $openids = array_chunk($friendList['data']['openid'], 5000);
            foreach ($openids as $key => $val) {
                foreach ($val as $key1 => $opneid) {
                    $openid_list[$key][$key1] = [
                        'openid' => $opneid,
                        'mpid' => $this->mid
                    ];
                }
                Db::name('syn_openid')->insertAll($openid_list[$key]);
            }
            $url = getHostDomain() . url('mp/Friends/SynFriends', ['next_openid' => $friendList['next_openid']]);
            $jdtCss = abs(ceil(($opneidTotal / $friendList['total'] * 100)));
            $this->assign('text', '同步openid');
            $this->assign('jdtCss', $jdtCss . '%');
            $this->assign('url', $url);
            return view('friend');
        } else {
            if ($wechatObj->errCode != '40001' && $wechatObj->errCode != '' && $wechatObj->errMsg != '') {
                if ($msg = wxApiResultErrorCode($wechatObj->errCode)) {
                    exit($msg);
                } else {
                    exit('errCode:' . $wechatObj->errCode . 'errMsg:' . $wechatObj->errMsg);
                }
            }
            $this->assign('jdtCss', '100%');
            $this->assign('text', '同步完成');
            return view('friend');
        }
    }

    public function synSelect()
    {
        $IN = input();
        if (!empty($IN) && isset($IN['openids'])) {
            $wechatObj = getWechatActiveObj();
            $friends = [];
            foreach ($IN['openids'] as $key => $val) {
                $results = $wechatObj->getUserInfo($val);
                if ($results) {
                    $friends[$key] = $results;
                    $friends[$key]['mpid'] = $this->mid;
                    $friends[$key]['tagid_list'] = json_encode($friends[$key]['tagid_list']);
                    if (!empty($friends[$key])) {
                        if (Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $val])->find()) {
                            Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $val])->update($friends[$key]);
                            $update = true;
                        } else {
                            $insert = Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $val])->insert($friends[$key]);
                        }
                    }
                } else {
                    if ($msg = wxApiResultErrorCode($wechatObj->errCode)) {
                        ajaxMsg('0', $msg);
                    } else {
                        ajaxMsg('0', '遇到错误：errCode:' . $wechatObj->errCode . 'errMsg:' . $wechatObj->errMsg);
                    }

                }
            }
            if ($update || $insert) {
                ajaxMsg('1', '同步成功');
            }

        } else {
            ajaxMsg('0', '你没有选择要同步的粉丝');
        }

    }


}