ProjectExperts.php 9.3 KB
<?php

namespace app\school\controller\review;

use app\common\controller\DoubleBase;
use fast\Random;
use think\Db;
use think\Validate;
use app\common\model\Territory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 大创专家管理
 *
 * @icon fa fa-circle-o
 */
class ProjectExperts extends DoubleBase
{

    protected $noNeedRight = ['*'];
    /**
     * ProjectExperts模型对象
     * @var \app\school\model\ProjectExperts
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\school\model\setting\ProjectExperts;
        $this->view->assign("territoryList", Territory::getTerritoryList());
    }

    /**
     * [import 专家导入]
     * @Author   七
     * @DateTime 2020-12-29-15:00
     */
    public function import()
    {
        $file = $this->request->param('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'));
        }
        $PHPReader = IOFactory::createReader('Xlsx');
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = IOFactory::createReader('Xls');
            if (!$PHPReader->canRead($filePath)) {
                throw new \Exception('只支持导入Excel文件!');
            }
        }
        $PHPReader->setReadDataOnly(true);
        $spreadsheet = $PHPReader->load($filePath); //加载文件
        $worksheet = $spreadsheet->getActiveSheet(); //加载第一个表
        $title = $worksheet->getTitle(); //获取tab名
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数
        if ($highestRow < 3) {
            $this->error('请勿上传空表格');
        }
        if ($highestRow > 1001) {
            $this->error('每次导入请控制数量在1000以下');
        }
        $content = [];
        $maxColumnNumber = Coordinate::columnIndexFromString($highestColumn); //最大列表
        for ($currentRow = 3; $currentRow <= $highestRow; $currentRow++) { //循环行
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) { //循环列
                $val = $worksheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = $val;
            }
            $fields = ['username','nickname','password','gender','position','mobile','email','introduction'];
            $temp = array_combine($fields, $values); //合并数组
            //先验证基础字段是否为空
            if(empty($temp['username']) || empty($temp['nickname']) || empty($temp['password'])
                    || empty($temp['gender']) || empty($temp['position']) || empty($temp['mobile'])
                    || empty($temp['email'])){
                $this->error('必填字段不能为空!');
            }
            $temp['gender'] = ($temp['gender'] == '男') ? 1 : 0;
            $temp['salt'] = Random::alnum();
            $temp['password'] = md5(md5($temp['password']) . $temp['salt']);
            $temp['type'] = 'review';
            $temp['school_id'] = SCHOOL_ID;
            array_push($content,$temp);
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->saveAll($content);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($result !== false){
            $this->success('导入成功!');
        }else{
            $this->error('导入失败!');
        }
    }

     /**
     * 查看
     */
    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('nickname');
            $params = [];
            if($this->shopIdAutoCondition && SCHOOL_ID){
                $params['school_id'] = SCHOOL_ID;
            }
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();

            $territoryModel = new Territory();
            foreach ($list as &$value) {
                $territoryInfo = $territoryModel->whereIn('id',$value['territory_id'])->column('territory_name');
                $value['territory_name'] = $territoryInfo ? implode(',',$territoryInfo) : '--';
            }

            $result = array("total" => $total, "rows" => $list);
            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->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SCHOOL_ID){
                    $params['school_id'] = SCHOOL_ID;
                }
                //规范为评审专家
                $params['type'] = 'review';
                if(!empty($params['territory_id'][0])) {
                    $params['territory_id'] = implode(',',$params['territory_id']);
                }else{
                    $params['territory_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);
                    }
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $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 edit($ids = null)
    {
        $row = $this->model->where(array('id'=>$ids,'school_id'=>SCHOOL_ID))->find();
        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'] = '';
                }
                $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);
                    }
                    $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['territory_id'] = !empty($row['territory_id']) ? explode(',',$row['territory_id']) : '';
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}