<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\PointLog as pointLogModel;
use app\common\model\User as userModel;
use think\Db;

class User extends Permissions
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $where = [];
            if (isset($post['ids']) and !empty($post['ids'])) {
                $where['id'] = ['in', $post['ids']];
            }
            if (isset($post['pid']) and !empty($post['pid'])) {
                $where['pid'] = intval($post['pid']);
            }
            if (isset($post["level"]) and "" != $post["level"]) {
                $where["level"] = $post["level"];
            }
            if (isset($post['nickname']) and !empty($post['nickname'])) {
                $where['nickname'] = ['like', '%' . $post['nickname'] . '%'];
            }
            if (isset($post['user_type']) and "" != $post['user_type']) {
                $where['user_type'] = $post['user_type'];
            }
            if (isset($post['user_cate']) and "" != $post['user_cate']) {
                $where['user_cate'] = $post['user_cate'];
            }
            if (isset($post['ip']) and !empty($post['ip'])) {
                $where['ip'] = $post['ip'];
            }
            if (isset($post['create_time']) and !empty($post['create_time'])) {
                $timerang = explode(' - ', $post['create_time']);
                $min_time = strtotime($timerang[0]);
                $max_time = strtotime($timerang[1]);
                $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
            }

            $model = new userModel();
            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('id desc')->select();

            foreach ($data as $k => $v) {
                $v['user_cate_text'] = $v->user_cate_text;
                $v['user_type_text'] = $v->user_type_text;
                $v['invite_code'] = $v->invite_code;
                $v['level_text'] = $v->level_text;
                $v['status_text'] = $v->status_text;
                $v['parent_name'] = $v->parent ? $v->parent->nickname : '';
                $v['child_count'] = $v->child_count;
                $v['stop_time_text'] = $v->stop_time_text;
                $data[$k] = $v;
            }
            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            $this->assign('user_cates', userModel::USER_CATES);
            $this->assign('user_types', userModel::USER_TYPES);
            $this->assign('vips', \app\common\model\User::GRADE);
            return $this->fetch();
        }
    }

    public function publish()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new userModel();

        $post = $this->request->post();
        if (!$this->request->isPost()) {
            $this->assign('user_cates', userModel::USER_CATES);
            $this->assign('user_types', userModel::USER_TYPES);
        } else {
            $validate = new \think\Validate([
                ['passport', 'require', '账号不能为空'],
                ['passport', 'max:50', '账号长度要小于50'],
                ['passport', 'unique:user', '该账号已经存在'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
        }

        if ($id > 0) {
            //修改操作
            if ($this->request->isPost()) {
                $user = $model->where('id', $id)->find();
                if (empty($user)) {
                    $this->error('id不正确');
                }
                unset($post['passport']);
                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    $this->error('修改失败' . $model->getError());
                } else {
                    $this->success('修改成功', 'index');
                }
            } else {
                $user = $model->where('id', $id)->find();
                if (!empty($user)) {
                    $this->assign('user', $user);
                    return $this->fetch();
                } else {
                    $this->error('id不正确');
                }
            }
        } else {
            //新增操作
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $post['ip'] = $this->request->ip();
                $post['create_time'] = time();
                $post['login_time'] = time();
                if (false == $model->allowField(true)->save($post)) {
                    $this->error('添加失败');
                } else {
                    $this->success('添加成功', 'index');
                }
            } else {
                return $this->fetch();
            }
        }
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if (false == Db::name('user')->where('id', $id)->delete()) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    public function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (false == Db::name('user')->where('id', $post['id'])->update(['status' => $post['status']])) {
                $this->error('设置失败');
            } else {
                $this->success('设置成功', 'index');
            }
        }
    }

    public function setPoint()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            $value = abs($this->request->param('value', 0, 'intval'));
            if (empty($value)) {
                $this->error("请输入积分数量");
            }
            $type = $post['type']??pointLogModel::TYPE_ADMIN_UPDATE;
            $action = $post['action']??1;
            $model = new userModel();
            $users = $model->where('id', 'in', $ids)->select();
            // 启动事务
            Db::startTrans();
            try {
                foreach ($users as $user) {
                    $pointLog = new pointLogModel();
                    $final = $action == 1 ? $user->point + $value : $user->point - $value;
                    $log = [
                        "user_id" => $user->id,
                        "before" => $user->point,
                        "symbol" => $action == 1 ? '+' : '-',
                        "change" => $value,
                        "final" => $final,
                        "type" => $type,
                        "remark" => "管理员" . session(self::ADMIN_ID) . ':' . session(self::ADMIN_NAME) . "操作",
                    ];
                    if (!$pointLog->save($log)) {
                        throw new \Exception("insert point_log fail");
                    }
                    $user->point = $final;
                    $user->save();
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error("修改失败" . $e->getMessage());
            }
            $this->success('修改成功');
        }
    }

    public function setVips()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            $vip_id = $this->request->param("vip", 0);
            $model = new userModel();
            $users = $model->where('id', 'in', $ids)->select();
            /** @var userModel $user */
            foreach ($users as $user) {
                $user->save([
                    'level' => $vip_id,
                    'stop_time' => $vip_id ? $user->createStopTime($vip_id) : 0
                ]);
            }
            $this->success('修改成功');
        }
    }

    //重置密码
    public function resetpass()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            if (false == Db::name('user')->where('id', $id)->update(['password' => password(123456)])) {
                $this->error('重置失败');
            } else {
                $this->success('重置成功', 'index');
            }
        }
    }
}