<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\love\controller;

use app\common\Constant;
use app\common\Fun;
use app\love\model\GiftModel;
use app\love\model\UserFavoriteModel;
use app\love\model\UserFriendModel;
use app\love\model\UserGiftModel;
use app\love\model\UserInviteModel;
use app\love\model\UserMatingModel;
use app\love\model\UserModel;
use app\love\model\UserSelectModel;
use app\love\model\UserVisitModel;

class UserwallController extends LoveBaseController
{
    private $_age = [[0, 100], [18, 25], [25, 30], [30, 40], [40, 50], [50, 100]];
    private $_high = [[0, 250], [150, 160], [161, 170], [171, 180], [180, 250]];
    private $_weight = [[0, 150], [40, 50], [51, 60], [61, 70], [71, 80], [81, 150]];

    /**
     * 缘份列表
     */
    public function index()
    {
        $list = UserModel::where('user_type', 2)
            ->where('check_status', 2)
            ->where('is_complete', 1)
            ->where('is_public', 1)
            ->where('id', '<>', cmf_get_current_user_id())
            ->where('sex', '<>', cmf_get_current_user()['sex'])
            ->limit(4)
            ->select();
        foreach ($list as $v) {
            $v['age'] = Fun::getAgeByBirth($v['birthday']);
        }
        $this->assign('list', $list);

        //未读消息数
        $unread_num = UserFriendModel::where('user_id', cmf_get_current_user_id())->sum('unread_num');
        $invite_num = UserInviteModel::where('to_id', cmf_get_current_user_id())
            ->where('status', 1)
            ->count();
        $this->assign('unread_num', $unread_num + $invite_num);

        return $this->fetch("");
    }

    /**
     * 列表
     */
    public function getList()
    {
        $param = $this->request->post();

        $where = [
            ['user_type', '=', 2],
            ['id', '<>', cmf_get_current_user_id()],
            ['check_status', '=', 2],
            ['is_complete', '=', 1],
            ['is_public', '=', 1],
            ['sex', '<>', cmf_get_current_user()['sex']],
        ];
        if (!empty($param['age'])) {
            $age        = $this->_age[$param['age']];
            $start_time = strtotime("-{$age[1]} year");
            $end_time   = strtotime("-{$age[0]} year");
            $where[]    = ['birthday', 'between', [$start_time, $end_time]];
        }
//        if (!empty($param['sex'])) {
//            $where[] = ['sex', '=', $param['sex']];
//        }
        if (!empty($param['id'])) {
            $where[] = ['id|realname', 'like', "%{$param['id']}%"];
        }
        if (!empty($param['high'])) {
            $high    = $this->_high[$param['high']];
            $where[] = ['high', 'between', [$high[0], $high[1]]];
        }
        if (!empty($param['weight'])) {
            $weight  = $this->_weight[$param['weight']];
            $where[] = ['weight', 'between', [$weight[0], $weight[1]]];
        }
        if (!empty($param['education'])) {
            $where[] = ['education', '=', $param['education']];
        }

        $list = UserModel::where($where)
            ->page($param['page'])
            ->limit(4)
            ->order($param['sort'])
            ->select();

        foreach ($list as $v) {
            $v['age'] = Fun::getAgeByBirth($v['birthday']);
        }
        $this->result($list, 1);
    }

