<?php

namespace app\admin\controller\user;

use app\api\model\UsersModel;
use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $selectpageFields = "id,nickname,mobile";

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * @description: 显示修改余额弹窗
     * @param {*}
     * @return {*}
     */
    public function editMoney($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $money['money'] = $params['money'];
                if ($params['money'] == 0) {
                    $this->error('请输入正确的余额数');
                }
                if (($row['money'] + $params['money']) < 0) {
                    $this->error('余额不足！');
                }
                if (!$params['intro']  || empty($params['intro'])) {
                    $this->error('请填写操作备注！');
                }
                UsersModel::addMoney($row['id'],$money['money'],1,1,$params['intro'],0,
                    null,null,null,null,null,$this->auth->id);
                $this->success();
            } else {
                $this->error('数据错误，请重新打开窗口！user_id', $row['id']);
            }
        }
        $this->view->assign("row",$row);
        return $this->view->fetch();
    }

    /**
     * @param null $ids
     * @return string
     * 佣金变动
     */
    public function editCommission($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $money['money']=$params['commission'];
                if ($params['commission'] == 0) {
                    $this->error('请输入正确的佣金');
                }
                if (($row['commission'] + $money['money']) < 0) {
                    $this->error('佣金不足以扣除！');
                }
                if (!$params['intro']  || empty($params['intro'])) {
                    $this->error('请填写操作备注！');
                }
                UsersModel::addCommission($row['id'],$money['money'],50,2,$params['intro'],0,
                    null,null,null,null,null,$this->auth->id);
                $this->success('操作成功');
            } else {
                $this->error('数据错误，请重新打开窗口！user_id', $row['id']);
            }
        }
        $this->view->assign("row",$row);
        return $this->view->fetch();
    }
}
