<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 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 cmf\controller\AdminBaseController;
use think\Db;

/**
 * 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;
        }

        $where   = [];
        $request = input('request.');

        if (!empty($request['uid'])) {
            $where['id'] = intval($request['uid']);
        }
        $keywordComplex = [];
        if (!empty($request['keyword'])) {
            $keyword = $request['keyword'];

            $keywordComplex['user_login|user_nickname|user_email|mobile']    = ['like', "%$keyword%"];
        }
        $usersQuery = Db::name('user');

        $auth_status = [1 => 'I', 2 => 'Ⅱ', 3 => 'Ⅲ', 4 => 'Ⅳ', 5 => 'Ⅴ'];
        $list = $usersQuery->whereOr($keywordComplex)->where($where)->order("create_time DESC")->paginate(10);
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }

    public function childs()
    {
        $content = hook_one('user_admin_index_view');

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

        $where   = [];
        $uid = $this->request->param('uid');
        $where['parent_user_id'] = intval($uid);
        $usersQuery = Db::name('user');
        $list = $usersQuery->where($where)->order("create_time DESC")->select()->toArray();
        $this->assign('uid', intval($uid));
        $uids = array_column($list, "id", NULL);
        if($uids){
            $list2 = $usersQuery->where('parent_user_id', 'in', $uids)->order("create_time DESC")->select();
        }else{
            $list2 = array();
        }
        $this->assign('list', $list);
        $this->assign('list2', $list2);
        // 渲染模板输出
        return $this->fetch();
    }

    public function exportExcel()
    {
        vendor("PHPExcel.PHPExcel");

        $className = "\PHPExcel";

        $objPHPExcel  = new $className();

        $result = Db::name('user')->field("id,user_nickname ,mobile ,score ,FROM_UNIXTIME(last_login_time) 'last_login_time',last_login_ip ,FROM_UNIXTIME(create_time) 'create_time',invitation_code ,invitation_count ,max_count ,parent_user_id ")->select();

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'ID编号')
            ->setCellValue('B1', '昵称')
            ->setCellValue('C1', '手机号')
            ->setCellValue('D1', 'HH余额')
            ->setCellValue('E1', '上次登录时间')
            ->setCellValue('F1', '上次登录IP')
            ->setCellValue('G1', '账号创建时间')
            ->setCellValue('H1', '邀请码')
            ->setCellValue('I1', '邀请次数')
            ->setCellValue('J1', '最大邀请次数')
            ->setCellValue('K1', '推荐人ID');

        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        $i = 2;  //定义一个i变量，目的是在循环输出数据是控制行数
        /*$i = 2,因为第一行是表头，所以写到表格时候只能从第二行开始写。*/
        $count = count($result);  //计算有多少条数据
        for ($i = 2; $i <= $count + 1; $i++) {
            $objPHPExcel->getActiveSheet(0)->setCellValue('A' . $i, $result[$i - 2]['id']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('B' . $i, $result[$i - 2]['user_nickname']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('C' . $i, $result[$i - 2]['mobile']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('D' . $i, $result[$i - 2]['score']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('E' . $i, $result[$i - 2]['last_login_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('F' . $i, $result[$i - 2]['last_login_ip']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('G' . $i, $result[$i - 2]['create_time']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('H' . $i, $result[$i - 2]['invitation_code']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('I' . $i, $result[$i - 2]['invitation_count']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('J' . $i, $result[$i - 2]['max_count']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('K' . $i, $result[$i - 2]['parent_user_id']);
        }
        /**接下来就是设置导入表的名称等内容了**/
        /*--------------下面是设置其他信息------------------*/

        $objPHPExcel->getActiveSheet()->setTitle('user');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="用户信息' . date('Ymd-His') . '.xls"');
        header('Cache-Control: max-age=0');

        //$PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $objWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件

    }


    public function add()
    {

        $id = $this->request->param('id');
        $type = $this->request->param('type');
        if (empty($id)) {
            $this->error("参数有误");
        }
        if (empty($type)) {
            $this->error("参数有误");
        }


        $where['id'] = $id;
        $data =
            Db::name('user')
            ->where($where)
            ->find();
        //var_dump($data);die();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function add_post()
    {

        $id = $this->request->param('id');
        $type = $this->request->param('type');
        $num = $this->request->param('num');
        $pwd = $this->request->param('pwd');

        if ($pwd !== '666888') {
            $this->error("操作密码有误");
        }

        if (empty($id)) {
            $this->error("参数有误");
        }
        if (empty($type)) {
            $this->error("参数有误");
        }

        if (($num < 0) || ($num == 0)) {
            $this->error("请输入正确的数值");
        }

        $where['id'] = $id;
        $uinfo =
            Db::name('user')
            ->where($where)
            ->find();

        if (empty($uinfo)) {
            $this->error("参数有误");
        }


        if ($type == 'add') {
            $data = ['type' => 1, 'user_id' => $uinfo['id'], 'balance_type' => 'score', 'change' => $num, 'amount' => $num + $uinfo['score'], 'detial' => $uinfo['id'], 'detial_type' => 'system_add', 'ctime' => time(), 'extension' => json_encode($uinfo)];
            Db::name('balance_log')
                ->data($data)
                ->insert();
            $data =
                Db::name('user')
                ->where($where)
                ->setInc('score', $num);
        } else {
            $data = ['type' => 1, 'user_id' => $uinfo['id'], 'balance_type' => 'score', 'change' => $num, 'amount' => $uinfo['score'] - $num, 'detial' => $uinfo['id'], 'detial_type' => 'system_reduce', 'ctime' => time(), 'extension' => json_encode($uinfo)];
            Db::name('balance_log')
                ->data($data)
                ->insert();
            $data =
                Db::name('user')
                ->where($where)
                ->setDec('score', $num);
        }
        $this->success("操作成功");
    }


    /*积分记录*/
    public function score()
    {


        $where   = [];
        $request = input('request.');
        //var_dump($request);

        if (!empty($request['uid'])) {
            $where['user_id'] = intval($request['uid']);
        }
        if (!empty($request['oid'])) {
            $where['detial'] = intval($request['oid']);
        }
        $keywordComplex = [];
        if (!empty($request['keyword'])) {
            $keyword = $request['keyword'];

            $keywordComplex['detial_type']    = ['like', "%$keyword%"];
        }
        $usersQuery = Db::name('BalanceLog');

        $list = $usersQuery->where($keywordComplex)->where($where)->order("id DESC")->paginate(100, false, ['query' => request()->param()]);
        //var_dump($where);
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('request', $request);
        // 渲染模板输出
        return $this->fetch();
    }



    /*实盘用户*/
    public function firm()
    {
        $content = hook_one('user_admin_index_view');

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

        $where   = [];
        $request = input('request.');

        if (!empty($request['uid'])) {
            $where['b.id'] = intval($request['uid']);
        }
        $keywordComplex = [];
        if (!empty($request['keyword'])) {
            $keyword = $request['keyword'];

            $keywordComplex['user_login|user_nickname|user_email|mobile']    = ['like', "%$keyword%"];
        }
        $usersQuery = Db::name('firm_user')->alias('a')->join("user b", "a.uid = b.id", "LEFT");

        $auth_status = [1 => 'I', 2 => 'Ⅱ', 3 => 'Ⅲ', 4 => 'Ⅳ', 5 => 'Ⅴ'];
        $list = $usersQuery->whereOr($keywordComplex)->where($where)->order("create_time DESC")->paginate(100);
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }


    /*实盘用户*/
    public function charge_apply()
    {

        $Query = Db::name('firm_user_charge_apply')->alias('a')->join("user b", "a.uid = b.id", "LEFT");

        $list = $Query->order("a.id DESC")->field("a.*,b.user_nickname")->paginate(10);
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }


    public function agree()
    {
        $id = input('param.id', 0, 'intval');
        if ($id) {
            $result = Db::name("firm_user_charge_apply")->where(["id" => $id, "status" => 2])->setField('status', 1);
            if ($result) {
                $this->success("审批已通过", "adminIndex/charge_apply");
            } else {
                $this->error('审批失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }


    public function editUser()
    {
        $id     = $this->request->param('id', 0, 'intval');
        $user = Db::name('user')->where('id', $id)->find();
        $this->assign($user);

        return $this->fetch();
    }

    public function editUserPost()
    {
        $id = $this->request->param('id', 0, 'intval');

        $data = $this->request->param();

        Db::name('user')->where('id', $id)
            ->strict(false)
            ->field('has_paypwd,is_google_check')
            ->update($data);

        $this->success('保存成功！');
    }

    /**
     * 本站用户拉黑
     * @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('数据传入失败！');
        }
    }


    /**
     * 后台修改认证等级
     */
    public function up_auth()
    {
        if ($_POST) {
            $id = $_POST['id'];
            $num = $_POST['num'];

            if ($num < 1 || $num > 5) {
                echo "要修改的等级错误,请重试！";
                return;
            }
            $data = Db::name("user")->where('id', $id)->update([
                'auth_id' => $num
            ]);
            if ($data) {
                echo "操作成功！";
            } else {
                echo "操作失败！";
            }
        } else {
            echo "请求类型有误！";
        }
    }

    /**
     * 本站用户启用
     * @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 edit()
    {
        $id     = $this->request->param('id', 0, 'intval');
        $firm_user = Db::name('firm_user')->where('uid', $id)->find();
        $this->assign($firm_user);

        return $this->fetch();
    }

    public function editPost()
    {
        $id = $this->request->param('id', 0, 'intval');

        $data = $this->request->param();

        Db::name('firm_user')->where('uid', $id)
            ->strict(false)
            ->field('is_free,subscribe_coin_symbol,subscribe_price,subscribe_days')
            ->update($data);

        $this->success('保存成功！');
    }
}
