<?php

namespace App\Services\BasicManagement;

use App\Services\CommonService;
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;
use Pinyin;

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)
            ->where('adms_shop_id', $user_info->adm_shop_id)
            ->first(['a.adm_account', 'a.adm_name', 'a.adm_phone', 'adms_province', 'adms_city', 'adms_county', 'adms_address']);
        if (!$info) {
            $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) {
            $info->adm_name = $info->adm_name??'';
            $info->adm_phone = $info->adm_phone??'';
            $info->adms_address = $info->adms_address??'';
            $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();
            $punishment_count1 = DB::table('violation_ticket_detail')
                ->leftJoin('violation_ticket', 'viti_id', '=', 'vtde_viti_id')
                ->where('vtde_adm_id', $user_info->adm_id)
                ->where('viti_bind_work',1)
                ->where('viti_create_time', 'like', $now_year_month. '%')
                ->select(DB::raw('sum(vtde_punish_money) as punishment_count1'))
                ->first();
            $punishment_count2 = DB::table('violation_ticket_detail')
                ->leftJoin('violation_ticket', 'viti_id', '=', 'vtde_viti_id')
                ->where('vtde_adm_id', $user_info->adm_id)
                ->where('viti_state',1)
                ->where('viti_bind_work',2)
                ->where('viti_create_time', 'like', $now_year_month. '%')
                ->select(DB::raw('sum(vtde_punish_money) as punishment_count2'))
                ->first();
            if ($find_data->service_price) {
                $count_show['service_price'] = $find_data->service_price / 100;//当月的服务绩效金额
            } else {
                $count_show['service_price'] = 0;//当月的服务绩效金额
            }
            if ($punishment_count1) {
                $punishment_count1_money = $punishment_count1->punishment_count1;
                $count_show['service_price'] += $punishment_count1_money/100;
            } else {
                $punishment_count1_money = 0;
            }
            if ($punishment_count2) {
                $punishment_count2_money = $punishment_count2->punishment_count2;
            } else {
                $punishment_count2_money = 0;
            }
            $punishment_count_money = $punishment_count1_money + $punishment_count2_money;
            $order_num = 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. '%')
                ->groupBy('pewo_wor_id')
                ->get();
            $count_show['order_num'] = count($order_num);//当月完成的工单量
            $count_show['punishment_count_money'] = $punishment_count_money/100;//当月完成的工单量
            $data['count_show'] = $count_show;
            $data['count_show'] = $count_show;
            return ['code'=>200, 'msg'=>'success', 'data'=>$data];
        } else {
            return ['code'=>500, 'msg'=>'暂无数据', 'data'=>''];
        }
    }

    // 获取个人所有门店信息
    public static function getPersonalShops($user_info)
    {
        $list_data = DB::table('admin_shop_role as asr')
            ->leftJoin('shop', 'shop.shop_id', '=', 'asr.shop_id')
            ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
            ->where('asr.adm_id', $user_info->adm_id)
            ->where('asr.adm_state', 1)
            ->where('asr.create_source', 1)
            ->where('role.rol_state', 1)
            ->where('shop.shop_state', 1)
            ->select('shop_store_name', 'asr.shop_id', 'asr.login_shop_wechat as login_shop')
            ->orderBy('asr.login_shop_wechat', 'asc')
            ->get();
        if(!empty($list_data)) {
            $data = [
                'info' => $list_data
            ];
            return ['code'=>200, 'msg'=>'success', 'data'=>$data];
        }else{
            return ['code'=>500, 'msg'=>'暂无数据', 'data'=>[]];
        }
    }

    // 个人中心
    public static function BusPersonal($user_info, $request)
    {
        $info = DB::table('business_account as ba')
            ->leftjoin('business_client as bc', 'bc.bucl_id', '=', 'ba.buac_bucl_id')
            ->leftjoin('shop as s', 's.shop_id', '=', 'ba.buac_shop_id')
            ->where('buac_id', $user_info->buac_id)
            ->first(['bucl_name', 'buac_name', 'buac_phone', 'buac_id', 'shop_store_name']);
        if ($info) {
            $data['info'] = $info;
            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')
            ->orderby('pewo_create_time', 'desc')
            ->groupBy('pewo_wor_id')
            ->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('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;//当月的服务绩效金额
        }
        $order_num = 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']. '%')
            ->groupBy('pewo_wor_id')
            ->get();
        $count_show['order_num'] = count($order_num);
        $data['count_show'] = $count_show;
        $list_items = $list_data->items();
        foreach ($list_items as $key => $value) {
            $list_items[$key]->pewo_performance_total_price = 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']. '%')
                ->where('pewo_wor_id', $value->pewo_wor_id)
                ->sum('pewo_performance_total_price');
            $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)
    {
        $find_admin = DB::table('admin')
            ->where('adm_id', '!=', $user_info->adm_id)
            ->where('adm_phone', $request['adm_phone'])
            ->first();
        if ($find_admin) {
            return ['code'=>500, 'msg'=>'手机号已存在', 'data'=>''];
        }
        $data['adm_name'] = $request['adm_name'];
        $data['adm_phone'] = $request['adm_phone'];
        $data['adm_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('admin')
            ->where('adm_id', $user_info->adm_id)
            ->update($data);
        $update_data['phone'] = $request['adm_phone'];
        $update_data['update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('admin_shop_role')
            ->where('adm_id', $user_info->adm_id)
            ->update($update_data);
        if ($res) {
            return ['code'=>200, 'msg'=>'编辑成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'编辑失败', 'data'=>''];
        }
    }

    // 收藏技师
    public static function collectionTh($user_info, $request)
    {
        $data['coth_shop_id'] = $user_info->adm_shop_id;
        $data['coth_adm_id'] = $request['adm_id'];//技师id
        $data['coth_create_adm_id'] = $user_info->adm_id;//收藏人id
        $data['coth_create_time'] = date('Y-m-d H:i:s');
        $find_coth_data = DB::table('collection_technician')
            ->where('coth_adm_id', $request['adm_id'])
            ->where('coth_create_adm_id', $user_info->adm_id)
            ->select('coth_id')
            ->first();
        if ($find_coth_data) {
            return ['code'=>500, 'msg'=>'此技师已收藏', 'data'=>'此技师已收藏'];
        }
        $res = DB::table('collection_technician')
            ->insertGetId($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'收藏成功', 'data'=>'收藏成功'];
        } else {
            return ['code'=>500, 'msg'=>'收藏失败', 'data'=>'收藏失败'];
        }
    }

    // 取消收藏技师
    public static function cancelCoTh($user_info, $request)
    {
        $res = DB::table('collection_technician')
            ->where('coth_create_adm_id', $user_info->adm_id)
            ->where('coth_adm_id', $request['adm_id'])
            ->delete();
        if ($res) {
            return ['code'=>200, 'msg'=>'取消收藏成功', 'data'=>'取消收藏成功'];
        } else {
            return ['code'=>500, 'msg'=>'取消收藏失败', 'data'=>'取消收藏失败'];
        }
    }

    // 我的收藏技师
    public static function myCoTh($user_info, $search_data)
    {
        $res = DB::table('collection_technician as coth')
            ->leftJoin('admin as a', 'a.adm_id', '=', 'coth.coth_adm_id')
            ->leftJoin('wash_grade_level as b', 'b.grle_id', '=', 'a.adm_grle_id')
            ->leftJoin('wash_grade_professional as c', 'c.grpr_id', '=', 'b.grle_grpr_id')
            ->where('coth_create_adm_id', $user_info->adm_id)
            ->where('adm_state', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['keywords'])) {
                    $query->where('adm_name', 'like', '%'.$search_data['keywords'].'%');
                }
            })
            ->select('adm_id', 'adm_name', 'adm_phone', 'grpr_name', 'grle_name')
            ->get()->toArray();
        foreach ($res as $key => $value) {
            $res[$key]->adm_coth_state = 1;
            $rest = mb_substr($value->adm_name, 0, 1, 'utf-8');
            if ($rest) {
                $mb = mb_strlen($rest,'utf-8');
                $st = strlen($rest);
                if ($st==$mb) {//英文
                    $res[$key]->firstLetter = strtoupper($rest);
                } else {//汉字
                    $res[$key]->firstLetter = substr(strtoupper(Pinyin::abbr($value->adm_name)), 0, 1);
                }
            } else {
                $res[$key]->firstLetter = '';
            }
        }
        return $res;
    }

    // 技师动态
    public static function technicianDynamics($user_info, $search_data)
    {
        $now_year_month = date('Y-m');
        $admin = DB::table('admin as a')
            ->leftJoin('admin_shop_role as d', 'd.adm_id', '=', 'a.adm_id')
            ->leftJoin('wash_grade_level as b', 'b.grle_id', '=', 'a.adm_grle_id')
            ->leftJoin('wash_grade_professional as c', 'c.grpr_id', '=', 'b.grle_grpr_id')
            ->where('d.shop_cid', $user_info->adm_cid)
            ->where('d.shop_id', $user_info->adm_shop_id)
            ->where('d.adm_state', 1)
            // ->whereIn('adm_leave', [3, 5])
            ->where('adm_type', '!=', 2)  //不等于虚拟加盟店
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('adm_name', 'like', '%' . $search_data['search_data'] . '%')
                        ->orwhere('adm_phone', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('a.adm_id', 'adm_name', 'adm_phone', 'grpr_name', 'grle_name', 'adm_account')
            ->orderBy('adm_id', 'desc')
            ->get()->toArray();
        foreach ($admin as $key => $value) {
            $work_order = DB::table('wash_work_technician_part as wotp')
                ->leftJoin('work_order as w', 'w.wor_id', '=', 'wotp.wotp_wor_id')
                ->where('wotp_service_adm_id', $value->adm_id)
                ->where('wor_create_time', 'like', $now_year_month.'%')
                ->select('wor_id', 'wor_state', 'wor_appoint_time', 'wor_achieve_time', 'wor_create_time')
                ->groupBy('wor_id')
                ->get()->toArray();
            $number = 0;
            $number1 = 0;
            $number2 = 0;
            foreach ($work_order as $key1 => $value1) {
                $number++;//总工单
                // if (in_array($value1->wor_state, [5,6,7])) {
                // }
                $endDay=date('Y-m-').date('t',strtotime(date('Y-m-d'))).' 23:59:59';
                if (in_array($value1->wor_state, [5,6,7,8,9]) && strtotime($value1->wor_create_time) >= strtotime(date('Y-m')) && strtotime($value1->wor_create_time) <= strtotime($endDay)) {
                    $number1++;
                }
                if (in_array($value1->wor_state, [10,12]) && strtotime($value1->wor_achieve_time) >= strtotime(date('Y-m-d')) && strtotime($value1->wor_achieve_time) <= strtotime($endDay)) {
                    $number2++;
                }
            }
            // 查询当前年月的技师的单量和绩效金额
            $find_data = DB::table('wash_performance_work')
                ->where('pewo_shop_id', $user_info->adm_shop_id)
                ->where('pewo_service_adm_id', $value->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) {
                $service_price = $find_data->service_price / 100;//当月的服务绩效金额
            } else {
                $service_price = 0;//当月的服务绩效金额
            }
            $admin[$key]->adm_name = $value->adm_name??'';
            $admin[$key]->adm_phone = $value->adm_phone??'';
            $admin[$key]->adm_account = $value->adm_account??'';
            $admin[$key]->service_price = $service_price;
            $admin[$key]->totalWork = $number;//总工单
            $admin[$key]->unFinished = $number1;//未完成工单
        }
        return $admin;
    }

    // 技师工单列表
    public static function workOrderTh($user_info, $request, $show_count = 10)
    {
        $today_start = date('Y-m-d', time()).' 00:00:00';
        $today_end = date('Y-m-d', time()).' 23:59:59';
        $list_data = DB::table('wash_work_technician_part as wotp')
            ->leftJoin('work_order as w', 'w.wor_id', '=', 'wotp.wotp_wor_id')
            ->leftJoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wotp.wotp_wor_id')
            ->where('wotp_service_adm_id', $request['adm_id'])
            ->where(function($query) use ($today_start,$today_end){
                $query->whereIn('wor_state', [5,6,7])
                    ->orWhere(function($query) use ($today_start,$today_end){
                        $query->whereIn('wor_state', [8,10])
                            ->whereBetween('wor_achieve_time', [$today_start, $today_end]);
                });
            })
            ->select('wor_id', 'wor_state', 'wor_appoint_time', 'wor_number', 'wor_address', 'wor_explain', 'wor_type', 'wor_delete', 'wocl_client_id', 'wocl_carowner_name', 'wocl_carowner_phone', 'wocl_bus_name', 'wor_create_id', 'wor_address_type', 'wor_shop_id', 'wor_address_id', 'wocl_car_num', 'wor_service_adm_id')
            ->orderBy('wor_appoint_time', 'ASC')
            ->paginate($show_count);
        $list_items2 = $list_data->items();
        if ($list_items2) {
            $wor_id = array_column($list_items2, 'wor_id'); //工单id
            $wor_create_id = array_unique(array_column($list_items2, 'wor_create_id')); //录单人id

            // 查询商品、项目信息
            $work_goods = DB::table('work_good as wg')
                ->leftjoin('goods as g', 'g.goo_id', '=', 'wg.wogo_goo_id')
                ->whereIn('wogo_wor_id', $wor_id)
                ->select('wogo_id', 'wogo_wor_id', 'wogo_goo_id', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_amount', 'wogo_goo_price', 'wogo_goo_guarantee', 'wogo_goo_type', 'wogo_state', 'wogo_goo_unit', 'wogo_goo_unta_id', 'goo_unit_conversion')
                ->get()->toArray();
            $service_adm_id = array_filter(array_unique(array_column($list_items2, 'wor_service_adm_id'))); //选的技师id
            $adm_id_merge = array_merge($wor_create_id, $service_adm_id);
            // 查询录单人信息
            $find_adm = DB::table('admin')
                ->whereIn('adm_id', $adm_id_merge)
                ->pluck('adm_name', 'adm_id')->toArray();

            foreach ($work_goods as $key => $value) {
                $work_goods[$key]->wogo_goo_amount = $value->wogo_goo_amount.$value->wogo_goo_unit;
            }

            $find_dis = DB::table('dispatch_bill')
                ->where('dego_shop_id', $user_info->adm_shop_id)
                ->whereIn('dego_wor_id', $wor_id)
                ->where('dego_order_type', 2)
                ->pluck('dego_type', 'dego_wor_id')->toArray();
            $find_dis_pic = DB::table('dispatch_bill')
                ->where('dego_shop_id', $user_info->adm_shop_id)
                ->whereIn('dego_wor_id', $wor_id)
                ->where('dego_order_type', 2)
                ->pluck('dego_pic', 'dego_wor_id')->toArray();
            foreach ($list_items2 as $key => $value) {
                // 组长
                if ($value->wor_service_adm_id) {
                    $list_items2[$key]->wor_service_adm_name = $find_adm[$value->wor_service_adm_id];
                } else {
                    $list_items2[$key]->wor_service_adm_name = '';
                }
                // 组员
                $find_wotp_data = DB::table('wash_work_technician_part')
                    ->where('wotp_wor_id', $value->wor_id)
                    ->where('wotp_service_adm_id', '<>', $value->wor_service_adm_id)
                    ->select('wotp_service_adm_id', 'wotp_service_adm_name')
                    ->get()->toArray();
                if ($find_wotp_data) {
                    $team_members = '';
                    foreach ($find_wotp_data as $m_key => $m_value) {
                        if ($team_members) {
                            $team_members = $m_value->wotp_service_adm_name.'、'.$team_members;
                        } else {
                            $team_members = $m_value->wotp_service_adm_name;
                        }
                    }
                    $list_items2[$key]->team_members = $team_members;
                }
                // 创建人
                if ($value->wor_create_id) {
                    $list_items2[$key]->adm_name = $find_adm[$value->wor_create_id];
                } else {
                    $list_items2[$key]->adm_name = '';
                }
                // 发货状态
                if (isset($find_dis[$value->wor_id])) {
                    $list_items2[$key]->dego_type = $find_dis[$value->wor_id];
                } else {
                    $list_items2[$key]->dego_type = 0;
                }
                if (strtotime($value->wor_appoint_time) >= strtotime(date('Y-m-d', time())) && strtotime($value->wor_appoint_time) <= strtotime(date('Y-m-d', time()).'23:59:59')) {
                    $list_items2[$key]->wor_time = '今日工单';
                } else {
                    $list_items2[$key]->wor_time = '';
                }
                // 施工地址
                if ($value->wor_address_type == 1) {//门店
                    $find_address = DB::table('shop')
                        ->where('shop_id', $value->wor_address_id)
                        ->select('shop_id', 'shop_store_name', 'shop_province', 'shop_city', 'shop_address', 'shop_county')
                        ->first();
                    $list_items2[$key]->shop_store_name = $find_address->shop_store_name;
                    $list_items2[$key]->wor_address = $find_address->shop_province.$find_address->shop_city.$find_address->shop_county.$find_address->shop_address;
                } elseif ($value->wor_address_type == 2) {
                    $find_address = DB::table('business_client')
                        ->where('bucl_id', $value->wor_address_id)
                        ->select('bucl_id', 'bucl_name', 'bucl_province', 'bucl_city', 'bucl_address', 'bucl_county')
                        ->first();
                    $list_items2[$key]->shop_store_name = $find_address->bucl_name;
                    $list_items2[$key]->wor_address = $find_address->bucl_province.$find_address->bucl_city.$find_address->bucl_county.$find_address->bucl_address;
                } else {
                    $find_address = DB::table('shop')
                        ->where('shop_id', $value->wor_shop_id)
                        ->select('shop_id', 'shop_store_name', 'shop_province', 'shop_city', 'shop_address', 'shop_county')
                        ->first();
                    $list_items2[$key]->shop_store_name = $find_address->shop_store_name;
                    $list_items2[$key]->wor_address = $find_address->shop_province.$find_address->shop_city.$find_address->shop_county.$find_address->shop_address;
                }
            }
            // 查询备注信息
            $order_reamrks = DB::table('order_remarks')
                ->whereIn('orre_wor_id', $wor_id)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_wor_id', 'orre_module')
                ->orderby('orre_id', 'desc')
                ->get();

            // 查找操作记录
            $order_log = DB::table('order_log')
                ->whereIn('orlo_wor_id', $wor_id)
                ->orderBy('orlo_id', 'desc')
                ->select('orlo_wor_id', 'orlo_time', 'orlo_create_adm_name', 'orlo_content')
                ->get();
        } else {
            $work_goods = [];
            $order_log = [];
            $order_reamrks = [];
        }
        $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_items2;                        //返回数据
        $data['work_goods'] = $work_goods;                //工单商品数据
        return $data;
    }

    // 审核列表
    public static function index($user_info, $search_data, $show_count = 10)
    {
        $list_data = DB::table('admin_process')
            ->leftJoin('role', 'rol_id', '=', 'adp_adm_rol_id')
            ->where('adp_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) { //状态搜索
                if (!empty($search_data['adp_state'])) {
                    $query->where('adp_state', $search_data['adp_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //业务员搜索
                if (!empty($search_data['keywords'])) {
                    $query->where('adp_adm_phone', 'like', '%' . $search_data['keywords'] . '%')
                        ->orWhere('adp_adm_name', 'like', '%' . $search_data['keywords'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //姓名搜索
                if (!empty($search_data['adp_adm_name'])) {

                    $query->Where('adp_adm_name', $search_data['adp_adm_name']);
                }
            })
            ->where(function ($query) use ($search_data) { //电话搜索
                if (!empty($search_data['adp_adm_phone'])) {
                    $query->where('adp_adm_phone', $search_data['adp_adm_phone']);
                }
            })
            ->select('adp_id', 'adp_adm_name', 'adp_adm_phone', 'adp_adm_rol_id', 'rol_name', 'adp_state', 'adp_create_time')
            ->orderBy('adp_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        $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 ['code' => 200, 'msg' => 'success', 'data' => $data];
    }

    // 驳回原因
    public static function getReason($user_info, $search_data, $show_count = 10)
    {
        $list_data = DB::table('admin_reason')
            ->leftJoin('admin_process', 'adp_id', '=', 'adr_adp_id')
            ->where('adr_adm_phone', $search_data['phone'])
            ->where('admin_process.adp_shop_id', $user_info->adm_shop_id)
            ->select('adr_reason', 'adr_create_name', 'adr_create_time', 'adr_rol_name')
            ->orderBy('adr_id', 'desc')
            ->get()->toArray();
        return ['code' => 200, 'msg' => 'success', 'data' => $list_data];
    }

    // 门店经营驾驶舱
    public static function dataCount($user_info, $search_data)
    {
        if (empty($search_data['create_time_start'])) {
            $search_data['create_time_start'] = date('Y-m-d');
        }
        if (empty($search_data['create_time_end'])) {
            $search_data['create_time_end'] = date('Y-m-d');
        }
        $list_data = DB::table('order')
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->where('ord_wor_state', '<>', 11)
            ->whereIn('ord_service_type', [1,2,3])
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('ord_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('ord_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->select('ord_id', 'ord_actual_price', 'ord_zero_price', 'ord_order_price', 'ord_service_type', 'ord_payment_way')
            ->get()->toArray();
        $ord_order_price = 0;
        $ord_actual_price = 0;
        $ord_zero_price = 0;
        $ord_num = 0;
        foreach ($list_data as $key => $value) {
            if (in_array($value->ord_service_type,[1,2,3])) {
                $ord_order_price += $value->ord_order_price;
            }
            if (in_array($value->ord_payment_way,[5,6,7])) {
                $ord_actual_price += $value->ord_order_price;
            } else {
                $ord_actual_price += $value->ord_actual_price;
            }
            $ord_zero_price += $value->ord_zero_price;
            $ord_num++;
        }
        $data['ord_order_price'] = $ord_order_price;
        $data['ord_actual_price'] = $ord_actual_price;
        $data['ord_num'] = $ord_num;
        if ($ord_num > 0) {
            $data['avg_order_amount'] = intval($ord_order_price/$ord_num);
        } else {
            $data['avg_order_amount'] = 0;
        }
        $order_goods = DB::table('order_goods')
            ->leftJoin('order', 'ord_id', '=', 'orgo_ord_id')
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->where('ord_wor_state', '<>', 11)
            ->whereIn('orgo_goo_type', [1,2])
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('ord_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('ord_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->select(DB::raw('count(*) as count, orgo_goo_name, sum(orgo_goo_amount) as orgo_goo_amount'))
            ->groupBy('orgo_goo_name')
            ->orderBy('count', 'desc')
            ->get()->toArray();
        $order_goods_price = DB::table('order_goods')
            ->leftJoin('order', 'ord_id', '=', 'orgo_ord_id')
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->where('ord_wor_state', '<>', 11)
            ->whereIn('orgo_goo_type', [1,2])
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('ord_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('ord_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->select(DB::raw('orgo_goo_name, sum(orgo_goo_amount) as orgo_goo_amount'))
            ->groupBy('orgo_goo_name')
            ->orderBy('orgo_goo_amount', 'desc')
            ->orderBy('orgo_goo_name', 'desc')
            ->get()->toArray();
        $other_count = 0;
        $goo_num = 0;
        $data['order_goods_data'] = [];
        foreach ($order_goods as $key => $value) {
            if ($key > 3) {
                $other_count += $value->count;
                $goo_num = 4;
            } else {
                $data['order_goods_data'][$key]['name'] = $value->orgo_goo_name;
                $data['order_goods_data'][$key]['count'] = $value->count;
                $goo_num = $key+1;
            }
        }
        if ($other_count > 0) {
            $data['order_goods_data'][$goo_num]['name'] = '其它';
            $data['order_goods_data'][$goo_num]['count'] = $other_count;
        }
        $orgo_goo_amount = 0;
        $goo_num = 0;
        $data['order_goods_price'] = [];
        foreach ($order_goods_price as $key => $value) {
            if ($key > 3) {
                $orgo_goo_amount += $value->orgo_goo_amount;
                $goo_num = 4;
            } else {
                $data['order_goods_price'][$key]['name'] = $value->orgo_goo_name;
                $data['order_goods_price'][$key]['count'] = $value->orgo_goo_amount;
                $goo_num = $key+1;
            }
        }
        if ($orgo_goo_amount > 0) {
            $data['order_goods_price'][$goo_num]['name'] = '其它';
            $data['order_goods_price'][$goo_num]['count'] = $orgo_goo_amount;
        }
        return ['code' => 200, 'msg' => 'success', 'data' => $data];
    }

    // 门店经营驾驶舱-销售额
    public static function salesVolume($user_info, $request)
    {
        if ($request['type'] == 1) {//日销售
            if (empty($request['time'])) {
                $request['time'] = date('Y-m');
            }
            $days = date("t",strtotime($request['time']));
            $data = [];
            $date = $request['time'].'-01';
            for ($i=0;$i<$days;$i++) {
                if ($i>0) {
                    $date = date('Y-m-d', strtotime($date)+60*60*24);
                }
                $data[$i]['date'] = $date;
                $data[$i]['ord_order_price'] = DB::table('order')
                    ->where('ord_shop_id', $user_info->adm_shop_id)
                    ->where('ord_wor_state', '<>', 11)
                    ->whereIn('ord_service_type', [1,2,3])
                    ->where('ord_create_time', '>=', $date)
                    ->where('ord_create_time', '<=', $date.' 23:59:59')
                    ->sum('ord_order_price');
            }
        }

        if ($request['type'] == 2) {//月销售
            if (empty($request['time'])) {
                $request['time'] = date('Y');
            }
            $date = $request['time'].'-01-01';
            for ($i=0;$i<12;$i++) {
                $next_date = date('Y-m-d', strtotime('+1 month',strtotime($date)));
                $data[$i]['date'] = date('Y-m', strtotime($date));
                $data[$i]['ord_order_price'] = DB::table('order')
                    ->where('ord_shop_id', $user_info->adm_shop_id)
                    ->where('ord_wor_state', '<>', 11)
                    ->whereIn('ord_service_type', [1,2,3])
                    ->where('ord_create_time', '>=', $date)
                    ->where('ord_create_time', '<', $next_date)
                    ->sum('ord_order_price');
                $date = $next_date;
            }
        }
        return ['code' => 200, 'msg' => 'success', 'data' => $data];
    }
}
