<?php

namespace app\admin\controller\users;

use app\admin\model\area\Addr;
use app\admin\model\users\UsersExtendSkills;
use app\common\controller\Backend;
use app\lib\model\UsersExtendSkillsModel;
use app\lib\model\UsersModel;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户管理
 *
 * @icon fa fa-users
 */
class Users extends Backend
{
    
    /**
     * Users模型对象
     * @var \app\admin\model\users\Users
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'id,nickname,mobile,realname';   //里面为搜索的字段
    protected $selectpageFields = "id,nickname,mobile,realname";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\users\Users;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("userTypeList", $this->model->getUserTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $search = $this->request->get("search", '');
            $map=[];
            if(!empty($search)){
                $map['id|mobile|nickname|realname'] = array('LIKE', '%' . $search . '%');
            }
            $total = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->field("*")
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $data['totalMoney'] = $this->model->where($where)->sum('money');
            $data['totalCommission'] = $this->model->where($where)->sum('commission');
            $data['totalAgentMoney'] = $this->model->where($where)->sum('agent_money');
            $result = array("total" => $total, "rows" => $list,'data'=>$data);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * @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->paramPost("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,10,$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();
    }
    /**
     * @description: 显示修改佣金弹窗
     * @param {*}
     * @return {*}
     */
    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->paramPost("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,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();
    }
    /**
     * @description: 显示代理商资金
     * @param {*}
     * @return {*}
     */
    public function editAgentMoney($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(!in_array($row['type'],array(2,3,4))){
            $this->error('该用户不是代理！');
        }
        if ($this->request->isPost()) {
            $params = $this->request->paramPost("row/a");
            if ($params) {
                $money['money']=$params['agent_money'];
                if ($params['agent_money'] == 0) {
                    $this->error('请输入正确的佣金');
                }
                if (($row['agent_money'] + $money['money']) < 0) {
                    $this->error('佣金不足以扣除！');
                }
                if (!$params['intro']  || empty($params['intro'])) {
                    $this->error('请填写操作备注！');
                }
                //更新账户余额
                UsersModel::addAgentMoney($row['id'],$money['money'],63,6,$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();
    }

    /**重置密码
     */
    public function resetpaypassword($ids = ''){
        $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'));
            }
        }
        $result = false;
        Db::startTrans();
        try {
            $arr = array();
            $arr['pay_password'] = md5("888888".$row['salt']);
            $result= $row->where(['id' => $ids])->update($arr);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('重置密码失败'));
        }
        $this->error(__('重置密码失败1'));
    }

    /**
     * 开通上门服务城市站
     */
    public function editExtendSkills($ids = null)
    {
        $row = $this->model->get($ids);
        $userskills=UsersExtendSkills::where(['user_id'=>$ids])->find();
        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->paramPost("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['card_type']==3){
                        if($userskills['expiration_time'] && $userskills['card_type']==3){
                            $expiration_time= date("Y-m-d H:i:s",strtotime("+1 year",strtotime($userskills['expiration_time'])));
                        }else{
                            $expiration_time= date("Y-m-d H:i:s",strtotime("+1 year",time()));
                        }
                        $result=  UsersExtendSkillsModel::insertData($ids,$params['card_type'],$expiration_time,$params['parent_user_id'],0,$params['site_name'],$params['province_id'],$params['city_id'],$params['area_id']);
                    }else if($params['card_type'] !=3 && $userskills){
                        $expiration_time = date("Y-m-d H:i:s",time());
                        $result=  UsersExtendSkillsModel::insertData($ids,$params['card_type'],$expiration_time);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $addr=Addr::cityName($userskills['area_id']>0?$userskills['area_id']:$userskills['city_id']);
        $this->view->assign("userskills",$userskills);
        $this->view->assign("addr",$addr);
        return $this->view->fetch();
    }
}
