allocatr/application/admin/controller/workers/Worker.php
2025-06-27 17:09:43 +08:00

706 lines
25 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\workers;
use app\admin\model\Area;
use app\admin\model\AuthGroup;
use app\admin\model\Item;
use app\admin\model\Order;
use app\admin\model\OrderDispatch;
use app\admin\model\WorkerItem;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;
/**
* 师傅列管理
*
* @icon fa fa-circle-o
*/
class Worker extends Backend
{
protected $noNeedRight = ['dispatchList','dispatchMapList'];
/**
* Worker模型对象
* @var \app\admin\model\Worker
*/
protected $model = null;
protected $items;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Worker;
$this->view->assign("statusList", $this->model->getStatusList());
$items = model('item')->getAll();
$this->items = $items;
Tree::instance()->init($items)->icon = ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'];
// dd($ruleList);
$res = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
foreach ($res as &$v) {
$v = $v->toArray();
$v['state'] = ['selected' => false];
$v['parent'] = $v['pid'] ?: '#';
$v['text'] = $v['title'];
unset($v['pid']);
unset($v['title']);
unset($v['level']);
unset($v['key_word']);
unset($v['sort']);
unset($v['status']);
}
$this->tree = $res;
$this->view->assign("tree", $res);
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
$this->assignconfig('permissions', [
'export' => !empty(array_intersect($this->auth->getGroupIds(),[1,11])),
]);
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
$items = $this->items;
$filtered = array_filter($items, function ($item) {
return $item['pid'] == 0;
});
$pid_map = array_column($filtered, null, 'id');
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$area_code = request()->get('area_id');
$filter = (array)json_decode(input()['filter'] ?? '', true);
$area_id = $filter['area_id'] ?? false;
$item_id = $filter['item_id'] ?? false;
$keyword = request()->get('keyword');
$build = $this->model
->with(['area','admin' => function($q){
$q->withField(['id','username']);
}])
->where($where)
->field('worker.id,admin_id,type,name,tel,area_id,create_time,deposit_amount,update_time,status,star,rate,rate_remark,remark,images,address')
->order($sort, $order);
if ($keyword) {
$build->where(function ($q) use ($keyword) {
$q->where('name', 'like', '%' . $keyword . '%')->whereOr('tel', 'like', '%' . $keyword . '%');
});
}
if ($area_id) {
$build->where('area_id', 'like', $this->getSelectAreaCode($area_id) . '%');
}
if ($item_id) {
$item_ids = $this->getItemsById($item_id);
$item_ids [] = $item_id;
$worker_ids = WorkerItem::whereIn('item_id',$item_ids)->column('worker_id');
$build->whereIn('id', $worker_ids);
}
if ($area_code) {
$build->where('area_id', 'like', $this->getSelectAreaCode($area_code) . '%');
}
$list = $build
->paginate($limit);
$data = [];
$worker_ids = [];
foreach ($list->items() as $item){
$dt = $item->toArray();
$tel = $dt['tel'];
if (preg_match('/^\d{7,}$/', $tel)) {
$dt['tel'] = mb_substr($tel, 0, 3, 'UTF-8') . '****' . mb_substr($tel, -4, null, 'UTF-8');
} else {
// 不处理非手机号,比如中文名称
$dt['tel'] = $tel;
}
$data[] = $dt;
$worker_ids [] = $item['id'];
}
$worker_item = WorkerItem::whereIn('worker_id',$worker_ids)->where('item_path_id',1)
->field('worker_id,item_id')->select();
$worker_item_map = [];
// dd($worker_item);
foreach ($worker_item as $item){
$worker_item_map[$item->worker_id] [] = $item->item_id;
}
foreach ($data as &$datum){
// dd($worker_item_map);
if (key_exists($datum['id'],$worker_item_map)){
foreach ($worker_item_map[$datum['id']] as $item){
$datum ['worker_item'][] = trim($pid_map[$item]['title']);
}
}else{
$datum ['worker_item'] = [];
}
$datum['worker_item'] = implode(',',$datum['worker_item']);
}
$result = array("total" => $list->total(), "rows" => $data);
// dd($result);
return $result;
}
$tree = $this->buildTree($items);
$formattedTree = $this->formatTree($tree);
$this->view->assign('items', $formattedTree);
return $this->view->fetch();
}
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);
}
$params['admin_id'] = $this->auth->id;
if((!empty($params['area_id'])) && isset($params['lng'])){
$area = Area::getByCode($params['area_id']);
if($area){
$location = getLocation($area->merge_name.' '.$params['address']);
if(!empty($location)){
$params['lng'] = $location['lng'];
$params['lat'] = $location['lat'];
}
}
}
// dd($params);
$result = $this->model->allowField(true)->save($params);
// dd($result);
$item_map = model('item')->getAll();
$item_map = array_column($item_map, 'level', 'id');
if ($result) {
$items = explode(',', $params['rules']);
if ($items) {
$insert = [];
foreach ($items as $item) {
if ($item == '') continue;
$insert [] = [
'worker_id' => $this->model->id,
'item_id' => $item,
'item_path_id' => $item_map[$item] ?? 0
];
}
model('WorkerItem')->insertAll($insert);
}
}
Db::commit();
} catch (ValidateException | PDOException | Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result === false) {
$this->error(__('No rows were inserted'));
}
$this->success();
}
public function edit($ids = null)
{
if (!$ids) {
if (request()->isPost()) {
$ids = input('id');
if (!$ids) {
$this->error('缺少订单ID');
}
} else {
$this->error('缺少订单ID');
}
}
// 获取当前ID对应的订单信息
$worker = $this->model->get($ids);
if (!$worker) {
$this->error('订单不存在');
}
// 判断是否为POST请求进行更新操作
if (request()->isPost()) {
// 获取表单提交的数据
$params = input('post.row/a');
$item_map = model('item')->getAll();
$item_map = array_column($item_map, 'level', 'id');
if ($ids) {
$items = explode(',', $params['rules'] ?? '');
WorkerItem::where('worker_id', $ids)->delete();
if ($items) {
$insert = [];
foreach ($items as $item) {
if ($item == '') continue;
$insert [] = [
'worker_id' => $ids,
'item_id' => $item,
'item_path_id' => $item_map[$item] ?? 0
];
}
WorkerItem::insertAll($insert);
}
}
unset($params['rules']);
$worker->save($params);
// 返回成功信息
$this->success('更新成功', 'index');
}
$area_name = model('area')->getNameByCode($worker->area_id);
$worker->area_name = str_replace(',', '/', $area_name ?? '');
$select_ids = WorkerItem::where('worker_id', $ids)->field('item_id')
->select();
$select_ids = array_column($select_ids, 'item_id');
foreach ($this->tree as $index => $item) {
if (in_array($item['parent'], $select_ids)) {
$this->tree[$index]['state']['selected'] = true;
}
}
// dd($area_name);
// 将订单数据传递到视图
$this->assign('row', $worker);
$this->assign("tree", $this->tree);
// 渲染编辑页面
return $this->fetch();
}
public function dispatchList()
{
$area_id = request()->get('area_id');
$item_id = request()->get('item_id');
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$build = model('worker')
->where('status', 1)
->where('type',2)
->with(['area'])
->withCount(['myorder' => function ($query) {
$query->where('status', Order::STATUS_FINISHED);
return 'finish_order';
},])
->withCount(['myorder' => function ($query) {
$query->where('status', '<', Order::STATUS_FINISHED)
->where('status', '>=', Order::STATUS_DRAFT);
return 'doing_order';
}])
->field(
['id', 'name', 'tel', 'area_id', 'lng', 'lat']
);
if ($area_id) {
$code = $this->getSelectAreaCode(substr_replace($area_id, '00', -2));
// dd($code);
$build->where('area_id', 'like', $code . '%');
}
if ($item_id) {
$ids = $this->getParentIdsFromArray($item_id,$this->items);
$worker_ids = WorkerItem::whereIn('item_id',$ids)->column('worker_id');
$build->whereIn('id',$worker_ids);
}
$list = $build
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
function getParentIdsFromArray($id, $items) {
$map = [];
foreach ($items as $item) {
$map[$item['id']] = $item['pid'];
}
$result = [];
while (isset($map[$id]) && $map[$id] != 0) {
$id = $map[$id];
$result[] = $id;
}
return $result;
}
public function dispatchMapList()
{
$order_id = request()->get('order_id');
$search = request()->get('search');
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$order = (new Order())->where('id',$order_id)->field(['id','lng','lat','item_id'])->select();
if (!empty($order)) {
$order = $order[0];
}
$worker_distance = Db::query("SELECT id
FROM (
SELECT id,
ST_Distance_Sphere(
point(lng, lat),
point(?, ?)
) AS distance
FROM fa_worker where status = 1 and type = 2
) AS t
WHERE distance < 50000
ORDER BY distance;",[$order->lng,$order->lat]);
$worker_ids = array_column($worker_distance,'id');
$ids = $this->getParentIdsFromArray($order->item_id,$this->items);
$worker_items_ids = (new WorkerItem())
->whereIn('item_id', $ids)
->whereIn('worker_id', $worker_ids)
->column('worker_id');
// $out_worker = OrderDispatch::where('order_id',$order->id)
// ->where('status',-30)->column('worker_id');
$out_worker_ids = array_intersect($worker_ids, $worker_items_ids);
// $out_worker_ids = array_values(array_diff($out_worker_ids, $out_worker));
$build = model('worker')
->where('status', 1)
->whereIn('id', $out_worker_ids);
if ($search){
$build->where(function ($q)use($search){
$q->where('name','like','%'.$search.'%')
->whereor('tel','like','%'.$search.'%');
});
}
$build->withCount(['myorder' => function ($query) {
$query->where('status', Order::STATUS_FINISHED);
return 'finish_order';
},])
->withCount(['myorder' => function ($query) {
$query->where('status', '<', Order::STATUS_FINISHED)
->where('status', '>=', Order::STATUS_DRAFT);
return 'doing_order';
}])
->field(
['id', 'name', 'tel', 'area_id', 'lng', 'lat','ST_Distance_Sphere(
point(lng, lat),
point('.$order->lng.','.$order->lat.')
) AS distance']
)->order('distance');
$list = $build
->paginate($limit);
$data = [];
foreach ($list->items() as $item){
$data [] = [
'id' => $item->id,
'name' => $item->name,
'tel' => $item->tel,
'lat' => $item->lat,
'lng' => $item->lng,
'distance' => $item->distance,
'doing_order' => $item->doing_order,
'finish_order' => $item->finish_order,
'star' => $item->star,
];
}
$result = array("total" => $list->total(), "rows" => $data,'order' => $order);
return $result;
}
public function status(){
$ids = input()['ids'] ?? [];
$status = input()['status'] ?? 1;
$res = Db::name('worker')->whereIn('id',$ids)->update([
'status' => $status
]);
return json([]);
}
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();
$count = 0;
Db::startTrans();
try {
foreach ($list as $item) {
$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'));
}
protected function buildparams($searchfields = null, $relationSearch = null)
{
$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);
unset($filter['item_id']);
unset($filter['area_id']);
$op = (array)json_decode($op, true);
$filter = $filter ? $filter : [];
$where = [];
$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);
$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] ?? '=';
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;
// ✅ 新增右匹配like%
case 'LIKE%':
$where[] = [$k, 'LIKE', "{$v}%"];
break;
// ✅ 新增:左匹配(%like
case '%LIKE':
$where[] = [$k, 'LIKE', "%{$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];
}
}