<?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\works;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\goods_category\GoodsCategory;
use app\common\model\master_worker\MasterWorker;
use app\common\model\works\ServiceWork;
use app\common\lists\ListsSearchInterface;
use think\db\Query;
use think\facade\Log;


/**
 * ServiceWork列表
 * Class ServiceWorkLists
 * @package app\adminapi\listsworks
 */
class ServiceWorkLists extends BaseAdminDataLists implements ListsSearchInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public function setSearch(): array
    {
        return [
            '=' => ['id','work_sn', 'real_name', 'mobile', 'address', 'title', 'category_type', 'base_service_fee', 'service_fee', 'work_status', 'service_status',  'data_type',  'finished_images', 'master_worker_id', 'work_amount','work_type','appoint_approval','refund_approval'],

        ];
    }

    public function queryWhere(){
        $where = [];
        if (isset($this->params['master_worker_name']) && !empty($this->params['master_worker_name'])) {
            $master_worker_ids = MasterWorker::where([['nickname|worker_number|mobile', 'like','%' .$this->params['master_worker_name'] . '%']])->column('id')??[0];
            $where[] = ['master_worker_id','in' ,$master_worker_ids];
        }
        if(isset($this->params['dispatch_time']) && !empty($this->params['dispatch_time'])){
            $time = [strtotime($this->params['dispatch_time'][0]), strtotime($this->params['dispatch_time'][1])];
            $where[] = ['dispatch_time', 'between', $time];
        }
        if(isset($this->params['receive_time']) && !empty($this->params['receive_time'])){
            $time = [strtotime($this->params['receive_time'][0]), strtotime($this->params['receive_time'][1])];
            $where[] = ['receive_time', 'between', $time];
        }
        if(isset($this->params['appointment_time']) && !empty($this->params['appointment_time'])){
            $time = [strtotime($this->params['appointment_time'][0]), strtotime($this->params['appointment_time'][1])];
            $where[] = ['appointment_time', 'between', $time];
        }
        if(isset($this->params['finished_time']) && !empty($this->params['finished_time'])){
            $time = [strtotime($this->params['finished_time'][0]), strtotime($this->params['finished_time'][1])];
            $where[] = ['finished_time', 'between', $time];
        }
        if(isset($this->params['create_time']) && !empty($this->params['create_time'])){
            $time = [strtotime($this->params['create_time'][0]), strtotime($this->params['create_time'][1])];
            $where[] = ['create_time', 'between', $time];
        }
        if(isset($this->params['update_time']) && !empty($this->params['update_time'])){
            $time = [strtotime($this->params['update_time'][0]), strtotime($this->params['update_time'][1])];
            $where[] = ['update_time', 'between', $time];
        }
        if(isset($this->params['appoint_approval']) && !empty($this->params['appoint_approval'])){
            // 时间 超过15分钟未确认
            $time = time()-15*60;
            $where[] = ['update_time', '<', $time];
            $where[] = ['refund_approval', '=', 0]; // 未退款
            $where[] = ['work_pay_status', '>', 0]; // 已支付
        }
        if(isset($this->params['workid']) && !empty($this->params['workid'])){
            $where[] = ['master_worker_id', '=', $this->params['workid']];
            $where[] = ['work_status', 'NOT IN', [7,8,9]];
        }
        if (isset($this->params['update_time']) && !empty($this->params['goods_category_id'])) {
            $goodsCategoryId = end($this->params['goods_category_id']);
            $goodsCategoryData = GoodsCategory::where(['status'=>1])->order(['pid' => 'asc','weigh' => 'desc', 'id' => 'desc'])
                ->select()->toArray();
            $ids =get_tree_ids($goodsCategoryData,$goodsCategoryId);
            $ids[] = $goodsCategoryId;
            $where[] = ['goods_category_id','in' ,$ids];
        }
        if(isset($this->params['work_status']) && (!empty($this->params['work_status']) || $this->params['work_status'] != '')){
            switch ($this->params['work_status']){
                case 0:
                    $where[] = ['service_status','<' ,3];
                    break;
            }
        }
        if(!isset($this->params['work_pay_status']) || (isset($this->params['work_pay_status']) && $this->params['work_pay_status'] == '')){
            $where[] = ['work_pay_status','>',0];
        }else{
            $where[] = ['work_pay_status','=',$this->params['work_pay_status']];
        }
        return $where;
    }
    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public function lists(): array
    {
        return ServiceWork::with([
            'worker'=>function(Query $query) {
                $query->field("id,worker_number,real_name,mobile");
            },
            'goodsCategory' =>function (Query $query) {
                $query->field('id,name');
            },
            'allocateWorkerLog' =>function(Query $query){
                $query->field('id,work_id,opera_log,create_time');
            },
            'serviceWorkLog' =>function(Query $query){
                $query->field('id,work_id,opera_log,create_time');
            },
            'serviceWorkCustomerLog' =>function(Query $query){
                $query->field('id,work_id,content,create_time');
            }
        ])
            ->where($this->searchWhere)
            ->where($this->queryWhere())
            ->field(['id', 'work_sn', 'real_name', 'mobile', 'address', 'title', 'category_type', 'goods_category_ids', 'goods_category_id', 'base_service_fee', 'service_fee', 'work_status','work_pay_status', 'service_status', 'dispatch_time', 'receive_time', 'appointment_time', 'finished_images', 'finished_time', 'master_worker_id', 'work_amount', 'work_type', 'create_time', 'update_time','lon', 'lat','appoint_approval','refund_approval','finally_door_time'])
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public function count(): int
    {
        return ServiceWork::where($this->searchWhere)->where($this->queryWhere())->count();
    }

}