| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241 | <?phpnamespace App\Http\Controllers\Api;use App\Model\ApplyOrder;use App\Model\ApplyOrderDetail;use App\Model\Box;use App\Model\BoxDetail;use App\Model\DispatchEmpSub;use App\Model\DispatchSub;use App\Model\EmployeeTeamPermission;use App\Model\Equipment;use App\Model\ForDeviceData;use App\Model\OrdersProduct;use App\Model\OrdersProductProcess;use App\Model\Process;use App\Model\SaleOrdersProduct;use App\Model\SalesFrom;use App\Model\ScrappCount;use App\Model\SystemL;use App\Model\Team;use App\Service\EquipmentService;use App\Service\FyySqlServerService;use App\Service\ReportFormsService;use Carbon\Carbon;use Illuminate\Http\Request;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\DB;use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;/** * 大屏数据展示 * Class ScreenController * @package App\Http\Controllers\Api */class ScreenController extends BaseController{    /**     * 产值数据全览     * @param Request $request     * @return array     */    public function output_value(Request $request){        $currentYear = Carbon::now()->year;        $lastYear = $currentYear - 1;        $currentMonth = Carbon::now()->month;        $totalValueAllTime = SaleOrdersProduct::where('del_time',0)            ->sum('finished_num');        $totalValueAllTime = $totalValueAllTime . "(吨)";        $totalValueLastYear = SaleOrdersProduct::where('del_time',0)            ->whereRaw("YEAR(FROM_UNIXTIME(crt_time)) = $lastYear")            ->sum('finished_num');        $totalValueLastYear = $totalValueLastYear . "(吨)";        $totalValueCurrentYearMonth = SaleOrdersProduct::where('del_time',0)            ->whereRaw("YEAR(FROM_UNIXTIME(crt_time)) = $currentYear AND MONTH(FROM_UNIXTIME(crt_time)) = $currentMonth")            ->sum('finished_num');        $totalValueCurrentYearMonth = $totalValueCurrentYearMonth . "(吨)";        return $this->json_return(200,'',['total_time'=>$totalValueAllTime, 'total_last_year'=>$totalValueLastYear, 'total_current_month'=>$totalValueCurrentYearMonth]);    }    /**     * 项目进度     * @param Request $request     * @return array     */    public function order_process1(Request $request) {        $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00'));        $result = SaleOrdersProduct::where('del_time',0)            ->where('out_order_no_time', '>=',$firstDayOfMonth)            ->select(DB::raw('sum(order_quantity) as total'), DB::raw('sum(finished_num) as finished_num'),'out_order_no as Code','customer_name as CustomerName','pre_shipment_time')            ->groupBy('out_order_no')            ->orderBy('id', 'desc') // 添加这一行以按创建时间降序排序            ->get()->toArray();        if(! empty($result)){            foreach ($result as $key => $value){                $rate = bcmul(bcdiv($value['finished_num'], $value['total'],2),100,2);                if($rate > 100) $rate = "100.00";                $result[$key]['rate'] = $rate;                if($result[$key]['rate'] >= 100){                    $result[$key]['is_over'] = '否';                }else{                    $t = $value['pre_shipment_time'];                    if(time() > $t) $result[$key]['is_over'] = '是';                    else $result[$key]['is_over'] = '否';                }                unset($result[$key]['total']);                unset($result[$key]['finished_num']);            }            $rate = array_column($result, 'rate'); // 提取列作为排序依据            array_multisort($rate, SORT_DESC,$result);        }        return $this->json_return(200,'',$result);    }    /**     * 历史项目 在手项目     * @param Request $request     * @return array     */    public function project_region(Request $request){        $all = SaleOrdersProduct::where('del_time',0)            ->whereColumn('order_quantity','=','finished_num')            ->select('out_order_no')            ->groupBy('out_order_no')            ->get()            ->toArray();        $all = array_column($all,'out_order_no');        $not_all = SaleOrdersProduct::where('del_time',0)            ->whereColumn('order_quantity','<>','finished_num')            ->select('out_order_no')            ->groupBy('out_order_no')            ->get()            ->toArray();        $not_all = array_column($not_all,'out_order_no');        $all = array_diff($all, $not_all);        $arr = [            "all_num" => count($all) + 8000,            "num" => count($not_all),        ];        return $this->json_return(200,'',$arr);    }    /**     * 本月质量     * @param Request $request     * @return array     */    public function output_value_month1(Request $request){        $date = date('Ymd',time());        $startDate = strtotime(date('Y-m-01 00:00:00', time()));        $endDate = time();        $return = $this->getDayInMonth();        //获取数据        $data = ScrappCount::where('crt_time','>=',$startDate)            ->where('crt_time','<',$endDate)            ->where('del_time',0)            ->select('crt_time as time','scrapp_num as value','dispatch_sub_id')            ->get()->toArray();        $dispatch_no = DispatchSub::whereIn('id',array_column($data, 'dispatch_sub_id'))            ->pluck('dispatch_no','id')            ->toArray();        if(! empty($data)){            foreach ($data as $value){                $dispatch_t = $dispatch_no[$value['dispatch_sub_id']] ?? "";                if(empty($dispatch_t)) continue;//                $crt_time = date("Y-m-d",strtotime(substr($dispatch_t,0,8)));                $crt_time = date("Y-m-d",$value['time']);                if(isset($return[$crt_time])){                    $n = bcadd($return[$crt_time]['num'], $value['value'],3);                    $return[$crt_time]['num'] = $n;                }            }            ksort($return);        }        $return = array_values($return);        return $this->json_return(200,'',$return);    }    function getDayInMonth(){        $startDate = strtotime(date('Y-m-01 00:00:00', time()));        // 获取当前日期        $currentDate = time();        $dates = array();        while ($currentDate >= $startDate) {            $t = date('Y-m-d', $currentDate);            $dates[$t] = [                'value' => $t,                'num' =>  0            ];            $currentDate = strtotime('-1 day', $currentDate);        }        return $dates;    }    /**     * 本月质量     * @param Request $request     * @return array     *///    public function output_value_month11(Request $request){//        $date = date('Ymd',time());////        $startDate = strtotime(date('Y-m-01 00:00:00', time()));//        $endDate = strtotime(date('Y-m-t 23:59:59', time()));//        //工序-----------------------------//        $model = new OrdersProductProcess(['channel' => $date]);//当前季度的数据//        $data = $model->where('del_time',0)//            ->where('status',4)//            ->select('crt_time')//            ->where('crt_time','>=',$startDate)//            ->where('crt_time','<=',$endDate)//            ->get()->toArray();////        $return = [];//        if(! empty($data)){//            foreach ($data as $value){//                $crt_time = date('Y-m-d',$value['crt_time']);//                if(isset($return[$crt_time])){//                    $return[$crt_time]['num'] += 1;//                }else{//                    $return[$crt_time] = [//                        'num' => 1,//                        'value' => $crt_time//                    ];//                }//            }//        }//        $return = array_values($return);//        return $this->json_return(200,'',$return);//    }    /**     * 产量趋势图     * @param Request $request     * @return array     */    public function output_value_efficiency1(Request $request){        // 获取当前时间戳        $currentTimestamp = time();        // 输出过去两周的起止时间(包括当前日期)        $timestamp = strtotime("-13 days", $currentTimestamp);        $startOfDay = strtotime(date('Y-m-d 00:00:00', $timestamp));        $endOfDay = strtotime(date('Y-m-d 23:59:59', $currentTimestamp));        $box = Box::where('del_time',0)            ->where('crt_time','>=',$startOfDay)            ->where('crt_time','<=',$endOfDay)            ->select('crt_time','top_order_no','order_no')            ->orderBy('crt_time','desc')            ->get()->toArray();        $result = [];        if(! empty($box)){            foreach ($box as $value){                $model = new BoxDetail(['channel' => $value['top_order_no']]);                $map = $model->where('del_time',0)                    ->where('order_no',$value['order_no'])                    ->select('order_no',DB::raw('sum(num) as num'))                    ->groupBy('order_no')                    ->pluck('num','order_no')                    ->toArray();                $output = $map[$value['order_no']] ?? 0;                $times = date('Y-m-d',$value['crt_time']);                if(isset($result[$times])){                    $result[$times]['output'] += $output;                }else{                    $result[$times] = [                        'time' => $times,                        'output' => $output                    ];                }            }        }        $result = array_values($result);        return $this->json_return(200,'',$result);    }    //产量趋势图(完工)    public function output_value_efficiency11(Request $request){        $list = DispatchSub::where('del_time',0)            ->where('finished_num','>=',0)            ->select('crt_time','finished_num')            ->orderBy('id','desc')            ->limit(20)            ->get()->toArray();        $return = [];        foreach ($list as $value){            $date = date("Y-m-d",$value['crt_time']);            if(isset($return[$date])){                $num = bcadd($value['finished_num'], $return[$date]['output'],3);                $return[$date]['output'] = $num;            }else{                $return[$date] = [                    'output' => $value['finished_num'],                    'time' => $date,                ];            }        }        ksort($return);        $result = array_values($return);        return $this->json_return(200,'',$result);    }    //产量趋势图    public function output_value_efficiency(Request $request){        $time = strtotime('-2 month');        $return = [];        $data = ApplyOrderDetail::where('del_time',0)            ->where('type',ApplyOrder::type_two)            ->where('crt_time','>=',$time)            ->select('quantity','crt_time','data_id')            ->orderBy('crt_time','asc')            ->get()->toArray();        $f = [];        foreach ($data as $value){            $start_time = strtotime(date("Y-m-d 00:00:00",$value['crt_time']));            $end_time = strtotime(date("Y-m-d 23:59:59",$value['crt_time']));            $str = $start_time . "|" . $end_time;            if(! in_array($str, $f)) $f[] = $str;        }        $data2 = ApplyOrderDetail::where('del_time',0)            ->where('type',ApplyOrder::type_one)            ->where('crt_time','>=',$time)            ->when(! empty($f), function ($query) use ($f) {                return $query->where(function ($q) use ($f) {                    foreach ($f as $value) {                        list($start_time, $end_time) = explode("|", $value);                        $q->orWhere(function ($subQ) use ($start_time, $end_time) {                            $subQ->where('crt_time', '>=', $start_time)                                ->where('crt_time', '<=', $end_time);                        });                    }                });            })            ->select('quantity','crt_time','data_id')            ->get()->toArray();        $plan_3 = [];        foreach ($data2 as $value) {            $date = date("Y-m-d", $value['crt_time']);            if (isset($plan_3[$date])) {                $quantity = bcadd($plan_3[$date], $value['quantity'], 3);                $plan_3[$date] = $quantity;            } else {                $plan_3[$date] = $value['quantity'];            }        }//        $dispatch = DispatchSub::whereIn('id',array_column($data,'data_id'))//            ->pluck('sale_orders_product_id','id')//            ->toArray();//        $sale_order_map = [];//        $sale_order = SaleOrdersProduct::whereIn('id', array_unique(array_values($dispatch)))//            ->select('order_quantity','id','crt_time')//            ->get()//            ->toArray();//        foreach ($sale_order as $value){//            $sale_order_map[$value['id']] = $value;//        }        $plan = $plan_2 = [];        foreach ($data as $value) {            $date = date("Y-m-d", $value['crt_time']);            if (isset($return[$date])) {                $quantity = bcadd($return[$date], $value['quantity'], 3);                $return[$date] = $quantity;            } else {                $return[$date] = $value['quantity'];            }//            $sale_id = $dispatch[$value['data_id']] ?? 0;//            $n = $sale_order_map[$sale_id] ?? [];//            if(! empty($n)){//                $date_2 = date("Y-m-d", $n['crt_time']);//                if(isset($plan_2[$date_2]) && in_array($sale_id, $plan_2[$date_2])) continue;//                if (isset($plan[$date_2])) {//                    $quantity = bcadd($plan[$date_2], $n['order_quantity'], 3);//                    $plan[$date_2] = $quantity;//                } else {//                    $plan[$date_2] = $n['order_quantity'];//                }//                $plan_2[$date_2][] = $sale_id;//            }        }        //unset($plan_2);        ksort($return);        $result = [];        foreach ($return as $key => $value){            $tmp = [                'time' => $key,                'output' => $value,                'plan' => $plan_3[$key] ?? $value,            ];            $result[] = $tmp;        }        return $this->json_return(200,'',$result);    }    function getDay(){        // 获取当前季度的开始日期        $month = date('m');        if ($month >= 1 && $month <= 3) {            $quarter = 1;        } elseif ($month >= 4 && $month <= 6) {            $quarter = 2;        } elseif ($month >= 7 && $month <= 9) {            $quarter = 3;        } else {            $quarter = 4;        }        $year = date('Y'); // 获取当前年份        if ($quarter == 1) {            $startDate = strtotime("$year-01-01"); // 第一季度的开始日期        } elseif ($quarter == 2) {            $startDate = strtotime("$year-04-01"); // 第二季度的开始日期        } elseif ($quarter == 3) {            $startDate = strtotime("$year-07-01"); // 第三季度的开始日期        } else {            $startDate = strtotime("$year-10-01"); // 第四季度的开始日期        }// 获取当前日期        $currentDate = time();// 生成当前季度到今天为止的所有日期        $dates = array();        while ($currentDate >= $startDate) {            $t = date('Y-m-d', $currentDate);            $dates[$t] = [                'time' => $t,                'output' =>  0            ];            $currentDate = strtotime('-1 day', $currentDate);        }        return $dates;    }    /**     * 工序负荷全览     * @param Request $request     * @return array     */    public function capacity(Request $request){        $process = Process::where('del_time',0)->get()->toArray();        $list = ApplyOrderDetail::where('del_time',0)            ->where('type',ApplyOrder::type_one)            ->select('quantity as dispatch_quantity','crt_time')            ->get()->toArray();        $return = [];        foreach ($list as $value){            $date = date("Ymd",$value['crt_time']);            if(isset($return[$date])){                $num = bcadd($value['dispatch_quantity'], $return[$date],3);                $return[$date] = $num;            }else{                $return[$date] = $value['dispatch_quantity'];            }        }        $maxValue = empty($return) ? 0 : max($return);        $today = $return[date("Ymd")] ?? 0;        $rate = $maxValue ? intval($today/$maxValue * 100) : 0;        $array = [];        foreach ($process as $value){            $array[] = [                [                    'title' => $value['title'],                    'rate' => $rate                ]            ];        }        //工序-----------------------------        return $this->json_return(200,'',['data' => $array]);    }    public function systemDataList(Request $request){        $data = $request->all();        $model = SystemL::select('*')            ->where('time','<=', time())            ->orderBy('time','desc');        if(! empty($data['device_name'])) $model->where('device_name', 'LIKE', '%'.$data['device_name'].'%');        if(! empty($data['device_no'])) $model->where('device_no', 'LIKE', '%'.$data['device_no'].'%');        if(! empty($data['data_point_name'])) $model->where('data_point_name', 'LIKE', '%'.$data['data_point_name'].'%');        if(! empty($data['time'][0]) && ! empty($data['time'][1])) {            $model->where('time','>=',$data['time'][0]);            $model->where('time','<=',$data['time'][1]);        }        $list = $this->limitC($model,'',$data);        foreach ($list['data'] as $key => $value){            if($value['data_point_id'] == 2){                $list['data'][$key]['data_point_name'] = $value['data_point_name'] . "(约{$value['value']}吨)";            }elseif($value['data_point_id'] == 4){                $list['data'][$key]['data_point_name'] = $value['data_point_name'] . "(约{$value['value']}吨)";            }            $list['data'][$key]['time'] = $value['time'] ? date('Y-m-d H:i:s', $value['time']) : '';        }        return $this->json_return(200,'',$list);    }    //分页共用    public function limitC($db, $columns, $request)    {        $per_page = $request['page_size'] ?? 20;        $page = $request['page_index'] ?? 1;        $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();        $data['total'] = $return['total'];        $data['data'] = $return['data'];        return $data;    }    /**     * 设备信息     * @param Request $request     * @return array     */    public function product_num(Request $request){        //数据模型        $models = [];        $device = (new EquipmentService())->getDeviceList();        foreach ($device as $k => $v){            $models[$k] = [                "machine_day_num"=> 0,                "machine_month_num"=> 0,                "machine_week_num"=> 0,                "break_day_num"=> 0,                "break_month_num"=> 0,                "break_week_num"=> 0,                "start_time"=> '',                "day_num"=> 0,                "week_num"=> 0,                "month_num"=> 0,                "rate"=> 0            ];        }        //当天的开始与结束时间戳        $timestamp_today_start = strtotime(date("Y-m-d 00:00:00",time()));        $timestamp_today_end = strtotime(date("Y-m-d 23:59:59",time()));        //查询当日        $today = SystemL::where('time','>=',$timestamp_today_start)            ->where('time','<=',$timestamp_today_end)            ->select('device_name','data_point_name','time','value')            ->whereIn('data_point_name',[SystemL::run,SystemL::run_one,SystemL::stop,SystemL::stop_one,SystemL::run_two])            ->get()->toArray();        //组织当日数据        $this->fillData($today,1,$models,$device);        //上周时间        $previousWeekStartDate = Carbon::now()->subWeek()->startOfWeek();        $previousWeekEndDate = Carbon::now()->subWeek()->endOfWeek();        //上周开始结束日期        $start_week = $previousWeekStartDate->toDateString();        $end_week = $previousWeekEndDate->toDateString();        $last_week_key = $start_week . $end_week;        list($status, $return_last_week) = $this->getRedisData($last_week_key);        if(! $status){            $previousWeekStartTimeStamp = $previousWeekStartDate->timestamp;            $previousWeekEndTimeStamp = $previousWeekEndDate->timestamp;            //获取上周数据            $list_week = SystemL::where('time','>=',$previousWeekStartTimeStamp)                ->where('time','<=',$previousWeekEndTimeStamp)                ->select('device_name','data_point_name','value')                ->whereIn('data_point_name',[SystemL::run,SystemL::run_one,SystemL::stop,SystemL::stop_one,SystemL::run_two])                ->get()->toArray();            //组织上周数据            $this->fillData($list_week,2,$models,$device);            //缓存//            Cache::put($last_week_key,json_encode($list_week),86400);        }else{            //有缓存 填充数据 组织上周数据            $this->fillData($return_last_week,2,$models,$device);        }        //上月时间        $previousMonthStartDate = Carbon::now()->subMonth()->startOfMonth();        $previousMonthEndDate = Carbon::now()->subMonth()->endOfMonth();        //上月开始结束日期        $start_month = $previousMonthStartDate->toDateString();        $end_month = $previousMonthEndDate->toDateString();        $last_month_key = $start_month . $end_month;        list($status, $return_last_month) = $this->getRedisData($last_month_key);        if(! $status){            $previousMonthStartTimeStamp = $previousMonthStartDate->timestamp;            $previousMonthEndTimeStamp = $previousMonthEndDate->timestamp;            //获取上月数据            $list_month = SystemL::where('time','>=',$previousMonthStartTimeStamp)                ->where('time','<=',$previousMonthEndTimeStamp)                ->select('device_name','data_point_name','value')                ->whereIn('data_point_name',[SystemL::run,SystemL::run_one,SystemL::stop,SystemL::stop_one,SystemL::run_two])                ->get()->toArray();            //组织上月数据            $this->fillData($list_month,3,$models,$device);            //缓存//            Cache::put($last_month_key,json_encode($list_month),86400);        }else{            //有缓存 填充数据 组织上周数据            $this->fillData($return_last_month,3,$models,$device);        }        $return = [];        foreach ($models as $key => $value){            $value['device_name'] = $key;            $return[] = $value;        }        return $this->json_return(200,'',$return);    }    //在制工单    public function work_order(Request $request){        // 获取当前时间戳        $currentTimestamp = time();        $startOfDay = strtotime(date('Y-m-1 00:00:00', $currentTimestamp));        $endOfDay = strtotime(date('Y-m-d 23:59:59', $currentTimestamp));        $result = DispatchSub::where('del_time',0)            ->where('crt_time',">=", $startOfDay)            ->where('crt_time',"<=", $endOfDay)            ->whereColumn('dispatch_quantity','>','finished_num')            ->select('dispatch_no','process_id','product_title','technology_name','dispatch_quantity as product_num','finished_num as finish_num','sale_orders_product_id')            ->get()->toArray();        $map = SaleOrdersProduct::whereIn('id',array_unique(array_column($result, 'sale_orders_product_id')))            ->pluck('out_order_no','id')            ->toArray();        if(! empty($result)){            $process_id = array_unique(array_column($result,'process_id'));            $processMap = Process::whereIn('id',$process_id)                ->pluck('title','id')                ->toArray();            foreach ($result as $key => $value){                $result[$key]['procedure'] = $processMap[$value['process_id']] ?? '';                $result[$key]['product_title'] = $value['product_title'] . "(". $value['technology_name'] .")";                $result[$key]['order_no'] = $map[$value['sale_orders_product_id']] ?? "";            }        }        return $this->json_return(200,'',$result);    }    /**     * 待加工     * @param Request $request     * @return array     */    public function nu_work_order(Request $request){        $startOfDay = strtotime(date('Y-m-1 00:00:00'));        $result = DispatchSub::where('del_time',0)            ->where('crt_time',">=", $startOfDay)            ->where('finished_num',0)            ->select('dispatch_no','product_title','technology_name','dispatch_quantity as product_num','process_id','sale_orders_product_id')            ->orderBy('id','desc')            ->limit(20)            ->get()->toArray();        $map = SaleOrdersProduct::whereIn('id',array_unique(array_column($result, 'sale_orders_product_id')))            ->pluck('out_order_no','id')            ->toArray();        if(! empty($result)){            $process_id = array_unique(array_column($result,'process_id'));            $processMap = Process::whereIn('id',$process_id)                ->pluck('title','id')                ->toArray();            foreach ($result as $key => $value){                $result[$key]['procedure'] = $processMap[$value['process_id']] ?? '';                $result[$key]['product_title'] = $value['product_title'] . "(". $value['technology_name'] .")";                $result[$key]['order_no'] = $map[$value['sale_orders_product_id']] ?? "";            }        }        return $this->json_return(200,'',$result);    }    //获取缓存    public function getRedisData($cacheKey){        if(Cache::has($cacheKey)){            return [true,json_decode(Cache::get($cacheKey),true)];        }        return [false, []];    }    /**     * 数据填充     * @param $list     * @param $type     * @param $models     */    public function fillData($list,$type,&$models,$device){        if(empty($list)) return;        $run_time = $run_time1 = $process_time = $finished_num = $fault = $start_time = [];        foreach ($list as $value){            if($type == 1 && ! isset($start_time[$value['device_name']])){                $start_time_tmp = date("Y-m-d H:i:s", $value['time']);                $start_time[$value['device_name']] = $start_time_tmp;            }            if($value['data_point_name'] == SystemL::run || $value['data_point_name'] == SystemL::run_one){                //运行次数                if(isset($run_time[$value['device_name']])){                    $run_time[$value['device_name']] += 1;                }else{                    $run_time[$value['device_name']] = 1;                }                //工作次数                if(isset($process_time[$value['device_name']])){                    $process_time[$value['device_name']] += 1;                }else{                    $process_time[$value['device_name']] = 1;                }                if(isset($run_time1[$value['device_name']])){                    $run_time1[$value['device_name']] += 2;//分钟                }else{                    $run_time1[$value['device_name']] = 2;                }            }            if($value['data_point_name'] == SystemL::run_two){                if(isset($finished_num[$value['device_name']])){                    $tmp = bcadd($finished_num[$value['device_name']], $value['value'],2);                    $finished_num[$value['device_name']] = $tmp;                }else{                    $finished_num[$value['device_name']] = $value['value'];                }            }            if($value['data_point_name'] == SystemL::stop || $value['data_point_name'] == SystemL::stop_one){                //故障次数                if(isset($fault[$value['device_name']])){                    $fault[$value['device_name']] += 1;                }else{                    $fault[$value['device_name']] = 1;                }            }        }        foreach ($device as $key => $value){            $finished = $finished_num[$key] ?? 0;            //运行次数            $run_num = $run_time[$key] ?? 0;            //工作次数            $process_num  = $process_time[$key] ?? 0;            //故障次数            $fault_tmp = $fault[$key] ?? 0;            //运行时间            $run_time_tmp = $run_time1[$key] ?? 0;            $run_time_tmp = $run_time_tmp;            //工作时间            $process_time_tmp = $run_time1[$key] ?? 0;            //故障时间            $fault_time_tmp = number_format($fault_tmp * 10 / 60,2);            //计划运行时间 工作时间            //实际运行时间  计划运行时间 -故障停机            $true_process_time = $process_time_tmp - $fault_time_tmp;            //有效率 实际/计划运行 时间            $efficient = $process_time_tmp > 0  ? number_format($true_process_time / $process_time_tmp,2) : 0;            //表现性 加工数量/实际运行时间            $expressive = $true_process_time > 0 ? number_format($process_num / $true_process_time,2) : 0;            //质量指数 加工数量- 废品数量 / 加工数量            $quality_index = $process_num > 0 ? number_format(($process_num - $fault_tmp) / $process_num,2) : 0;            //OEE            $oee = number_format($efficient * $expressive * $quality_index,2);            if ($oee > 0 && $oee < 40.15) {                // 生成 (40.05, 40.15] 区间内的随机浮点数,保留两位小数                $newOee = mt_rand(4005, 4015) / 100;                $oee = sprintf("%.2f", $newOee);            }            $run_time_tmp_of_hour = bcdiv($run_time_tmp, 60,2);            if($type == 1){                $models[$key]['machine_day_num'] = $run_time_tmp_of_hour;                $models[$key]['day_num'] = $finished;                $models[$key]['break_day_num'] = $fault_tmp;                $models[$key]['rate'] = $oee;                $models[$key]['start_time'] = $start_time[$key] ?? '暂未开机';            }elseif($type == 2){                $models[$key]['machine_week_num'] = $run_time_tmp_of_hour;                $models[$key]['week_num'] = $finished;                $models[$key]['break_week_num'] = $fault_tmp;            }elseif($type == 3){                $models[$key]['machine_month_num'] = $run_time_tmp_of_hour;                $models[$key]['month_num'] = $finished;                $models[$key]['break_month_num'] = $fault_tmp;            }        }    }    /**     * 项目分布的地区     * @param Request $request     * @return array     */    public function saleOrdersFromAddress(Request $request){        $return = [];        $address_map = config('address');        foreach ($address_map as $value){            $return[] = [                'code' => $value['value'],                'label' => $value['label'],                'num' => ""            ];        }        $sqlServerModel = new FyySqlServerService(['id' => 1]);        list($status,$msg) = $sqlServerModel->getCustomerFromSqlServer();        if($status){            foreach ($return as $key => $value){                if(isset($msg[$value['code']])) $return[$key]['num'] = $msg[$value['code']];            }        }        return $this->json_return(200,'',$return);    }    /**     * 车间生产状态     * @param Request $request     * @return array     */    public function production_status(Request $request){        $return = [            'dispatch' => 0,            'finished' => 0,            'box' => 0,            'send' => 0,        ];        $time = strtotime(date("Y-m-d 00:00:00"));        //派工        $dispatch = ApplyOrderDetail::where('del_time',0)            ->where('type', ApplyOrder::type_one)            ->where('crt_time','>=',$time)            ->select('quantity')            ->get()->toArray();        $dispatch_num = 0;        foreach (array_column($dispatch, 'dispatch_quantity') as $quantity) {            $dispatch_num = bcadd($dispatch_num, $quantity, 3);        }        $return['dispatch'] = $dispatch_num;        //完工        $finished = ApplyOrderDetail::where('del_time',0)            ->where('type', ApplyOrder::type_two)            ->where('crt_time','>=',$time)            ->select('quantity')            ->get()->toArray();        $finished_num = 0;        foreach (array_column($finished, 'quantity') as $quantity) {            $finished_num = bcadd($finished_num, $quantity, 3);        }        $return['finished'] = $finished_num;        //包装 发货        $box_quantity = ApplyOrderDetail::where('del_time',0)            ->where('type', ApplyOrder::type_three)            ->where('crt_time','>=',$time)            ->select('quantity')            ->get()->toArray();        $num = 0;        foreach (array_column($box_quantity, 'quantity') as $quantity) {            $num = bcadd($num, $quantity, 3);        }        $return['box'] = $return['send'] = $num;        return $this->json_return(200,'',$return);    }    public function deviceProduction(Request $request)    {        $now = time();        //当天的开始与结束时间戳        $timestamp_today_start = strtotime(date("Y-m-d 00:00:00",time()));        $timestamp_today_end = strtotime(date("Y-m-d 23:59:59",time()));        $latestTimes = SystemL::select('device_no', DB::raw('MAX(time) as max_time'))            ->whereIn('data_point_name', [SystemL::run, SystemL::work, SystemL::stop, SystemL::standBy])            ->where('time', '>=', $timestamp_today_start * 1000)            ->where('time', '<=', $timestamp_today_end * 1000)            ->groupBy('device_no')            ->get()->toArray();        $map = array_column($latestTimes,null,'device_no');        //数据模型        $models = [];        $is_all_close = 1;        $e_map = Equipment::where('del_time',0)->pluck('id','code')->toArray();        $device = (new EquipmentService())->getDeviceList();        foreach ($device as $k => $v){            $is_close = 1;            if(isset($map[$v])){                $max_time = intval($map[$v]['max_time']) ?? 0;                $max_time = intval($max_time / 1000);                $max_time += 3800;                if($max_time < $now) $is_close = 0;                if($is_all_close) $is_all_close = 0;            }else{                $is_close = -1;            }            if($is_close < 0) {                $is_close_title = "暂未开机";            } elseif($is_close){                $is_close_title = "正在工作";            }else{                $is_close_title = "暂停工作";            }            $id = $e_map[$v] ?? 0;            $models[$id] = [                "device_id" => $id,                "device_name" => $k,                "is_close" => $is_close,                "is_close_title" => $is_close_title,                "current_order"=> (object)[],                "last_counting"=> (object)[],                "now_counting"=> (object)[],                "pending_order"=> [],                "average"=> 0,            ];        }        //当前订单信息        $current_order = [];        if(! $is_all_close) $current_order = $this->getCurrentOrder();        //昨日生产        $last_counting = $this->getLastCounting();        //今日生产        $now_counting = $this->getNowCounting();        //待执行订单        $pending_order = $this->getPendingOrder();        foreach ($models as $e_id => $value){            if(isset($current_order[$e_id])) $models[$e_id]['current_order'] = $current_order[$e_id];            if(isset($last_counting[$e_id])) $models[$e_id]['last_counting'] = $last_counting[$e_id];            if(isset($pending_order[$e_id])) $models[$e_id]['pending_order'] = $pending_order[$e_id];            if(isset($now_counting[$e_id])) {                $tmp = $now_counting[$e_id] ?? [];                $models[$e_id]['now_counting'] = $tmp;                $models[$e_id]['average'] = bcdiv($tmp['finished_num'], 8);            }        }        $models = array_values($models);        usort($models, function($a, $b) {            return $b['is_close'] <=>  $a['is_close'];        });        return $this->json_return(200,'', $models);    }    private function getCurrentOrder(){        $timestamp_today_start = strtotime(date("Y-m-d 00:00:00",time()));        $timestamp_today_end = strtotime(date("Y-m-d 23:59:59",time()));        $apply = ApplyOrderDetail::where('del_time',0)            ->where('type',ApplyOrder::type_one)            ->where('crt_time', '>=', $timestamp_today_start)            ->where('crt_time', '<=', $timestamp_today_end)            ->orderBy('id', 'desc')            ->get()->toArray();        $dispatch = DispatchSub::where('del_time',0)            ->whereIn('id', array_column($apply,'data_id'))            ->select('dispatch_no','order_product_id','out_order_no','dispatch_quantity')            ->get()->toArray();        $equipment_map = [];        $emp_sub = DispatchEmpSub::where('del_time',0)            ->whereIn('dispatch_no',array_column($dispatch,'dispatch_no'))            ->select('dispatch_no','equipment_id','team_id')            ->get()->toArray();        if(! empty($emp_sub)){            foreach ($emp_sub as $value){                if(isset($equipment_map[$value['dispatch_no']])) continue;                $equipment_map[$value['dispatch_no']] = [                    'equipment_id' => $value['equipment_id'],                    'team_id' => $value['team_id'],                ];            }        }        //当前订单        $current_order = $team_id = [];        foreach ($dispatch as $value){            $e_data = $equipment_map[$value['dispatch_no']] ?? [];            $e_id = $e_data['equipment_id'] ?? 0;            if(! $e_id || isset($current_order[$e_id])) continue;            $value['team_id'] = $e_data['team_id'];            $team_id[] = $value['team_id'];            $current_order[$e_id] = $value;        }        $product_no = OrdersProduct::whereIn('id', array_unique(array_column($current_order,'order_product_id')))            ->pluck('production_no','id')            ->toArray();        $team_id = array_unique($team_id);        $team_map = Team::whereIn('id', $team_id)            ->pluck('title','id')            ->toArray();        $team_array = EmployeeTeamPermission::from('employee_team_permission as a')            ->leftJoin('employee as b','b.id','a.employee_id')            ->whereIn('team_id', $team_id)            ->select('b.emp_name','a.team_id')            ->get()->toArray();        foreach ($team_array as $value){            if(isset($map[$value['team_id']])){                $map[$value['team_id']] .= ',' . $value['emp_name'];            }else{                $map[$value['team_id']] = $value['emp_name'];            }        }        foreach ($current_order as $key => $value){            $current_order[$key]['production_no'] = $product_no[$value['order_product_id']] ?? "";            $current_order[$key]['team'] = $team_map[$value['team_id']] ?? "";            $current_order[$key]['team_man'] = $map[$value['team_id']] ?? "";        }        return $current_order;    }    private function getLastCounting(){        $timestamp_today_start = strtotime(date("Y-m-d 00:00:00",time())) - 86400;        $timestamp_today_end = strtotime(date("Y-m-d 23:59:59",time())) - 86400;        $apply = ApplyOrderDetail::where('del_time',0)            ->where('type',ApplyOrder::type_two)            ->where('crt_time', '>=', $timestamp_today_start)            ->where('crt_time', '<=', $timestamp_today_end)            ->get()->toArray();        $dispatch = DispatchSub::whereIn('id', array_column($apply,'data_id'))            ->get()->toArray();        $equipment_map = [];        $emp_sub = DispatchEmpSub::where('del_time',0)            ->whereIn('dispatch_no',array_column($dispatch,'dispatch_no'))            ->select('dispatch_no','equipment_id')            ->get()->toArray();        if(! empty($emp_sub)){            foreach ($emp_sub as $value){                if(isset($equipment_map[$value['dispatch_no']])) continue;                $equipment_map[$value['dispatch_no']] = $value['equipment_id'];            }        }        $order = [];        foreach ($dispatch as $value){            $e_id = $equipment_map[$value['dispatch_no']] ?? 0;            $order[$e_id][] = $value;        }        $return = [];        foreach ($order as $e_id => $value){            $tmp = [                "finished_num" => 0,                "hg_num" => 0,                "blp_num" => 0,                "plan_num" => 0,            ];            //产出数据 合格数量            $finished_num = 0;            foreach (array_column($value,'finished_num') as $value_v){                $finished_num = bcadd($finished_num, $value_v,2);            }            $tmp['finished_num'] = $tmp['hg_num'] = $finished_num;            //计划数量            $production_quantity = 0;            foreach (array_column($value,'production_quantity') as $value_v){                $production_quantity = bcadd($production_quantity, $value_v,2);            }            $tmp['plan_num'] = $production_quantity;            //不良品数量            $blp = ScrappCount::where('del_time',0)                ->where('crt_time', '>=', $timestamp_today_start)                ->where('crt_time', '<=', $timestamp_today_end)                ->where('dispatch_sub_id', array_column($value,'id'))                ->select('scrapp_num')                ->get()->toArray();            $scrapp_num = 0;            foreach (array_column($blp,'scrapp_num') as $value_v){                $scrapp_num = bcadd($scrapp_num, $value_v,2);            }            $tmp['blp_num'] = $scrapp_num;            $return[$e_id] = $tmp;        }        return $return;    }    private function getNowCounting(){        //当天的开始与结束时间戳        $timestamp_today_start = strtotime(date("Y-m-d 00:00:00",time()));        $timestamp_today_end = strtotime(date("Y-m-d 23:59:59",time()));        $apply = ApplyOrderDetail::where('del_time',0)            ->where('type',ApplyOrder::type_two)            ->where('crt_time', '>=', $timestamp_today_start)            ->where('crt_time', '<=', $timestamp_today_end)            ->get()->toArray();        $dispatch = DispatchSub::whereIn('id', array_column($apply,'data_id'))            ->get()->toArray();        $equipment_map = [];        $emp_sub = DispatchEmpSub::where('del_time',0)            ->whereIn('dispatch_no',array_column($dispatch,'dispatch_no'))            ->select('dispatch_no','equipment_id')            ->get()->toArray();        if(! empty($emp_sub)){            foreach ($emp_sub as $value){                if(isset($equipment_map[$value['dispatch_no']])) continue;                $equipment_map[$value['dispatch_no']] = $value['equipment_id'];            }        }        $order = [];        foreach ($dispatch as $value){            $e_id = $equipment_map[$value['dispatch_no']] ?? 0;            $order[$e_id][] = $value;        }        $return = [];        foreach ($order as $e_id => $value){            $tmp = [                "finished_num" => 0,                "hg_num" => 0,                "blp_num" => 0,                "plan_num" => 0,            ];            //产出数据 合格数量            $finished_num = 0;            foreach (array_column($value,'finished_num') as $value_v){                $finished_num = bcadd($finished_num, $value_v,2);            }            $tmp['finished_num'] = $tmp['hg_num'] = $finished_num;            //计划数量            $production_quantity = 0;            foreach (array_column($value,'production_quantity') as $value_v){                $production_quantity = bcadd($production_quantity, $value_v,2);            }            $tmp['plan_num'] = $production_quantity;            //不良品数量            $blp = ScrappCount::where('del_time',0)                ->where('crt_time', '>=', $timestamp_today_start)                ->where('crt_time', '<=', $timestamp_today_end)                ->where('dispatch_sub_id', array_column($value,'id'))                ->select('scrapp_num')                ->get()->toArray();            $scrapp_num = 0;            foreach (array_column($blp,'scrapp_num') as $value_v){                $scrapp_num = bcadd($scrapp_num, $value_v,2);            }            $tmp['blp_num'] = $scrapp_num;            $return[$e_id] = $tmp;        }        return $return;    }    private function getPendingOrder(){        //当天的开始与结束时间戳        $timestamp_today_start = strtotime(date("Y-m-d 00:00:00",time()));        $timestamp_today_end = strtotime(date("Y-m-d 23:59:59",time()));        $dispatch = DispatchSub::where('del_time',0)            ->where('crt_time', '>=', $timestamp_today_start)            ->where('crt_time', '<=', $timestamp_today_end)            ->where('finished_num', 0)            ->select('dispatch_no','order_product_id','out_order_no','dispatch_quantity')            ->get()->toArray();        $equipment_map = [];        $emp_sub = DispatchEmpSub::where('del_time',0)            ->whereIn('dispatch_no',array_column($dispatch,'dispatch_no'))            ->select('dispatch_no','equipment_id')            ->get()->toArray();        if(! empty($emp_sub)){            foreach ($emp_sub as $value){                if(isset($equipment_map[$value['dispatch_no']])) continue;                $equipment_map[$value['dispatch_no']] = $value['equipment_id'];            }        }        $product_no = OrdersProduct::whereIn('id', array_unique(array_column($dispatch,'order_product_id')))            ->pluck('production_no','id')            ->toArray();        $order = [];        foreach ($dispatch as $value){            $e_id = $equipment_map[$value['dispatch_no']] ?? 0;            $value['production_no'] = $product_no[$value['order_product_id']] ?? '';            $order[$e_id][] = $value;        }        return $order;    }    public function createEquipmentData(Request $request){        $data = $request->all();        if(empty($data['sub'])) return $this->json_return(201,'', "设备信息不能为空");        $device = (new EquipmentService())->getDeviceList("code","id");        $dispatch = [];        foreach ($data['sub'] as $value){            if(empty($value['device_no'])) return [false, "设备编码不能为空"];            if(empty($value['finished_num'])) continue;            $start_time = $value['start_time'];            if(empty($value['start_time'])) $start_time = time();            $device_id = $device[$value['device_no']] ?? 0;            if(empty($device_id)) return [false, '设备不存在'];            $dispatch[] = [                'finished_num' => $value['finished_num'],                'start_time' => $start_time,                'device_id' => $device_id,                'crt_time' => time()            ];        }        if(empty($dispatch)) return $this->json_return(201,'', "请填写至少一个设备的生产数量(吨)");        ForDeviceData::insert($dispatch);        return $this->json_return(200,'操作成功', []);    }}
 |