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


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


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

    /**
     * 获取数据权限
     * $this->adminInfo['data_rules']
     * province city admin_id sale_group_id sale_id  property_head_id
     */
    public function queryDataWhere(){
        $where = [];
        $data_rules = $this->adminInfo['data_rules'];
        if (isset($data_rules['province']) && !empty($data_rules['province'])) {
            $where[] = ['province','in' ,$data_rules['province']];
        }
        if (isset($data_rules['city']) && !empty($data_rules['city'])) {
            $where[] = ['city','in' ,$data_rules['city']];
        }
        if (isset($data_rules['sale_group_id']) && !empty($data_rules['sale_group_id'])) {
            $work_ids = PropertyOrder::where('sale_group_id','in',$data_rules['sale_group_id'])->column('work_id')??[];
            $where[] = ['id','in' ,$work_ids];
        }
        if (isset($data_rules['sale_id']) && !empty($data_rules['sale_id'])) {
            $work_ids = PropertyOrder::where('sale_id','in',$data_rules['sale_id'])->column('work_id')??[];
            $where[] = ['id','in' ,$work_ids];
        }
        if (isset($data_rules['property_head_id']) && !empty($data_rules['property_head_id'])) {
            $work_ids = PropertyOrder::where('property_head_id','in',$data_rules['property_head_id'])->column('work_id')??[];
            $where[] = ['id','in' ,$work_ids];
        }
        return $where;
    }
    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/07/10 15:06
     */
    public function setSearch(): array
    {
        return [
            '=' => ['id','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', 'city'],
            '%like%'=>[ 'work_sn','mobile','real_name', 'title', 'address']
        ];
    }

    public function queryWhere(){
        $where = [];
        if (isset($this->params['master_worker_name']) && !empty($this->params['master_worker_name'])) {
            $master_worker_ids = MasterWorker::where([['worker_number|mobile|real_name', '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'][0]) && !empty($this->params['dispatch_time'][1])){
            $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'][0]) && !empty($this->params['receive_time'][1])){
            $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'][0]) && !empty($this->params['appointment_time'][1])){
            $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'][0]) && !empty($this->params['finished_time'][1])){
            $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'][0]) && !empty($this->params['create_time'][1])){
            $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'][0]) && !empty($this->params['update_time'][1])){
            $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']];
        }

        if(isset($this->params['property_activity_id']) && !empty($this->params['property_activity_id'])){
            if($this->params['property_activity_id'] == 2){
                $where[] = ['order_effective_id','>',0];
            }else{
                $where[] = ['property_activity_id','>',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/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('tenant_id', $this->adminInfo['tenant_id'])
            ->where($this->searchWhere)
            ->where($this->queryWhere())
            ->where($this->queryDataWhere())
            ->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','property_activity_id','order_effective_id'])
            ->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('tenant_id', $this->adminInfo['tenant_id'])->where($this->queryWhere())->where($this->queryDataWhere())->count();
    }

}