DiverseYouthNightSchool/application/admin/controller/school/classes/ClassesLib.php

1141 lines
40 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\admin\controller\school\classes;
use app\admin\model\Admin;
use app\admin\model\dyqc\ManystoreShop;
use app\common\controller\Backend;
use app\common\model\school\classes\lib\Spec;
use app\common\model\school\classes\Order;
use app\manystore\model\Manystore;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
use think\Model;
use think\Url;
/**
* 机构课程库
*
* @icon fa fa-circle-o
*/
class ClassesLib extends Backend
{
protected $noNeedLogin = ["miniqrcode"];
protected $qSwitch = true;
protected $qFields = ["teacher_id","user_id","shop_id","manystore_id"];
/**
* 是否开启Validate验证
*/
protected $modelValidate = true;
/**
* ClassesLib模型对象
* @var \app\admin\model\school\classes\ClassesLib
*/
protected $model = null;
//不用审核允许修改的字段
protected $no_auth_fields = ["title","user_id","teacher_id","classes_type","classes_cate_ids","classes_label_ids","self_label_tag",'headimage','images','notice','content',"virtual_num","virtual_collect","underline_price"];
//更新数据是否需要触发审核开关
protected $need_auth = false;
protected $have_auth = false;
protected $success_auth = false;
protected $error_auth = false;
public function _initialize()
{
$this->model = new \app\admin\model\school\classes\ClassesLib;
parent::_initialize();
$this->view->assign("addTypeList", $this->model->getAddTypeList());
$this->view->assign("typeList", $this->model->getTypeList());
$this->view->assign("addressTypeList", $this->model->getAddressTypeList());
$this->view->assign("statusList", $this->model->getStatusList());
$this->view->assign("authStatusList", $this->model->getAuthStatusList());
$this->view->assign("recommendList", $this->model->getRecommendList());
$this->view->assign("hotList", $this->model->getHotList());
$this->view->assign("newList", $this->model->getNewList());
$this->view->assign("selfhotList", $this->model->getSelfhotList());
$this->view->assign("classesTypeList", $this->model->getClassesTypeList());
$this->view->assign("classesTypeListJson", json_encode($this->model->getClassesTypeList(), JSON_UNESCAPED_UNICODE));
$this->view->assign("classes_number_only_one", config("site.classes_number_only_one"));
$this->view->assign("specStatusList", (new \app\admin\model\school\classes\ClassesSpec)->getStatusList());
$this->getCity();
$this->getAuthMsg();
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
$this->searchFields = ["id","title","address","address_detail","address_city","user.nickname","user.realname","user.mobile","shop.name"];
//设置过滤方法
$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, $page, $alias, $bind, $excludearray) = $this->buildparams(null, null, ["has_expire"]);
if (isset($excludearray['has_expire']['value']) && $excludearray['has_expire']['value']) {
$has_expire = $excludearray['has_expire']['value'];
$as = (new \app\common\model\school\classes\ClassesLib())->getWithAlisaName();
switch ($has_expire) {
case '1': //查过期
$expireWhere = [
$as . '.end_time', '<=', time(),
];
break;
case '2': //查未过期
$expireWhere = [
$as . '.end_time', '>', time(),
];
break;
default:
}
} else {
$expireWhere = [[]];
}
$list = $this->model
->with(['manystore', 'shop', 'user', 'admin'])
->where($where)
->where(...$expireWhere)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->getRelation('manystore')->visible(['nickname']);
$row->getRelation('shop')->visible(['name', 'image', 'address_city', 'province', 'city', 'district', 'address', 'address_detail']);
$row->getRelation('user')->visible(['nickname', 'realname', 'mobile', 'avatar']);
$row->getRelation('admin')->visible(['nickname']);
}
$rows = $list->items();
$types = \app\admin\model\school\classes\Type::column("name", 'id');
foreach ($rows as $k => &$v) {
$v["classes_type_name"] = $types[$v["classes_type"]] ?? "";
$v["miniqrcode_link"] = Url::build("/school/classes/classes_lib/miniqrcode", ["ids" => $v["id"]]);
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
protected function authClasses(&$params,$row=null){
//审核失败需填写原因
if($params["auth_status"] == '2' && empty($params["reason"])){
$this->error("审核失败需填写原因");
}
if($params["auth_status"] == '2'){
//审核不通过会平台下架
$params["status"] = '3';
}
//更新
if($row){
if($params["auth_status"] != '1' && $row["auth_status"] == '1'){
$this->error("审核已通过的课程不允许再修改审核状态!");
}
if($params["auth_status"] != '0' && $row["auth_status"] == '0'){
//填写审核时间和审核人
$params["auth_time"] = time();
$params["admin_id"] = $this->auth->id;
if($params["auth_status"] == '1'){
//审核通过
$this->success_auth = true;
}
if($params["auth_status"] == '2'){
//审核通过
$this->error_auth = true;
}
}
//审核通过
if($this->success_auth){
//如果是平台下架,则更新成正常下架
if($params["status"] == '3') $params["status"] = '2';
//调用通过事件
// $data = ['shop' => $row];
// \think\Hook::listen('classes_auth_success_after', $data);
}
if($this->error_auth){
//调用通过事件
// $data = ['shop' => $row];
// \think\Hook::listen('classes_auth_fail_after', $data);
}
}else{
//新增
}
}
protected function updateCheck($id,$params=[],$row=null){
if($params && $row){
if(!$this->no_auth_fields_check($params,$row)){
return true;
}
}
// 课程存在未完成订单则不允许操作
$order = Order::where("classes_lib_id",$id)->where("status","in","0,3")->find();
if($order)$this->error("存在正在使用中的课程订单或存在正在售后中的课程订单无法继续操作!");
// 课程存在售后订单则不允许操作
}
protected function update_check(&$params,$row=null)
{
if($row){
if(empty($params["shop_id"]))$params["shop_id"] = $row["shop_id"];
if(empty($params["teacher_id"]))$params["teacher_id"] = $row["teacher_id"];
}
// try {
$classesLib = new \app\common\model\school\classes\ClassesLib();
$classesLib->no_auth_fields = $this->no_auth_fields;
$classesLib->need_auth = $this->need_auth;
$classesLib->have_auth = $this->have_auth;
$classesLib->classesCheck($params,null,$row);
$this->need_auth = $classesLib->need_auth;
$this->have_auth = $classesLib->have_auth;
// }catch (\Exception $e){
// $this->error($e->getMessage());
// }
//特有认证判断
$this->authClasses($params,$row);
// var_dump($row);die;
//更新
if($row){
}else{
//新增
//新增
$params["add_type"] = '2';
$params["add_id"] = $this->auth->id;
}
}
protected function update_classes($classes_lib_id){
//课时数必须大于等于课时核销数
$count = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$classes_lib_id)->count();
$classes_num = \app\common\model\school\classes\ClassesLib::where("id",$classes_lib_id)->value("classes_num");
if($count < $classes_num){
throw new \Exception("课时数必须大于等于课时核销数");
}
\app\common\model\school\classes\ClassesLib::update_classes($classes_lib_id);
}
/**
* 添加
*
* @return string
* @throws \think\Exception
*/
public function add()
{
if (false === $this->request->isPost()) {
return $this->view->fetch();
}
$params = $this->request->post('row/a');
if (empty($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
$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()->validate($validate);
}
$this->update_check($params,$row=null);
$result = $this->model->allowField(true)->save($params);
\app\common\model\school\classes\ClassesLib::add_virtual_init($this->model["id"]);
$this->update_classes($this->model["id"]);
if($this->have_auth){
//调用通过事件
$data = ['classes' => $this->model];
\think\Hook::listen('classes_auth_need_after', $data);
}
if($this->success_auth){
//调用通过事件
$data = ['classes' => $this->model];
\think\Hook::listen('classes_auth_success_after', $data);
}
if($this->error_auth){
//调用通过事件
$data = ['classes' => $this->model];
\think\Hook::listen('classes_auth_fail_after', $data);
}
Db::commit();
} catch (ValidateException|PDOException|\Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result === false) {
$this->error(__('No rows were inserted'));
}
$this->success();
}
/**
* 添加
*
* @return string
* @throws \think\Exception
*/
public function addnew($row=null)
{
if (false === $this->request->isPost()) {
return $this->view->fetch();
}
$params = $this->request->post('row/a');
if (empty($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
$params = $this->preExcludeFields($params);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
unset($params["id"]);
if($row){
//如果走的复制
if(empty($params["shop_id"]))$params["shop_id"] = $row["shop_id"];
if(empty($params["teacher_id"]))$params["teacher_id"] = $row["teacher_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()->validate($validate);
}
$this->update_check($params,$row=null);
$spec = $params["spec"];
unset($params["spec"]);
$result = $this->model->allowField(true)->save($params);
\app\common\model\school\classes\ClassesLib::add_virtual_init($this->model["id"]);
//添加课程规格
foreach ($spec as $k=>$v){
$v["classes_lib_id"] = $this->model["id"];
unset($v["id"]);
(new \app\common\model\school\classes\ClassesSpec)->allowField(true)->save($v);
}
//因为是批量添加,所有规格重新进行检测,防止出现时间重叠
$specss = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$this->model["id"])->select();
foreach ($specss as $k=>$specs){
$params =$specs->toArray();
(new \app\common\model\school\classes\ClassesSpec)->specCheck($params,null,$specs);
}
$this->update_classes($this->model["id"]);
if($this->have_auth){
//调用通过事件
$data = ['classes' => $this->model];
\think\Hook::listen('classes_auth_need_after', $data);
}
if($this->success_auth){
//调用通过事件
$data = ['classes' => $this->model];
\think\Hook::listen('classes_auth_success_after', $data);
}
if($this->error_auth){
//调用通过事件
$data = ['classes' => $this->model];
\think\Hook::listen('classes_auth_fail_after', $data);
}
Db::commit();
} catch (ValidateException|PDOException|\Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result === false) {
$this->error(__('No rows were inserted'));
}
$this->success();
}
/**
* 编辑
*
* @param $ids
* @return string
* @throws DbException
* @throws \think\Exception
*/
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) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
if (false === $this->request->isPost()) {
$spec = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$row["id"])->field("id,classes_lib_id,name,start_time,end_time,limit_num,status,weigh")->order('weigh desc,id desc')->select();
foreach ($spec as $k=>&$v){
$v["time"] = date("Y/m/d H:i",$v["start_time"])." - ".date("Y/m/d H:i",$v["end_time"]);
}
$row["spec"] = json_encode($spec);
$this->view->assign('row', $row);
return $this->view->fetch();
}
$params = $this->request->post('row/a');
if (empty($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
$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()->validate($validate);
}
$this->update_check($params,$row);
$spec = $params["spec"] ?? [];
// var_dump($spec);
$delete_spec_ids = $params["delete_spec_ids"] ?? [];
unset($params["spec"]);
unset($params["delete_spec_ids"]);
$result = $row->allowField(true)->save($params);
//添加课程规格
foreach ($spec as $k=>$v){
$v["classes_lib_id"] = $row["id"];
//有id更新否则新增
if(isset($v["id"]) && $v["id"]){
\app\common\model\school\classes\ClassesSpec::update((new \app\common\model\school\classes\ClassesSpec)->checkAssemblyParameters($v));
}else{
\app\common\model\school\classes\ClassesSpec::create((new \app\common\model\school\classes\ClassesSpec)->checkAssemblyParameters($v));
}
}
//删除规格
foreach ($delete_spec_ids as $k=>$delete_spec){
(new \app\common\model\school\classes\ClassesSpec)->updateCheck($delete_spec["id"]);
$delete_spec->delete();
}
//因为是批量添加,所有规格重新进行检测,防止出现时间重叠
$specss = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$row["id"])->select();
foreach ($specss as $k=>$specs){
$params =$specs->toArray();
(new \app\common\model\school\classes\ClassesSpec)->specCheck($params,null,$specs);
}
$this->update_classes($row["id"]);
if($this->have_auth){
//调用通过事件
$data = ['classes' => $row];
\think\Hook::listen('classes_auth_need_after', $data);
}
if($this->success_auth){
//调用通过事件
$data = ['classes' => $row];
\think\Hook::listen('classes_auth_success_after', $data);
}
if($this->error_auth){
//调用通过事件
$data = ['classes' => $row];
\think\Hook::listen('classes_auth_fail_after', $data);
}
// protected $have_auth = false;
Db::commit();
} catch (ValidateException|PDOException|\Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if (false === $result) {
$this->error(__('No rows were updated'));
}
$this->success();
}
/**
* 删除
*
* @param $ids
* @return void
* @throws DbException
* @throws DataNotFoundException
* @throws ModelNotFoundException
*/
public function del($ids = null)
{
if (false === $this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ?: $this->request->post("ids");
if (empty($ids)) {
$this->error(__('Parameter %s can not be empty', 'ids'));
}
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($pk, 'in', $ids)->select();
foreach ($list as $item) {
$this->updateCheck($item->id);
}
$count = 0;
Db::startTrans();
try {
foreach ($list as $item) {
//删除课程规格
Spec::where("classes_lib_id",$item->id)->delete();
$count += $item->delete();
}
Db::commit();
} catch (PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
}
$this->error(__('No rows were deleted'));
}
/**
* 复制课程
*
* @param $ids
* @return string
* @throws DbException
* @throws \think\Exception
*/
public function copy($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
if (false === $this->request->isPost()) {
$spec = \app\common\model\school\classes\ClassesSpec::where("classes_lib_id",$row["id"])->field("id,classes_lib_id,name,start_time,end_time,limit_num,status,weigh")->order('weigh desc,id desc')->select();
foreach ($spec as $k=>&$v){
$v["time"] = date("Y/m/d H:i",$v["start_time"])." - ".date("Y/m/d H:i",$v["end_time"]);
}
$row["spec"] = json_encode($spec);
$this->view->assign('row', $row);
return $this->view->fetch();
}
$this->addnew($row);
}
/**
* Selectpage的实现方法
*
* 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
* 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
*
*/
protected function selectpage()
{
//设置过滤方法
$this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
//搜索关键词,客户端输入以空格分开,这里接收为数组
$word = (array)$this->request->request("q_word/a");
//当前页
$page = $this->request->request("pageNumber");
//分页大小
$pagesize = $this->request->request("pageSize");
//搜索条件
$andor = $this->request->request("andOr", "and", "strtoupper");
//排序方式
$orderby = (array)$this->request->request("orderBy/a");
//显示的字段
$field = $this->request->request("showField");
//主键
$primarykey = $this->request->request("keyField");
//主键值
$primaryvalue = $this->request->request("keyValue");
//搜索字段
// $searchfield = (array)$this->request->request("searchField/a");
$searchfield = [
'id','title', 'address', 'address_detail'
];
//自定义搜索条件
$custom = (array)$this->request->request("custom/a");
//是否返回树形结构
$istree = $this->request->request("isTree", 0);
$ishtml = $this->request->request("isHtml", 0);
if ($istree) {
$word = [];
$pagesize = 999999;
}
$order = [];
foreach ($orderby as $k => $v) {
$order[$v[0]] = $v[1];
}
$field = $field ? $field : 'name';
//如果有primaryvalue,说明当前是初始化传值
if ($primaryvalue !== null) {
$where = [$primarykey => ['in', $primaryvalue]];
$pagesize = 999999;
} else {
$where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
$logic = $andor == 'AND' ? '&' : '|';
$searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
$searchfield = str_replace(',', $logic, $searchfield);
$word = array_filter(array_unique($word));
if (count($word) == 1) {
$query->where($searchfield, "like", "%" . reset($word) . "%");
} else {
$query->where(function ($query) use ($word, $searchfield) {
foreach ($word as $index => $item) {
$query->whereOr(function ($query) use ($item, $searchfield) {
$query->where($searchfield, "like", "%{$item}%");
});
}
});
}
if ($custom && is_array($custom)) {
foreach ($custom as $k => $v) {
if (is_array($v) && 2 == count($v)) {
$query->where($k, trim($v[0]), $v[1]);
} else {
$query->where($k, '=', $v);
}
}
}
};
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
if($this->shopIdAutoCondition){
//判断省市区编码是否在授权列表内
["provinces" =>$provinces,"citys"=> $citys, "districts"=>$districts,"address_citys"=>$address_citys] = Admin::getHaveCity($this->auth->id);
if(is_array($provinces)){
$this->model->where('province',"in",$provinces);
}
if(is_array($citys)){
$this->model->where('city',"in",$citys);
}
if(is_array($districts)){
$this->model->where('district',"in",$districts);
}
}
$list = [];
$total = $this->model->where($where)->count();
if ($total > 0) {
if($this->shopIdAutoCondition){
//判断省市区编码是否在授权列表内
["provinces" =>$provinces,"citys"=> $citys, "districts"=>$districts,"address_citys"=>$address_citys] = Admin::getHaveCity($this->auth->id);
if(is_array($provinces)){
$this->model->where('province',"in",$provinces);
}
if(is_array($citys)){
$this->model->where('city',"in",$citys);
}
if(is_array($districts)){
$this->model->where('district',"in",$districts);
}
}
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);
//如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
$primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
//修复自定义data-primary-key为字符串内容时给排序字段添加上引号
$primaryvalue = array_map(function ($value) {
return '\'' . $value . '\'';
}, $primaryvalue);
$primaryvalue = implode(',', $primaryvalue);
$this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
} else {
$this->model->order($order);
}
$datalist = $this->model->where($where)
->page($page, $pagesize)
->select();
foreach ($datalist as $index => $item) {
unset($item['password'], $item['salt']);
if ($this->selectpageFields == '*') {
$result = [
$primarykey => $item[$primarykey] ?? '',
$field => $item[$field] ?? '',
];
} else {
$result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
}
$result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
$list[] = $result;
}
if ($istree && !$primaryvalue) {
$tree = Tree::instance();
$tree->init(collection($list)->toArray(), 'pid');
$list = $tree->getTreeList($tree->getTreeArray(0), $field);
if (!$ishtml) {
foreach ($list as &$item) {
$item = str_replace('&nbsp;', ' ', $item);
}
unset($item);
}
}
}
//这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
return json(['list' => $list, 'total' => $total]);
}
/**
* 生成查询所需要的条件,排序方式
* @param mixed $searchfields 快速查询的字段
* @param boolean $relationSearch 是否关联查询
* @return array
*/
protected function buildparams($searchfields = null, $relationSearch = null,$excludefields = [])
{
$searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
$relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
$search = $this->request->get("search", '');
$filter = $this->request->get("filter", '');
$op = $this->request->get("op", '', 'trim');
$sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
$order = $this->request->get("order", "DESC");
$offset = max(0, $this->request->get("offset/d", 0));
$limit = max(0, $this->request->get("limit/d", 0));
$limit = $limit ?: 999999;
//新增自动计算页码
$page = $limit ? intval($offset / $limit) + 1 : 1;
if ($this->request->has("page")) {
$page = max(0, $this->request->get("page/d", 1));
}
$this->request->get([config('paginate.var_page') => $page]);
$filter = (array)json_decode($filter, true);
$op = (array)json_decode($op, true);
$filter = $filter ? $filter : [];
$where = [];
$excludearray = [];
$alias = [];
$bind = [];
$name = '';
$aliasName = '';
if (!empty($this->model) && $relationSearch) {
$name = $this->model->getTable();
$alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
$aliasName = $alias[$name] . '.';
}
$sortArr = explode(',', $sort);
foreach ($sortArr as $index => & $item) {
$item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
}
unset($item);
$sort = implode(',', $sortArr);
if($this->shopIdAutoCondition){
//判断省市区编码是否在授权列表内
["provinces" =>$provinces,"citys"=> $citys, "districts"=>$districts,"address_citys"=>$address_citys] = Admin::getHaveCity($this->auth->id);
if(is_array($provinces)){
$where[] = [$aliasName.'province','in',$provinces];
}
if(is_array($citys)){
$where[] = [$aliasName.'city','in',$citys];
}
if(is_array($districts)){
$where[] = [$aliasName.'district','in',$districts];
}
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
}
if ($search) {
$searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
foreach ($searcharr as $k => &$v) {
$v = stripos($v, ".") === false ? $aliasName . $v : $v;
}
unset($v);
$where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
}
$index = 0;
foreach ($filter as $k => $v) {
if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
continue;
}
$sym = $op[$k] ?? '=';
//忽略的查询条件出现在忽略数组中 2022年9月6日18:55:17
if(in_array($k, $excludefields)){
$excludearray[$k]['value'] = $v;
$excludearray[$k]['op'] = $sym;
if (stripos($k, ".") === false) {
$excludearray[$k]['alias'] = $aliasName;
}
unset($filter[$k]);
unset($op[$k]);
continue;
}
if (stripos($k, ".") === false) {
$k = $aliasName . $k;
}
$v = !is_array($v) ? trim($v) : $v;
$sym = strtoupper($op[$k] ?? $sym);
//null和空字符串特殊处理
if (!is_array($v)) {
if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
$sym = strtoupper($v);
}
if (in_array($v, ['""', "''"])) {
$v = '';
$sym = '=';
}
}
switch ($sym) {
case '=':
case '<>':
$where[] = [$k, $sym, (string)$v];
break;
case 'LIKE':
case 'NOT LIKE':
case 'LIKE %...%':
case 'NOT LIKE %...%':
$where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
break;
case '>':
case '>=':
case '<':
case '<=':
$where[] = [$k, $sym, intval($v)];
break;
case 'FINDIN':
case 'FINDINSET':
case 'FIND_IN_SET':
$v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
$findArr = array_values($v);
foreach ($findArr as $idx => $item) {
$bindName = "item_" . $index . "_" . $idx;
$bind[$bindName] = $item;
$where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
}
break;
case 'IN':
case 'IN(...)':
case 'NOT IN':
case 'NOT IN(...)':
$where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
break;
case 'BETWEEN':
case 'NOT BETWEEN':
$arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
return $v != '' && $v !== false && $v !== null;
})) {
continue 2;
}
//当出现一边为空时改变操作符
if ($arr[0] === '') {
$sym = $sym == 'BETWEEN' ? '<=' : '>';
$arr = $arr[1];
} elseif ($arr[1] === '') {
$sym = $sym == 'BETWEEN' ? '>=' : '<';
$arr = $arr[0];
}
$where[] = [$k, $sym, $arr];
break;
case 'RANGE':
case 'NOT RANGE':
$v = str_replace(' - ', ',', $v);
$arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr)) {
continue 2;
}
//当出现一边为空时改变操作符
if ($arr[0] === '') {
$sym = $sym == 'RANGE' ? '<=' : '>';
$arr = $arr[1];
} elseif ($arr[1] === '') {
$sym = $sym == 'RANGE' ? '>=' : '<';
$arr = $arr[0];
}
$tableArr = explode('.', $k);
if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
&& !empty($this->model) && $this->relationSearch) {
//修复关联模型下时间无法搜索的BUG
$relation = Loader::parseName($tableArr[0], 1, false);
$alias[$this->model->$relation()->getTable()] = $tableArr[0];
}
$where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
break;
case 'NULL':
case 'IS NULL':
case 'NOT NULL':
case 'IS NOT NULL':
$where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
break;
default:
break;
}
$index++;
}
if (!empty($this->model)) {
$this->model->alias($alias);
}
$model = $this->model;
$where = function ($query) use ($where, $alias, $bind, &$model) {
if (!empty($model)) {
$model->alias($alias);
$model->bind($bind);
}
foreach ($where as $k => $v) {
if (is_array($v)) {
call_user_func_array([$query, 'where'], $v);
} else {
$query->where($v);
}
}
};
return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind,$excludearray];
}
/**
* 跳转链接
* @return string
* @throws \think\Exception
* @throws \think\db\exception\BindParamException
* @throws \think\exception\DbException
* @throws \think\exception\PDOException
*/
public function url($ids = ''){
$param = $this->request->param();
if($this->request->isPost()){
try{
if(isset($param['ids']))$ids = $param['ids'];
//设置模拟资格
$url = \app\common\model\school\classes\ClassesLib::getPath($ids);
}catch (\Exception $e){
$this->error($e->getMessage());
}
$this->success($url);
}
$row = $this->model->get($ids);
$this->view->assign('vo', $row);
return $this->view->fetch();
}
/**
* 微信小程序码
* @return string
* @throws \think\Exception
* @throws \think\db\exception\BindParamException
* @throws \think\exception\DbException
* @throws \think\exception\PDOException
*/
public function miniqrcode($ids = ''){
$param = $this->request->param();
try{
if(isset($param['ids']))$ids = $param['ids'];
//设置模拟资格
$url = \app\common\model\school\classes\ClassesLib::getMiniQrcodeLink($ids);
}catch (\Exception $e){
$this->error($e->getMessage());
}
return $url["response"];
}
/**
* 查看微信小程序码
* @return string
* @throws \think\Exception
* @throws \think\db\exception\BindParamException
* @throws \think\exception\DbException
* @throws \think\exception\PDOException
*/
public function lookminiqrcode($ids = ''){
$param = $this->request->param();
if($this->request->isPost()){
try{
if(isset($param['ids']))$ids = $param['ids'];
//设置模拟资格
$url = \app\common\model\school\classes\ClassesLib::getMiniQrcodeLink($ids);
}catch (\Exception $e){
$this->error($e->getMessage());
}
$this->success("生成小程序码成功",null,$url);
}
$row = $this->model->get($ids);
$this->view->assign('vo', $row);
return $this->view->fetch();
}
}