<?php

namespace app\admin\controller\weixin;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use addons\weixin\library\WechatService;
use app\admin\model\weixin\Reply as WechatReply;

/**
 * 微信粉丝用户
 *
 * @icon fa fa-circle-o
 */
class Fans extends Backend
{
    /**
     * User模型对象
     * @var \app\admin\model\weixin\Fans
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\weixin\Fans;
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 更新粉丝信息
     */
    public function syncWechatFans()
    {
        $page_index = input('page', 0);
        $page_size = input('limit', 20);
        if ($page_index == 0) {
            //建立连接,同时获取所有用户openid  拉去粉丝信息列表(一次拉取调用最多拉取10000个关注者的OpenID,可以通过多次拉取的方式来满足需求。)
            $openid_list = [];
            $is_continue = true;
            $next_openid = null;
            do {
                $item_result = WechatService::getUserList($next_openid);
                if(empty($item_result['data']['openid'])){
                    $this->error('公众号暂无粉丝');
                }
                $next_openid = $item_result["next_openid"];
                $openid_item = $item_result['data']["openid"];
                if (empty($openid_item)) {
                    $is_continue = false;
                } else {
                    $is_continue = false;
                    foreach ($openid_item as $k => $v) {
                        $openid_list[] = $v;
                    }
                }
            } while ($is_continue);

            //将粉丝列表存入session
            session('wechat_openid_list', $openid_list);
            $total = count($openid_list);
            if ($openid_list % $page_size == 0) {
                $page_count = $total / $page_size;
            } else {
                $page_count = (int)($total / $page_size) + 1;
            }

            $data = array(
                'total'      => $total,
                'page_count' => $page_count,
            );
            $this->success('ok', '', $data);

        } else {
            //对应页数更新用户粉丝信息
            $openid_list = session('wechat_openid_list');
            if (empty($openid_list)) {
                $this->error('');
            }
            $start = ($page_index - 1) * $page_size;
            $page_fans_openid_list = array_slice($openid_list, $start, $page_size);

            if (empty($page_fans_openid_list)) {
                $this->error('');
            }

            $result = WechatService::getUserListInfo($page_fans_openid_list);
            if ($result['user_info_list']) {
                foreach ($result['user_info_list'] as $k => $v) {
                    $nickname_decode = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $v['nickname']);
                    $nickname        = preg_replace_callback('/./u',
                        function (array $match) {
                            return strlen($match[0]) >= 4 ? '' : $match[0];
                        },
                        $v['nickname']);
                    $add_data        = [
                        'nickname'         => $nickname,
                        'nickname_decode'  => $nickname_decode,
                        'headimgurl'       => $v['headimgurl'],
                        'sex'              => $v['sex'],
                        'language'         => $v['language'],
                        'country'          => $v['country'],
                        'province'         => $v['province'],
                        'city'             => $v['city'],
                        'openid'           => $v['openid'],
                        'unionid'          => $v['unionid'] ?? '',
                        'groupid'          => '',
                        'is_subscribe'     => 1,
                        'remark'           => $v['remark'],
                        'subscribe_time'   => $v['subscribe_time'] ?? 0,
                        'subscribe_scene'  => $v['subscribe_scene'] ?? 0,
                        'unsubscribe_time' => $v['unsubscribe_time'] ?? 0,
                        'update_date'      => time()
                    ];
                    $info = $this->model->where(['openid' => $v['openid']])->field('openid')->find();
                    if (!empty($info)) {
                        $this->model->where(['openid' => $v['openid']])->update($add_data);
                    } else {
                        $this->model->insert($add_data);
                    }
                }
            }
            $this->success('ok');
        }
    }
}