<?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: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------

namespace app\user\controller;

use api\user\model\UserLikeModel;
use app\common\Constant;
use app\common\Excel;
use app\common\Fun;
use app\love\model\ActiveApplyModel;
use app\love\model\UserFriendModel;
use app\love\model\UserGiftModel;
use app\love\model\UserInviteModel;
use app\love\model\UserMatingModel;
use app\love\model\UserMessageModel;
use app\love\model\UserSelectLogModel;
use app\love\model\UserSelectModel;
use app\love\model\UserVisitModel;
use app\user\model\UserFavoriteModel;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\db\Query;
use \think\facade\Request;

/**
 * Class AdminIndexController
 * @package app\user\controller
 *
 * @adminMenuRoot(
 *     'name'   =>'用户管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 10,
 *     'icon'   =>'group',
 *     'remark' =>'用户管理'
 * )
 *
 * @adminMenuRoot(
 *     'name'   =>'用户组',
 *     'action' =>'default1',
 *     'parent' =>'user/AdminIndex/default',
 *     'display'=> true,
 *     'order'  => 10000,
 *     'icon'   =>'',
 *     'remark' =>'用户组'
 * )
 */
class AdminIndexController extends AdminBaseController
{

    /**
     * 后台本站用户列表
     * @adminMenu(
     *     'name'   => '本站用户',
     *     'parent' => 'default1',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('user_admin_index_view');

        if (!empty($content)) {
            return $content;
        }

        $count = Db::name('user')
            ->where(function (Query $query) {
                $data = $this->request->param();
                $query->where('user_type', 2);
                $query->where('is_complete', 1);
                if (!empty($data['uid'])) {
                    $query->where('id', intval($data['uid']));
                }

                if (!empty($data['keyword'])) {
                    $keyword = $data['keyword'];
                    $query->where('realname', 'like', "%$keyword%");
                }

                if (!empty($data['sex'])) {
                    $query->where('sex', $data['sex']);
                }

                if (!empty($data['check_status'])) {
                    $query->where('check_status', $data['check_status']);
                }
            })
            ->count();
        $this->assign('total',$count);

        $list = Db::name('user')
            ->where(function (Query $query) {
                $data = $this->request->param();
                $query->where('user_type', 2);
                $query->where('is_complete', 1);
                if (!empty($data['uid'])) {
                    $query->where('id', intval($data['uid']));
                }

                if (!empty($data['keyword'])) {
                    $keyword = $data['keyword'];
                    $query->where('realname', 'like', "%$keyword%");
                }

                if (!empty($data['sex'])) {
                    $query->where('sex', $data['sex']);
                }

                if (!empty($data['check_status'])) {
                    $query->where('check_status', $data['check_status']);
                }
            })
            ->order("check_status asc,create_time DESC")
            ->paginate(10, false, [
                'query' => Request::param(),//不丢失已存在的url参数
            ]);

        $this->assign('sex', $this->request->param('sex') ?: 0);
        $this->assign('is_complete', $this->request->param('is_complete') ?: 0);
        $this->assign('check_status', $this->request->param('check_status') ?: 0);

        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }

    /**
     * 审核
     */
    public function checkPost()
    {
        $data = $this->request->post();
        UserModel::update($data, ['id' => $data['id']]);

        $this->success('操作成功');
    }

    /**
     * 详情
     */
    public function show()
    {
        //获取id
        $id = input('param.id');
        if (empty($id)) {
            $this->error(lang('信息不存在或已删除'));
        }

        //获取信息
        $info           = UserModel::get($id);
        $info['family'] = $info['family'] ? implode('，', json_decode($info['family'], true)) : '未填写';
        $info['have_house'] = Constant::COND_TINYINT[$info['have_house']];
        $info['have_car'] = Constant::COND_TINYINT[$info['have_car']];
        $info['with_parent_live'] = Constant::COND_TINYINT[$info['with_parent_live']];
        if (empty($info)) {
            $this->error(lang('信息不存在或已删除'));
        }
        $this->assign('info', $info);

        $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);

