| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663 | <?phpnamespace App\Service;use App\Model\BasicType;use App\Model\Construction;use App\Model\ConstructionFile;use App\Model\ConstructionInfo;use App\Model\ConstructionProductInfo;use App\Model\Customer;use App\Model\CustomerInfo;use App\Model\DeliveryNote;use App\Model\DeliveryNoteDetail;use App\Model\Depart;use App\Model\Employee;use App\Model\EmployeeDepartPermission;use App\Model\Oa;use App\Model\OaSub;use App\Model\OaSubEmployee;use App\Model\OaSubReportEmployee;use App\Model\OaSubRule;use App\Model\Product;use App\Model\ProductInventorySet;use App\Model\ReturnExchangeOrder;use App\Model\ReturnExchangeOrderProductInfo;use App\Model\SalesOrder;use App\Model\SalesOrderInfo;use App\Model\SalesOrderProductInfo;use App\Model\ScheduleInfo;use App\Model\SeeRange;use App\Model\Storehouse;use Carbon\Carbon;use Illuminate\Database\Eloquent\Builder;use Illuminate\Support\Facades\DB;//use Barryvdh\DomPDF\Facade as PDF;use Barryvdh\DomPDF\PDF;/** * 施工订单 */class ConstructionService extends Service{    /**     * 施工订单编辑     * @param $data     * @param $user     * @return array     */    public function constructionEdit($data,$user){        list($status,$msg) = $this->constructionRule($data, $user, false);        if(!$status) return [$status,$msg];        $params = $this->getDataFile($data);        (new OperationLogService())->setOperationList($params,$user,2);        try {            DB::beginTransaction();            $model = Construction::where('id', $data['id'])->first();            $model->model_type = $data['model_type'];            $model->order_number = $data['order_number'];            $model->title = $data['title'] ?? '';            $model->customer_id = $data['customer_id'] ?? 0;            $model->customer_contact_id = $data['customer_contact_id'] ?? 0;            $model->install_method = $data['install_method'] ?? 0;            $model->install_position = $data['install_position'] ?? 0;            $model->sales_order_id = $data['sales_order_id'] ?? 0;            $model->construction_fee = $data['construction_fee'] ?? 0;            $model->service_price = $data['service_price'] ?? 0;//            $model->construction_time = $data['construction_time'] ?? 0;            $model->handover_time = $data['handover_time'] ?? 0;            $model->urgency = $data['urgency'] ?? 0;            $model->mark = $data['mark'] ?? '';            $model->address1 = ! empty($data['address1']) ? json_encode($data['address1']) : '';            $model->address2 = $data['address2'] ?? '';            $model->introduction = $data['introduction'] ?? '';            $model->storehouse_id = $data['storehouse_id'] ?? 0;            $model->start_time = $data['start_time'] ?? 0;            $model->end_time = $data['end_time'] ?? 0;            $model->schedule_id = $data['schedule_id'] ?? 0;            $model->day_stamp = $data['day_stamp'] ?? 0;            $model->day_start_stamp = $data['day_start_stamp'] ?? 0;            $model->day_end_stamp = $data['day_end_stamp'] ?? 0;            $model->product_introduction = $data['product_introduction'] ?? "";            $model->vin_no = $data['vin_no'] ?? "";            $model->save();            $time = time();            ConstructionInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->where('type',ConstructionInfo::type_two)                ->update(['del_time' => $time]);            ConstructionProductInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => $time]);            $old = ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->select('file')                ->get()->toArray();            $old = array_column($old,'file');            ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => $time]);            if(! empty($data['construction_contact'])){                $insert = [];                foreach ($data['construction_contact'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'contact_type' => $value['id'],                        'contact_info' => $value['info'],                        'type' => ConstructionInfo::type_one,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['employee_one'])){                $insert = [];                foreach ($data['employee_one'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'employee_id' => $value,                        'type' => ConstructionInfo::type_two,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['product'])){                $insert = [];                foreach ($data['product'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'product_id' => $value['product_id'],                        'number' => $value['number'],                        'cost' => $value['cost'] ?? 0,                        'retail_price' => $value['retail_price'] ?? 0,                        'mark' => $value['mark'] ?? '',                        'crt_time' => $time,                        'storehouse_id' => $data['storehouse_id'] ?? 0,                        'basic_type_id' => $value['basic_type_id'],                        'price' => $value['price'],                        'final_amount' => $value['final_amount'] ?? 0,                    ];                }                ConstructionProductInfo::insert($insert);                //锁定库存//                if($data['model_type'] == Construction::Model_type_one) ProductInventoryService::changeLockNumber($user,$msg[0],$msg[1]);            }            if(! empty($data['schedule_info_id'])) ScheduleInfo::where('id',$data['schedule_info_id'])->update(['is_use' => 1]);            $new = [];            if(! empty($data['file'])){                $insert = [];                foreach ($data['file'] as $value){                    $insert[] = [                        'order_number' => $data['order_number'],                        'construction_id' => $data['id'],                        'file' => $value['url'],                        'name' => $value['name'],                        'mark' => $value['mark'] ?? "",                        'crt_time' => $time,                    ];                    if(in_array($value['url'], $old)) {                        foreach ($old as $o_k => $o_v){                            if($o_v == $value['url']) unset($old[$o_k]);                        }                    }else{                        $new[] = $value['url'];                    }                }                ConstructionFile::insert($insert);            }            DB::commit();        }catch (\Exception $exception){            DB::rollBack();            return [false,$exception->getMessage()];        }        if(! empty($data['check'])) {            list($status,$msg) = (new CheckService())->checkAll([                "id" => $model->id,                "order_number" => $data['order_number'],                "opt_case" => CheckService::five,                "menu_id" => $data['menu_id']            ],$user);//            if(! $status) return [true, '保存成功,施工单确认失败,异常信息:' . $msg];        }        return [true, ['file' => ['new' => $new, 'old' => $old]]];    }    /**     * 施工订单新增     * @param $data     * @param $user     * @return array     */    public function constructionAdd($data,$user){        list($status,$msg) = $this->constructionRule($data,$user);        if(!$status) return [$status,$msg];        try {            DB::beginTransaction();            $model = new Construction();            $model->model_type = $data['model_type'];            $model->order_number = $data['order_number'];            $model->title = $data['title'] ?? '';            $model->customer_id = $data['customer_id'] ?? 0;            $model->customer_contact_id = $data['customer_contact_id'] ?? 0;            $model->install_method = $data['install_method'] ?? 0;            $model->install_position = $data['install_position'] ?? 0;            $model->sales_order_id = $data['sales_order_id'] ?? 0;            $model->construction_fee = $data['construction_fee'] ?? 0;            $model->service_price = $data['service_price'] ?? 0;//            $model->construction_time = $data['construction_time'] ?? 0;            $model->handover_time = $data['handover_time'] ?? 0;            $model->urgency = $data['urgency'] ?? 0;            $model->mark = $data['mark'] ?? '';            $model->address1 = ! empty($data['address1']) ? json_encode($data['address1']) : '';            $model->address2 = $data['address2'] ?? '';            $model->introduction = $data['introduction'] ?? '';            $model->crt_id = $user['id'];            $model->depart_id = $data['depart_id'] ?? 0;            $model->top_depart_id = $data['top_depart_id'] ?? 0;            $model->storehouse_id = $data['storehouse_id'] ?? 0;            $model->start_time = $data['start_time'] ?? 0;            $model->end_time = $data['end_time'] ?? 0;            $model->schedule_id = $data['schedule_id'] ?? 0;            $model->day_stamp = $data['day_stamp'] ?? 0;            $model->day_start_stamp = $data['day_start_stamp'] ?? 0;            $model->day_end_stamp = $data['day_end_stamp'] ?? 0;            $model->product_introduction = $data['product_introduction'] ?? "";            $model->vin_no = $data['vin_no'] ?? "";            $model->save();            $time = time();            if(! empty($data['construction_contact'])){                $insert = [];                foreach ($data['construction_contact'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'contact_type' => $value['id'],                        'contact_info' => $value['info'],                        'type' => ConstructionInfo::type_one,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['employee_one'])){                $insert = [];                foreach ($data['employee_one'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'employee_id' => $value,                        'type' => ConstructionInfo::type_two,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['product'])){                $insert = [];                foreach ($data['product'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'product_id' => $value['product_id'],                        'number' => $value['number'],                        'cost' => $value['cost'] ?? 0,                        'retail_price' => $value['retail_price'] ?? 0,                        'mark' => $value['mark'] ?? '',                        'crt_time' => $time,                        'storehouse_id' => $data['storehouse_id'] ?? 0,                        'basic_type_id' => $value['basic_type_id'],                        'price' => $value['price'],                        'final_amount' => $value['final_amount'] ?? 0,                    ];                }                ConstructionProductInfo::insert($insert);                //锁定库存//                if($data['model_type'] == Construction::Model_type_one) ProductInventoryService::changeLockNumber($user,$msg[0],[]);            }            if(! empty($data['schedule_info_id'])) ScheduleInfo::where('id',$data['schedule_info_id'])->update(['is_use' => 1]);            $new = [];            if(! empty($data['file'])){                $insert = [];                foreach ($data['file'] as $value){                    $insert[] = [                        'order_number' => $data['order_number'],                        'construction_id' => $model->id,                        'file' => $value['url'],                        'name' => $value['name'],                        'mark' => $value['mark'] ?? "",                        'crt_time' => $time,                    ];                    if(! empty($value['url'])) $new[] = $value['url'];                }                ConstructionFile::insert($insert);            }            //单据创建时是否校验库存            (new CheckService())->orderInventoryInsert(['order_number' => $data['order_number'], 'is_check_stock' => $data['is_check_stock']]);            DB::commit();        }catch (\Exception $exception){            DB::rollBack();            if (str_contains($exception->getMessage(), '1062') || str_contains($exception->getMessage(), 'Duplicate entry')) {                return [false, '网络波动,请重新操作!'];            }            return [false,$exception->getMessage()];        }        (new OperationLogService())->setOperationList($data,$user);        if(! empty($data['check'])) {            list($status,$msg) = (new CheckService())->checkAll([                "id" => $model->id,                "order_number" => $data['order_number'],                "opt_case" => CheckService::five,                "menu_id" => $data['menu_id']            ],$user);//            if(! $status) return [true, '保存成功,施工单确认失败,异常信息:' . $msg];        }        return [true, ['file' => ['new' => $new]]];    }    /**     * 施工订单删除     * @param $data     * @return array     */    public function constructionDel($data,$user){        if($this->isEmpty($data,'id')) return [false,'请选择数据!'];        $construction = Construction::where('del_time',0)->where('id',$data['id'])->first();        if(empty($construction)) return [false,'施工单不存在或已被删除'];        $construction = $construction->toArray();        if($construction['state'] > Construction::STATE_ZERO) return [false,'请确认施工单状态,操作失败'];        $product_save = $this->getSaveDetail($data['id']);        try {            DB::beginTransaction();            Construction::where('id',$data['id'])->update([                'del_time'=> time()            ]);            ConstructionInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => time()]);            $old = ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->select('file')                ->get()->toArray();            $old = array_column($old,'file');            ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => time()]);            ConstructionProductInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => time()]);            (new RangeService())->RangeDelete($data['id'],SeeRange::type_two);            //锁定库存释放//            if($construction['model_type'] == Construction::Model_type_one) ProductInventoryService::changeLockNumber($user,[],$product_save);            DB::commit();        }catch (\Exception $exception){            DB::rollBack();            return [false,$exception->getMessage()];        }        return [true, ['file' => ['old' => $old]]];    }    /**     * 施工订单详情     * @param $data     * @return array     */    public function detail($data,$user){        if(empty($data['id']) && empty($data['order_number'])) return [false,'请选择数据!'];        if(! empty($data['id'])){            $construction = Construction::where('del_time',0)                ->where('id',$data['id'])                ->first();        }else{            $construction = Construction::where('del_time',0)                ->where('order_number',$data['order_number'])                ->first();            $data['id'] = empty($construction->id) ? 0 : $construction->id;        }        if(empty($construction)) return [false,'施工订单不存在或已被删除'];        $construction = $construction->toArray();        $construction['state_title'] = Construction::$name[$construction['state']] ?? '';        $address_map = config('address');        $address_str = [];        if(! empty($construction['address1'])) {            $tmp = json_decode($construction['address1'],true);            $construction['address1'] = $tmp;            $this->findLabelsByValue($address_map,$tmp,$address_str);            $tmp = implode(' ',$address_str);            $tmp .= ' ' . $construction['address2'];            $address = $tmp;        }else{            $address = $construction['address2'];        }        $construction['address'] = $address;        $start_time = $construction['start_time'] ? date("Y-m-d H:i",$construction['start_time']) : '';        $end_time = $construction['end_time'] ? date("Y-m-d H:i",$construction['end_time']) : '';        $construction['construction_period'] = $start_time . '——' . $end_time;        $sales = SalesOrder::where('id',$construction['sales_order_id'])->value('order_number');        $construction['sales_order_number'] = $sales;        $sales_info = SalesOrderInfo::where('del_time',0)            ->where('sales_order_id',$construction['sales_order_id'])            ->where('type', SalesOrderInfo::type_two)            ->get()->toArray();        $emp = Employee::whereIn('id',array_unique(array_column($sales_info,'data_id')))            ->pluck('emp_name','id')            ->toArray();        $sale_man = $sale_man_tmp = [];        foreach ($sales_info as $value){            if(! in_array($value['data_id'], $sale_man_tmp)){                $tt = $emp[$value['data_id']] ?? '';                $tmp = [                    'id' => $value['data_id'],                    'name' => $tt?? '',                ];                $sale_man[] = $tmp;                $sale_man_tmp[] = $value['data_id'];            }        }        $construction['sale_man'] = $sale_man;        unset($sale_man_tmp);        $customer_title = Customer::where('id',$construction['customer_id'])->value('title');        $construction['customer_title'] = $customer_title ?? "";        $info = CustomerInfo::from('customer_info as a')            ->leftJoin('basic_type as b','b.id','a.contact_type')            ->where('a.del_time',0)            ->where('a.customer_id',$construction['customer_id'])            ->where('a.contact_type','>',0)            ->select('b.title','a.contact_info')            ->get()->toArray();        $construction['customer_array'] = $info;        $info = CustomerInfo::from('customer_info as a')            ->leftJoin('basic_type as b','b.id','a.contact_type')            ->where('a.del_time',0)            ->where('a.customer_id',$construction['customer_id'])            ->where('a.contact_type','>',0)            ->select('b.title','a.contact_info')            ->get()->toArray();        $construction['customer_array'] = $info;        $construction['storehouse_title'] = $construction['storehouse_id'] > 0 ? Storehouse::where('id',$construction['storehouse_id'])->value('title') : "";        $emp_title = Employee::where('id',$construction['customer_contact_id'])->value('emp_name');        $construction['customer_contact_title'] = $emp_title;        $construction['employee_two'] = $construction['employee_one'] = $construction['construction_contact'] = $construction['product'] = [];        $array = [            $construction['install_method'],            $construction['install_position'],            $construction['urgency'],        ];        $basic_map = BasicType::whereIn('id',$array)            ->pluck('title','id')            ->toArray();        $construction = [$construction];        foreach ($construction as $key => $value){            $construction[$key]['install_method_title'] = $basic_map[$value['install_method']] ?? '';            $construction[$key]['install_position_title'] = $basic_map[$value['install_position']] ?? '';            $construction[$key]['urgency_title'] = $basic_map[$value['urgency']] ?? '';        }        $construction = $construction[0];        $construction['file'] = [];        $file = ConstructionFile::where('del_time',0)            ->where('construction_id',$construction['id'])            ->select('id','construction_id','file','name','mark')            ->get()->toArray();        $fileUploadService = new FileUploadService();        foreach ($file as $value){            $construction['file'][] = [                'url' => $value['file'],                'name' => $value['name'],                'mark' => $value['mark'],                'show_url' => $fileUploadService->getFileShow($value['file']),            ];        }        $construction_info = ConstructionInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->select('id','construction_id','employee_id','type','contact_type','contact_info')            ->get()->toArray();        $emp_map = Employee::whereIn('id',array_unique(array_merge_recursive([$construction['crt_id']],array_column($construction_info,'employee_id'))))            ->pluck('emp_name','id')            ->toArray();        $basic_map2 = BasicType::whereIn('id',array_unique(array_column($construction_info,'contact_type')))            ->pluck('title','id')            ->toArray();        foreach ($construction_info as $value){            if($value['type'] == ConstructionInfo::type_one){                $tmp = [                    'id' => $value['contact_type'],                    'title' => $basic_map2[$value['contact_type']] ?? '',                    'info' => $value['contact_info']                ];                $construction['construction_contact'][] = $tmp;            }elseif ($value['type'] == ConstructionInfo::type_two){                $tmp = [                    'id' => $value['employee_id'],                    'name' => $emp_map[$value['employee_id']] ?? '',                ];                $construction['employee_one'][] = $tmp;            }elseif ($value['type'] == ConstructionInfo::type_three){                $tmp = [                    'id' => $value['employee_id'],                    'name' => $emp_map[$value['employee_id']] ?? '',                ];                $construction['employee_two'][] = $tmp;            }        }        $p_info = ConstructionProductInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->get()->toArray();        $basic_price = BasicType::whereIn('id',array_unique(array_column($p_info,'basic_type_id')))->pluck('title','id')->toArray();        $map = (new ProductService())->getProductDetail(array_column($p_info,'product_id'));        foreach ($p_info as $value){            $tmp = $map[$value['product_id']] ?? [];            $value['title'] = $tmp['title'] ?? "";            $value['code'] = $tmp['code'] ?? "";            $value['size'] = $tmp['size'] ?? "";            $value['unit'] = $tmp['unit'] ?? "";            $value['bar_code'] = $tmp['bar_code'] ?? "";            $value['basic_type_title'] = $basic_price[$value['basic_type_id']] ?? "";            $construction['product'][] = $value;        }        $construction['crt_name'] = $emp_map[$construction['crt_id']] ?? '';        $construction['crt_time'] = $construction['crt_time'] ? date("Y-m-d H:i:s",$construction['crt_time']): '';        //可见范围        $return = (new RangeService())->RangeDetail($data['id'],SeeRange::type_two);        $construction['depart'] = $return[0] ?? [];        $construction['employee'] = $return[1] ?? [];        return [true, $construction];    }    public function constructionCommon($data,$user,$field = []){        if(empty($field)){            $field = ['title','id','model_type','order_number','customer_id','customer_contact_id','install_method','install_position','sales_order_id','construction_fee','construction_time','handover_time','urgency','crt_id','crt_time','mark','state','address1','address2','introduction','service_price','storehouse_id','start_time','end_time','pq_state','day_start_stamp','day_end_stamp','vin_no'];        }        $model = Construction::Clear($user,$data);        $model = $model->where('del_time',0)            ->orderby('id', 'desc');        if(empty($data['select_field'])){            $model->select($field);        }else{            $model->select('sales_order_id');        }        if(isset($data['state'])) {            $today_stamp = strtotime(date("Y-m-d H:i:00"));            if($data['state'] == Construction::STATE_DIFF_TWO){                $model->where('state', Construction::STATE_TWO);                $model->where('start_time', '>', $today_stamp);            }elseif($data['state'] == Construction::STATE_TWO){                $model->where('state', Construction::STATE_TWO);                $model->where('start_time', '<=', $today_stamp);            }else{                $model->where('state', $data['state']);            }        }        if(isset($data['pq_state'])) $model->where('pq_state', $data['pq_state']);        if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');        if(! empty($data['model_type'])) $model->where('model_type',$data['model_type']);        if(! empty($data['time_type'])) {            if($data['time_type'] == 1) {                $start = strtotime('today');                $end = strtotime('tomorrow') - 1;            }elseif ($data['time_type'] == 2){                $start = strtotime('this week',strtotime('today'));                $end = strtotime('this week +6 days 23:59:59', strtotime('today'));            }            if(! empty($start) && ! empty($end)) {                $model->where('crt_time','>=',$start);                $model->where('crt_time','<=',$end);            }        }        if(! empty($data['construction_period'][0]) && ! empty($data['construction_period'][1])) {            $return = $this->changeDateToTimeStampAboutRange($data['construction_period']);            $model->where('start_time','>=',$return[0]);            $model->where('end_time','<=',$return[1]);        }        if(! empty($data['pq_period'][0]) && ! empty($data['pq_period'][1])) {            $model->where('day_start_stamp','>=',$this->changeDateToDateMin($data['pq_period'][0]));            $model->where('day_end_stamp','<=',$this->changeDateToDateMin($data['pq_period'][1]));        }        if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {            $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);            $model->whereBetween('crt_time',[$return[0],$return[1]]);        }        if(! empty($data['sale_order'])){            $sale_id = (new SalesOrderService())->orderNumberSearch($user, $data, $data['sale_order']);            $model->whereIn('sales_order_id',$sale_id);        }        if(! empty($data['install_method'])) {            $id = (new BasicTypeService())->basicTypeSearchId($data['install_method']);            $model->whereIn('install_method',$id);        }        if(! empty($data['install_position'])) {            $id = (new BasicTypeService())->basicTypeSearchId($data['install_position']);            $model->whereIn('install_position',$id);        }        if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');        if(! empty($data['select_field'])) return $model->get()->toArray();        if(! empty($data['smart_search'])){            $sale_id = (new SalesOrderService())->orderNumberSearch($user, $data, $data['smart_search']);            $service_2 = new CustomerService();            $customer_id = $service_2->titleSearch($user, $data, $data['smart_search']);            $customer_id_2 = $service_2->contactSearch($data['smart_search']);            $customer_id = array_unique(array_merge_recursive($customer_id,$customer_id_2));            $model->where(function (Builder $query) use ($data, $customer_id,$sale_id) {                $query->where('order_number', 'LIKE', '%'.$data['smart_search'].'%')                    ->orWhereIn('customer_id', $customer_id)                    ->orWhereIn('sales_order_id',$sale_id);            });        }        if(! empty($data['crt_title'])){            $id = (new EmployeeService())->searchByEmpName($data['crt_title']);            $model->whereIn('crt_id', $id);        }        if(! empty($data['js'])){            $js = $this->searchByJs($data['js']);            $model->whereIn('id',$js);        }        if(! empty($data['wx_crt_time'][0]) && ! empty($data['wx_crt_time'][1])) {            $model->where('crt_time','>=',$data['wx_crt_time'][0]);            $model->where('crt_time','<=',$data['wx_crt_time'][1]);        }        return $model;    }    public function searchByJs($js){        $id = (new EmployeeService())->searchByEmpName($js);        $construction_id = ConstructionInfo::where('del_time',0)            ->where('type', ConstructionInfo::type_three)            ->whereIn('employee_id', $id)            ->select('construction_id')            ->get()->toArray();        return array_unique(array_column($construction_id,'construction_id'));    }    /**     * 施工订单列表     * @param $data     * @param $user     * @return array     */    public function constructionList($data,$user){        $model = $this->constructionCommon($data, $user);        if(is_array($model)) return $model;        $list = $this->limit($model,'',$data);        $list = $this->fillData($list);        $count = $this->countData("crt_time", $data, $user);        $list['today'] = $count[0] ?? 0;        $list['yesterday'] = $count[1] ?? 0;        return [true, $list];    }    public function countData($column = "", $data, $user){        if(empty($column) || empty($data['from_wx'])) return [0, 0];        // 获取今天的开始和结束时间戳        $todayStart = Carbon::today()->startOfDay()->timestamp;        $todayEnd = Carbon::today()->endOfDay()->timestamp;        // 获取昨天的开始和结束时间戳        $yesterdayStart = Carbon::yesterday()->startOfDay()->timestamp;        $yesterdayEnd = Carbon::yesterday()->endOfDay()->timestamp;        $data['wx_' . $column] = [$todayStart, $todayEnd];        $model = $this->constructionCommon($data, $user);        // 查询今天的数据条数        $todayCount = $model->count();        $data['wx_' . $column] = [$yesterdayStart, $yesterdayEnd];        $model = $this->constructionCommon($data, $user);        // 查询昨天的数据条数        $yesterdayCount = $model->count();        return [$todayCount, $yesterdayCount];    }    /**     * 参数规则     * @param $data     * @param $user     * @param $is_add     * @return array     */    public function constructionRule(&$data, $user, $is_add = true){        if(empty($data['model_type'])) return [false,'工单模板类型不能为空'];        if(! in_array($data['model_type'],Construction::$model_type)) return [false,'工单模板类型错误'];        if($data['model_type'] == Construction::Model_type_one && empty($data['storehouse_id'])) return [false,'请选择仓库'];        if(empty($data['menu_id'])) return [false, '菜单信息不能为空'];        if(empty($data['sales_order_id'])) return [false,'请选择合同'];        $sale = SalesOrder::where('del_time',0)->where('id',$data['sales_order_id'])->first();        if(empty($sale)) return [false,'合同不存在或已被删除'];        $sale = $sale->toArray();        if($sale['state'] < SalesOrder::State_two) return [false,'合同未通过确认,不允许新建施工单'];        if($sale['state'] >= SalesOrder::State_seven) return [false,'请确认合同状态,新建施工单失败'];        if($sale['top_depart_id'] == $user['head']['id']){            //总社的订单 需要派单 才能建施工            if($sale['state'] < SalesOrder::State_four) return [false,'合同未门店派单,不允许新建施工单'];        }//        if(empty($data['customer_id'])) return [false, '订单合同暂无客户,请补充完信息再进行施工单操作'];        list($status,$msg) = $this->limitingSendRequestBackgExpire("construction" . $sale['order_number']);        if(! $status) return [false, $msg];        if(empty($data['product'])) return [false,'请选择产品'];        if(empty($data['construction_period'][0]) || empty($data['construction_period'][1])) return [false,'请填写施工时间范围'];        $data['start_time'] = $this->changeDateToDateMin($data['construction_period'][0]);        $data['end_time'] = $this->changeDateToDateMin($data['construction_period'][1]);        if(! empty($data['construction_fee'])){            $res = $this->checkNumber($data['construction_fee']);            if(! $res) return [false,'施工费用请输入不超过两位小数并且大于0的数值'];        }        if(! empty($data['service_price'])){            $res = $this->checkNumber($data['service_price']);            if(! $res) return [false,'服务价格请输入不超过两位小数并且大于0的数值'];        }        if(! empty($data['construction_time'])) $data['construction_time'] = $this->changeDateToDateMin($data['construction_time']);        if(! empty($data['handover_time'])) $data['handover_time'] = $this->changeDateToDateMin($data['handover_time']);        //所属部门 以及  顶级部门        if(empty($data['depart_id'])) {            $data['depart_id'] = $this->getDepart($user);            $data['top_depart_id'] = $user['depart_map'][$data['depart_id']] ?? 0;        }        $product_submit = $product_id = [];        foreach ($data['product'] as $value){            if(empty($value['number'])) return [false,'产品数量不能为空'];            $res = $this->checkNumber($value['number']);            if(! $res) return [false,'请输入正确的产品数量'];            $key = $value['product_id'] . ',' .$data['storehouse_id'];            if(isset($product_submit[$key])){                $product_submit[$key] += $value['number'];            }else{                $product_submit[$key] = $value['number'];            }            $product_id[] = $value['product_id'];        }        //剩余能施工        $id = $data['id'] ?? 0;        $s_product = $this->getSaveReturnCompareMessage($id, $data['sales_order_id']);        //比较        foreach ($product_submit as $pro => $number){            $tmp = explode(',',$pro);            $p = $tmp[0];            if(! isset($s_product[$p])) return [false,'施工产品错误,合同中不存在该产品'];            $s_number = $s_product[$p];            if($number > $s_number) return [false,'施工产品数量不能超过合同产品数据(包含已退货产品)'];        }        $id = $data['id'] ?? 0;        $product_save = $this->getSaveDetail($id);        //是否校验库存        ProductInventoryService::is_check($user,$data);        $data['is_check_stock'] = $user['is_check_stock'];        if($data['model_type'] == Construction::Model_type_one){            //到店安装 才校验库存//            list($status,$msg) = (new ProductInventoryService())->compareStock($user,$product_id, $product_submit, $product_save);//            if(! $status) return [false, $msg];        }else{            $data['is_check_stock'] = ProductInventorySet::type_two;        }        if($is_add){            $prefix = Construction::$prefix[$data['model_type']];            $order_number = OrderNoService::createConstructionOrderNumber($prefix);            if(! $order_number) return [false,'工单编号生成失败!'];            $data['order_number'] = $order_number;        }else{            if(empty($data['id'])) return [false,'ID不能为空'];            $construction = Construction::where('del_time',0)                ->where('id',$data['id'])->first();            if(empty($construction)) return [false, '施工单不存在或已被删除'];            $construction = $construction->toArray();            if($construction['state'] > Construction::STATE_ZERO) return [false,'请确认施工单单据状态,修改失败'];            //订单编辑提交限制            $current_top_depart_id = $this->getMyTopDepart($user);            list($status, $msg) = $this->returnOrderEditErrorCommon($current_top_depart_id, $construction['top_depart_id']);            if(! $status) return [false, $msg];        }        return [true, [$product_submit, $product_save]];    }    /**     * 数据拼接     * @param $data     * @return array     */    public function fillData($data){        if(empty($data['data'])) return $data;        $array = array_unique(array_merge_recursive(array_column($data['data'],'install_method'),array_column($data['data'],'urgency'),array_column($data['data'],'install_position')));        $basic_map = BasicType::whereIn('id',$array)            ->pluck('title','id')            ->toArray();        $emp = Employee::whereIn('id',array_unique(array_merge_recursive(array_column($data['data'],'crt_id'),array_column($data['data'],'customer_contact_id'))))            ->pluck('emp_name','id')            ->toArray();        $customer = Customer::whereIn('id',array_unique(array_column($data['data'],'customer_id')))            ->pluck('title','id')            ->toArray();        $sales_map = SalesOrder::whereIn('id',array_unique(array_column($data['data'],'sales_order_id')))->pluck('order_number','id')->toArray();        $storehouse = Storehouse::whereIn('id',array_unique(array_column($data['data'],'storehouse_id')))            ->pluck('title','id')            ->toArray();        //分派的总社或分社        $dispatch = $this->getDispatchData($data['data']);        //施工产品        $product_map = $this->getProduct($data['data']);        //订单状态数据组织        $state_array = $this->getStateMake($data['data']);        //负责人        $construction_info_map = $this->getFzEmployee(array_column($data['data'],'id'));        $address_map = config('address');        foreach ($data['data'] as $key => $value){            $address_str = [];            $product_tmp = $product_map[$value['id']] ?? [];            $data['data'][$key]['product_detail'] = implode(',',$product_tmp);            if(! empty($value['address1'])) {                $tmp = json_decode($value['address1'],true);                $this->findLabelsByValue($address_map,$tmp,$address_str);                $tmp = implode(' ',$address_str);                $tmp .= ' ' . $value['address2'];                $address = $tmp;            }else{                $address = $value['address2'];            }            $start_time = $value['start_time'] ? date("Y-m-d H:i",$value['start_time']) : '';            $end_time = $value['end_time'] ? date("Y-m-d H:i",$value['end_time']) : '';            $data['data'][$key]['construction_period'] = $start_time . '——' . $end_time;            $data['data'][$key]['address'] = $address;            $data['data'][$key]['model_type_title'] = Construction::$model_type_title[$value['model_type']] ?? '';            $data['data'][$key]['install_position_title'] = $basic_map[$value['install_position']] ?? '';            $data['data'][$key]['install_method_title'] = $basic_map[$value['install_method']] ?? '';            $data['data'][$key]['urgency_title'] = $basic_map[$value['urgency']] ?? '';            $data['data'][$key]['customer_title'] = $customer[$value['customer_id']] ?? '';            $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';            $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';            $data['data'][$key]['state_title'] = $this->makeState($data['data'][$key], $state_array);            $data['data'][$key]['customer_contact_title'] = $emp[$value['customer_contact_id']] ?? '';            $tmp_sales = $sales_map[$value['sales_order_id']] ?? "";//            $tmp_sales_time = $tmp_sales['handover_time'] ? date("Y-m-d") : "";            $data['data'][$key]['sales_order_number'] = $tmp_sales;            $data['data'][$key]['handover_time'] = $value['handover_time'] ? date("Y-m-d",$value['handover_time']) : "";            $data['data'][$key]['storehouse_title'] = $storehouse[$value['storehouse_id']] ?? '';            $data['data'][$key]['dispatch_company'] = $dispatch[$value['sales_order_id']] ?? '';            $data['data'][$key]['fz'] = $construction_info_map[$value['id']] ?? "";//            $data['data'][$key]['pq_state_title'] = Construction::$pq_name[$value['pq_state']] ?? '';//            $str = "";//            $start_time = $value['day_start_stamp'] ? date("Y-m-d H:i",$value['day_start_stamp']) : '';//            $end_time = $value['day_end_stamp'] ? date("Y-m-d H:i",$value['day_end_stamp']) : '';//            if(! empty($start_time) && ! empty($end_time)) $str = $start_time . '——' . $end_time;//            $data['data'][$key]['pq_period'] = $str;        }        return $data;    }    public function getFzEmployee($construction_id = []){        if(empty($construction_id)) return [];        $construction_info = ConstructionInfo::where('del_time',0)            ->where('type',ConstructionInfo::type_three)            ->whereIn('construction_id',$construction_id)            ->select('construction_id','employee_id')            ->get()->toArray();        $emp_map2 = Employee::whereIn('id',array_unique(array_column($construction_info,'employee_id')))            ->pluck('emp_name','id')            ->toArray();        $construction_info_map = [];        foreach ($construction_info as $value){            $emp = $emp_map2[$value['employee_id']] ?? "";            if(! $emp) continue;            if(isset($construction_info_map[$value['construction_id']])){                $construction_info_map[$value['construction_id']] .= ',' . $emp;            }else{                $construction_info_map[$value['construction_id']] = $emp;            }        }        return $construction_info_map;    }    public function getStateMake($data){        if(empty($data)) return [];        $order_no = [];        foreach ($data as $value){            if(! in_array($value['state'], [Construction::State_minus_one,Construction::STATE_ONE])) continue;            $order_no[] = $value['order_number'];        }        return (new OaService())->getOaTeamDetailList($order_no);    }    public function makeState($value, $state_array){        $today_stamp = strtotime(date("Y-m-d H:i:00"));        if(! empty($state_array[$value['order_number']])){            $return = $state_array[$value['order_number']];            if($value['state'] == Construction::State_minus_one){                $state = "驳回:" . $return;            }else{                $state = "待" . $return . "审核";            }        }elseif($value['state'] == Construction::STATE_ZERO){            $state = "待" . $value['crt_name'] . "提交";        }elseif($value['state'] == Construction::STATE_TWO && $value['start_time'] > $today_stamp){            $state = Construction::$name[Construction::STATE_DIFF_TWO] ?? '';        }else{            $state = Construction::$name[$value['state']] ?? '';        }        return $state;    }    public function getProduct($data){        $search_id = array_column($data,'id');        if(empty($search_id)) return [];        $product = ConstructionProductInfo::where('del_time',0)            ->whereIn('construction_id',$search_id)            ->select('product_id','construction_id')            ->get()->toArray();        $product_map = Product::whereIn('id',array_unique(array_column($product,'product_id')))->pluck('title','id')->toArray();        $return = [];        foreach ($product as $value){            $product_tmp = $product_map[$value['product_id']] ?? "";            if($product_tmp) $return[$value['construction_id']][] = $product_tmp;        }        return $return;    }    public function getDispatchData($data){        $search_id = [];        foreach ($data as $value){            $search_id[] = $value['sales_order_id'];        }        if(empty($search_id)) return [];        $see = SeeRange::where('del_time',0)            ->whereIn('data_id',$search_id)            ->where('data_type',SeeRange::type_seven)            ->where('type',SeeRange::data_three)            ->select('data_id','param_id')            ->get()->toArray();        $map = Depart::whereIn('id',array_unique(array_column($see,'param_id')))            ->pluck('title','id')            ->toArray();        $see_array = [];        foreach ($see as $value){            $see_array[$value['data_id']] = $map[$value['param_id']] ?? "";        }        return $see_array;    }    /**     * 获取施工单号     * @param $data     * @return array     */    public function constructionGet($data){        if(empty($data['model_type'])) return [false,'工单模板类型不能为空'];        if(! isset(Construction::$prefix[$data['model_type']])) return [false,'工单模板类型错误'];        $prefix = Construction::$prefix[$data['model_type']];        $order_number = OrderNoService::createConstructionOrderNumber($prefix);        if(! $order_number) return [false,'工单编号生成失败!'];        return [true,['order_number' => $order_number]];    }    /**     * 获取保存详情     * @param $id     * @return array     */    public function getSaveDetail($id){        $product_save = [];        if(empty($id)) return $product_save;        $sub = ConstructionProductInfo::where('construction_id',$id)            ->where('del_time',0)            ->get()->toArray();        foreach ($sub as $value){            $key = $value['product_id'] . ',' . $value['storehouse_id'];            if(isset($product_save[$key])){                $product_save[$key] += $value['number'];            }else{                $product_save[$key] = $value['number'];            }        }        return $product_save;    }    public function getSaveReturnCompareMessage($id = 0, $sales_order_id = 0){        $construction = Construction::where('del_time',0)            ->where('sales_order_id',$sales_order_id)            ->select('id')->get()->toArray();        $construction_id = array_column($construction,'id');        $product_save = [];        $sub = ConstructionProductInfo::where('del_time',0)            ->whereIn('construction_id',$construction_id)            ->when(! empty($id), function ($query) use ($id) {                return $query->where('construction_id', '<>',$id);            })            ->get()->toArray();        foreach ($sub as $value){            if(isset($product_save[$value['product_id']])){                $product_save[$value['product_id']] += $value['number'];            }else{                $product_save[$value['product_id']] = $value['number'];            }        }        $product_save2 = [];        $sub1 = ReturnExchangeOrder::where('del_time',0)            ->where('type',ReturnExchangeOrder::Order_type)            ->where('model_type',ReturnExchangeOrder::Model_type_one)            ->where('data_id',$sales_order_id)            ->get()->toArray();        $sub1_array = ReturnExchangeOrderProductInfo::where('del_time',0)            ->whereIn('return_exchange_id',array_column($sub1,'id'))            ->get()->toArray();        foreach ($sub1_array as $value){            if(isset($product_save2[$value['product_id']])){                $product_save2[$value['product_id']] += $value['number'];            }else{                $product_save2[$value['product_id']] = $value['number'];            }        }        $sales_order_product = [];        $sales_product = SalesOrderProductInfo::where('del_time',0)            ->where('sales_order_id',$sales_order_id)            ->get()->toArray();        foreach ($sales_product as $value){            $product_save_tmp = $product_save[$value['product_id']] ?? 0;            $product_save_tmp2 = $product_save2[$value['product_id']] ?? 0;            if(isset($sales_order_product[$value['product_id']])){                $sales_order_product[$value['product_id']] += $value['number'];            }else{                $sales_order_product[$value['product_id']] = $value['number'] - $product_save_tmp - $product_save_tmp2;            }        }        return $sales_order_product;    }    public function deliveryNoteEdit($data,$user){        list($status, $msg) = $this->deliveryNoteEditRule($data, $user);        if(! $status) return [false, $msg];        list($model, $new, $old) = $msg;        try {            if(! isset($data['is_edit']) || $data['is_edit']) {                if(isset($data['is_submit'])) $model->state = 1;                $model->upd_id = $user['id'];                $model->construction_order_number = $data['construction_order_number'] ?? '';                $model->sales_order_number = $data['sales_order_number'] ?? '';                $model->start_time = $data['start_time'] ?? '';                $model->end_time = $data['end_time'] ?? '';                $model->vin_no = $data['vin_no'] ?? '';                $model->system = $data['system'] ?? '';                $model->mile = $data['mile'] ?? '';                $model->is_wait = $data['is_wait'] ?? '';                $model->customer_name = $data['customer_name'] ?? '';                $model->customer_mobile = $data['customer_mobile'] ?? '';                $model->sale_man = $data['sale_man'] ?? '';                $model->install_man = $data['install_man'] ?? '';                $model->is_brash = $data['is_brash'] ?? '';                $model->is_chong = $data['is_chong'] ?? '';                $model->service_mark = $data['service_mark'] ?? '';                $model->mark = $data['mark'] ?? '';                $model->break = $data['break'] ? json_encode($data['break']):json_encode([]);                $model->break_mark = $data['break_mark'] ? json_encode($data['break_mark']):json_encode([]);                $model->project_id = $data['project_id'] ? json_encode($data['project_id']):json_encode([]);                $model->other_project_mark = $data['other_project_mark'] ?? '';                $model->img = $data['img'] ?? '';                $model->img1 = $data['img1'] ?? '';                $model->img2 = $data['img2'] ?? '';                $model->img3 = $data['img3'] ?? '';                $model->depart_id = $data['depart_id'] ?? 0;                $model->top_depart_id = $data['top_depart_id'] ?? 0;                $model->save();                $id = $model->id;                $time = time();                DeliveryNoteDetail::where('del_time',0)                    ->where('delivery_note_id', $id)                    ->update(['del_time' => $time]);                $insert = [];                if(! empty($data['sale_man'])){                    $array = explode(',', $data['sale_man']);                    foreach ($array as $value){                        $insert[] = [                            'delivery_note_id' => $id,                            'type' => DeliveryNoteDetail::TYPE_ONE,                            'data_id' => $value,                            'crt_time' => $time,                        ];                    }                }                if(! empty($data['install_man'])){                    $array = explode(',', $data['install_man']);                    foreach ($array as $value){                        $insert[] = [                            'delivery_note_id' => $id,                            'type' => DeliveryNoteDetail::TYPE_TWO,                            'data_id' => $value,                            'crt_time' => $time,                        ];                    }                }                if(! empty($insert)) DeliveryNoteDetail::insert($insert);            }else{                if(isset($data['is_submit'])){                    $model->state = 1;                    $model->save();                }            }            if(isset($data['is_submit'])) $this->updateSaleOrder($model->id);        }catch (\Throwable $e){            return [false, $e->getMessage()];        }        return [true, ['file' => ['old' => $old, 'new' => $new]]];    }    public function updateSaleOrder($id){        $d = DeliveryNote::where('id',$id)->first();        if(empty($d)) return;        $d = $d->toArray();        if(! empty($d['img2'])) $img[] = $d['img2'];        if(! empty($d['img3'])) $img[] = $d['img3'];        $sale = SalesOrder::where('del_time',0)            ->where('order_number',$d['sales_order_number'])            ->first();        if(empty($sale)) return;        $id = $sale->id;        if($sale->state < SalesOrder::State_seven){            $sale->state = SalesOrder::State_seven;            $sale->save();        }        $time = time();        $insert = [];        if(! empty($img)){            foreach ($img as $value){                $insert[] = [                    'sales_order_id' => $id,                    'type' => SalesOrderInfo::type_seven,                    'file' => $value,                    'crt_time' => $time,                ];            }        }        if(! empty($insert)) SalesOrderInfo::insert($insert);    }    public function deliveryNoteEditRule(&$data, $user){        if(empty($data['construction_order_number'])) return [false, '施工单编号不能为空'];        $construction = Construction::where('del_time',0)            ->where('order_number', $data['construction_order_number'])            ->first();        if(empty($construction)) return [false, '施工单:' . $data['construction_order_number'] . '不存在或已被删除'];        $construction = $construction->toArray();        $data['depart_id'] = $construction['depart_id'];        $data['top_depart_id'] = $construction['top_depart_id'];        //是否交车        $is_submit = 0;        if(isset($data['is_submit'])) $is_submit = 1;        //校验        if($is_submit && $construction['state'] != Construction::STATE_FOUR) return [false, '施工单:' . $data['construction_order_number'] . '未完结,无法交车'];        //校验        if(empty($data['sales_order_number'])) return [false, '销售订单号不能为空'];        list($status, $msg) = (new SalesOrderService())->detail(['order_number' => $data['sales_order_number']], $user);        if(! $status) return [false, $msg];        if($is_submit && $msg['payment_receipt_list']['not_receipt_amount'] > 0 && $msg['model_type'] == SalesOrder::Model_type_one) {            return [false, '销售订单:' . $data['sales_order_number'] . '还有未回款金额, 交车失败'];        }        $new = $old = [];        if(isset($data['id'])) {            $model = DeliveryNote::where('id',$data['id'])->first();            if(empty($model) || $model->del_time > 0) return [false,'交车单不存在或已被删除!'];            if($is_submit){                if(! $model->img3 && ! $data['img3']) return [false, '保存并交车时,必须客户确认签字!'];            }else{                if($model->img3) return [false,'客户已确认签字,保存失败!'];            }            $bool = DeliveryNote::where('del_time',0)                ->where('construction_order_number',$data['construction_order_number'])                ->where('id','<>',$data['id'])->first();            if($bool) return [false,'施工单:' . $data['construction_order_number'] . '已创建交车单!'];            $is_edit = 0;//不能编辑            if(! $model->img3){                $is_edit = 1;                if($model->img2 != "" && $data['img2'] != $model->img2) {                    $old[] = $model->img2;                }else{                    if($data['img2'] != "") $new[] = $data['img2'];                }                if($model->img3 != "" && $data['img3'] != $model->img3) {                    $old[] = $model->img3;                }else{                    if($data['img3'] != "") $new[] = $data['img3'];                }            }            $data['is_edit'] = $is_edit;        } else {            $bool = DeliveryNote::where('del_time',0)                ->where('construction_order_number',$data['construction_order_number'])                ->first();            if($bool) return [false,'施工单:' . $data['construction_order_number'] . '已创建交车单!'];            $model = new DeliveryNote();            $model->crt_id = $user['id'];            if($data['img2'] != "") $new[] = $data['img2'];            if($data['img3'] != "") $new[] = $data['img3'];            if($is_submit && ! $data['img3']) return [false, '保存并交车时,必须客户确认签字!'];        }        return [true, [$model, $new, $old]];    }    public function deliveryNoteList($data)    {        $model = DeliveryNote::where('del_time',0)            ->select("*")            ->orderBy("id","desc");        if(! empty($data['customer_name'])) $model->where('customer_name', 'LIKE', '%'.$data['customer_name'].'%');        if(! empty($data['sales_order_number'])) $model->where('sales_order_number', 'LIKE', '%'.$data['sales_order_number'].'%');        if(! empty($data['sale_man_title'])) {            $id = $this->searchForMan($data['sale_man_title'], DeliveryNoteDetail::TYPE_ONE);            $model->whereIn('id', $id);        }        if(! empty($data['install_man_title'])) {            $id = $this->searchForMan($data['install_man_title'], DeliveryNoteDetail::TYPE_TWO);            $model->whereIn('id', $id);        }        if(! empty($data['end_time'][0]) && ! empty($data['end_time'][1])) {            $return = $this->changeDateToTimeStampAboutRange($data['end_time']);            $model->whereBetween('end_time',[$return[0],$return[1]]);        }        $list = $this->limit($model,'', $data);        $list = $this->fillDeliveryNoteData($list);        return [true, $list];    }    public function fillDeliveryNoteData($data){        if(empty($data['data'])) return $data;        $emp = $this->returnMan($data['data']);        foreach ($data['data'] as $key => $value){            $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';            $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';            $data['data'][$key]['sale_man_title'] = $this->returnMan2($value['sale_man'],$emp);            $data['data'][$key]['install_man_title'] = $this->returnMan2($value['install_man'],$emp);            $data['data'][$key]['state_title'] = DeliveryNote::$name[$value['state']] ?? "";        }        return $data;    }    public function searchForMan($title, $type){        $emp = Employee::where('del_time',0)            ->where('emp_name', 'LIKE', '%'.$title.'%')            ->select('id')            ->get()->toArray();        $emp = array_column($emp,'id');        if(empty($emp)) return [];        $delivery_note_id = DeliveryNoteDetail::where('del_time',0)            ->where('type', $type)            ->whereIn('data_id', $emp)            ->select('delivery_note_id')            ->get()->toArray();        return array_unique(array_column($delivery_note_id,'delivery_note_id'));    }    public function returnMan($data = []){        if(empty($data)) return [];        $man = [];        foreach ($data as $value){            if(! empty($value['sale_man'])){                $tmp = explode(',', $value['sale_man']);                foreach ($tmp as $t){                    if(! in_array($t, $man)) $man[] = $t;                }            }            if(! empty($value['install_man'])){                $tmp = explode(',', $value['install_man']);                foreach ($tmp as $t){                    if(! in_array($t, $man)) $man[] = $t;                }            }            if(! in_array($value['crt_id'], $man)) $man[] = $value['crt_id'];        }        $emp = Employee::whereIn('id', $man)            ->pluck('emp_name','id')            ->toArray();        return $emp;    }    public function returnMan2($value,$emp){        $str_man = "";        if(! empty($value)){            $tmp = explode(',', $value);            foreach ($tmp as $t){                $t2 = $emp[$t] ?? "";                if($t2) $str_man .= $t2 . ",";            }            $str_man = rtrim($str_man, ',');        }        return $str_man;    }    public function deliveryNoteDetail($data){        if(isset($data['id'])) $model = DeliveryNote::where('id',$data['id'])->where('del_time',0)->first();        if(isset($data['construction_order_number'])) $model = DeliveryNote::where('id',$data['construction_order_number'])->where('del_time',0)->first();        if(empty($model)) return [false,'单据不存在或已被删除'];        $detail = $model->toArray();        $emp = $this->returnMan([$detail]);        $fileUploadService = new FileUploadService();        $detail['img2_url'] = $fileUploadService->getFileShow($detail['img2']);        $detail['img3_url'] = $fileUploadService->getFileShow($detail['img3']);        $detail['sale_man_title'] = $this->returnMan2($detail['sale_man'], $emp);        $detail['install_man_title'] = $this->returnMan2($detail['install_man'], $emp);        $detail['crt_name'] = $emp[$detail['crt_id']] ?? "";        $detail['crt_time'] = $detail['crt_time'] ? date('Y-m-d H:i:s',$detail['crt_time']) : '';        $img_list = ConstructionFile::where('order_number',$detail['construction_order_number'])            ->where('del_time',0)            ->select('file as url','name','mark')->get()->toArray();        $detail['file'] = $img_list;        return [true, $detail];    }    public function deliveryNoteDel($data,$user){        if(empty($data['id'])) return [false, '请选择删除的交车单数据'];        $model = DeliveryNote::where('id', $data['id'])->first();        if($model->del_time > 0) return [false, '交车单不存在或已被删除!'];        if($model->state > DeliveryNote::STATE_ZERO) return [false, '交车单已交车,删除失败'];        $old = [];        if($model->img2 != "" ) $old[] = $model->img2;        if($model->img3 != "" ) $old[] = $model->img3;        DeliveryNote::where('id',$data['id'])->update(            [                'del_time' => time(),                'upd_id' => $user['id'],            ]        );        DeliveryNoteDetail::where('del_time',0)            ->where('delivery_note_id', $data['id'])->update(['del_time' => time(),]);        return [true, ['file' => ['old' => $old]]];    }    public function constructionPdf($data, $user){        if(empty($data['id'])) return [false, '请选择下载的施工单'];        $construction = Construction::where('del_time',0)            ->where('id',$data['id'])            ->first();        if(empty($construction)) return [false, '施工单不存在或已被删除'];        $construction = $construction->toArray();        $customer_title = Customer::where('id',$construction['customer_id'])->value('title');        $construction['customer_title'] = $customer_title ?? "";        $construction['sales_order_number'] = SalesOrder::where('id',$construction['sales_order_id'])->value('order_number') ?? '';        $construction['handover_time'] = $construction['handover_time'] ? date("Y-m-d H:i:s",$construction['handover_time']): '';        $construction['crt_time'] = $construction['crt_time'] ? date("Y-m-d H:i:s",$construction['crt_time']): '';        $construction_info = ConstructionInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->where('type',CustomerInfo::type_two)            ->select('id','employee_id')            ->get()->toArray();        $emp_list = Employee::whereIn('id',array_unique(array_merge_recursive([$construction['crt_id']],array_column($construction_info,'employee_id'))))            ->select('emp_name','id','mobile')            ->get()->toArray();        $emp_map = [];        foreach ($emp_list as $value){            $emp_map[$value['id']] = [                'name' => $value['emp_name'],                'mobile' => $value['mobile'],            ];        }        $emp_message = EmployeeDepartPermission::from('employee_depart_permission as a')            ->leftJoin('depart as b', 'b.id', 'a.depart_id')            ->select('a.employee_id', 'b.title')            ->whereIn('employee_id',array_column($emp_list,'id'))            ->get()->toArray();        $emp_message_map = [];        foreach ($emp_message as $value){            if(isset($emp_message_map[$value['employee_id']])){                $emp_message_map[$value['employee_id']] .= ',' . $value['title'];            }else{                $emp_message_map[$value['employee_id']] = $value['title'];            }        }        $crt_name = ($emp_map[$construction['crt_id']]['name'] ?? '') . '  ' . ($emp_message_map[$construction['crt_id']] ?? '') . '  ' . ($emp_map[$construction['crt_id']]['mobile'] ?? '');        $construction['crt_name'] = $crt_name;        $xt_name = "";        foreach ($construction_info as $value){            $xt_name .=  ($emp_map[$value['employee_id']]['name'] ?? '') . '  ' . ($emp_message_map[$value['employee_id']] ?? '') . '  ' . ($emp_map[$value['employee_id']]['mobile'] ?? '') . " | ";        }        $xt_name = rtrim($xt_name, " | ");        $construction['xt_name'] = $xt_name;        $p_info = ConstructionProductInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->get()->toArray();        $map = (new ProductService())->getProductDetail(array_column($p_info,'product_id'));        $unit_map = BasicType::whereIn('id',array_column($map,'unit'))            ->pluck('title','id')->toArray();        $product = [];        $count = 0;        foreach ($p_info as $value){            $tmp = $map[$value['product_id']] ?? [];            $value['count'] = $count+1;            $value['title'] = $tmp['title'] ?? "";            $value['code'] = $tmp['code'] ?? "";            $value['size'] = $tmp['size'] ?? "";            $value['unit'] = $unit_map[$tmp['unit']] ?? "";            $product[] = $value;        }        //工单进展        $detail  = $this->getOaJz($data,$user);        $order_message = ['order' => $construction, 'product' => $product,'detail'=> $detail];        $pdf = app('dompdf.wrapper')->loadView('pdf.construction', $order_message);        $file_name = time().rand(1000,9999);        $filename =  '施工单_' . $file_name.'.' . 'pdf';        $pdf->save(storage_path('app/public/export/' . $filename));        return [true, ['file' => $filename]];    }    public function getOaJz($data,$user)    {        $oa = Oa::where('menu_id', 34)            ->where('del_time',0)            ->where('channel',$user['depart_top'][0]['depart_id'])            ->first();        if(empty($oa)) return [];        $oa = $oa->toArray();        $list = OaSub::where('oa_id', $oa['id'])->where('del_time', 0)->get()->toArray();        $oa_sub_ids = [];        foreach ($list as $v) {            $oa_sub_ids[] = $v['id'];        }        $oaEmployee = OaSubEmployee::wherein('oa_sub_id', $oa_sub_ids)->get()->toArray();        $emp_list = Employee::whereIn('id',array_column($oaEmployee,'employee_id'))            ->select('emp_name','id','mobile')            ->get()->toArray();        $emp_map = [];        foreach ($emp_list as $value){            $emp_map[$value['id']] = [                'name' => $value['emp_name'],                'mobile' => $value['mobile'],            ];        }        $emp_message = EmployeeDepartPermission::from('employee_depart_permission as a')            ->leftJoin('depart as b', 'b.id', 'a.depart_id')            ->whereIn('a.employee_id',array_column($emp_list,'id'))            ->select('a.employee_id', 'b.title')            ->get()->toArray();        $emp_message_map = [];        foreach ($emp_message as $value){            if(isset($emp_message_map[$value['employee_id']])){                $emp_message_map[$value['employee_id']] .= ',' . $value['title'];            }else{                $emp_message_map[$value['employee_id']] = $value['title'];            }        }        $oaEmployeeKey = [];        foreach ($oaEmployee as $v) {            $str = "";            $tmp = $emp_map[$v['employee_id']] ?? [];            $tmp2 = $emp_message_map[$v['employee_id']] ?? "";            $str = $tmp['name'] . " " . $tmp2 . " " . $tmp['mobile'];            $oaEmployeeKey[$v['oa_sub_id']][] = [                'id' => $v['employee_id'],                'emp_name' => $str,            ];        }        $return = [];        foreach ($list as $v) {            $return[$v['sort']][] = [                'emp_id' => $oaEmployeeKey[$v['id']],                'index' => $v['h5_key'],            ];        }        $detail = [];        foreach ($return as $v) {            $children = "";            foreach ($v as $vv) {                $children .= implode('|',array_column($vv['emp_id'],'emp_name')) . ',';            }            $detail[] = rtrim($children,',');        }        return $detail;    }    public function constructionOperation($data, $user){        if(empty($data['order_number'])) return [false, '施工单号不能为空'];        if(empty($data['type'])) return [false, '操作类型不能为空'];        $order = Construction::where('del_time',0)            ->where('order_number',$data['order_number'])            ->first();        if(empty($order)) return [false,'施工单不存在或已被删除,操作失败'];        $order = $order->toArray();        $send_data = [];        if($data['type'] == 1){            if($order['state'] != Construction::STATE_TWO) return [false, '请确认施工单单据状态,操作完结失败'];            $state = Construction::STATE_THREE;            //提醒分配人            $info = ConstructionInfo::where('del_time',0)                ->where('construction_id',$order['id'])                ->where('type', ConstructionInfo::type_three)                ->select('opt_id')                ->get()->toArray();            $opt_id = array_unique(array_column($info,'opt_id'));            if(! empty($opt_id)){                $emp_map = Employee::whereIn('id', $opt_id)                    ->pluck('emp_name','id')                    ->toArray();                foreach ($opt_id as $value){                    $emp_tmp = $emp_map[$value] ?? "";                    $send_data[] = [                        'employee_id' => $value,                        'type' => 2,                        'state' => 0,                        'menu_id' => 34,                        'order_number' => $order['order_number'],                        'tmp_data' => [                            $order['order_number'],                            "施工单",                            '待确认',                            $emp_tmp,                            date('Y-m-d H:i:s'),                        ],                    ];                }            }        }else{            if($order['state'] != Construction::STATE_THREE) return [false, '请确认施工单单据状态,操作待确认失败'];            $state = Construction::STATE_FOUR;            //提醒创建人            $emp_tmp = Employee::where('id', $order['crt_id'])->value('emp_name');            $send_data[] = [                'employee_id' => $order['crt_id'],                'type' => 2,                'state' => 0,                'menu_id' => 34,                'order_number' => $order['order_number'],                'tmp_data' => [                    $order['order_number'],                    "施工单",                    '已完结',                    $emp_tmp,                    date('Y-m-d H:i:s'),                ],            ];        }        Construction::where('order_number',$data['order_number'])            ->update(['state' => $state]);        (new OaService())->sendWxOaCheckMessage($send_data);        return [true, ''];    }}
 |