| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897 | <?phpnamespace App\Service;use App\Model\BasicType;use App\Model\Customer;use App\Model\Depart;use App\Model\DepartIndex;use App\Model\Employee;use App\Model\InOutRecord;use App\Model\InvoiceOrder;use App\Model\InvoiceOrderInfo;use App\Model\LastJc;use App\Model\Product;use App\Model\ProductAdjustment;use App\Model\ProductCategory;use App\Model\PurchaseOrder;use App\Model\PurchaseOrderInfo;use App\Model\ReturnExchangeOrder;use App\Model\ReturnExchangeOrderProductInfo;use App\Model\SalesOrder;use App\Model\SalesOrderProductInfo;use App\Model\SeeRange;use App\Model\Setting;use Carbon\Carbon;use Illuminate\Support\Facades\DB;class StatisticsService extends Service{    public function statisticsCustomer($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择客资创建时间区间'];        $model = Customer::Clear($user,$data);        $model = $model->where('del_time',0)            ->select('id','model_type','customer_from','top_depart_id')            ->orderby('id', 'desc');        if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {            $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);            $model->where('crt_time','>=',$return[0]);            $model->where('crt_time','<=',$return[1]);        }        $list = $model->get()->toArray();        $list1 = $this->fillStatisticsCustomer($list);        $list2 = $this->fillStatisticsCustomer2($list);        $list3 = $this->fillStatisticsCustomer3($list);        return [true, ['bt' => $list1, 'zz' => $list2, 'table' => $list3]];    }    public function fillStatisticsCustomer($data){        if(empty($data)) return $data;        $customer_from = array_unique(array_column($data,'customer_from'));        $basic_type = BasicType::where('del_time',0)            ->whereIn('id',$customer_from)            ->where('type',2)            ->pluck('title','id')            ->toArray();        $return = [];        foreach ($data as $value){            $tmp = $basic_type[$value['customer_from']] ?? "";            if(! $tmp) continue;            if(isset($return[$tmp])){                $return[$tmp]['total'] += 1;            }else{                $return[$tmp] = [                    'total' => 1,                    'title' => $tmp                ];            }        }        return array_values($return);    }    public function fillStatisticsCustomer2($data){        if(empty($data)) return $data;        $depart = Depart::where('del_time',0)            ->where('parent_id',0)            ->where('is_main',0)            ->pluck('title','id')            ->toArray();        $return = [];        foreach ($depart as $key => $value){            $return[$key] = [                'title' => $value,                'total' => 0            ];        }        $top_depart_id = SeeRange::where('del_time',0)            ->where('data_type',SeeRange::type_one)            ->where('type',SeeRange::data_three)            ->whereIn('data_id', array_column($data,'id'))            ->select('param_id as fp_top_depart_id')            ->get()->toArray();        $top_depart_map = [];        foreach ($top_depart_id as $value){            if(isset($top_depart_map[$value['fp_top_depart_id']])){                $top_depart_map[$value['fp_top_depart_id']] += 1;            }else{                $top_depart_map[$value['fp_top_depart_id']] = 1;            }        }        foreach ($return as $key => $value){            if(isset($top_depart_map[$key])) $return[$key]['total'] = $top_depart_map[$key];        }        $return = array_values($return);        usort($return, function($a, $b) {            return $b['total'] - $a['total'];        });        return $return;    }    public function fillStatisticsCustomer3($data){        if(empty($data)) return $data;        $array = array_unique(array_column($data,'customer_from'));        $basic_map = BasicType::whereIn('id',$array)            ->pluck('title','id')            ->toArray();        $return_first = $customer_from_map = $header = [];        foreach ($data as $value){            $title = $basic_map[$value['customer_from']] ?? "";            if(! $title) continue;            if(isset($return_first[$title])){                $return_first[$title]['total'] += 1;            }else{                $return_first[$title] = [                    'title' => $title,                    'total' => 1,                ];            }            $customer_from_map[$value['id']] = $value['customer_from'];            if(! in_array($title, $header)) $header[] = $title;        }        $header_tmp = $header_return = [];        foreach ($header as $value){            $header_tmp[] = [                "title" => $value,                "total" => 0,            ];            $header_return[] = [                "title" => $value            ];        }        $return_first = array_values($return_first);        $depart = Depart::where('del_time',0)            ->where('parent_id',0)            ->where('is_main',0)            ->pluck('title','id')            ->toArray();        $return = [];        foreach ($depart as $key => $value){            $return[$key] = [                'title' => $value,                'total' => 0,                'customer_from' => $header_tmp,            ];        }        $top_depart_id = SeeRange::where('del_time',0)            ->where('data_type',SeeRange::type_one)            ->where('type',SeeRange::data_three)            ->whereIn('data_id', array_column($data,'id'))            ->select('param_id as fp_top_depart_id','data_id as customer_id')            ->get()->toArray();        $top_depart_map = $top_depart_map2 = [];        foreach ($top_depart_id as $value){            if(isset($top_depart_map[$value['fp_top_depart_id']])){                $top_depart_map[$value['fp_top_depart_id']] += 1;            }else{                $top_depart_map[$value['fp_top_depart_id']] = 1;            }            $customer_from_tmp = $customer_from_map[$value['customer_id']] ?? 0;            if($customer_from_tmp){                if(isset($top_depart_map2[$value['fp_top_depart_id']][$customer_from_tmp])){                    $top_depart_map2[$value['fp_top_depart_id']][$customer_from_tmp] += 1;                }else{                    $top_depart_map2[$value['fp_top_depart_id']][$customer_from_tmp] = 1;                }            }        }        foreach ($return as $key => $value){            if(isset($top_depart_map[$key])) {                $num = $top_depart_map[$key];                if($num <= 0) {                    unset($return[$key]);                    continue;                }else{                    $return[$key]['total'] = $top_depart_map[$key];                }            }else{                unset($return[$key]);                continue;            }            if(isset($top_depart_map2[$key])) {                $tmp = $top_depart_map2[$key];                foreach ($tmp as $k => $v){                    $title = $basic_map[$k] ?? "";                    if(! $title) continue;                    foreach ($return[$key]['customer_from'] as $kk => $vv){                        if($vv['title'] == $title){                            $return[$key]['customer_from'][$kk]['total'] = $v;                        }                    }                }            }        }        $return = array_values($return);        usort($return, function($a, $b) {            return $b['total'] - $a['total'];        });        return ['header' => $header_return,'left' => $return_first, 'right' => $return];    }    //销售统计饼图 根据合同类型区分(例如线上合同、线下合同)    public function statisticsBt($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择销售订单时间区间'];        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //需要所有数据的门店        $setting = Setting::where('setting_name','bt_top_depart_id')->first();        $bt_top_depart_id = $setting['setting_value'] ?? [];        $bt_top_depart_id = json_decode($bt_top_depart_id,true);        //当前门店是否在设置门店中        $bool = in_array($current_top_depart_id,$bt_top_depart_id);        $model = SalesOrder::where('del_time',0)            ->when(! $bool, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->select('model_type','contract_fee as total','top_depart_id');        if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {            $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);            $model->where('crt_time','>=',$return[0]);            $model->where('crt_time','<=',$return[1]);        }        $list = $model->get()->toArray();        $list = $this->fillStatisticsBt($list,$bt_top_depart_id,$bool);        return [true, $list];    }    public function fillStatisticsBt($data,$bt_top_depart_id,$bool){        if(empty($data)) return $data;        $return = [];        foreach ($data as $value){            $model_type_title = SalesOrder::$model_type_title[$value['model_type']] ?? "";            if($bool){                if($value['model_type'] != SalesOrder::Model_type_two){                    if(in_array($value['top_depart_id'], $bt_top_depart_id)){                        $this->makeThis($return,$value,$model_type_title);                    }                }else{                    $this->makeThis($return,$value,$model_type_title);                }            }else{                $this->makeThis($return,$value,$model_type_title);            }        }        return array_values($return);    }    public function makeThis(&$return,$value,$model_type_title){        if(isset($return[$value['model_type']])){            $total = bcadd($value['total'], $return[$value['model_type']]['total'],2);            $return[$value['model_type']]['total'] = $total;        }else{            $return[$value['model_type']] = [                'model_type' => $value['model_type'],                'model_type_title' => $model_type_title,                'total' => $value['total'],            ];        }    }    //省 订单类型细分统计    public function statisticsProvince($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //销售订单类型        $model_type = 0;        if(! empty($data['model_type'])) $model_type = $data['model_type'];        //门店设置的指标 按照区域汇总        $index_map = DepartIndex::where('del_time',0)            ->pluck('param_one','top_depart_id')            ->toArray();        //分社所属省        $depart_map = $province_map = [];        $depart = Depart::where('parent_id',0)            ->where('province','<>','')            ->where('del_time',0)            ->select('province','id')            ->get()->toArray();        foreach ($depart as $value){            $depart_map[$value['id']] = $value['province'];            $province_map[$value['province']][] = $value['id'];        }        $address_map = config('address');        $address_map = array_column($address_map,'label','value');        //省        $final_address_map = [];        foreach ($address_map as $key => $value){            $tmp = [                'key' => $key,                'title' => $value,                'total' => 0,                'index' => 0            ];            $top_depart_id = $province_map[$key] ?? [];            if(! empty($top_depart_id)){                foreach ($top_depart_id as $depart_id){                    $index = $index_map[$depart_id] ?? 0;                    $tmp['index'] = bcadd($tmp['index'], $index,2);                }            }            $final_address_map[] = $tmp;        }        //特殊的门店        $setting = Setting::where('setting_name','bt_top_depart_id')->first();        $bt_top_depart_id = $setting['setting_value'] ?? [];        $bt_top_depart_id = json_decode($bt_top_depart_id,true);        //当前门店是否在设置门店中        $bool = in_array($current_top_depart_id,$bt_top_depart_id);        $sale_order = SalesOrder::where("del_time",0)            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->when(! $bool, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->when(! empty($model_type), function ($query) use ($model_type) {                return $query->where('model_type',$model_type);            })            ->select('id','top_depart_id','contract_fee','model_type')            ->get()->toArray();        //合同        $purchase_map = $sale_order_id = [];        foreach ($sale_order as $value){            $area = $depart_map[$value['top_depart_id']] ?? 0;            if(! $area) continue;            if($value['model_type'] != SalesOrder::Model_type_two){                if(in_array($value['top_depart_id'], $bt_top_depart_id)){                    $sale_order_id[] = $value['id'];                    $this->makeData($purchase_map,$value,$area);                }            }else{                $sale_order_id[] = $value['id'];                $this->makeData($purchase_map,$value,$area);            }        }        //退货的差异        $returnExchange_map = [];        $returnExchange = ReturnExchangeOrder::where('del_time',0)            ->where('type',ReturnExchangeOrder::Order_type)             ->whereIn('data_id',array_unique($sale_order_id))            ->select('top_depart_id','difference_amount')            ->get()->toArray();        foreach ($returnExchange as $value){            $area = $depart_map[$value['top_depart_id']] ?? 0;            if(! $area) continue;            if(isset($returnExchange_map[$area])){                $total = bcadd($returnExchange_map[$area], $value['difference_amount'],2);                $returnExchange_map[$area] = $total;            }else{                $returnExchange_map[$area] = $value['difference_amount'];            }        }        foreach ($final_address_map as $key => $value){            $purchase_tmp = $purchase_map[$value['key']] ?? 0;            $return_tmp = $returnExchange_map[$value['key']] ?? 0;            $final_address_map[$key]['total'] = bcsub($purchase_tmp, $return_tmp,2);        }        usort($final_address_map, function($a, $b) {            return $b['total'] - $a['total'];        });        return [true, $final_address_map];    }    public function makeData(&$purchase_map, $value,$area){        if(isset($purchase_map[$area])){            $total = bcadd($purchase_map[$area], $value['contract_fee'],2);            $purchase_map[$area] = $total;        }else{            $purchase_map[$area] = $value['contract_fee'];        }    }    //大区 订单类型细分统计    public function statisticsArea($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //销售订单类型        $model_type = 0;        if(! empty($data['model_type'])) $model_type = $data['model_type'];        //门店设置的指标 按照区域汇总        $index_map = DepartIndex::where('del_time',0)            ->pluck('param_one','top_depart_id')            ->toArray();        //分社所属大区        $depart_map = $area_map = [];        $depart = Depart::where('parent_id',0)            ->where('area','>',0)            ->where('del_time',0)            ->select('area','id')            ->get()->toArray();        foreach ($depart as $value){            $depart_map[$value['id']] = $value['area'];            $area_map[$value['area']][] = $value['id'];        }        //大区        $area = Depart::$area;        $area_map = [];        foreach ($area as $key => $value){            $tmp = [                'key' => $key,                'title' => $value,                'total' => 0,                'index' => 0            ];            $top_depart_id = $area_map[$key] ?? [];            if(! empty($top_depart_id)){                foreach ($top_depart_id as $depart_id){                    $index = $index_map[$depart_id] ?? 0;                    $tmp['index'] = bcadd($tmp['index'], $index,2);                }            }            $area_map[] = $tmp;        }        //特殊的门店        $setting = Setting::where('setting_name','bt_top_depart_id')->first();        $bt_top_depart_id = $setting['setting_value'] ?? [];        $bt_top_depart_id = json_decode($bt_top_depart_id,true);        //当前门店是否在设置门店中        $bool = in_array($current_top_depart_id,$bt_top_depart_id);        $sale_order = SalesOrder::where("del_time",0)            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->when(! $bool, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->when(! empty($model_type), function ($query) use ($model_type) {                return $query->where('model_type',$model_type);            })            ->select('top_depart_id','contract_fee','model_type','id')            ->get()->toArray();        $purchase_map = $sale_order_id = [];        foreach ($sale_order as $value){            $area = $depart_map[$value['top_depart_id']] ?? 0;            if(! $area) continue;            if($value['model_type'] != SalesOrder::Model_type_two){                if(in_array($value['top_depart_id'], $bt_top_depart_id)){                    $sale_order_id[] = $value['id'];                    $this->makeData($purchase_map,$value,$area);                }            }else{                $sale_order_id[] = $value['id'];                $this->makeData($purchase_map,$value,$area);            }        }        //退货的差异        $returnExchange_map = [];        $returnExchange = ReturnExchangeOrder::where('del_time',0)            ->where('type',ReturnExchangeOrder::Order_type)             ->whereIn('data_id',array_unique($sale_order_id))            ->select('top_depart_id','difference_amount')            ->get()->toArray();        foreach ($returnExchange as $value){            $area = $depart_map[$value['top_depart_id']] ?? 0;            if(! $area) continue;            if(isset($returnExchange_map[$area])){                $total = bcadd($returnExchange_map[$area], $value['difference_amount'],2);                $returnExchange_map[$area] = $total;            }else{                $returnExchange_map[$area] = $value['difference_amount'];            }        }        foreach ($area_map as $key => $value){            $purchase_tmp = $purchase_map[$value['key']] ?? 0;            $return_tmp = $returnExchange_map[$value['key']] ?? 0;            $area_map[$key]['total'] = bcsub($purchase_tmp, $return_tmp,2);        }        usort($area_map, function($a, $b) {            return $b['total'] - $a['total'];        });        return [true, $area_map];    }    // 省|大区下的门店  订货统计    public function statisticsAreaDepart($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        if(empty($data['area']) && empty($data['province'])) return [false, '大区或省份必须选择一个'];        if(! empty($data['area']) && ! empty($data['province']))return [false, '大区或省份有且只能有一个'];        if(! empty($data['area']) && ! isset(Depart::$area[$data['area']])) return [false, '该大区不存在'];        $address_map = config('address');        $address_map = array_column($address_map,'label','value');        if(! empty($data['province']) && ! isset($address_map[$data['province']])) return [false, '该省不存在'];        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //销售订单类型        $model_type = 0;        if(! empty($data['model_type'])) $model_type = $data['model_type'];        if(! empty($data['area'])){            $depart = Depart::where('parent_id',0)                ->where('del_time',0)                ->where('area',$data['area'])                ->select('id','title')                ->get()                ->toArray();            if(empty($depart)) return [false, '该大区下不存在门店'];        }else{            $depart = Depart::where('parent_id',0)                ->where('del_time',0)                ->where('province',$data['province'])                ->select('id','title')                ->get()                ->toArray();            if(empty($depart)) return [false, '该省下不存在门店'];        }        //门店设置的指标        $index_map = DepartIndex::where('del_time',0)            ->whereIn('top_depart_id',array_column($depart,'id'))            ->pluck('param_one','top_depart_id')            ->toArray();        //特殊的门店        $setting = Setting::where('setting_name','bt_top_depart_id')->first();        $bt_top_depart_id = $setting['setting_value'] ?? [];        $bt_top_depart_id = json_decode($bt_top_depart_id,true);        //当前门店是否在设置门店中        $bool = in_array($current_top_depart_id,$bt_top_depart_id);        //合同        $sale_order = SalesOrder::where("del_time",0)            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->when(! $bool, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->when(! empty($model_type), function ($query) use ($model_type) {                return $query->where('model_type',$model_type);            })            ->select('top_depart_id','contract_fee','id','model_type')            ->get()->toArray();        //向总社采购的钱        $purchase_map = $sale_order_id = [];        foreach ($sale_order as $value){            if($value['model_type'] != SalesOrder::Model_type_two){                if(in_array($value['top_depart_id'], $bt_top_depart_id)){                    $sale_order_id[] = $value['id'];                    $this->makeData($purchase_map,$value,$value['top_depart_id']);                }            }else{                $sale_order_id[] = $value['id'];                $this->makeData($purchase_map,$value,$value['top_depart_id']);            }        }        //退货的差异        $returnExchange_map = [];        $returnExchange = ReturnExchangeOrder::where('del_time',0)            ->whereIn('top_depart_id',array_column($depart,'id'))            ->where('type',ReturnExchangeOrder::Order_type)             ->whereIn('data_id',array_unique($sale_order_id))            ->select('top_depart_id','difference_amount')            ->get()->toArray();        foreach ($returnExchange as $value){            if(isset($returnExchange_map[$value['top_depart_id']])){                $total = bcadd($returnExchange_map[$value['top_depart_id']], $value['difference_amount'],2);                $returnExchange_map[$value['top_depart_id']] = $total;            }else{                $returnExchange_map[$value['top_depart_id']] = $value['difference_amount'];            }        }        foreach ($depart as $key => $value){            $purchase_tmp = $purchase_map[$value['id']] ?? 0;            $return_tmp = $returnExchange_map[$value['id']] ?? 0;            $depart[$key]['total'] = bcsub($purchase_tmp, $return_tmp,2);            $depart[$key]['index'] = $index_map[$value['id']] ?? 0;        }        return [true, $depart];    }    //某个门店 关于产品以及分类的统计  订货统计    public function statisticsAreaDepartProduct($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        if(empty($data['top_depart_id'])) return [false, '请选择门店'];        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //特殊的门店        $setting = Setting::where('setting_name','bt_top_depart_id')->first();        $bt_top_depart_id = $setting['setting_value'] ?? [];        $bt_top_depart_id = json_decode($bt_top_depart_id,true);        //当前门店是否在设置门店中        $bool = in_array($current_top_depart_id,$bt_top_depart_id);        //销售订单类型        $model_type = 0;        if(! empty($data['model_type'])) $model_type = $data['model_type'];        //时间 =》 钱        $purchase_map1 = $this->getTime($return);        //产品 =》 数量        $purchase_category_map = $purchase_map = [];        $sale_order = SalesOrder::where("del_time",0)            ->where('top_depart_id',$data['top_depart_id'])            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->when(! $bool, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->when(! empty($model_type), function ($query) use ($model_type) {                return $query->where('model_type',$model_type);            })            ->select('id','crt_time')            ->get()->toArray();        $purchase_for_time = array_column($sale_order,'crt_time','id');        $sale_order_id = array_column($sale_order,'id');        $purchase_product = SalesOrderProductInfo::where("del_time",0)            ->whereIn('sales_order_id',$sale_order_id)            ->select('sales_order_id','product_id','number','price','final_amount','sports_bag_id')            ->get()->toArray();        //退换货        list($returnExchange_map,$returnExchange_map_2) = $this->returnExchange($data,$sale_order_id);        //产品        $product_list = Product::whereIn('id',array_unique(array_merge_recursive(array_column($purchase_product,'product_id'),array_keys($returnExchange_map,'product_id'))))            ->select('id','product_category','title','code')            ->get()->toArray();        $product_list_map = array_column($product_list,null,'id');        $category_return = ProductCategory::where('del_time',0)            ->where('parent_id',0)            ->pluck('title','id')            ->toArray();        foreach ($purchase_product as $value){            if($value['sports_bag_id'] > 0){                $money = $value['final_amount'];            }elseif($value['final_amount'] > 0){                $money = $value['final_amount'];            }else{                $money = bcmul($value['price'],$value['number'],2);            }            $crt_time = $purchase_for_time[$value['sales_order_id']];            $crt_time = date("Y-m-d",$crt_time);            //产品信息            $product_tmp = $product_list_map[$value['product_id']] ?? [];            $time_money = 0;            if(isset($returnExchange_map_2[$crt_time])) {                $time_money = $returnExchange_map_2[$crt_time] ?? 0;                unset($returnExchange_map_2[$crt_time]);            }            //钱            if(isset($purchase_map1[$crt_time])){                $time_total = bcadd($purchase_map1[$crt_time]['total'],$money,2);                $time_total = bcsub($time_total,$time_money,2);                $purchase_map1[$crt_time]['total'] = $time_total;            }            $return_number = $return_total = 0;            $return_category_number = $return_category_total = 0;            if(isset($returnExchange_map[$value['product_id']])){                $tmp = $returnExchange_map[$value['product_id']];                $return_number = bcsub($value['number'], $tmp['number'],2);                $return_total = bcsub($money, $tmp['total'],2);                $return_category_number = $return_number;                $return_category_total = $return_total;            }            //-------根据产品            //数量            if(isset($purchase_map[$value['product_id']])){                $tmp_number = bcadd($purchase_map[$value['product_id']]['number'], $value['number'],2);                $tmp_money = bcadd($purchase_map[$value['product_id']]['total'], $money,2);                $purchase_map[$value['product_id']]['number'] = $tmp_number;                $purchase_map[$value['product_id']]['total'] = $tmp_money;            }else{                //减去退换货                $number = bcsub($value['number'], $return_number,2);                $total = bcsub($money, $return_total,2);                $purchase_map[$value['product_id']] = [                    'title' => $product_tmp['title'] . "(" . $product_tmp['code'] .")",                    'number' => $number,                    'total' => $total                ];            }            //-------根据产品            //-------根据产品大类            //数量            $category_tmp = json_decode($product_tmp['product_category']);            $category_tmp = min($category_tmp);            //退换货            $number_2 = bcsub($value['number'], $return_category_number,2);            $total_2 = bcsub($money, $return_category_total,2);            if(isset($purchase_category_map[$category_tmp])){                $tmp_number = bcadd($purchase_map[$value['product_id']]['number'], $value['number'],2);                $tmp_number = bcsub($tmp_number,$number_2,2);                $tmp_money = bcadd($purchase_map[$value['product_id']]['total'], $money,2);                $tmp_money = bcsub($tmp_money,$total_2,2);                $purchase_category_map[$category_tmp]['number'] = $tmp_number;                $purchase_category_map[$category_tmp]['total'] = $tmp_money;            }else{                $num = bcsub($value['number'],$number_2,2);                $tol = bcsub($money,$total_2,2);                $purchase_category_map[$category_tmp] = [                    'number' => $num,                    'title' => $category_return[$category_tmp] ?? "",                    'total' => $tol                ];            }        }        return [true, ['money' => array_values($purchase_map1), 'product_num' => array_values($purchase_map), 'category_num' => array_values($purchase_category_map)]];    }    public function getTime($data){        $startTimestamp = $data[0]; // 起始时间戳        $endTimestamp = $data[1];   // 结束时间戳        // 创建 DateTime 对象        $startDate = new \DateTime();        $endDate = new \DateTime();        $startDate->setTimestamp($startTimestamp);        $endDate->setTimestamp($endTimestamp);        // 创建 DatePeriod 对象        $interval = new \DateInterval('P1D'); // 每天的间隔        $dateRange = new \DatePeriod($startDate, $interval, $endDate);        // 遍历日期范围并输出每个日期        $return = [];        foreach ($dateRange as $date) {            $day = $date->format('Y-m-d');            $return[$day] = [                'day' => $day,                'total' => 0            ];        }        return $return;    }    public function returnExchange($data,$sale_order_id){        $returnExchange_map = $returnExchange_map_2 = [];        $returnExchange = ReturnExchangeOrder::where('del_time',0)            ->where('type',ReturnExchangeOrder::Order_type)            ->whereIn('data_id', $sale_order_id)            ->select('id')            ->get()->toArray();        $returnExchange_product = ReturnExchangeOrderProductInfo::where("del_time",0)            ->whereIn('return_exchange_id',array_column($returnExchange,'id'))            ->select('return_exchange_id','product_id','number','return_exchange_price as price','crt_time')            ->get()->toArray();        foreach ($returnExchange_product as $value){            $money = bcmul($value['price'],$value['number'],2);            if(isset($returnExchange_map[$value['product_id']])){                $tmp_money = bcadd($returnExchange_map[$value['product_id']]['total'], $money,2);                $tmp_number = bcadd($returnExchange_map[$value['product_id']]['number'], $value['number'],2);                $returnExchange_map[$value['product_id']] = [                    'number' => $tmp_number,                    'total' => $tmp_money                ];            }else{                $returnExchange_map[$value['product_id']] = [                    'number' => $value['number'],                    'total' => $money                ];            }            $crt_time = date("Y-m-d",$value['crt_time']);            if(isset($returnExchange_map_2[$crt_time])){                $tmp_money_2 = bcadd($returnExchange_map_2[$crt_time], $money,2);                $returnExchange_map_2[$crt_time] = $tmp_money_2;            }else{                $returnExchange_map_2[$crt_time] = $money;            }        }        return [$returnExchange_map,$returnExchange_map_2];    }    //线下订单    public function statisticsModelTypeOne($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        if(empty($data['x'])) return [false, '请选择X轴维度'];        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //线下 销售订单类型        $model_type = SalesOrder::Model_type_one;        $sale_order = SalesOrder::where("del_time",0)            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->where('model_type',$model_type)            ->when(! empty($current_top_depart_id) && $current_top_depart_id != $head, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->select('id','top_depart_id','contract_fee','crt_id')            ->get()->toArray();        //合同        $sale_order_id = array_column($sale_order,'id');        $statistics = [];        if($data['x'] == "crt_id"){            $emp = Employee::whereIn('id', array_unique(array_column($sale_order,'crt_id')))                ->pluck('emp_name','id')                ->toArray();            //退货的差异            $returnExchange_map = [];            $returnExchange = ReturnExchangeOrder::where('del_time',0)                ->where('type',ReturnExchangeOrder::Order_type)                ->whereIn('data_id',array_unique($sale_order_id))                ->select('top_depart_id','difference_amount','data_id')                ->get()->toArray();            foreach ($returnExchange as $value){                if(isset($returnExchange_map[$value['data_id']])){                    $total = bcadd($returnExchange_map[$value['data_id']], $value['difference_amount'],2);                    $returnExchange_map[$value['data_id']] = $total;                }else{                    $returnExchange_map[$value['data_id']] = $value['difference_amount'];                }            }            foreach ($sale_order as $value){                $crt_name = $emp[$value['crt_id']] ?? "";                if(! $crt_name) continue;                $return_money = $returnExchange_map[$value['id']] ?? 0;                $tmp = bcsub($value['contract_fee'], $return_money,2);                if(isset($statistics[$value['crt_id']])){                    $total = bcadd($tmp,$statistics[$value['crt_id']]['total'],2);                    $statistics[$value['crt_id']]['total'] = $total;                }else{                    $statistics[$value['crt_id']] = [                        'title' => $crt_name,                        'total' => $tmp,                    ];                }            }        }elseif($data['x'] == "product"){            $sales_product = SalesOrderProductInfo::where('del_time',0)                ->whereIn('sales_order_id',$sale_order_id)                ->select('product_id','number','retail_price','price')                ->get()->toArray();            $product = Product::whereIn('id',array_unique(array_column($sales_product,'product_id')))                ->select('id','title','code')                ->get()->toArray();            $product_map = [];            foreach ($product as $value){                $product_map[$value['id']] = $value['title'] . "(" . $value['code']. ")";            }            //退货的差异            $returnExchange_map = [];            $returnExchange = ReturnExchangeOrder::where('del_time',0)                ->where('type',ReturnExchangeOrder::Order_type)                ->whereIn('data_id',array_unique($sale_order_id))                ->select('id')                ->get()->toArray();            $return_product = ReturnExchangeOrderProductInfo::where('del_time',0)                ->whereIn('return_exchange_id', array_column($returnExchange,'id'))                ->select('product_id','number','return_exchange_price')                ->get()->toArray();            foreach ($return_product as $value){                $tmp = bcmul($value['number'],$value['return_exchange_price'],2);                if(isset($returnExchange_map[$value['product_id']])){                    $total = bcadd($returnExchange_map[$value['product_id']], $tmp,2);                    $returnExchange_map[$value['product_id']] = $total;                }else{                    $returnExchange_map[$value['product_id']] = $tmp;                }            }            foreach ($sales_product as $value){                $product_tmp = $product_map[$value['product_id']] ?? "";                if(! $product_tmp) continue;                if($value['price'] > 0){                    $tmp = bcmul($value['price'], $value['number'],2);                }else{                    $tmp = bcmul($value['retail_price'], $value['number'],2);                }                $return_tmp = 0;                if(isset($returnExchange_map[$value['product_id']])){                    $return_tmp = $returnExchange_map[$value['product_id']] ?? 0;                    unset($returnExchange_map[$value['product_id']]);                }                $tmp = bcsub($tmp,$return_tmp,2);                if(isset($statistics[$value['product_id']])){                    $total = bcadd($tmp,$statistics[$value['product_id']]['total'],2);                    $statistics[$value['product_id']]['total'] = $total;                }else{                    $statistics[$value['product_id']] = [                        'title' => $product_tmp,                        'total' => $tmp,                    ];                }            }        }        foreach ($statistics as $key => $value){            if(floatval($value['total']) <= 0) unset($statistics[$key]);        }        $statistics = array_values($statistics);        usort($statistics, function($a, $b) {            return $b['total'] - $a['total'];        });        return [true, $statistics];    }    //线上订单    public function statisticsModelTypeFour($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        if(empty($data['x'])) return [false, '请选择X轴维度'];        //总社id        $head = $user['head']['id'] ?? 0;        //当前门店        $current_top_depart_id = $this->getMyTopDepart($user);        //线下 销售订单类型        $model_type = SalesOrder::Model_type_four;        $sale_order = SalesOrder::where("del_time",0)            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->where('model_type',$model_type)            ->when(! empty($current_top_depart_id) && $current_top_depart_id != $head, function ($query) use ($current_top_depart_id) {                return $query->where('top_depart_id', $current_top_depart_id);            })            ->select('id','top_depart_id','contract_fee','plat_type')            ->get()->toArray();        //合同        $sale_order_id = array_column($sale_order,'id');        $statistics = [];        if($data['x'] == "order_from"){            $array = array_unique(array_column($sale_order,'plat_type'));            $basic_map = BasicType::whereIn('id',$array)                ->pluck('title','id')                ->toArray();            //退货的差异            $returnExchange_map = [];            $returnExchange = ReturnExchangeOrder::where('del_time',0)                ->where('type',ReturnExchangeOrder::Order_type)                ->whereIn('data_id',array_unique($sale_order_id))                ->select('top_depart_id','difference_amount','data_id')                ->get()->toArray();            foreach ($returnExchange as $value){                if(isset($returnExchange_map[$value['data_id']])){                    $total = bcadd($returnExchange_map[$value['data_id']], $value['difference_amount'],2);                    $returnExchange_map[$value['data_id']] = $total;                }else{                    $returnExchange_map[$value['data_id']] = $value['difference_amount'];                }            }            foreach ($sale_order as $value){                $plat_type = $basic_map[$value['plat_type']] ?? "";                if(! $plat_type) continue;                $return_money = $returnExchange_map[$value['id']] ?? 0;                $tmp = bcsub($value['contract_fee'], $return_money,2);                if(isset($statistics[$value['plat_type']])){                    $total = bcadd($tmp,$statistics[$value['plat_type']]['total'],2);                    $statistics[$value['plat_type']]['total'] = $total;                }else{                    $statistics[$value['plat_type']] = [                        'title' => $plat_type,                        'total' => $tmp,                    ];                }            }        }elseif($data['x'] == "product"){            $sales_product = SalesOrderProductInfo::where('del_time',0)                ->whereIn('sales_order_id',$sale_order_id)                ->select('product_id','number','retail_price','price')                ->get()->toArray();            $product = Product::whereIn('id',array_unique(array_column($sales_product,'product_id')))                ->select('id','title','code')                ->get()->toArray();            $product_map = [];            foreach ($product as $value){                $product_map[$value['id']] = $value['title'] . "(" . $value['code']. ")";            }            //退货的差异            $returnExchange_map = [];            $returnExchange = ReturnExchangeOrder::where('del_time',0)                ->where('type',ReturnExchangeOrder::Order_type)                ->whereIn('data_id',array_unique($sale_order_id))                ->select('id')                ->get()->toArray();            $return_product = ReturnExchangeOrderProductInfo::where('del_time',0)                ->whereIn('return_exchange_id', array_column($returnExchange,'id'))                ->select('product_id','number','return_exchange_price')                ->get()->toArray();            foreach ($return_product as $value){                $tmp = bcmul($value['number'],$value['return_exchange_price'],2);                if(isset($returnExchange_map[$value['product_id']])){                    $total = bcadd($returnExchange_map[$value['product_id']], $tmp,2);                    $returnExchange_map[$value['product_id']] = $total;                }else{                    $returnExchange_map[$value['product_id']] = $tmp;                }            }            foreach ($sales_product as $value){                $product_tmp = $product_map[$value['product_id']] ?? "";                if(! $product_tmp) continue;                if($value['price'] > 0){                    $tmp = bcmul($value['price'], $value['number'],2);                }else{                    $tmp = bcmul($value['retail_price'], $value['number'],2);                }                $return_tmp = 0;                if(isset($returnExchange_map[$value['product_id']])){                    $return_tmp = $returnExchange_map[$value['product_id']] ?? 0;                    unset($returnExchange_map[$value['product_id']]);                }                $tmp = bcsub($tmp,$return_tmp,2);                if(isset($statistics[$value['product_id']])){                    $total = bcadd($tmp,$statistics[$value['product_id']]['total'],2);                    $statistics[$value['product_id']]['total'] = $total;                }else{                    $statistics[$value['product_id']] = [                        'title' => $product_tmp,                        'total' => $tmp,                    ];                }            }        }        foreach ($statistics as $key => $value){            if(floatval($value['total']) <= 0) unset($statistics[$key]);        }        $statistics = array_values($statistics);        usort($statistics, function($a, $b) {            return $b['total'] - $a['total'];        });        return [true, $statistics];    }    public function statisticsJc($data,$user){        $model = Product::ProductClear2($user,$data);        $model = $model->where('del_time',0)            ->select('title','id','code','depart_id','top_depart_id','product_attribute')            ->orderby('product_attribute', 'desc')            ->orderby('id', 'desc');        if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');        if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');        if(isset($data['product_attribute'])) $model->where('product_attribute', $data['product_attribute']);        if(! empty($data['product_category_id'])) $model->where('product_category_id', $data['product_category_id']);        if(! empty($data['product_category'])) {            $product_category = ProductCategory::where('del_time',0)                ->where('title', 'LIKE', '%'.$data['product_category'].'%')                ->select('id')                ->get()->toArray();            $model->whereIn('product_category_id',array_unique(array_column($product_category,'id')));        }        $list = $this->limit($model,'',$data);        $list = $this->fillData($list,$user,$data);        return [true, $list];    }    public function fillData($data, $user, $search){        if(empty($data['data'])) return $data;        //产品        $product = array_column($data['data'],'id');        //本月入库 本月出库        list($in, $out) = $this->getThisMonthData($product,$user,$search);        //上月结存 汇总这个月之前的出入        list($last_in,$last_out) = $this->getLastMonthBalance($product,$user,$search);        foreach ($data['data'] as $key => $value){            $last_in_tmp = $last_in[$value['id']] ?? [];            $last_in_money = $last_in_tmp['total'] ?? 0;//本月之前入的金额            $last_in_number = $last_in_tmp['number'] ?? 0;//本月之前入的数量            $last_out_tmp = $last_out[$value['id']] ?? [];            $last_out_money = $last_out_tmp['total'] ?? 0;//本月之前出的金额            $last_out_number = $last_out_tmp['number'] ?? 0;//本月之前出的数量            //上月结存            $last_jc_money = bcsub($last_in_money,$last_out_money,2);//结存金额            $last_jc_number = bcsub($last_in_number,$last_out_number,2);//结存数量            $last_jc_price = floatval($last_jc_number) ? bcdiv($last_jc_money,$last_jc_number,2) : 0;//结存单价            $data['data'][$key]['last_jc_money'] = $last_jc_money;            $data['data'][$key]['last_jc_number'] = $last_jc_number;            $data['data'][$key]['last_jc_price'] = $last_jc_price;            //本月入库            $this_in_tmp = $in[$value['id']] ?? [];            $this_in_money = $this_in_tmp['total'] ?? 0;//本月入的金额            $this_in_number = $this_in_tmp['number'] ?? 0;//本月入的数量            $this_in_price = floatval($this_in_number) ? bcdiv($this_in_money,$this_in_number,2) : 0;//本月入单价            $data['data'][$key]['this_in_money'] = $this_in_money;            $data['data'][$key]['this_in_number'] = $this_in_number;            $data['data'][$key]['this_in_price'] = $this_in_price;            //本月出库            $this_out_tmp = $out[$value['id']] ?? [];            $this_out_money = $this_out_tmp['total'] ?? 0;//本月出的金额            $this_out_number = $this_out_tmp['number'] ?? 0;//本月出的数量            //单价= (上月结存金额+本月入库金额) /上月结存数量+本月入库数量            $amount = bcadd($last_jc_money, $this_in_money,2);            $number = bcadd($last_jc_number, $this_in_number,2);            $this_out_price = floatval($number) ? bcdiv($amount,$number,2) : 0;//本月出单价            $data['data'][$key]['this_out_money'] = $this_out_money;            $data['data'][$key]['this_out_number'] = $this_out_number;            $data['data'][$key]['this_out_price'] = $this_out_price;            //本月结存            //本月结存 数量/金额=本月入库+上月结存+(-本月出库)            $this_jc_money = bcsub(bcadd($this_in_money,$last_jc_money,2),$this_out_money,2);            $this_jc_number = bcadd(bcadd($this_in_number,$last_jc_number,2),$this_out_number,2);            $this_jc_price = floatval($this_jc_number) ? bcdiv($this_jc_money,$this_jc_number,2) : 0;//本月结存单价            $data['data'][$key]['this_jc_money'] = $this_jc_money;            $data['data'][$key]['this_jc_number'] = $this_jc_number;            $data['data'][$key]['this_jc_price'] = $this_jc_price;        }        return $data;    }    //本月入库 出库(库存流水)    public function getThisMonthData($product = [], $user = [], $search = []){        $in = $out = [];        $startStamp = strtotime(date("Y-m-01 00:00:00"));        $endStamp = strtotime(date("Y-m-t 23:59:59"));        //本月出和入的数据        $model = InOutRecord::TopClear($user,$search);        $list = $model->where('del_time',0)            ->where('crt_time','>=',$startStamp)            ->where('crt_time','<=',$endStamp)            ->whereIn('product_id',$product)            ->select('product_id','number','price')            ->get()->toArray();        foreach ($list as $value){            if($value['number'] >= 0){                $tmp_total = bcmul($value['number'], $value['price'], 2);                if(isset($in[$value['product_id']])){                    $number = bcadd($in[$value['product_id']]['number'], $value['number'],2);                    $total = bcadd($in[$value['product_id']]['total'], $tmp_total,2);                    $in[$value['product_id']]['number'] = $number;                    $in[$value['product_id']]['total'] = $total;                }else{                    $in[$value['product_id']] = [                        'number' => $value['number'],                        'total' => $tmp_total,                    ];                }            }else{                $number = abs($value['number']);                $tmp_total = bcmul($number, $value['price'], 2);                if(isset($out[$value['product_id']])){                    $number = bcadd($out[$value['product_id']]['number'], $number,2);                    $total = bcadd($out[$value['product_id']]['total'], $tmp_total,2);                    $out[$value['product_id']]['number'] = $number;                    $out[$value['product_id']]['total'] = $total;                }else{                    $out[$value['product_id']] = [                        'number' => $number,                        'total' => $tmp_total,                    ];                }            }        }        return [$in, $out];    }    //上月结存(汇总这个月之前的出入)(库存流水)    public function getLastMonthBalance($product = [], $user = [], $search = []){        //用户提交的上月结存        $lastData = $this->getLastMonthJc($product,$user,$search);        $startStamp = strtotime(date("Y-m-01 00:00:00"));        $model = InOutRecord::TopClear($user,$search);        $list = $model->where('del_time',0)            ->where('crt_time','<',$startStamp)            ->whereIn('product_id',$product)            ->select('product_id','number','price','top_depart_id')            ->get()->toArray();        $map = [];        foreach ($list as $val){            $map[$val['product_id'] . $val['top_depart_id']] = $val;        }        //先结存表        $in = $out = [];        foreach ($lastData as $value){            $key = $value['product_id'] . '|' . $value['top_depart_id'];            if($value['number'] >= 0){                if(isset($in[$key])){                    $number = bcadd($in[$key]['number'], $value['number'],2);                    $total = bcadd($in[$key]['total'], $value['total'],2);                    $in[$key]['number'] = $number;                    $in[$key]['total'] = $total;                }else{                    $in[$key] = [                        'number' => $value['number'],                        'total' => $value['total'],                    ];                }            }else{                $number = abs($value['number']);                $total = abs($value['total']);                if(isset($out[$key])){                    $number = bcadd($out[$key]['number'], $number,2);                    $total = bcadd($out[$key]['total'], $total,2);                    $out[$key]['number'] = $number;                    $out[$key]['total'] = $total;                }else{                    $out[$key] = [                        'number' => $number,                        'total' => $total,                    ];                }            }        }        //后库存流水        foreach ($list as $value){           $key = $value['product_id'] . '|' . $value['top_depart_id'];            if($value['number'] >= 0){                if(isset($in[$key])) continue;                $tmp_total = bcmul($value['number'], $value['price'], 2);                if(isset($in[$value['product_id']])){                    $number = bcadd($in[$value['product_id']]['number'], $value['number'],2);                    $total = bcadd($in[$value['product_id']]['total'], $tmp_total,2);                    $in[$value['product_id']]['number'] = $number;                    $in[$value['product_id']]['total'] = $total;                }else{                    $in[$value['product_id']] = [                        'number' => $value['number'],                        'total' => $tmp_total,                    ];                }            }else{                if(isset($out[$key])) continue;                $number = abs($value['number']);                $tmp_total = bcmul($number, $value['price'], 2);                if(isset($out[$value['product_id']])){                    $number = bcadd($out[$value['product_id']]['number'], $number,2);                    $total = bcadd($out[$value['product_id']]['total'], $tmp_total,2);                    $out[$value['product_id']]['number'] = $number;                    $out[$value['product_id']]['total'] = $total;                }else{                    $out[$value['product_id']] = [                        'number' => $number,                        'total' => $tmp_total,                    ];                }            }        }        //两个数组组合过滤        $new_in = $new_out = [];        foreach ($in as $key => $value){            $tmp = explode('|', $key);            $product_id = $tmp[0];            if(isset($new_in[$product_id])){                $number = bcadd($new_in[$product_id]['number'], $value['number'],2);                $total = bcadd($new_in[$product_id]['total'], $value['total'],2);                $new_in[$product_id] = [                    'number' => $number,                    'total' => $total,                ];            }else{                $new_in[$product_id] = [                    'number' => $value['number'],                    'total' => $value['total'],                ];            }        }        foreach ($out as $key => $value){            $tmp = explode('|', $key);            $product_id = $tmp[0];            if(isset($new_out[$product_id])){                $number = bcadd($new_out[$product_id]['number'], $value['number'],2);                $total = bcadd($new_out[$product_id]['total'], $value['total'],2);                $new_out[$product_id] = [                    'number' => $number,                    'total' => $total,                ];            }else{                $new_out[$product_id] = [                    'number' => $value['number'],                    'total' => $value['total'],                ];            }        }        return [$new_in, $new_out];    }    public function getLastMonthJc($product = [], $user = [], $search = []){        // 如果存在上月结存数据则使用这个        $top_depart_id = 0;        if(! empty($search['top_depart_id'])) $top_depart_id = $search['top_depart_id'];        $startStamp = strtotime(date("Y-m-01 00:00:00"));        $result = LastJc::where('del_time',0)            ->whereIn('product_id',$product)            ->where('time','<',$startStamp)            ->when(! empty($top_depart_id), function ($query) use ($top_depart_id) {                return $query->where('top_depart_id',$top_depart_id);            })            ->select('product_id','top_depart_id','total','number','price')            ->orderBy('time','desc')            ->get()->toArray();        $return = [];        $tmp = [];        foreach ($result as $value){            $key = $value['product_id'] . $value['top_depart_id'];            if(in_array($key, $tmp)) continue;            $return[] = $value;            $tmp[] = $key;        }        return $return;    }    //本月入库(单据)暂时没用    public function getThisMonthIn1($product = [], $user = [], $search = []){        $return = [];        $startStamp = strtotime(date("Y-m-01 00:00:00"));        $endStamp = strtotime(date("Y-m-t 23:59:59"));        //本月采购单        $model = PurchaseOrder::Clear($user,$search);        $list = $model->where('del_time',0)            ->where('state', PurchaseOrder::STATE_Four)            ->where('crt_time','>=',$startStamp)            ->where('crt_time','<=',$endStamp)            ->select('id')            ->get()->toArray();        if(empty($list)) return $return;        //本月采购产品        $purchase_product_array = [];        $purchase_product = PurchaseOrderInfo::where('del_time',0)            ->whereIn('product_id',$product)            ->whereIn('purchase_order_id',array_column($list,'id'))            ->select('product_id','number','price')            ->get()->toArray();        foreach ($purchase_product as $value){            $total = bcmul($value['number'],$value['price'],2);            if(isset($purchase_product_array[$value['product_id']])){                $purchase_product_array[$value['product_id']]['number'] += $value['number'];                $total_tmp = bcadd($purchase_product_array[$value['product_id']]['total'], $total, 2);                $purchase_product_array[$value['product_id']]['total'] = $total_tmp;            }else{                $purchase_product_array[$value['product_id']] = [                    'number' => $value['number'],                    'total' => $total,                ];            }        }        //本月退货(采购)        $model2 = ReturnExchangeOrder::Clear($user, $search);        $return_list = $model2->where('del_time',0)            ->where('state', ReturnExchangeOrder::State_two)            ->where('type',ReturnExchangeOrder::Order_type2)            ->where('crt_time','>=',$startStamp)            ->where('crt_time','<=',$endStamp)            ->select('id')            ->get()->toArray();        //本月退货产品        $return_product_array = [];        if(! empty($return_list)){            $return_product = ReturnExchangeOrderProductInfo::where('del_time',0)                ->where('return_exchange_id', array_column($return_list, 'id'))                ->whereIn('product_id',$product)                ->where('return_or_exchange',ReturnExchangeOrderProductInfo::type_one)                ->select('product_id','number','return_or_exchange')                ->get()->toArray();            foreach ($return_product as $value){                $total = bcmul($value['number'],$value['return_or_exchange'],2);                if(isset($return_product_array[$value['product_id']])){                    $return_product_array[$value['product_id']]['number'] += $value['number'];                    $total_tmp = bcadd($return_product_array[$value['product_id']]['total'], $total, 2);                    $return_product_array[$value['product_id']]['total'] = $total_tmp;                }else{                    $return_product_array[$value['product_id']] = [                        'number' => $value['number'],                        'total' => $total,                    ];                }            }        }        foreach ($return_product_array as $p => $n){            $number_tmp = -$n['number'];            $total_tmp = -$n['total'];            $purchase_product_tmp = $purchase_product_array[$p] ?? [];            if(empty($purchase_product_tmp)){                $purchase_product_array[$p] = [                    'number' => $number_tmp,                    'total' => $total_tmp,                ];            }else{                $purchase_product_array[$p]['number'] += $number_tmp;                $total_tmp2 = bcadd($purchase_product_array[$p]['total'], $total_tmp, 2);                $purchase_product_array[$p]['total'] += $total_tmp2;            }        }        return $purchase_product_array;    }    //新的进销存统计通用搜索底层抽象    public function statisticsJcNewCommonOrigin($data,$user,$field = []){        if(! empty($data['count_month'])) {            $startStamp = $this->changeDateToDate($data['count_month']);        }else{            $startStamp = strtotime(date("Y-m-01 00:00:00"));        }        $endTimeStamp = strtotime('first day of next month', $startStamp) - 1;        //-------- 结存数量汇总 ---------- //        //上月结存        $last_month_stock = "SUM(CASE WHEN crt_time < $startStamp THEN number ELSE 0 END)";        //本月入库        $this_month_in = "SUM(CASE WHEN crt_time >= $startStamp AND crt_time <= $endTimeStamp AND number > 0 THEN number ELSE 0 END)";        //本月出库        $this_month_out = "SUM(CASE WHEN crt_time >= $startStamp AND crt_time <= $endTimeStamp AND number < 0 THEN number ELSE 0 END)";        //本月结存        $this_month_stock = "($last_month_stock + $this_month_in + $this_month_out)";        //-------- 结存数量汇总 ---------- //        //-------- 结存金额汇总 ---------- //        $order_type = ProductAdjustment::prefix;        //上月结存        $last_month_stock_m = "ROUND(                                    SUM(                                        CASE                                             WHEN crt_time < $startStamp and number <> 0 THEN (number * price)                                            WHEN crt_time < $startStamp and number = 0 and order_type = '$order_type' THEN price                                            ELSE 0                                         END                                    ),                                2)";        //本月入库        $this_month_in_m = "ROUND(                                  SUM(                                      CASE                                             WHEN crt_time >= $startStamp and crt_time <= $endTimeStamp and number > 0 THEN (number * price)                                            WHEN crt_time >= $startStamp and crt_time <= $endTimeStamp and number = 0 and price >= 0 and order_type = '$order_type' THEN price                                            ELSE 0                                       END                                 ),                             2)";        //本月出库        $this_month_out_m = "ROUND(                                  SUM(                                      CASE                                             WHEN crt_time >= $startStamp and crt_time <= $endTimeStamp and number < 0 THEN (number * price)                                            WHEN crt_time >= $startStamp and crt_time <= $endTimeStamp and number = 0 and price < 0 and order_type = '$order_type' THEN price                                            ELSE 0                                       END                                 ),                             2)";        //上月结存//        $last_month_stock_m = "ROUND(SUM(CASE WHEN crt_time < $startStamp THEN (number * price) ELSE 0 END), 2)";//        //本月入库//        $this_month_in_m = "ROUND(SUM(CASE WHEN crt_time >= $startStamp AND number > 0 THEN (number * price) ELSE 0 END), 2)";//        //本月出库//        $this_month_out_m = "ROUND(SUM(CASE WHEN crt_time >= $startStamp AND number < 0 THEN (number * price) ELSE 0 END), 2)";        //-------- 结存金额汇总 ---------- //        if(empty($field)){            $field = ['product_id as id',                DB::raw("$last_month_stock as last_jc_number"),                DB::raw("$last_month_stock_m as last_jc_money"),                DB::raw("$this_month_in as this_in_number"),                DB::raw("$this_month_in_m as this_in_money"),                DB::raw("$this_month_out as this_out_number"),                DB::raw("$this_month_out_m as this_out_money"),//                DB::raw("$this_month_stock as this_jc_number")];            ];        }        $model = InOutRecord::TopClear($user,$data);        $model = $model->where('del_time',0)            ->select($field)            ->groupBy('product_id')            ->havingRaw("$last_month_stock != 0 OR $this_month_in != 0 OR $this_month_out != 0 OR $this_month_stock != 0");        return $model;    }    //新的进销存统计通用搜索    public function statisticsJcNewCommon($data,$user, $field = []){        $model = $this->statisticsJcNewCommonOrigin($data, $user, $field);        if(! empty($data['product_name']) || ! empty($data['product_category_name']) || ! empty($data['code'])) {            $id = $this->searchForProduct($data, $user);            $model->whereIn('product_id', $id);        }        return $model;    }    //新的进销存统计    public function statisticsJcNew($data,$user){        $model = $this->statisticsJcNewCommon($data, $user);        $model->orderBy('product_id','desc');        $list = $this->limit($model,'',$data);        $list = $this->fillDataNew($list);        return [true, $list];    }    public function fillDataNew($data){        if(empty($data['data'])) return $data;        //产品        $map = (new ProductService())->getProductDetail(array_column($data['data'],'id'));        foreach ($data['data'] as $key => $value){            //上月结存            $last_jc_price = floatval($value['last_jc_number']) ? bcdiv($value['last_jc_money'],$value['last_jc_number'],2) : 0;//结存单价            $data['data'][$key]['last_jc_price'] = $last_jc_price;            //本月入库            $this_in_price = floatval($value['this_in_number']) ? bcdiv($value['this_in_money'],$value['this_in_number'],2) : 0;//本月入单价            $data['data'][$key]['this_in_price'] = $this_in_price;            //本月出库            //单价= (上月结存金额+本月入库金额) /上月结存数量+本月入库数量            $amount = bcadd($value['last_jc_money'], $value['this_in_money'],2);            $number = bcadd($value['last_jc_number'], $value['this_in_number'],2);            $this_out_price = floatval($number) ? bcdiv($amount,$number,2) : 0;//本月出单价            $data['data'][$key]['this_out_price'] = $this_out_price;            //本月结存            //本月结存 数量/金额=本月入库+上月结存+(-本月出库)            $this_jc_money = bcadd(bcadd($value['this_in_money'],$value['last_jc_money'],2),$value['this_out_money'],2);            $this_jc_number = bcadd(bcadd($value['this_in_number'],$value['last_jc_number'],2),$value['this_out_number'],2);            $this_jc_price = floatval($this_jc_number) ? bcdiv($this_jc_money,$this_jc_number,2) : 0;//本月结存单价            $data['data'][$key]['this_jc_money'] = $this_jc_money;            $data['data'][$key]['this_jc_number'] = $this_jc_number;            $data['data'][$key]['this_jc_price'] = $this_jc_price;            //产品            $tmp = $map[$value['id']] ?? [];            $data['data'][$key]['title'] = $tmp['title'] ?? "";            $data['data'][$key]['code'] = $tmp['code'] ?? "";            //负数改为正数            $data['data'][$key]['this_out_number'] = abs($value['this_out_number']);            $data['data'][$key]['this_out_money'] = abs($value['this_out_money']);        }        return $data;    }    public function searchForProduct($data, $user){        $search = [];        if(! empty($data['product_name'])) $search['title'] = $data['product_name'];        if(! empty($data['product_category_name'])) $search['product_category'] = $data['product_category_name'];        if(! empty($data['code'])) $search['code'] = $data['code'];        $model = (new ProductService())->productCommon($search, $user, ['id']);        $product = $model->get()->toArray();        return array_column($product,'id');    }    public function statisticsAreaDepartProduct222($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        if(empty($data['top_depart_id'])) return [false, '请选择门店'];        //向总社采购的钱        $purchase_map = [];        $purchase = PurchaseOrder::where('del_time',0)            ->where('top_depart_id',$data['top_depart_id'])            ->where('order_type',[PurchaseOrder::Order_type_three,PurchaseOrder::Order_type_four])            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->select('id')            ->get()->toArray();        $purchase_product = PurchaseOrderInfo::where("del_time",0)            ->whereIn('purchase_order_id',array_column($purchase,'id'))            ->select('product_id','number','price','final_amount','sports_bag_id')            ->get()->toArray();        foreach ($purchase_product as $value){            if($value['sports_bag_id'] > 0){                $money = $value['final_amount'];            }elseif($value['final_amount'] > 0){                $money = $value['final_amount'];            }else{                $money = bcmul($value['price'],$value['number'],2);            }            if(isset($purchase_map[$value['product_id']])){                $tmp_money = bcadd($purchase_map[$value['product_id']]['total'], $money,2);                $tmp_number = bcadd($purchase_map[$value['product_id']]['number'], $value['number'],2);                $purchase_map[$value['product_id']] = [                    'number' => $tmp_number,                    'total' => $tmp_money                ];            }else{                $purchase_map[$value['product_id']] = [                    'number' => $value['number'],                    'total' => $money                ];            }        }        //退货的差异//        $returnExchange_map = $this->returnExchange($data,$return);        //产品        $product_list = Product::whereIn('id',array_unique(array_merge_recursive(array_column($purchase_product,'product_id'),array_keys([],'product_id'))))            ->select('id','product_category','title')            ->get()->toArray();        $product_list_map = array_column($product_list,null,'id');        $category = $category_sum = [];        foreach ($purchase_map as $key => $value){//            if(isset($returnExchange_map[$key])){//                $tmp = $returnExchange_map[$key];//                $number = bcsub($value['number'], $tmp['number'],2);//                $total = bcsub($value['total'], $tmp['total'],2);//                $purchase_map[$key] = [//                    'number' => $number,//                    'total' => $total,//                ];//            }            $product_tmp = $product_list_map[$key] ?? [];            $purchase_map[$key]['title'] = $product_tmp['title'];            $category_tmp = json_decode($product_tmp['product_category']);            $category_tmp = $category_tmp[0];            if(! in_array($category_tmp,$category)) $category[] = $category_tmp;            if(isset($category_sum[$category_tmp])){                $tmp_number = bcadd($category_sum[$category_tmp]['number'], $purchase_map[$key]['number'],2);                $tmp_total = bcadd($category_sum[$category_tmp]['total'], $purchase_map[$key]['total'],2);                $category_sum[$category_tmp] = [                    'number' => $tmp_number,                    'total' => $tmp_total,                ];            }else{                $category_sum[$category_tmp] = [                    'number' =>  $purchase_map[$key]['number'],                    'total' => $purchase_map[$key]['total'],                ];            }        }        //根据产品大类 $category_sum        $category_return = ProductCategory::whereIn('id',$category)            ->select('id','title')            ->get()->toArray();        foreach ($category_return as $key => $value){            $tmp = $category_sum[$value['id']] ?? [];            $category_return[$key]['number'] = $tmp['number'];            $category_return[$key]['total'] = $tmp['total'];        }        //根据产品 $purchase_map        dd($purchase_map);        return [true, ''];    }    public function statisticsProvince2222($data,$user){        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);        //门店设置的指标 按照区域汇总        $index_map = DepartIndex::where('del_time',0)            ->pluck('param_one','top_depart_id')            ->toArray();        //分社所属省        $depart_map = $province_map = [];        $depart = Depart::where('parent_id',0)            ->where('province','<>','')            ->where('del_time',0)            ->select('province','id')            ->get()->toArray();        foreach ($depart as $value){            $depart_map[$value['id']] = $value['province'];            $province_map[$value['province']][] = $value['id'];        }        $address_map = config('address');        $address_map = array_column($address_map,'label','value');        //大区        $final_address_map = [];        foreach ($address_map as $key => $value){            $tmp = [                'key' => $key,                'title' => $value,                'total' => 0,                'index' => 0            ];            $top_depart_id = $province_map[$key] ?? [];            if(! empty($top_depart_id)){                foreach ($top_depart_id as $depart_id){                    $index = $index_map[$depart_id] ?? 0;                    $tmp['index'] = bcadd($tmp['index'], $index,2);                }            }            $final_address_map[] = $tmp;        }        //向总社采购的钱        $purchase_map = [];        $purchase = PurchaseOrder::where('del_time',0)            ->where('order_type',[PurchaseOrder::Order_type_three,PurchaseOrder::Order_type_four])            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->select('top_depart_id','purchase_total')            ->get()->toArray();        foreach ($purchase as $value){            $area = $depart_map[$value['top_depart_id']] ?? 0;            if(! $area) continue;            if(isset($purchase_map[$area])){                $total = bcadd($purchase_map[$area], $value['purchase_total'],2);                $purchase_map[$area] = $total;            }else{                $purchase_map[$area] = $value['purchase_total'];            }        }        //退货的差异        $returnExchange_map = [];        $returnExchange = ReturnExchangeOrder::where('del_time',0)            ->where('type',ReturnExchangeOrder::Order_type2)            ->where('crt_time','>=',$return[0])            ->where('crt_time','<=',$return[1])            ->where('crt_time','<=',$return[1])            ->select('top_depart_id','difference_amount')            ->get()->toArray();        foreach ($returnExchange as $value){            $area = $depart_map[$value['top_depart_id']] ?? 0;            if(! $area) continue;            if(isset($returnExchange_map[$area])){                $total = bcadd($returnExchange_map[$area], $value['difference_amount'],2);                $returnExchange_map[$area] = $total;            }else{                $returnExchange_map[$area] = $value['difference_amount'];            }        }        foreach ($final_address_map as $key => $value){            $purchase_tmp = $purchase_map[$value['key']] ?? 0;            $return_tmp = $returnExchange_map[$value['key']] ?? 0;            $final_address_map[$key]['total'] = bcsub($purchase_tmp, $return_tmp,2);        }        return [true, $final_address_map];    }    public function fillStatisticsBt1($data){        if(empty($data)) return $data;        $total = floatval(array_sum(array_column($data,'total')));        // 设置一个最小显示阈值,比如0.5%        $threshold = 0.5;        // 用于存储调整后的数据        $adjustedData = [];        $otherTotal = 0;        $other = [];        foreach ($data as $value) {            $model_type_title = SalesOrder::$model_type_title[$value['model_type']] ?? "";            $rate = $total ? $value['total'] / $total : 0;            // 检查是否低于阈值            if ($rate * 100 < $threshold) {                // 小于阈值的部分加到"其他"中                $otherTotal += $value['total'];                $other[] = $model_type_title;            } else {                // 保留更多小数位数                $adjustedData[] = [                    'model_type' => $value['model_type'],                    'total' => $value['total'],                    'model_type_title' => $model_type_title,                    'rate' => round($rate * 100, 2)                ];            }        }        // 如果有"其他"值,则添加到数据集中        if ($otherTotal > 0) {            $other_title = implode(',',$other);            $adjustedData[] = [                'model_type' => -1, // 自定义一个类型标识                'total' => $otherTotal,                'model_type_title' => '其他(' . $other_title . ')',                'rate' => round($otherTotal / $total * 100, 2)            ];        }        return $adjustedData;    }}
 |