<?php
namespace app\workerapi\lists;

use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\lists\ListsSearchInterface;
use app\common\model\works\ServiceWork;
use app\workerapi\logic\MasterWorkerLogic;
use app\workerapi\logic\SaleLogic;
use think\facade\Db;


/**
 * MasterWorkerRegister列表
 * Class MasterWorkerRegisterLists
 * @package app\workerapi\lists
 */
class MasterWorkerRegisterLists extends BaseWorkerDataLists implements ListsSearchInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public function setSearch(): array
    {
        $sale_id = SaleLogic::getSaleIdByToken($this->params['sale_token']??'00000');
        $this->params['sale_id'] = $sale_id;
        return [
            '=' => ['maintain_exp_type', 'other_exp_type', 'city', 'vehicle_type', 'status','is_credential','sale_id'],
            '%like%' => ['name', 'mobile'],
        ];
    }


    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public function lists(): array
    {
        $list = MasterWorkerRegister::where($this->searchWhere)
            ->field(['*'])
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        $workCount = array_column(ServiceWork::where('master_worker_id','>',0)
            ->whereIn('master_worker_id', array_filter(array_column($list, 'worker_id'), function($value) { return $value != 0; })??[-1])
            ->field(['master_worker_id',Db::raw('COUNT(id) as work_total')])
            ->group('master_worker_id')
            ->select()->toArray(),'work_total','master_worker_id');

        foreach ($list as &$item) {
            $item['work_total'] = $workCount[$item['worker_id']]??0;
            if((int)$item['status'] === 1){
                $item['status'] = $this->requiredMasterWorker($item['worker_id'])?1:2;
            }
        }
        return $list;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2025/02/25 09:29
     */
    public function count(): int
    {
        return MasterWorkerRegister::where($this->searchWhere)->count();
    }


    public function requiredMasterWorker($master_worker_id): bool
    {
        $masterWorker = MasterWorker::where('id',$master_worker_id)->findOrEmpty();
        if(!$masterWorker->isEmpty()){
            // 该工程师所有必须任务是否完成
            $taskRequired = MasterWorkerLogic::taskRequired($master_worker_id,$masterWorker->identity_source);
            if($masterWorker->audit_state == 1 && $taskRequired){
                return true;
            }
        }
        return false;
    }


}