<?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\adminapi\service\DistributeLeafletsService;
use app\common\model\master_worker\MasterWorker;
use app\common\lists\ListsSearchInterface;
use app\common\model\master_worker\MasterWorkerTeam;
use app\common\model\works\ServiceWork;
use think\db\Query;
use think\facade\Db;
use think\facade\Log;

/**
 * MasterWorker列表
 * Class MasterWorkerLists
 * @package app\adminapi\listsmaster_worker
 */
class MasterWorkerLists extends BaseAdminDataLists implements ListsSearchInterface
{
    public $count = 0;
    public $range = 0;
    public $lon = 0;
    public $lat = 0;
    //所有派单限制条件： 工程师保护期  工程师可用金额限制(除去保护期工程师)     工程师接单状态   订单产品分类  订单坐标筛选    订单坐标距离排序
    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public function setSearch(): array
    {
        // 派单搜索条件 - 工程师接单状态
        return [
            '=' => ['mw.sn', 'mw.real_name', 'mw.account', 'mw.password', 'mw.mobile', 'mw.sex', 'mw.channel', 'mw.is_disable', 'mw.is_new_user', 'mw.create_time', 'mw.update_time', 'mw.accept_order_status', 'mw.cooperation','mw.audit_state', 'mw.work_status'],
            //'in' => ['mw.time_period']
        ];
    }

    public function queryWhere(){
        $where = [];
        $where[] = ['mw.team_role','in',[0,1]];
        if(isset($this->params['time_period']) && !empty($this->params['time_period'])){
            $sqls = [];
            foreach ($this->params['time_period'] as $item) {
                $sqls[] = "FIND_IN_SET({$item}, time_period) > 0";
            }
            $query_sql = implode(' OR ', $sqls);
            Log::write('query_sql:'.$query_sql);

            $period_ids = MasterWorker::where('time_period','<>', '')->whereRaw($query_sql)->column('id');
            $where[] = [ 'mw.id','IN',$period_ids?:[0]];
        }
        if (isset($this->params['labels']) && !empty($this->params['labels'])) {
            $sqls = [];
            foreach ($this->params['labels'] as $item) {
                $sqls[] = "FIND_IN_SET({$item}, labels) > 0";
            }
            $query_sql = implode(' OR ', $sqls);
            $period_ids = MasterWorker::where('labels','<>', '')->whereRaw($query_sql)->column('id');
            $where[] = [ 'mw.id','IN',$period_ids?:[0]];
        }
        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);
            Log::write('query_sql:'.$query_sql);

            $period_ids = MasterWorker::where('category_ids','<>', '')->whereRaw($query_sql)->column('id');
            $where[] = [ 'mw.id','IN',$period_ids?:[0]];
        }
        if( isset($this->params['longitude']) && isset($this->params['latitude']) && isset($this->params['range'])
            && !empty($this->params['longitude']) && !empty($this->params['latitude']) && !empty($this->params['range']) ){
            $this->lon = $this->params['longitude'];
            $this->lat = $this->params['latitude'];
            $this->range = $this->params['range'];
        }
        // 用户昵称
        if (isset($this->params['nickname']) && !empty($this->params['nickname'])) {
            $where[] = ['mw.nickname|mw.worker_number', 'like','%' .$this->params['nickname'] . '%'];
        }
        if (isset($this->params['worker_number']) && !empty($this->params['worker_number'])) {
            $where[] = ['mw.worker_number', 'like','%' .$this->params['worker_number'] . '%'];
        }
        if (isset($this->params['worker_exp_type']) && !empty($this->params['worker_exp_type'])) {
            $where[] = ['mwr.maintain_exp_type', '=', $this->params['worker_exp_type']];
        }
        if(isset($this->params['min_work_number']) && is_numeric($this->params['min_work_number'])){
            $where[] =[ 'mw.work_total','>=',$this->params['min_work_number']];
        }
        if(isset($this->params['max_work_number']) && is_numeric($this->params['max_work_number'])){
            $where[] =[ 'mw.work_total','<= ',$this->params['max_work_number']];
        }
        if(isset($this->params['order_id']) && $this->params['order_id']){
            $lon_lat = (ServiceWork::where('id',$this->params['order_id'])->column("lon,lat,goods_category_id"))[0];
            $this->lon = $lon_lat['lon'];
            $this->lat = $lon_lat['lat'];
            $goods_category_id = $lon_lat['goods_category_id'];
            // 派单搜索条件 - 工程师保护期  工程师可用金额限制(除去保护期工程师)  订单产品分类  订单坐标筛选(暂不按距离筛选只按距离排序)
            $ids = DistributeLeafletsService::getIntersection($goods_category_id??0);
            $where[] = [ 'mw.id','IN',$ids];
            $where[] = [ 'mw.work_status','=',0];
        }
        Log::debug('MasterWorker-where:'.json_encode($where));
        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.*','mwr.maintain_exp_type','mwr.other_exp_type'];
        $orders = ['mw.id' => 'desc'];
        $having = 'mw.id > 0';
        $queryWhere = $this->queryWhere();
        //dd($queryWhere,$this->searchWhere);
        // 派单搜索条件 - 订单坐标距离排序
        if($this->lat && $this->lon){
            $fields[] = Db::raw('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))), 2) AS user_distance');
            $orders = 'user_distance';
            $having = '(user_distance - mw.distance) <= 0';
            if($this->range){
                $having = 'user_distance <= '.$this->range;
            }
        }
        $list = MasterWorker::alias('mw')
            ->join('master_worker_register mwr', 'mwr.worker_id = mw.id')
            ->where($this->searchWhere)
            ->where($queryWhere)
            ->field($fields)
            ->limit($this->limitOffset, $this->limitLength)
            ->having($having)
            ->order($orders)
            ->select()->toArray();
        $workCount = array_column(ServiceWork::where('master_worker_id','>',0)
            ->whereNotIn('work_status', [7,8,9])
            ->whereIn('master_worker_id', array_column($list, 'id'))
            ->field(['master_worker_id',Db::raw('COUNT(id) as work_total')])
            ->group('master_worker_id')
            ->select()->toArray(),'work_total','master_worker_id');
        $teams = MasterWorkerTeam::whereIn('master_worker_id', array_column($list, 'id'))->column('team_name','master_worker_id');
        foreach ($list as &$item) {
            $item['work_total'] = $workCount[$item['id']]??0;
            $item['team_name'] = $teams[$item['id']]??'';
        }
        return $list;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public function count(): int
    {
        $fields = ['mw.*','mwr.maintain_exp_type','mwr.other_exp_type'];
        $orders = ['mw.id' => 'desc'];
        $having = 'mw.id > 0';
        $queryWhere = $this->queryWhere();
        // 派单搜索条件 - 订单坐标距离排序
        if($this->lat && $this->lon){
            $fields[] = Db::raw('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))), 2) AS user_distance');
            $orders = 'user_distance';
            $having = '(user_distance - mw.distance) <= 0';
            if($this->range){
                $having = 'user_distance <= '.$this->range;
            }
        }
        return count(MasterWorker::alias('mw')
            ->join('master_worker_register mwr', 'mwr.worker_id = mw.id')
            ->where($this->searchWhere)
            ->where($queryWhere)
            ->field($fields)
            ->having($having)
            ->select()->toArray());
    }
}