    /**
     * 详情
     */
    public function detail()
    {
        //获取会员信息
        $id      = $this->request->param('id');
        $user_id = cmf_get_current_user_id();
        $this->assign('user_id', $user_id);
        if (empty($id)) {
            $this->error('该会员不存在！');
        }
        $user = UserModel::get(['id' => $id, 'user_type' => 2]);
        if (empty($user)) {
            $this->error('该会员不存在！');
        }

        //信息处理
        $user->star++;
        $user->save();
        $user['age'] = Fun::getAgeByBirth($user['birthday']);
        $user['have_house'] = Constant::COND_TINYINT[$user['have_house']];
        $user['have_car'] = Constant::COND_TINYINT[$user['have_car']];
        $user['with_parent_live'] = Constant::COND_TINYINT[$user['with_parent_live']];
        $user['sex_text'] = $user['sex_text'];
        if (empty($user['more'])) {
            $user['more'] = [];
        }
        $this->assign('user', $user);

        //择偶要求
        $mating = UserMatingModel::get(['user_id' => $id]);
        $mating['have_house'] = Constant::COND_TINYINT[$mating['have_house']];
        $mating['have_car'] = Constant::COND_TINYINT[$mating['have_car']];
        $mating['with_parent_live'] = Constant::COND_TINYINT[$mating['with_parent_live']];
        $this->assign('mating', $mating);

        //礼物列表
        $gift = GiftModel::all();
        $this->assign('gift', $gift);

        //收到的礼物
        $user_gift = UserGiftModel::with('gift')->where('to_id', $id)->limit(4)->order('create_time desc')->select();
        $this->assign('user_gift', $user_gift);

        //收藏
        $where          = [
            ['user_id', '=', $user_id],
            ['uid', '=', $id],
        ];
        $favorite_check = UserFavoriteModel::where($where)->find();
        $this->assign('is_favorite', $favorite_check ? 'true' : 'false');

        //选择
        $select_check = UserSelectModel::where($where)->find();
        $this->assign('is_select', $select_check ? 'true' : 'false');

        //增加访客记录
        //足迹
        $current_user = UserModel::get($user_id);
        if ($user_id != $id && $current_user['show_footmark'] == 1) {
            $visit = UserVisitModel::get(['from_id' => $user_id, 'to_id' => $id]);
            $time  = time();
            if (empty($visit)) {
                UserVisitModel::create([
                    'from_id'         => $user_id,
                    'to_id'           => $id,
                    'num'             => 1,
                    'create_time'     => $time,
                    'last_visit_time' => $time,
                ]);
            } else {
                $visit->num++;
                $visit->last_visit_time = $time;
                $visit->save();
            }
        }

        //是否好友
        $is_friend = UserFriendModel::get([
            'user_id'   => $id,
            'friend_id' => $user_id,
        ]);
        $this->assign('is_friend', $is_friend ? 'true' : 'false');

        $this->assign('share_image_url', $user['main_image_thumb']);
        $this->assign('share_link', $this->request->url(true));
        $this->assign('share_desc', $user['username'] . (empty($user['signature']) ? '' : ('：' . $user['signature'])));
        return $this->fetch();
    }

    /**
     * 赠送礼物
     */
    public function giveGift()
    {
        $this->checkStatus();

        $post    = $this->request->param();
        $from_id = cmf_get_current_user_id();
        if ($from_id == $post['to_id']) {
            $this->error('不可以给自己送礼');
        }

        UserGiftModel::create([
            'from_id'     => $from_id,
            'to_id'       => $post['to_id'],
            'gift_id'     => $post['gift_id'],
            'create_time' => time(),
        ]);
        $this->success('赠送成功');
    }

    /**
     * 收到的礼物
     */
    public function userGift()
    {
        $id        = $this->request->param('id');
        $user_gift = UserGiftModel::with('gift')->where('to_id', $id)->limit(4)->order('create_time desc')->select();
        $this->result($user_gift, 1);
    }

    /**
     * 收藏
     */
    public function favorite()
    {
        $this->checkStatus();

        $id      = $this->request->param('id');
        $user_id = cmf_get_current_user_id();
        if ($id == $user_id) {
            $this->error('不可以收藏自己');
        }
        $where = [
            ['user_id', '=', $user_id],
            ['uid', '=', $id],
        ];
        $check = UserFavoriteModel::where($where)->find();
        if ($check) {
            UserFavoriteModel::where($where)->delete();
        } else {
            UserFavoriteModel::create([
                'user_id'     => $user_id,
                'uid'         => $id,
                'create_time' => time(),
            ]);
        }
        $this->success('操作成功');
    }

    /**
     * 选择
     */
    public function select()
    {
        $this->checkStatus();

        $id      = $this->request->param('id');
        $user_id = cmf_get_current_user_id();
        if ($id == $user_id) {
            $this->error('不可以选择自己');
        }

        //已互选
        $is_select = UserSelectModel::where('user_id|uid', '=', $user_id)->where('is_confirm', 1)->find();
        if ($is_select) {
            $this->error('您已有互选对象！');
        }

        //判断性别
        $from_user = UserModel::get($user_id);
        $to_user   = UserModel::get($id);
        if ($from_user['sex'] == $to_user['sex']) {
            $this->error('请选择异性！');
        }

        //此人已恋爱，请重新选择
        $is_love = UserSelectModel::where('user_id|uid', '=', $id)->where('is_confirm', 1)->find();
        if ($is_love) {
            $this->error('此人正在交往中，请重新选择！');
        }

        //选择
        $where = [
            ['user_id', '=', $user_id],
            ['uid', '=', $id],
        ];
        $check = UserSelectModel::where($where)->find();
        if ($check) {
            UserSelectModel::where($where)->delete();
        } else {
            UserSelectModel::create([
                'user_id'     => $user_id,
                'uid'         => $id,
                'create_time' => time(),
            ]);
        }
        $this->success('操作成功');
    }

