<?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_commission;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsSearchInterface;
use app\common\model\master_commission\MasterWorkerCommissionConfig;
use app\common\model\master_worker\MasterWorker;
use app\common\model\works\ServiceWorkAllocateWorkerLog;
use think\facade\Db;


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


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/12/16 17:37
     */
    public function setSearch(): array
    {
        return [
            '=' => ['n.commission_config_id', 'n.master_worker_id', 'n.day_num', 'n.order_num', 'n.signing_date', 'n.signing_date_end'],
        ];
    }

    public function queryWhere()
    {
        $where = [];
        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[] = [ 'n.master_worker_id','in',$period_ids?:[0]];
        }
        if (isset($this->params['mobile']) && !empty($this->params['mobile'])) {
            $mw_ids = MasterWorker::where('mobile', $this->params['mobile'])->column('id');
            $where[] = [ 'n.master_worker_id','in',$mw_ids?:[0]];
        }
        if (isset($this->params['worker_number']) && !empty($this->params['worker_number'])) {
            $mw_ids = MasterWorker::where([[ 'mw.worker_number','like','%'.$this->params['worker_number'].'%']])->column('id');
            $where[] = [ 'n.master_worker_id','in',$mw_ids?:[0]];
        }
        if (isset($this->params['real_name']) && !empty($this->params['real_name'])) {
            $mw_ids = MasterWorker::where([[ 'mw.worker_number','like','%'.$this->params['real_name'].'%']])->column('id');
            $where[] = [ 'n.master_worker_id','in',$mw_ids?:[0]];
        }
        $mwids = MasterWorkerCommissionConfig::where('voucher_status', 2)->column('master_worker_id');
        $where[] = [ 'n.master_worker_id','in',$mwids?:[0]];
        return $where;
    }

    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/12/16 17:37
     */
    public function lists(): array
    {
        $lists = Db::name('master_worker_commission_notice')->alias('n')
            ->leftJoin('master_worker mw', 'n.master_worker_id = mw.id')
            ->leftJoin('service_work sw', 'n.master_worker_id = sw.master_worker_id AND sw.create_time >= n.signing_date AND sw.create_time <= n.signing_date_end')
            ->field([
                'n.id', 'n.commission_config_id', 'n.master_worker_id', 'n.day_num', 'n.order_num', 'n.signing_date', 'n.signing_date_end',
                'mw.real_name', 'mw.nickname', 'mw.worker_number', 'mw.mobile','mw.labels',
                Db::raw("COUNT(CASE WHEN sw.service_status = 3 THEN sw.id ELSE null END) AS order_count"),
                Db::raw("MAX(CASE WHEN sw.service_status = 3 THEN sw.finished_time ELSE null END) max_time")
            ])
            ->where($this->searchWhere)
            ->where($this->queryWhere())
            ->group('n.master_worker_id, n.id')
            ->limit($this->limitOffset, $this->limitLength)
            ->select()->toArray();
        foreach ($lists as &$item) {
            $item['labels'] = $item['labels']?array_map(function ($item) { return intval($item); },explode(',',$item['labels'])):'';
            $item['allocate_num'] = ServiceWorkAllocateWorkerLog::where(['master_worker_id'=>$item['master_worker_id']])->count();
        }
        return $lists;
    }
    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/12/16 17:37
     */
    public function count(): int
    {
        return Db::name('master_worker_commission_notice')->alias('n')
            ->with('masterWorker')
            ->leftJoin('service_work sw', 'n.master_worker_id = sw.master_worker_id AND sw.create_time >= n.signing_date AND sw.create_time <= n.signing_date_end')
            ->field([
                'n.id', 'n.commission_config_id', 'n.master_worker_id', 'n.day_num', 'n.order_num', 'n.signing_date', 'n.signing_date_end',
                Db::raw("COUNT(sw.id) AS order_count"),
                Db::raw("MAX(sw.finished_time) max_time")
            ])
            ->where($this->searchWhere)
            ->where($this->queryWhere())
            ->group('n.master_worker_id, n.id')
            ->count();
    }

    public function setExcelComplexFields(): array
    {
        $zh_cn_fields = [
            '工程师ID','工程师编号', '工程师姓名','工程师手机号','启动时间(签约时间)', '规则天数','应达标时间','单量规则','工单数','是否达标','达标时间'
        ];
        $data_fields = ['master_worker_id','worker_number','real_name','mobile',function ($row) {
            return $row['signing_date']?date('Y-m-d H:i:s',$row['signing_date']):'';
        },'day_num',function ($row) {
            return $row['signing_date_end']?date('Y-m-d H:i:s',$row['signing_date_end']):'';
        },'order_num','order_count',function ($row) {
            return ($row['order_num']>$row['order_count'])? '否' : '是';
        },function ($row) {
            return ($row['order_num']>$row['order_count'])?'':($row['max_time']?date('Y-m-d H:i:s',$row['max_time']):'');
        }];
        return [
            'zh_cn_fields' => $zh_cn_fields,
            'data_fields' => $data_fields
        ];
    }
}