Staff.php 8.9 KB
<?php

namespace app\admin\controller\inspection;

use app\admin\model\User;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;

/**
 * 员工管理
 *
 * @icon fa fa-circle-o
 */
class Staff extends Backend
{
    
    /**
     * Staff模型对象
     * @var \app\admin\model\inspection\Staff
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\inspection\Staff();

        $tree = Tree::instance();
        $departModel = new \app\admin\model\inspection\Depart();
        $tree->init(collection($departModel->order('weigh asc,id asc')->select())->toArray(), 'pid');
        $departdata = ['' => ['depart_name' => '请选择部门']];
        foreach ($tree->getTreeList($tree->getTreeArray(0), 'depart_name') as $k => $v) {
            $departdata[$v['id']] = $v;
        }
        $this->view->assign("departList", $departdata);
    }




    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $depart_id = $this->request->param('depart_id',-1);

            if($depart_id == -1){
                $_where = [];
            }else{
                //获取下级所有子部门ID
                $tree = Tree::instance();
                $departModel = new \app\admin\model\inspection\Depart();
                $tree->init(collection($departModel->order('weigh asc,id asc')->select())->toArray(), 'pid');
                $depart_ids = $tree->getChildrenIds($depart_id);

                array_push($depart_ids,$depart_id);
                $_where = ['depart_id'=>['in',$depart_ids]];
            }
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['depart'])
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('depart')->visible(['depart_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

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

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $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 . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $staffModel = new \app\admin\model\inspection\Staff();
                    if($staffModel->where(['staff_code'=>$params['staff_code']])->find()){
                        $this->error("当前工号重复");
                    }

                    $result = $this->model->allowField(true)->save($params);
                    if($result !== false){
                        $userModel = new User();
                        $data['username'] = $params['mobile'];
                        $data['nickname'] = $params['staff_name'];
                        $salt = \fast\Random::alnum();
                        $data['password'] = \app\common\library\Auth::instance()->getEncryptPassword($params['password'], $salt);
                        $data['salt'] = $salt;
                        $data['status'] = "normal";
                        $data['mobile'] = $params['mobile'];
                        $data['group_id'] = 2;
                        $rule = [
                            'username'  => 'require|unique:user,username',
                            'mobile' => 'require|unique:user',
                        ];
                        $msg = [
                            'username.require'      => '请输入手机号',
                            'username.unique'      => '手机号不能重复',
                        ];
    
                        $validate   = Validate::make($rule,$msg);
                        $result = $validate->check($data);
    
                        if(!$result) {
                            $this->error($validate->getError());
                        }
    
                        $userModel->save($data);
    
                        $this->model->save(['user_id'=>$userModel->id]);
                    }
                    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 inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $depart_id = $this->request->param('depart_id');
        $this->assign('depart_id',$depart_id);

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

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($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) {
                $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);
                    }

                    $staffModel = new \app\admin\model\inspection\Staff();
                    if($staffModel->where(['staff_code'=>$params['staff_code'],'id'=>['neq',$row['id']]])->find()){
                        $this->error("当前工号重复");
                    }

                    $result = $row->allowField(true)->save($params);
                    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) {

                    $userModel = new User();
                    $userInfo = $userModel->where(['id'=>$row['user_id']])->find();

                    $data = ['password'=>$params['password']];
                    if(empty($params['password'])){
                        unset($data['password']);
                    }
                    if($userInfo){
                        $userInfo->save($data);
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $userModel = new User();
        $user = $userModel->where(['id'=>$row['user_id']])->find();
        $row['username'] =empty($user)?'':$user['username'];

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



}