<?php
namespace app\workerapi\lists;

use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\lists\ListsExtendInterface;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerTeam;
use app\common\lists\ListsSearchInterface;
use app\common\model\works\ServiceWork;
use app\workerapi\logic\MasterWorkerTeamLogic;


/**
 * ServiceWork列表
 * Class ServiceWorkLists
 * @package app\workerapi\listsworks
 */
class MasterWorkerLists extends BaseWorkerDataLists implements ListsSearchInterface,ListsExtendInterface
{
    public function setSearch(): array
    {
        return [
            '%like%' => ['real_name'],
        ];
    }

    public function queryWhere(){
        $where = [];
        if($this->request->controller() == 'MasterWorkerTeam' && $this->request->action() == 'getMemberList'){
            $team = MasterWorkerTeam::where('master_worker_id',$this->userId)->findOrEmpty();
            if ($team->isEmpty()) {
                $where[] = ['team_id','=',-1];
            }else{
                $where[] = ['team_id','=',$team['id']];
                $where[] = ['team_role','=',2];
            }
        }
        return $where;
    }

    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author whitef
     * @date 2024/07/10 15:06
     */
    public function lists(): array
    {
        $list = MasterWorker::where($this->searchWhere)
            ->where($this->queryWhere())
            ->where('is_disable',0)
            ->field(['id','nickname','avatar','mobile','real_name','team_role'])
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'asc'])
            ->select()
            ->toArray();
        // 完工数 本月收益
        foreach ($list as &$item){
            $item['work_total'] = ServiceWork::where(['user_confirm_status'=>5])->where(['master_worker_id'=>$item['id']])->count();
            $item['income'] = MasterWorkerAccountLog::where(['worker_id'=>$item['id']])
                ->where(['change_object'=>WorkerAccountLogEnum::UM,'change_type'=>WorkerAccountLogEnum::UM_INC_ADMIN,'action'=>WorkerAccountLogEnum::INC])
                ->whereBetweenTime('create_time',date('Y-m-01 00:00:00',time()),date('Y-m-d 23:59:59',time()))
                ->sum('change_amount');
        }
        return $list;
    }
    /**
     * @notes 获取数量
     * @return int
     * @author whitef
     * @date 2024/07/10 15:06
     */
    public function count(): int
    {
        return MasterWorker::where($this->searchWhere)->where($this->queryWhere())->count();
    }
    public function extend(): array
    {
        return MasterWorkerTeamLogic::getDetail($this->userId);
    }

}