<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\master_worker;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\master_worker\MasterWorker;
use app\common\lists\ListsSearchInterface;
use app\common\model\works\ServiceWork;
use think\facade\Db;
use think\facade\Log;

/**
 * MasterWorker列表
 * Class MasterWorkerOnlineLists
 * @package app\adminapi\listsmaster_worker
 */
class MasterWorkerOnlineLists extends BaseAdminDataLists implements ListsSearchInterface
{
    public $count = 0;
    public $lon = 0;
    public $lat = 0;
    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public function setSearch(): array
    {
        // 派单搜索条件 - 工程师接单状态
        return [
            '=' => ['mw.real_name', 'mw.mobile', 'mw.accept_order_status'],
            '%like%' => ['sa.service_name'],
        ];
    }
    
    public function queryWhere(){
        $where = [];
        
        if(isset($this->params['category_ids']) && !empty($this->params['category_ids'])){
            $sqls = [];
            $category_ids =[];
            foreach ($this->params['category_ids'] as $val){
                ($val = json_decode($val,true))?($category_ids[] = end($val)):($category_ids[] = $val);
            }
            foreach ($category_ids as $item) {
                $sqls[] = "FIND_IN_SET({$item}, category_ids) > 0";
            }
            $query_sql = implode(' OR ', $sqls);
            $period_ids = MasterWorker::where('category_ids','<>', '')->whereRaw($query_sql)->column('id');
            $where[] = [ 'mw.id','IN',$period_ids?:[0]];
        }
        if(isset($this->params['address']) && $this->params['address']){
            $lon_lat = get_address_lat_lng($this->params['address']);;
            $this->lon = $lon_lat['lon'];
            $this->lat = $lon_lat['lat'];
            
        }
        return $where;
    }
    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public function lists(): array
    {
        $fields = ['mw.id,mw.avatar,mw.real_name,mw.mobile,mw.work_total,mw.distance,mw.accept_order_status,mw.address,mw.service_area_id,mws.comprehensive_score, mws.weight_score,sa.service_name,mwr.credential_images'];
        $orders = ['mw.id' => 'desc'];
        $queryWhere = $this->queryWhere();
        // 根据位置排序
        $distanceWhereSql = 'mw.id > 0';
        if ($this->lat && $this->lon) {
            $user_distance = 'ROUND(6371 * 1000 * ACOS(COS(RADIANS('.$this->lat.')) * COS(RADIANS(mw.lat)) * COS(RADIANS(mw.lon) - RADIANS('.$this->lon.')) + SIN(RADIANS('.$this->lat.')) * SIN(RADIANS(mw.lat))))';
            $fields[] = Db::raw($user_distance.' AS user_distance');
            // 修改排序规则为按照距离正序排序
            $orders = ['user_distance' => 'asc'];
            $distanceWhereSql = '('.$user_distance.' ) <= 100000';
        } 
        
        $list = MasterWorker::alias('mw')
            ->join('master_worker_score mws', 'mws.worker_id = mw.id')
            ->join('service_area sa', 'sa.id = mw.service_area_id')
            ->join('master_worker_register mwr', 'mwr.worker_id = mw.id')
            ->where(['mw.is_disable' => 0, 'mw.work_status' => 0,'mw.audit_state' => 1])
            ->where($this->searchWhere)
            ->where($queryWhere)
            ->whereRaw($distanceWhereSql)
            ->field($fields)
            ->limit($this->limitOffset, $this->limitLength)
            ->order($orders)
            ->select()->toArray();
        foreach($list as &$item){
            $item['order_num'] = ServiceWork::where('master_worker_id',$item['id'])
                                    ->where('work_type','<>',2)
                                    ->where('service_status','<',4)
                                    ->whereBetween('appointment_time',[strtotime(date("Y-m-d")),strtotime(date("Y-m-d 23:59:59"))])
                                    ->count();
            $item['credential_images'] = $item['credential_images'] ? json_decode($item['credential_images'],true) : [];
        }
        return $list;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public function count(): int
    {
        $queryWhere = $this->queryWhere();
        $distanceWhereSql = 'mw.id > 0';
        if($this->lat && $this->lon){
            $user_distance = 'ROUND(6371* 1000 * ACOS(COS(RADIANS('.$this->lat.')) * COS(RADIANS(mw.lat)) * COS(RADIANS(mw.lon) - RADIANS('.$this->lon.')) + SIN(RADIANS('.$this->lat.')) * SIN(RADIANS(mw.lat))))';
            $fields[] = Db::raw($user_distance.' AS user_distance');
            $distanceWhereSql = '('.$user_distance.' ) <= 100000';
        }
        return MasterWorker::alias('mw')
            ->join('service_area sa', 'sa.id = mw.service_area_id')
            ->where(['mw.is_disable' => 0, 'mw.work_status' => 0,'mw.audit_state' => 1])
            ->where($this->searchWhere)
            ->where($queryWhere)
            ->whereRaw($distanceWhereSql)
            ->count();
    }
}