<?php
namespace app\adminapi\lists\master_worker;

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


/**
 * MasterWorkerServiceOrder列表
 * Class MasterWorkerServiceOrderLists
 * @package app\adminapi\lists
 */
class MasterWorkerServiceOrderLists extends BaseAdminDataLists implements ListsSearchInterface
{

    public $sqlJoin = '';

    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/11/15 17:21
     */
    public function setSearch(): array
    {
        return [];
    }

    public function queryWhere()
    {
        $where = [];
        if (isset($this->params['real_name']) && !empty($this->params['real_name'])) {
            $where[] = ['a.real_name','like' ,"%".$this->params['real_name']."%"];
        }
        if (isset($this->params['worker_number']) && !empty($this->params['worker_number'])) {
            $where[] = ['a.worker_number','like' ,"%".$this->params['worker_number']."%"];
        }
        if (isset($this->params['recruiting_behalf']) && !empty($this->params['recruiting_behalf'])) {
            $where[] = ['a.recruiting_behalf','like' ,"%".$this->params['recruiting_behalf']."%"];
        }
        if (isset($this->params['is_recruiting_behalf']) && !empty($this->params['is_recruiting_behalf'])) {
            if ($this->params['is_recruiting_behalf'] == 1)
                $where[] = ['a.recruiting_behalf','<>' ,""];
            else
                $where[] = ['a.recruiting_behalf','=' ,""];
        }
        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[] = [ 'a.id','IN',$period_ids?:[0]];
        }
        if (isset($this->params['mobile']) && !empty($this->params['mobile'])) {
            $where[] = ['a.mobile','=' ,$this->params['mobile']];
        }
        if (isset($this->params['cooperation']) && !empty($this->params['cooperation'])) {
            $where[] = ['a.cooperation','=' ,$this->params['cooperation']];
        }
        if (!empty($this->params['start_time'])) {
            $this->sqlJoin .= '    AND  b.update_time >= '.strtotime($this->params['start_time']);
        }
        if (!empty($this->params['end_time'])) {
            $this->sqlJoin .= '    AND  b.update_time < '.strtotime($this->params['end_time'])+86400;
        }
        return $where;
    }


    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/11/15 17:21
     */
    public function lists(): array
    {
        $queryWhere = $this->queryWhere();
        $lists = Db::name('master_worker')->alias('a')->field([
                'a.id','a.real_name','a.nickname','a.worker_number','a.recruiting_behalf','a.mobile','a.cooperation','a.category_ids',
                Db::raw("COUNT(b.id) AS all_count"),
                Db::raw("SUM(CASE WHEN b.service_status = 3 THEN 1 ELSE 0 END) AS success_count"),
                Db::raw("SUM(CASE WHEN b.service_status = 4 OR b.service_status = 5 THEN 1 ELSE 0 END) AS fail_count"),
                Db::raw("SUM(b.work_total) work_total"),
                Db::raw("SUM(b.worker_price) worker_price"),
            ])
            ->leftJoin('service_work b', 'a.id = b.master_worker_id'.$this->sqlJoin)
            ->where($queryWhere)
            ->group('a.id')
            ->order('a.id desc')
            ->limit($this->limitOffset, $this->limitLength)
            ->select()->toArray();
        $categoryData = GoodsCategory::select()->toArray();
        foreach ($lists as &$item) {
            $item['category_name'] = $item['category_ids']?implode('、',array_column(get_parent_info($categoryData,explode(',',$item['category_ids'])),'name')):'';
        }
        return $lists;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/11/15 17:21
     */
    public function count(): int
    {
        $queryWhere = $this->queryWhere();
        return Db::name('master_worker')->alias('a')->field([
                'a.id','a.real_name','a.nickname','a.worker_number','a.recruiting_behalf',
                Db::raw("SUM(CASE WHEN b.service_status = 3 THEN 1 ELSE 0 END) AS success_count"),
                Db::raw("SUM(CASE WHEN b.service_status = 4 OR b.service_status = 5 THEN 1 ELSE 0 END) AS fail_count"),
                Db::raw("SUM(b.work_total) work_total"),
                Db::raw("SUM(b.worker_price) worker_price"),
            ])
            ->leftJoin('service_work b', 'a.id = b.master_worker_id'.$this->sqlJoin)
            ->where($queryWhere)
            ->group('a.id')
            ->count();
    }

}