    /**
     * 申请聊天（旧）
     */
    /*public function chat()
    {
        $this->checkStatus();

        $id      = $this->request->param('id');
        $user_id = cmf_get_current_user_id();
        $time    = time();

        //聊天申请
        $invite_get   = UserInviteModel::where([
            ['from_id', '=', $id],
            ['to_id', '=', $user_id],
        ])->find();
        $invite_apply = UserInviteModel::where([
            ['from_id', '=', $user_id],
            ['to_id', '=', $id],
        ])->find();

        //都没有邀请
        if (empty($invite_get) && empty($invite_apply)) {
            UserInviteModel::create([
                'from_id'     => $user_id,
                'to_id'       => $id,
                'create_time' => $time,
            ]);
            UserModel::where('id', $id)->setInc('invite_num');
            $this->error('请等待对方通过聊天邀请');
        }

        //已收到过邀请
        if (!empty($invite_get)) {
            if ($invite_get['status'] == 1) {
                UserFriendModel::create([
                    'user_id'       => $id,
                    'friend_id'     => $user_id,
                    'last_msg_time' => time(),
                ]);
                UserFriendModel::create([
                    'user_id'       => $user_id,
                    'friend_id'     => $id,
                    'last_msg_time' => time(),
                ]);
                $invite_get->status = 2;
                $invite_get->save();
                $this->success('', url('message/detail') . '?id=' . $id);
            } elseif ($invite_get['status'] == 2) {
                $this->success('', url('message/detail') . '?id=' . $id);
            } else {
                $this->error('您已拒绝过对方的聊天邀请');
            }
        }

        //已发起过邀请
        if (!empty($invite_apply)) {
            if ($invite_apply['status'] == 1) {
                $this->error('请等待对方同意申请');
            } elseif ($invite_apply['status'] == 2) {
                $this->success('', url('message/detail') . '?id=' . $id);
            } else {
                $this->error('对方拒绝跟您聊天');
            }
        }
    }*/

    /**
     * 申请聊天
     */
    /*public function chat()
    {
        $this->checkStatus();

        $id      = $this->request->param('id');
        $user_id = cmf_get_current_user_id();
        $time    = time();

        //聊天申请
        $invite_get   = UserInviteModel::where([
            ['from_id', '=', $id],
            ['to_id', '=', $user_id],
        ])->find();
        $invite_apply = UserInviteModel::where([
            ['from_id', '=', $user_id],
            ['to_id', '=', $id],
        ])->find();

        //都没有邀请
        if (empty($invite_get) && empty($invite_apply)) {
            UserInviteModel::create([
                'from_id'     => $user_id,
                'to_id'       => $id,
                'create_time' => $time,
            ]);
            UserModel::where('id', $id)->setInc('invite_num');
            $this->error('请等待对方通过聊天邀请');
        }

        //已收到过邀请
        if (!empty($invite_get)) {
            if ($invite_get['status'] == 1) {
                UserFriendModel::create([
                    'user_id'       => $id,
                    'friend_id'     => $user_id,
                    'last_msg_time' => time(),
                ]);
                UserFriendModel::create([
                    'user_id'       => $user_id,
                    'friend_id'     => $id,
                    'last_msg_time' => time(),
                ]);
                $invite_get->status = 2;
                $invite_get->save();
                $this->success('', url('message/detail') . '?id=' . $id);
            } elseif ($invite_get['status'] == 2) {
                $this->success('', url('message/detail') . '?id=' . $id);
            } else {
                $this->error('您已拒绝过对方的聊天邀请');
            }
        }

        //已发起过邀请
        if (!empty($invite_apply)) {
            if ($invite_apply['status'] == 1) {
                $this->error('请等待对方同意申请');
            } elseif ($invite_apply['status'] == 2) {
                $this->success('', url('message/detail') . '?id=' . $id);
            } else {
                $this->error('对方拒绝跟您聊天');
            }
        }
    }*/

    /**
     * 聊天
     */
    public function chat()
    {
        $this->checkStatus();

        $id      = $this->request->param('id');
        $user_id = cmf_get_current_user_id();
        $time    = time();

        $select = UserSelectModel::where('user_id|uid', '=', $user_id)
            ->where('is_confirm', 1)
            ->find();
        if (!empty($select)) {
            $this->error('您已有心上人，请一心一意对待哦(*^_^*)');
        }

        $has_freind = UserFriendModel::where([
            'user_id'   => $user_id,
            'friend_id' => $id,
        ])->find();

        //无好友先添加成好友
        if (empty($has_freind)) {
            UserFriendModel::create([
                'user_id'       => $id,
                'friend_id'     => $user_id,
                'last_msg_time' => $time,
            ]);
            UserFriendModel::create([
                'user_id'       => $user_id,
                'friend_id'     => $id,
                'last_msg_time' => $time,
            ]);
        }
        $this->success('', url('message/detail') . '?id=' . $id);
    }
}
