<?php
/**
 * 文件名称（数据统计）
 * 文件简单描述（用于进行数据统计分析）
 * @author DouBin
 * @Date: 2024/10/15
 * @Time: 17:49
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;

use App\Exports\BasicExport;
use App\Http\Controllers\Common\CommonController;
use App\Models\Admin;
use App\Models\OrderList;
use App\Models\OrderRejected;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;

class DataStatisticsService extends Service{

    /**|---------------------------------------------------------------------------------
     * @name 获取公司数据统计信息
     * @retrun /multitype:array
     * @author dou 2022-12-05 005 下午 6:50:11
     * |---------------------------------------------------------------------------------
     */
    public static function getSerStatistics ( $session , $input ){
        $page_size = $input['page_size']??10;
        $admindata = Admin::whereRaw("((company_id='".$session['company_id']."' and admin_groupnew=2) or admin_groupnew=3) and enable=1")
            ->select('id','company_name')
//            ->paginate($page_size)
            ->get();
        $admindata = CommonService::dataToArray($admindata);
        $return = [];
        if($admindata){
            $time_start = $input['time_start'];
            if($input['search_type'] == 'week') {
                $time_end = date("Y-m-d", strtotime($input['time_start'] . " +7 day"));
            }if($input['search_type'] == 'month') {
                $time_end = date("Y-m-d", strtotime($input['time_start'] . " +1 month"));
            }
            if(isset($input['goods_brand']) && !empty($input['goods_brand'])){
                $where = " and gone_orders.goods_brand='".$input['goods_brand']."'";
            }
            foreach($admindata as $k => $v){
                $order_listnum = OrderList::leftjoin('orders', 'orders.order_num', '=', 'order_list.order_num')->whereRaw("gone_order_list.ser_id='".$v['id']."' and gone_order_list.create_time BETWEEN '".$time_start."' and '".$time_end."' and gone_order_list.is_delete=1 and gone_order_list.get_time != '' and gone_order_list.company_id = '".$session['company_id']."'".$where)->count();//接单数量
//                $order_listnums = OrderList::whereRaw("ser_id='".$v['id']."' and create_time BETWEEN '".$time_start."' and '".$time_end."' and is_delete=1 and company_id = '".$session['company_id']."'")->count();//工单数量
                $order_rejectednum = OrderRejected::leftjoin('orders', 'or_order_num', '=', 'order_num')->whereRaw("or_ser_id='".$v['id']."' and or_creact_time BETWEEN '".$time_start."' and '".$time_end."' and or_show=1 and or_type = 1 and company_id = '".$session['company_id']."'".$where)->count();//拒单数量
//                $order_fivenum = OrderRejected::leftjoin('orders', 'or_order_num', '=', 'order_num')->whereRaw("or_ser_id='".$v['id']."' and or_creact_time BETWEEN '".$time_start."' and '".$time_end."' and order_status<50 and or_show=1 and or_type = 2 and company_id = '".$session['company_id']."'")->count();//拒单数量
                $order_fivenum = OrderList::leftjoin('orders', 'orders.order_num', '=', 'order_list.order_num')->whereRaw("gone_order_list.ser_id='".$v['id']."' and ((gone_order_list.get_time = '' and (UNIX_TIMESTAMP('".date("Y-m-d H:i:s")."')-UNIX_TIMESTAMP(gone_order_list.create_time)>600)) or (UNIX_TIMESTAMP(gone_order_list.get_time)-UNIX_TIMESTAMP(gone_order_list.create_time))>600) and gone_order_list.create_time BETWEEN '".$time_start."' and '".$time_end."' and gone_order_list.is_delete = 1 and gone_order_list.company_id = '".$session['company_id']."' and time(gone_order_list.create_time)>='08:30:00' and time(gone_order_list.create_time)<='18:00:00'".$where)->count();//超十分钟未接单数量
                $order_listAllnum = OrderList::leftjoin('orders', 'orders.order_num', '=', 'order_list.order_num')->whereRaw("gone_order_list.ser_id='".$v['id']."' and gone_order_list.create_time BETWEEN '2024-08-19' and '".$time_end."' and gone_order_list.is_delete=1 and gone_order_list.get_time != '' and gone_order_list.company_id = '".$session['company_id']."'".$where)->count();//总接单数量
//                $order_listAllnums = OrderList::whereRaw("ser_id='".$v['id']."' and create_time BETWEEN '2024-08-19' and '".$time_end."' and is_delete=1 and company_id = '".$session['company_id']."'")->count();//工单数量
                $order_rejectedAllnum = OrderRejected::leftjoin('orders', 'or_order_num', '=', 'order_num')->whereRaw("or_ser_id='".$v['id']."' and or_creact_time BETWEEN '2024-08-19' and '".$time_end."' and or_show=1 and or_type = 1 and company_id = '".$session['company_id']."'".$where)->count();//总拒单数量
//                $order_fiveAllnum = OrderRejected::leftjoin('orders', 'or_order_num', '=', 'order_num')->whereRaw("or_ser_id='".$v['id']."' and or_creact_time BETWEEN '2024-08-19' and '".$time_end."' and order_status<50 and or_show=1 and or_type = 2 and company_id = '".$session['company_id']."'")->count();//总拒单数量
                $order_fiveAllnum = OrderList::leftjoin('orders', 'orders.order_num', '=', 'order_list.order_num')->whereRaw("gone_order_list.ser_id='".$v['id']."' and ((gone_order_list.get_time = '' and (UNIX_TIMESTAMP('".date("Y-m-d H:i:s")."')-UNIX_TIMESTAMP(gone_order_list.create_time)>600)) or (UNIX_TIMESTAMP(gone_order_list.get_time)-UNIX_TIMESTAMP(gone_order_list.create_time))>600) and gone_order_list.create_time BETWEEN '2024-08-19' and '".$time_end."' and gone_order_list.is_delete = 1 and gone_order_list.company_id = '".$session['company_id']."' and time(gone_order_list.create_time)>='08:30:00' and time(gone_order_list.create_time)<='18:00:00'".$where)->count();//超十分钟未接单数量
                $sql = "SELECT CAST((SUM(UNIX_TIMESTAMP(gone_order_list.feeds_time))-SUM(UNIX_TIMESTAMP(gone_order_list.get_time)))/COUNT(gone_order_list.id) as SIGNED) as timenum FROM gone_order_list LEFT JOIN `gone_orders` ON gone_order_list.`order_num` = gone_orders.`order_num` WHERE gone_order_list.ser_id='".$v['id']."' and gone_order_list.get_time != '' and gone_order_list.get_time!='0000-00-00 00:00:00' and gone_order_list.feeds_time != '' and gone_order_list.feeds_time!='0000-00-00 00:00:00' and gone_order_list.create_time BETWEEN '".$time_start."' and '".$time_end."' and gone_order_list.is_delete=1 and gone_order_list.company_id = '".$session['company_id']."'".$where;
                $data = DB::select($sql);
                $sql1 = "SELECT CAST((SUM(UNIX_TIMESTAMP(gone_order_list.get_time))-SUM(UNIX_TIMESTAMP(gone_order_list.create_time)))/COUNT(gone_order_list.id) as SIGNED) as pdnum FROM gone_order_list LEFT JOIN `gone_orders` ON gone_order_list.`order_num` = gone_orders.`order_num` WHERE gone_order_list.ser_id='".$v['id']."' and gone_order_list.get_time != '' and gone_order_list.get_time!='0000-00-00 00:00:00' and gone_order_list.create_time BETWEEN '".$time_start."' and '".$time_end."' and time(gone_order_list.create_time)>='08:30:00' and time(gone_order_list.create_time)<='18:00:00' and gone_order_list.is_delete=1 and gone_order_list.company_id = '".$session['company_id']."'".$where;
                $data1 = DB::select($sql1);
                $sqls = "SELECT CAST((SUM(UNIX_TIMESTAMP(gone_order_list.feeds_time))-SUM(UNIX_TIMESTAMP(gone_order_list.get_time)))/COUNT(gone_order_list.id) as SIGNED) as timenum FROM gone_order_list LEFT JOIN `gone_orders` ON gone_order_list.`order_num` = gone_orders.`order_num` WHERE gone_order_list.ser_id='".$v['id']."' and gone_order_list.create_time BETWEEN '2024-08-19' and '".$time_end."' and gone_order_list.get_time != '' and gone_order_list.get_time!='0000-00-00 00:00:00' and gone_order_list.feeds_time != '' and gone_order_list.feeds_time!='0000-00-00 00:00:00' and gone_order_list.is_delete=1 and gone_order_list.company_id = '".$session['company_id']."'".$where;// and is_delete=1
                $datas = DB::select($sqls);
                $sqls1 = "SELECT CAST((SUM(UNIX_TIMESTAMP(gone_order_list.get_time))-SUM(UNIX_TIMESTAMP(gone_order_list.create_time)))/COUNT(gone_order_list.id) as SIGNED) as pdnum FROM gone_order_list LEFT JOIN `gone_orders` ON gone_order_list.`order_num` = gone_orders.`order_num` WHERE gone_order_list.ser_id='".$v['id']."' and gone_order_list.create_time BETWEEN '2024-08-19' and '".$time_end."' and gone_order_list.get_time != '' and gone_order_list.get_time!='0000-00-00 00:00:00' and time(gone_order_list.create_time)>='08:30:00' and time(gone_order_list.create_time)<='18:00:00' and gone_order_list.is_delete=1 and gone_order_list.company_id = '".$session['company_id']."'".$where;// and is_delete=1
                $datas1 = DB::select($sqls1);
                $return[$k]['id'] = $v['id'];//门店id
                $return[$k]['company_name'] = $v['company_name'];//门店名称
                $return[$k]['all_num'] = $order_listnum+$order_rejectednum;//总数量
                $return[$k]['order_listnum'] = $order_listnum;//接单数量
                $return[$k]['order_rejectednum'] = $order_rejectednum;//拒单数量
                $return[$k]['order_fivenum'] = $order_fivenum;//超十五分钟未接单数量
                if(($order_listnum+$order_rejectednum) == 0){
                    $gl = "0.00%";
                    $glf = "0.00%";
                }else {
                    $gl = sprintf("%.2f", $order_rejectednum / ($order_listnum + $order_rejectednum) * 100);
                    $gl = $gl."%";
                    if($return[$k]['order_fivenum']>$return[$k]['all_num']){
                        $glf = "100.00%";
                    }else{
                        $glf = sprintf("%.2f", $return[$k]['order_fivenum'] / ($return[$k]['all_num']) * 100);
                        $glf = $glf."%";
                    }
                }
                $return[$k]['rejectRate'] = $gl;//拒单率
                $return[$k]['fiveRate'] = $glf;//超十五分钟未结单率
                if($data){
                    $pdAgeing = self::Compute_Time($data1[0]['pdnum']);
                    $sgAgeing = self::Compute_Time($data[0]['timenum']);
                }else{
                    $pdAgeing = "0时0分0秒";
                    $sgAgeing = "0时0分0秒";
                }
                $return[$k]['pdAgeing'] = $pdAgeing;//接单时效
                $return[$k]['sgAgeing'] = $sgAgeing;//施工时效
                $return[$k]['all_nums'] = $order_listAllnum+$order_rejectedAllnum;//总数量
                $return[$k]['order_listnums'] = $order_listAllnum;//接单数量
                $return[$k]['order_rejectednums'] = $order_rejectedAllnum;//拒单数量
                $return[$k]['order_fivenallum'] = $order_fiveAllnum;//拒超十五分钟未接单数量
                if(($order_listAllnum+$order_rejectedAllnum) == 0){
                    $gls = "0.00%";
                    $glfs = "0.00%";
                }else {
                    $gls = sprintf("%.2f", $order_rejectedAllnum / ($order_listAllnum + $order_rejectedAllnum) * 100);
                    $gls = $gls."%";
                    if($return[$k]['order_fivenallum']>$return[$k]['all_nums']){
                        $glfs = "100.00%";
                    }else{
                        $glf = sprintf("%.2f", $return[$k]['order_fivenallum'] / ($return[$k]['all_nums']) * 100);
                        $glfs = $glf."%";
                    }
                }
                $return[$k]['rejectRates'] = $gls;//拒单率
                $return[$k]['fiveRates'] = $glfs;//超十五分钟未结单率
                if($data){
                    $pdAgeings = self::Compute_Time($datas1[0]['pdnum']);
                    $sgAgeings = self::Compute_Time($datas[0]['timenum']);
                }else{
                    $pdAgeings = "0时0分0秒";
                    $sgAgeings = "0时0分0秒";
                }
                $return[$k]['pdAgeings'] = $pdAgeings;//接单时效
                $return[$k]['sgAgeings'] = $sgAgeings;//施工时效
            }
        }
        if(isset($input['is_excel']) && $input['is_excel']==2 ){
            $time1 = date("Y.m.d", strtotime($input['time_start']));
            if($input['search_type'] == 'week') {
                $timeshow = '本周';
                $time_end = date("Y-m-d", strtotime($input['time_start'] . " +7 day"));
            }if($input['search_type'] == 'month') {
                $timeshow = '本月';
                $time_end = date("Y-m-d", strtotime($input['time_start'] . " +1 month"));
            }
            $time2 = date("Y.m.d", strtotime($time_end . " -1 day"));
            $excel['time'] = $timeshow.$time1."-".$time2;
            $excel['data'] = $return;
            $excel['session'] = $session;
            $exporter = New BasicExport();
            $rea = $exporter->creacrExporSerStatistics($excel);
            if($rea){
                return response()->json(['Data' => $rea, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1]);
            }else{
                return response()->json(['Data' => $rea, 'ErrorMessage' => '无数据', 'ErrorCode' => ErrorInc::DATA_EMPTY]);
            }
        }else {
            return response()->json(['Data' => $return, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1]);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取公司详细数据信息
     * @retrun /multitype:array
     * @author dou 2024/10/17 14:30
     * |---------------------------------------------------------------------------------
    */
    public static function getSerStatisticsDetail ( $session , $input ){
        $admindata = Admin::whereRaw("((company_id='".$session['company_id']."' and admin_groupnew=2) or admin_groupnew=3) and enable=1")
            ->pluck('company_name','id');
        $time_start = $input['time_start'];
        if($input['search_type'] == 'week') {
            $time_end = date("Y-m-d", strtotime($input['time_start'] . " +7 day"));
        }if($input['search_type'] == 'month') {
            $time_end = date("Y-m-d", strtotime($input['time_start'] . " +1 month"));
        }
//        $sql = "SELECT (UNIX_TIMESTAMP(feeds_time)-UNIX_TIMESTAMP(get_time)) AS sgtime,(UNIX_TIMESTAMP(get_time)-UNIX_TIMESTAMP(create_time)) AS jdtime,stauas,order_num,ser_id,create_time,get_time,feeds_time FROM gone_order_list WHERE create_time BETWEEN '".$time_start."' and '".$time_end."' and is_delete=1 and company_id = ".$session['company_id']." order by create_time";
//        $datas = DB::select($sql);
        $page_size = $input['page_size']??10;
        $is_excel = $input['is_excel']??'0';
        if ($is_excel == 2) {
            DB::connection()->enableQueryLog();#开启执行日志
        }
        if(isset($input['goods_brand']) && !empty($input['goods_brand'])){
            $where = " and gone_orders.goods_brand='".$input['goods_brand']."'";
        }
        $paginate = OrderList::leftjoin('orders', 'orders.order_num', '=', 'order_list.order_num')
            ->leftjoin('order_msg', 'order_msg.id', '=', 'order_list.order_goods_id')
            ->whereBetween('order_list.create_time',[$time_start,$time_end])
            ->whereRaw("gone_order_list.company_id='".$session['company_id']."' and gone_order_list.is_delete=1".$where)
            ->selectRaw("(UNIX_TIMESTAMP(gone_order_list.feeds_time)-UNIX_TIMESTAMP(gone_order_list.get_time)) AS sgtime,(UNIX_TIMESTAMP(gone_order_list.get_time)-UNIX_TIMESTAMP(gone_order_list.create_time)) AS jdtime,stauas,gone_order_list.order_num,gone_order_list.ser_id,gone_order_list.create_time,gone_order_list.get_time,gone_order_list.feeds_time,gone_order_msg.goods_name")
            ->orderBy('create_time','ASC')
            ->paginate($page_size);
        if ($is_excel == 2) {
            DB::connection()->enableQueryLog();#开启执行日志
            $sql = DB::getQueryLog()[1];
        }
        $datas = CommonService::dataToArray($paginate->items());
        $statusName = ['10'=>'未接单','20'=>'未接单','30'=>'安装中','34'=>'待审核','40'=>'已完成','50'=>'已撤销','55'=>'已撤销（补邮费）'];
        $return = [];
        foreach($datas as $k => $v){
            $return[$k]['company_name'] = $admindata[$v['ser_id']];//公司名称
            $return[$k]['order_num'] = $v['order_num'];//订单单号
            $return[$k]['goods_name'] = $v['goods_name'];//商品名称
            $return[$k]['stauas'] = $statusName[$v['stauas']];//订单状态
            $return[$k]['create_time'] = $v['create_time'];//派单时间
            $return[$k]['get_time'] = $v['get_time'];//接单时间
            $return[$k]['feeds_time'] = $v['feeds_time'];//反馈时间
            if($v['get_time'] != '' && $v['get_time'] != '0000-00-00 00:00:00'){
                $return[$k]['jdAgeing'] = self::Compute_Time($v['jdtime']);//接单时效
                if($v['jdtime']<300){
                    $return[$k]['fiveStandard'] = '达标';//5分钟接单达标
                }else{
                    $return[$k]['fiveStandard'] = '不达标';//5分钟接单达标
                }
                if($v['jdtime']<600){
                    $return[$k]['tenStandard'] = '达标';//10分钟接单达标
                }else{
                    $return[$k]['tenStandard'] = '不达标';//10分钟接单达标
                }
            }else{
                $return[$k]['jdAgeing'] = '';//接单时效
                $return[$k]['fiveStandard'] = '不达标';//5分钟接单达标
                $return[$k]['tenStandard'] = '不达标';//10分钟接单达标
            }

            if($v['feeds_time'] != '' && $v['feeds_time'] != '0000-00-00 00:00:00'){
                $return[$k]['sgAgeing'] = self::Compute_Time($v['sgtime']);//施工时效
                if($v['sgtime']<43200){
                    $return[$k]['Standard12Hours'] = '达标';//12小时履约达标
                }else{
                    $return[$k]['Standard12Hours'] = '不达标';//12小时履约达标
                }
                if($v['sgtime']<86400){
                    $return[$k]['Standard24Hours'] = '达标';//24小时履约达标
                }else{
                    $return[$k]['Standard24Hours'] = '不达标';//24小时履约达标
                }
            }else{
                $return[$k]['sgAgeing'] = "";//施工时效
                $return[$k]['Standard12Hours'] = '不达标';//12小时履约达标
                $return[$k]['Standard24Hours'] = '不达标';//24小时履约达标
            }
            $time = explode(' ', $v['create_time'])[1];
            if($time>='08:30:00' && $time<='18:00:00'){
                $return[$k]['takeEffect'] = "是";//是否计入时效考核
            }else{
                $return[$k]['takeEffect'] = "否";//是否计入时效考核
            }
        }
        if(isset($input['is_excel']) && $input['is_excel']==2 ){
            $excel = new CommonController();
            return $excel->getExcelOut($input['Pri_id'], $sql, $session,200,['function_name'=>'服务商绩效明细','function_model'=>'SerStatisticsDetail']);
        }else {
            return response()->json(['Data' => $return, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1]);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 转化为时分秒
     * @param string timediff 时间
     * @retrun  /multitype:string
     * @author dou 2024/8/23 11:43
     * |---------------------------------------------------------------------------------
     */
    public static function Compute_Time($timediff ){
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        //$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $res = $days.'天'.$hours.'时'.$mins.'分'.$secs.'秒';
        return $res;
    }
}
