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

namespace app\miniapp\controller;


use app\common\model\MiniappMsg;
use app\common\model\MiniappUser;
use think\Db;
use think\facade\Request;
use think\facade\Url;

class Miniapp extends Base
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub


    }

    /**
     * 授权后的会员列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function userList()
    {
        $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[] = ['create_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[] = ['gender', '=', $_data['sex']];
            }
        }
        $post['nickname'] = $nickname;
        $post['times'] = $times;
        $post['need'] = $need;
        $post['sex'] = $sex;
        $model = new MiniappUser();
        $users = $model->where('mpid', '=', $this->_mid)
            ->where($where)
            ->paginate(15);
        $page = $users->render();
        $this->assign('users', $users);
        $this->assign('post', $post);
        $this->assign('page', $page);
        $this->assign('menu_title', '会员管理');
        return view('userlist');

    }

    /**
     * 功能配置
     * @param string $type
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function setting($type = 'wxpay')
    {
        if (Request::isAjax()) {
            $input = input('post.');
            Db::name('setting')->where(['name' => $input['setting_name'], 'mpid' => $this->_mid, 'cate' => 'miniapp'])->delete();
            $data['name'] = $input['setting_name'];
            $data['mpid'] = $this->_mid;
            $data['cate'] = 'miniapp';
            $data['value'] = json_encode($input);
            if (Db::name('setting')->insert($data)) {
                ajaxMsg('1', '配置成功');
            } else {
                ajaxMsg('0', '配置失败了');
            }
        } else {
            $result = Db::name('setting')->where(['name' => $type, 'mpid' => $this->_mid, 'cate' => 'miniapp'])->find();
            switch ($type) {
                case 'wxpay':
                    $arr1 = [
                        'appid' => '',
                        'appsecret' => '',
                        'mchid' => '',
                        'paysignkey' => '',
                        'apiclient_cert' => '',
                        'apiclient_key' => '',
                        'setting_name' => '',
                    ];
                    $array = json_decode($result['value'], true);
                    $arr2 = $array ? $array : [];
                    $config = array_merge($arr1, $arr2);
                    $this->assign('payUrl', getHostDomain() . Url::build('service/Payment/wxPay', '', false));
                    $this->assign('config', $config);
                    break;
                case 'sms':
                    $arr1 = [
                        'txsms' => [
                            'appid' => '',
                            'appsecret' => '',
                        ],
                        'alisms' => [
                            'appid' => '',
                            'appsecret' => '',
                        ]
                    ];
                    $config = json_decode($result['value'], true);
                    foreach ($arr1 as $key => $val) {
                        if (isset($config[$key])) {
                            $config[$key] = array_merge($arr1[$key], $config[$key]);
                        }
                    }
                    $this->assign('config', $config);
                    break;
                case 'cloud':
                    $arr1 = [
                        'qiniu' => [
                            'accessKey' => '',
                            'secretKey' => '',
                            'bucke' => '',
                            'domain' => '',
                            'status' => '',
                        ],

                    ];
                    $config = json_decode($result['value'], true);
                    foreach ($arr1 as $key => $val) {
                        if (isset($config[$key])) {
                            $config[$key] = array_merge($arr1[$key], $config[$key]);
                        }
                    }
                    $this->assign('config', $config);
                    break;
            }
            $this->assign('type', $type);
            return view();
        }
    }

    /**
     * 消息列表
     * @param int $status
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMsgList($status = 0)
    {
        $model = new MiniappMsg();
        $msgList = $model->where(['status' => $status, 'mpid' => $this->_mid])->field('openid,count(msg_id) as msg_total')->group('openid')->paginate(15);
        $userModel = new MiniappUser();
        foreach ($msgList as $key => $val) {
            $msgContent = $model->where(['openid' => $val['openid']])->order('msg_id DESC')->field('type,content,create_time as time')->find();
            switch ($msgContent['type']) {
                case 'image':
                    $msgList[$key]['content'] = '[图片消息]';
                    break;
                default:
                    $msgList[$key]['content'] = $msgContent['content'];
                    break;
            }
            $msgList[$key]['create_time'] = $msgContent['time'];
            $member = $userModel->where([['mpid', '=', $this->_mid], ['openid', '=', $val['openid']]])->find();
            if (empty($member)) {
                //有可能是游客
                $msgList[$key]['avatarurl'] = '/public/static/images/header.jpg';
                $msgList[$key]['nickname'] = '[游客]';
            } else {
                $msgList[$key]['avatarurl'] = $member['avatarurl'];
                $msgList[$key]['nickname'] = $member['nickname'];
            }

        }
        $this->assign('msgList', $msgList);
        $this->assign('status', $status);
        return view('getmsglist');
    }

    /**
     * 回复文本消息处理
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function replyMsg()
    {
        $openid = input('openid');
        $model = new MiniappMsg();
        if (Request::isAjax()) {
            if (empty($msg_content = input('msg_content'))) {
                ajaxMsg(0, '消息不能为空');
            }
            $data = [
                'touser' => $openid,
                'msgtype' => 'text',
                'text' => [
                    'content' => $msg_content
                ]
            ];
            $object = getMiniProgramObj();
            $result = $object->sendCustomMessage($data);
            if (isset($result['errcode']) && $result['errcode'] == '0' && isset($result['errmsg']) && $result['errmsg'] == 'ok') {
                $model->save(['status' => 1], ['openid' => $openid]);
                $msg['openid'] = $openid;
                $msg['mpid'] = $this->_mid;
                $msg['create_time'] = time();
                $msg['type'] = 'text';
                $msg['content'] = $msg_content;
                $msg['status'] = 1;
                $msg['is_reply'] = 1;
                $model->allowField(true)->insert($msg);
                ajaxMsg(1, '发送成功');
            } else {
                ajaxMsg(0, $object->getErrorMsg());
            }

        } else {

            $userModel = new MiniappUser();
            $msgList = $model->where(['mpid' => $this->_mid, 'openid' => $openid])->order('msg_id DESC')->paginate(15);
            $user = $userModel->where([['mpid', '=', $this->_mid], ['openid', '=', $openid]])->find();
            if (empty($user)) {
                //有可能是游客
                $user['avatarurl'] = '/public/static/images/header.jpg';
                $user['nickname'] = '[游客]';
            }
            foreach ($msgList as $k => $v) {
                $msgList[$k]['avatarurl'] = $user['avatarurl'];
                $msgList[$k]['nickname'] = $user['nickname'];
                if ($v['is_reply'] == 1) {
                    $msgList[$k]['avatarurl'] = $this->miniappInfo['logo'];
                    $msgList[$k]['nickname'] = $this->miniappInfo['name'];
                }
                switch ($v['type']) {
                    case 'image':
                        $msgList[$k]['content'] = "<img onclick='openMsgImsg(this)'  class='msg_image' src=\"{$v['content']}\">";
                        break;
                }

            }
            $this->assign('openid', $openid);
            $this->assign('msgList', $msgList);
            return view('replymsg');
        }
    }

    /**
     * 回复图片处理
     * @param $openid
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function replyImgByMsg($openid)
    {
        $file = \request()->file('image');
        $info = $file->rule('md5')->validate(['ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . DS . 'uploads');
        if ($info) {
            $info->getSaveName();
            $imgPath = '/uploads' . DS . $info->getSaveName();
            $object = getMiniProgramObj();
            $result = $object->uploadMedia(['media' => '@' . ROOT_PATH . $imgPath], 'image');
            if (isset($result['media_id']) && $result['media_id'] != '') {
                $data = [
                    'touser' => $openid,
                    'msgtype' => 'image',
                    'image' => [
                        'media_id' => $result['media_id']
                    ]
                ];
                $object = getMiniProgramObj();
                $result = $object->sendCustomMessage($data);
                if (isset($result['errcode']) && $result['errcode'] == '0' && isset($result['errmsg']) && $result['errmsg'] == 'ok') {
                    $model = new MiniappMsg();
                    $model->save(['status' => 1], ['openid' => $openid]);
                    // $mpInfo=getMpInfo($this->mid);
                    $msg['openid'] = $openid;
                    $msg['mpid'] = $this->_mid;
                    $msg['create_time'] = time();
                    $msg['type'] = 'image';
                    $msg['content'] = getHostDomain() . $imgPath;
                    $msg['status'] = 1;
                    $msg['is_reply'] = 1;
                    $model->allowField(true)->insert($msg);
                    ajaxMsg(1, '发送成功');
                } else {
                    ajaxMsg(0, $object->getErrorMsg());
                }
            }
            unlink($imgPath);
        } else {
            ajaxMsg(0, $file->getError());
        }
    }

    /**
     * 删除消息
     * @param $id
     * @param $openid
     *
     */
    public function delMsg($id, $openid)
    {
        if (Request::isAjax()) {
            $model = new  MiniappMsg();
            if ($model->where(['msg_id' => $id, 'openid' => $openid, 'mpid' => $this->_mid])->delete()) {
                ajaxMsg(1, '操作成功');
            } else {
                ajaxMsg(0, '操作失败');
            }
        }
    }

    public function topNav()
    {
        $this->redirect('userlist');
    }


}