        return $this->fetch();
    }

    /**
     * 本站用户拉黑
     * @adminMenu(
     *     'name'   => '本站用户拉黑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户拉黑',
     *     'param'  => ''
     * )
     */
    public function ban()
    {
        $id = input('param.id', 0, 'intval');
        if ($id) {
            $result = Db::name("user")->where(["id" => $id, "user_type" => 2])->setField('user_status', 0);
            if ($result) {
                $this->success("会员拉黑成功！", "adminIndex/index");
            } else {
                $this->error('会员拉黑失败,会员不存在,或者是管理员！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 本站用户启用
     * @adminMenu(
     *     'name'   => '本站用户启用',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户启用',
     *     'param'  => ''
     * )
     */
    public function cancelBan()
    {
        $id = input('param.id', 0, 'intval');
        if ($id) {
            Db::name("user")->where(["id" => $id, "user_type" => 2])->setField('user_status', 1);
            $this->success("会员启用成功！", '');
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 删除用户
     */
    public function delete()
    {
        $id = input('param.id', 0, 'intval');
        if ($id > 1) {
            Db::startTrans();
            try {
                UserModel::destroy($id);
                ActiveApplyModel::where('user_id', $id)->delete();
                UserFavoriteModel::where('user_id|uid', '=', $id)->delete();
                UserFriendModel::where('user_id|friend_id', '=', $id)->delete();
                UserGiftModel::where('from_id|to_id', '=', $id)->delete();
                UserInviteModel::where('from_id|to_id', '=', $id)->delete();
                UserLikeModel::where('user_id', '=', $id)->delete();
                UserMatingModel::where('user_id', '=', $id)->delete();
                UserMessageModel::where('from_id|to_id', '=', $id)->delete();
                UserSelectModel::where('user_id|uid', '=', $id)->delete();
                UserSelectLogModel::where('user_id1|user_id2', '=', $id)->delete();
                Db::name('user_token')->where('user_id', '=', $id)->delete();
                UserVisitModel::where('from_id|to_id', '=', $id)->delete();
                Db::commit();
            } catch (\Exception $e) {
                //回滚事务
                Db::rollback();
                $this->error('会员删除失败,会员不存在,或者是管理员！');
            }
            $this->success("会员删除成功！", "adminIndex/index");
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 导出
     */
    public function export()
    {
        $data = $this->request->param();

        $where = [
            ['user_type', '=', 2],
            ['is_complete', '=', 1],
        ];

        if (!empty($data['uid'])) {
            $where[] = ['id', '=', intval($data['uid'])];
        }

        if (!empty($data['keyword'])) {
            $where[] = ['realname', 'like', "%{$data['keyword']}%"];
        }

        if (!empty($data['sex'])) {
            $where[] = ['sex', '=', $data['sex']];
        }

        if (!empty($data['check_status'])) {
            $where[] = ['check_status', '=', $data['check_status']];
        }

        $list  = UserModel::where($where)->order("check_status asc,create_time DESC")->select();
        $data = [];
        foreach ($list as $v) {
            $data[] = [
                'name' => $v['realname'],
                'sex' => $v['sex_text'],
                'age' => Fun::getAgeByBirth($v['birthday']),
                'mobile' => $v['mobile'],
                'company' => $v['company'],
                'native' => $v['native'],
                'marry' => $v['marry'],
            ];
        }

        if (empty($data)) {
            return '暂无数据';
        }

        $excel = new Excel();
        $title = [
            ['name','姓名'],
            ['sex','性别'],
            ['age','年龄'],
            ['mobile','电话'],
            ['company','单位'],
            ['native','籍贯'],
            ['marry','婚姻状况'],
        ];
        $excel->export('本站用户',$title,$data,['mobile']);
    }
}
