car4s/application/admin/controller/Org5a.php
2022-06-04 17:38:43 +08:00

260 lines
11 KiB
PHP

<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use fast\Pinyin;
/**
* 数据导入辅助
*
* @icon fa fa-circle-o
*/
class Org5a extends Backend
{
/**
* Log模型对象
* @var \app\admin\model\import\Log
*/
protected $model = null;
/**
* 是否开启数据限制
* 支持auth/personal
* 表示按权限判断/仅限个人
* 默认为禁用,若启用请务必保证表中存在admin_id字段
*/
protected $dataLimit = false;
/**
* 数据限制字段
*/
protected $dataLimitField = 'admin_id';
/**
* 是否开启Validate验证
*/
protected $modelValidate = true;
/**
* 数据限制开启时自动填充限制字段值
*/
protected $dataLimitFieldAutoFill = true;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Org5a;
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
public function inmysql(){
$file='教育工委各支部.xls';
$sheet = 0;
$filePath = ROOT_PATH . DS . 'public' . DS . $file;
if (!is_file($filePath)) {
$this->error(__('没找到文件'));
}
//实例化reader
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['xls', 'xlsx'])) {
$this->error(__('不支持的格式'));
}
if ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
}
if (!$PHPExcel = $reader->load($filePath)) {
$this->error(__('不支持的格式'));
}
$currentSheet = $PHPExcel->getSheet($sheet); //读取文件中的第一个工作表
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
//$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
$fields = [];
var_dump($allRow);
for ($curline = 1; $curline <= $allRow; $curline++) {
$shequ = $currentSheet->getCellByColumnAndRow(1, $curline)->getCalculatedValue();
$this->model = new \app\admin\model\Org5a;
$fsq = $this->model->where(['name'=>$shequ])->find();
//var_dump($fsq->id);exit();
if(empty($fsq->id)){
$data=array(
'name'=>$shequ,
'pid'=>2463,
'type_id'=>7,
'status'=>1,
'cerated_time'=>date('Y-m-d H:i:s',time()),
'uniacid'=>157,
'status'=>1,
'orderby'=>1,
);
$this->model->isUpdate(false)->save($data);
$sid=$this->model->id;
}else{
$sid=$fsq->id;
}
$cun = $currentSheet->getCellByColumnAndRow(2, $curline)->getCalculatedValue();
$this->model = new \app\admin\model\Org5a;
$fc = $this->model->where(['name'=>$cun,'pid'=>$sid])->find();
if(empty($fc->id)){
$cdata=array(
'name'=>$cun,
'pid'=>$sid,
'type_id'=>7,
'status'=>1,
'cerated_time'=>date('Y-m-d H:i:s',time()),
'uniacid'=>157,
'status'=>1,
'orderby'=>1,
);
$this->model->isUpdate(false)->save($cdata);
}
}
echo '2222';
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$step = $params['step'];
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);
}
//新建表导入处理
if ($params['newtable']) {
$prefix = Config::get('database.prefix');
$table = $prefix . $params['newtable'];
$check = db()->query("SHOW TABLES LIKE '%{$table}%';");
if ($check) {
$this->error(__($params['newtable'] . '表已经存在'));
}
} else {
if (!$params['table']) $this->error('未选择目标表');
}
$fileData = $this->fileData($params);
$fileData['params'] = http_build_query($params);
$fileData['newtable'] = $params['newtable'];
if (!$step) {
$this->success('匹配到' . $fileData['count'] . '列,开始预览', '', $fileData);
}
$insert = $fileData['insert'];
$fieldArr = $fileData['fieldArr'];
//是否包含admin_id字段
$has_admin_id = false;
foreach ($fieldArr as $name => $key) {
if ($key == 'admin_id') {
$has_admin_id = true;
break;
}
}
if ($has_admin_id) {
foreach ($insert as &$val) {
if (!isset($val['admin_id']) || empty($val['admin_id'])) {
$val['admin_id'] = $this->auth->isLogin() ? $this->auth->id : 0;
}
}
}
$prefix = Config::get('database.prefix');
$count = 0;
if ($params['update']) {
foreach ($insert as &$val) {
$count += Db::name(str_replace($prefix, "", $params['table']))
->where($params['update'], $val['pid'])
->update($val);
}
} else {
if ($params['to']) {
$file = db('attachment')->where('url', $fileData['path'])->find();
$this->fieldModel = new \app\admin\model\salary\Field;
$fields = $this->fieldModel->where('name', 'not in', ['pid', 'name', 'status', 'create_time', 'update_time', 'deletetime'])->select();
$toData = [];
// dump($fields);
$insertData = [];
foreach ($insert as $key => $val) {
foreach ($fields as $ke => $field) {
if (isset($val[$field['name']])) {
$toData[$ke]['pid'] = $val['pid'];
$toData[$ke]['name'] = $val['name'];
$toData[$ke]['type'] = $field['name'];
$toData[$ke]['type_name'] = $field['desc'];
$toData[$ke]['field_type'] = $field['type'];
$toData[$ke]['je'] = $val[$field['name']];
$toData[$ke]['filename'] = $file['filename'];
$toData[$ke]['sha1'] = $file['sha1'];
$toData[$ke]['createtime'] = time();
}
}
if ($insertData) $insertData = array_merge($insertData, $toData);
else $insertData = $toData;
}
// dump($insertData);
// exit;
Db::name(str_replace($prefix, "", $params['to']))->where('sha1', $file['sha1'])->delete();
$res = Db::name(str_replace($prefix, "", $params['to']))->insertAll($insertData);
} else {
$res = Db::name(str_replace($prefix, "", $params['table']))->insertAll($insert);
}
$count = count($insert);
}
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 ($count !== false) {
$params['status'] = 'normal';
$result = $this->model->allowField(true)->save($params);
$tip = $params['update'] ? '成功更新' : '成功新增';
$this->success($tip . $count . '条记录', '', array('count' => $count));
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("update", $this->request->request('update'));
$this->view->assign("to", $this->request->request('to'));
return $this->view->fetch();
}
}