Teacher.php 16.1 KB
<?php

namespace app\school\controller\basic;

use app\common\controller\ManystoreBase;
use fast\Random;
use think\Db;
use think\Exception;
use app\common\model\Territory;
use think\Config;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;


/**
 * 教师
 *
 * @icon fa fa-circle-o
 */
class Teacher extends ManystoreBase
{

    /**
     * Teacher模型对象
     * @var \app\school\model\basic\Teacher
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\school\model\basic\Teacher;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("educations", $this->model->getEducational());
        $this->view->assign("degree", $this->model::DEGREE);
        $this->view->assign("position", $this->model::POSITION);
        $this->view->assign("teacherType", \app\school\model\basic\Teacher::$teacherType);
        $this->view->assign("territoryList", Territory::getTerritoryList());
    }

    /**
     * 教师首页
     * @return string|\think\response\Json
     */
    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();
            $count = $this->model->where($where)->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $territoryModel = new Territory();
            foreach ($list as &$value) {
                $territoryIds = explode(',',$value['territory_id']);
                $territoryInfo = $territoryModel->whereIn('id',$value['territory_id'])->column('territory_name');
                $value['territory_name'] = $territoryInfo ? implode(',',$territoryInfo) : '--';
            }
            $result = array("total" => $count, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
//            dump();die;
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($this->shopIdAutoCondition && SCHOOL_ID){
                    $params['school_id'] = SCHOOL_ID;
                }
                if(!empty($params['territory_id'][0])) {
                    $params['territory_id'] = implode(',',$params['territory_id']);
                }else{
                    $params['territory_id'] = '';
                }

                if($this->model->where(['job_num' => $params['job_num'],'school_id' => SCHOOL_ID])->find()) {
                    $this->error('工号已存在');
                }

                if($this->model->where(['mobile' => $params['mobile'],'school_id' => SCHOOL_ID])->find()) {
                    $this->error('手机号已存在');
                }
                if($this->model->where(['email' => $params['email'],'school_id' => SCHOOL_ID])->find()) {
                    $this->error('邮箱已存在');
                }
                $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);
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    unset($params['confirem_password'] );
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } 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', ''));
        }
        return $this->view->fetch();
    }


    public function down()
    {
        $filePath = $_SERVER['DOCUMENT_ROOT'].'/assets/file/导入模板.xlsx';
        $fileinfo = pathinfo($filePath);
        header('Content-type: application/x-'.$fileinfo['extension']);
        header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
        header('Content-Length: '.filesize($filePath));
        readfile($filePath);
        exit();
    }

    /**
     * 教师xls导入功能
     */
    public function import()
    {
        set_time_limit(0);
        ignore_user_abort(true);
        ini_set('memory_limit', '1024M');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        //加载文件
        $insert = [];
        $importCount = Config::get('import_count');
        try {
            $data = importExecl($filePath);
            if(count($data) > $importCount) {
                exception("每次只能导入{$importCount}条数据");
            }
            //判断该学校是否存在
            $school = Db::name('college')->where(['college_name'=>$data['sheetName'][0],'school_id' => SCHOOL_ID])->find();
            if(!$school) {
                exception('院校不存在');
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('读取数据失败,稍后请重新尝试'));
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $currentSheetName = $PHPExcel->getSheetNames();  //读取文件中的第一个工作表
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            //判断该学校是否存在
            $school = Db::name('college')->where(['college_name'=>$currentSheetName[0],'school_id' => SCHOOL_ID])->find();
            if(!$school) {
                $this->error(__('院校不存在'));
            }
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                if(!implode('',$values)){
                    //删除空行
                    continue;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (empty($insert)) {
            $this->error('没有数据可更新');
        }
        
        //开始导入
        Db::startTrans();
        try{
            $saveInfo = [];
            foreach ($insert as $key => $val) {
                if(!isset($val['username']) || empty($val['username'])) {
                    exception("教师姓名不能为空");
                }
                if(!isset($val['job_num']) || empty($val['job_num'])) {
                    exception($val['username']." 工号不能为空");
                }
                if(!isset($val['education']) || $val['education'] === '') {
                    exception($val['username']." 学历不能为空");
                }
                if(!isset($val['mobile']) || empty($val['mobile'])) {
                    exception($val['username']." 手机号不能为空");
                }
                if(!isset($val['mobile']) || empty($val['mobile'])) {
                    exception($val['username']." 手机号不能为空");
                }
                if(!isset($val['email']) || empty($val['email'])) {
                    exception($val['username']." 邮箱不能为空");
                }
                if(!isset($val['position']) || $val['position'] === '') {
                    exception($val['username']." 职称不能为空");
                }
                if(!isset($val['degree']) || $val['degree'] === '') {
                    exception($val['username']." 学位不能为空");
                }
                //查看工号是否已经存在 存在就跳过
                $jobNo = $this->model->where(['school_id' => $school['school_id'],'job_num' => $val['job_num']])->find();
                if($jobNo) {
                    exception('教师:'.$val['username'].' 工号已存在');
                }
                $tmp['username']    = $val['username'];
                $tmp['job_num']     = $val['job_num'];
                $tmp['degree']      = $val['degree'];
                $tmp['education']   = $val['education'];
                $tmp['mobile']      = $val['mobile'];
                $tmp['email']       = $val['email'];
                $tmp['position']    = $val['position'];
                $tmp['college_id']  = $school['id'];
                $tmp['school_id']   = $school['school_id'];
                $salt               = Random::alnum();
                $tmp['salt']        = $salt;
                $tmp['password']    = md5(md5('666888') . $salt);
                $tmp['createtime']  = time();
                $saveInfo[] = $tmp;
            }
            if(!empty($saveInfo)) {
                $this->model->saveAll($saveInfo);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('导入失败,请重试(如有问题请联系平台管理员)');
        }
        $this->success();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if(!empty($params['territory_id'][0])) {
                    $params['territory_id'] = implode(',',$params['territory_id']);
                }else{
                    $params['territory_id'] = '';
                }

                if($this->model->where(['job_num' => $params['job_num'],'school_id' => SCHOOL_ID])->where('id','neq',$row['id'])->find()) {
                    $this->error('工号已存在');
                }

                if($this->model->where(['mobile' => $params['mobile'],'school_id' => SCHOOL_ID])->where('id','neq',$row['id'])->find()) {
                    $this->error('手机号已存在');
                }
                if($this->model->where(['email' => $params['email'],'school_id' => SCHOOL_ID])->where('id','neq',$row['id'])->find()) {
                    $this->error('邮箱已存在');
                }

                $result = false;
                Db::startTrans();
                if(!empty($params['password'])){
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }else{
                    unset($params['password'] );
                }
                unset($params['confirem_password'] );
                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);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } 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', ''));
        }
        $row['json'] = $row['resume'];
        $row['resume'] = !empty($row['resume']) ? json_decode($row['resume'] , true) :'';
        $row['territory_id'] = !empty($row['territory_id']) ? explode(',',$row['territory_id']) : '';
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}