<?php

namespace App\Services\BasicManagement;

use Illuminate\Database\Eloquent\Model;
use App\Models\BasicManagement\Admin;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\BasicManagement\AdminValidator;
use BlueCity\Core\Inc\ErrorInc;

class AdminService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new Admin();
        $this->mainValidator = new AdminValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function searchPage($user_info, $search_data, $show_count = 10)
    {
        $list_data = DB::table('wash_Admin_list as a')
            ->leftJoin('wash_Admin_client as b', 'a.reli_id', '=', 'b.recl_reli_id')
            ->where('reli_cid', $user_info->adm_cid)
            ->where('reli_shop_id', $user_info->adm_shop_id)
            ->where('reli_state', '<>', 2) //预约单状态：1待结单2已接单3取消订单4已撤回
            ->where(function ($query) use ($search_data) { //业务员搜索
                if (!empty($search_data['chun_adm_id'])) {
                    $query->where('chun_adm_id', $search_data['chun_adm_id'])
                        ->where('reli_type', 2);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['reli_number'])) {
                    $query->where('reli_number', 'like', '%' . $search_data['reli_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['recl_name'])) {
                    $query->where('recl_name', 'like', '%' . $search_data['recl_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['recl_phone'])) {
                    $query->where('recl_phone', 'like', '%' . $search_data['recl_phone'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['recl_car_num'])) {
                    $query->where('recl_car_num', 'like', '%' . $search_data['recl_car_num'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //车型
                if (!empty($search_data['recl_car_vehicle_type'])) {
                    $query->where('recl_car_vehicle_type', 'like', '%' . $search_data['recl_car_vehicle_type'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {//买家类型：1会员零售2客户单位3速电派单4第三方派单5运营中心给门店派单
                if (!empty($search_data['reli_type'])) {
                    $query->where('reli_type', $search_data['reli_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['reli_service_type'])) {
                    $query->where('reli_service_type', $search_data['reli_service_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['reli_create_id'])) {
                    $query->where('reli_create_id', $search_data['reli_create_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['reli_state'])) {
                    $query->where('reli_state', $search_data['reli_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['reli_remark'])) {
                    $query->where('reli_remark', 'like', '%' . $search_data['reli_remark'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('reli_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('reli_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('reli_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['reli_client_id'])) {
                    $query->where('reli_client_id', $search_data['reli_client_id']);
                }
            })
            ->select('reli_id', 'reli_create_id', 'reli_order_number', 'reli_number', 'reli_actual_price', 'reli_client_type', 'reli_state', 'reli_appoint_time', 'reli_appoint_remark', 'reli_remark', 'reli_order_price', 'reli_client_id','recl_channel_unit', 'recl_name', 'recl_phone', 'recl_car_num', 'recl_province', 'recl_city', 'recl_county', 'recl_address', 'recl_car_vehicle_type', 'recl_car_vin', 'recl_car_brand_series')
            ->orderBy('reli_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();

        if ($list_items) {
            $reli_id = array_column($list_items, 'reli_id'); //预约单id

            // 查询商品、项目信息
            $order_goods = DB::table('wash_Admin_items')
                ->whereIn('reit_reli_id', $reli_id)
                ->select('reit_id', 'reit_reli_id', 'reit_sepr_id', 'reit_goo_name', 'reit_goo_goods_encode', 'reit_sepr_id', 'reit_sepr_name', 'reit_part_state')
                ->get()->toArray();

            // 账号id
            $adm_id = array_column($list_items, 'reli_create_id'); //id
            $adm_id = array_filter(array_unique($adm_id));
            // 查询账号id对应姓名
            $adm_name = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id')
                ->toArray();
            foreach ($list_items as $key => $value) {
                // 创建人
                if ($value->reli_create_id) {
                    $list_items[$key]->create_name = $adm_name[$value->reli_create_id];
                } else {
                    $list_items[$key]->create_name = '';
                }
            }

            // 查询备注信息
            $order_reamrks = DB::table('wash_order_remarks')
                ->whereIn('orre_primary_id', $reli_id)
                ->where('orre_type', 1)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_primary_id', 'orre_module')
                ->orderby('orre_id', 'desc')
                ->get();

            // 查找操作记录
            $order_log = DB::table('wash_order_log')
                ->whereIn('orre_primary_id', $reli_id)
                ->where('orre_type', 1)
                ->orderBy('orlo_id', 'desc')
                ->select('orre_primary_id', 'orlo_time', 'orlo_create_adm_name', 'orlo_content')
                ->get();
        } else {
            $order_goods = [];
            $order_log = [];
            $order_reamrks = [];
        }
        // 查询预约单状态对应的预约单数量
        $state_count = DB::table('wash_Admin_list')
            ->where('reli_cid', $user_info->adm_cid)
            ->where('reli_shop_id', $user_info->adm_shop_id)
            ->where('reli_state', '<>', 1)
            ->select(DB::raw('count(*) as count, reli_state'))
            ->groupBy('reli_state')
            ->get();
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        $data['order_goods'] = $order_goods;                //预约单商品数据
        $data['state_count'] = $state_count;
        $data['order_log'] = $order_log;                    //操作记录
        $data['order_reamrks'] = $order_reamrks;           //预约单备注
        $data['now_time'] = date('Y-m-d H:i:s');           //当前时间
        return $data;
    }

    // 个人中心
    public static function personal($user_info, $request)
    {
        $info = DB::table('admin as a')
            ->leftjoin('admin_set as adms', 'adms.adms_adm_id', '=', 'a.adm_id')
            ->where('a.adm_id', $user_info->adm_id)
            ->first(['a.adm_account', 'a.adm_name', 'a.adm_phone', 'adms_province', 'adms_city', 'adms_county', 'adms_address']);
        if ($info) {
            $data['info'] = $info;

            // 查询当前年月的技师的单量和绩效金额
            $now_year_month = date('Y-m');
            $find_data = DB::table('wash_performance_work')
                ->where('pewo_shop_id', $user_info->adm_shop_id)
                ->where('pewo_service_adm_id', $user_info->adm_id)
                ->where('pewo_create_time', 'like', $now_year_month. '%')
                ->select(DB::raw('count(*) as count,sum(pewo_performance_total_price) as service_price'))
                ->first();
            if ($find_data->service_price) {
                $count_show['service_price'] = $find_data->service_price / 100;//当月的服务绩效金额
            } else {
                $count_show['service_price'] = 0;//当月的服务绩效金额
            }
            $count_show['order_num'] = $find_data->count;//当月完成的工单量
            $data['count_show'] = $count_show;
            return ['code'=>200, 'msg'=>'success', 'data'=>$data];
        } else {
            return ['code'=>500, 'msg'=>'暂无数据', 'data'=>''];
        }
    }

    // 工单统计
    public static function getOrderNumList($user_info, $request, $show_count = 10)
    {
        $list_data = DB::table('wash_performance_work')
            ->where('pewo_shop_id', $user_info->adm_shop_id)
            ->where('pewo_service_adm_id', $user_info->adm_id)
            ->where('pewo_create_time', 'like', $request['time']. '%')
            ->select('pewo_create_time', 'pewo_wor_number', 'pewo_wor_id', 'pewo_id', 'pewo_sepr_name', 'pewo_performance_total_price')
            ->paginate($show_count);
        $find_data = DB::table('wash_performance_work')
            ->where('pewo_shop_id', $user_info->adm_shop_id)
            ->where('pewo_service_adm_id', $user_info->adm_id)
            ->where('pewo_create_time', 'like', $request['time']. '%')
            ->select(DB::raw('count(*) as count,sum(pewo_performance_total_price) as service_price'))
            ->first();
        if ($find_data->service_price) {
            $count_show['service_price'] = $find_data->service_price / 100;//当月的服务绩效金额
        } else {
            $count_show['service_price'] = 0;//当月的服务绩效金额
        }
        $count_show['order_num'] = $find_data->count;//当月完成的工单量
        $data['count_show'] = $count_show;

        $list_items = $list_data->items();
        foreach ($list_items as $key => $value) {
            $list_items[$key]->pewo_create_time = date("Y-m-d",strtotime($value->pewo_create_time));
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        return $data;
    }

    // 个人中心-编辑
    public static function edit($user_info, $request)
    {
        $data['adm_name'] = $request['adm_name'];
        $data['adm_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('admin')
            ->where('adm_id', $user_info->adm_id)
            ->update($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'编辑成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'编辑失败', 'data'=>''];
        }
    }
}
