<?php
namespace app\workerapi\lists;

use app\common\lists\ListsSearchInterface;
use app\common\model\spare_part\SparePart;
use app\common\model\works\ServiceWork;
use app\common\model\works\ServiceWorkSpare;


/**
 * SparePart列表
 * Class SparePartLists
 * @package app\workerapi\lists
 */
class ServiceWorkSparePartLists extends BaseWorkerDataLists implements ListsSearchInterface
{
    protected $count = 0;

    /**
     * 设置搜索条件
     * @return array[]
     * @author liuguanci
     * @date 2024/7/11 下午1:46
     */
    public function setSearch(): array
    {
        if(isset($this->params['user_id']) && !empty($this->params['user_id'])){
            $this->params['master_worker_id'] = $this->params['user_id'];
        }
        return [
            '=' => ['work_sn','master_worker_id'],
        ];
    }
    /*
     * 查询条件
     * @return array
     * @author liuguanci
     * @date 2024/7/11 下午1:46
     */
    public function queryWhere(){
        $where = [];
        if(isset($this->params['spare_name']) && !empty($this->params['spare_name'])){
            $where[] = ['spare_name','like','%'.$this->params['spare_name'].'%'];
        }
        return $where;
    }
    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/09/14 15:08
     */
    public function lists(): array
    {
        // 配件信息
        $spare_parts = [];
        $service_work_spare_id = ServiceWork::where($this->searchWhere)->value('service_work_spare_id');
        if($service_work_spare_id){
            $work_spare_parts = json_decode(ServiceWorkSpare::where('id',$service_work_spare_id)->value('spare_parts'),true);
            $spare_parts = SparePart::where('id','in',array_column($work_spare_parts,'id'))
                ->where($this->queryWhere())
                ->field(['id', 'goods_category_id', 'spare_name', 'spare_image', 'spare_number', 'spare_unit','spare_status'])
                ->select()
                ->toArray();
            $spare_parts = array_column($spare_parts,null,'id');
            foreach (array_column($work_spare_parts,null,'id') as $k=>&$v){
                isset($spare_parts[$k]) && $spare_parts[$k] = array_merge($spare_parts[$k],$v);
            }
            $this->count = SparePart::where('id','in',array_column($work_spare_parts,'id'))
                ->where($this->queryWhere())
                ->count();
        }
        return $spare_parts?array_values($spare_parts):[];
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/09/14 15:08
     */
    public function count(): int
    {
        return $this->count;
    }

}