<?php
namespace App\Services\Business;
use App\Models\Business\WashOrder;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Models\Business\OrderSettlementDetails;
use App\Services\ReceivablePay\ReceivablePayService;
use App\Services\WeChatApplet\User\MemberCarService;
use App\Http\Models\Api\DispatchBill;
use App\Http\Models\Api\CashierDesk;

class NewOrderService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new WashOrder();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 新增订单
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-11
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function newOrder($data)
    {
        $find_order = DB::table('order')
            ->where('ord_shop_id', $data['ord_shop_id'])
            ->first();
        $ord_id = WashOrder::insertGetId($data);
        if (empty($find_order) && $ord_id) {
            $find_inv_data = DB::table('shop as s')
                ->leftJoin('settle_in as si', 'si.shop_name', '=', 's.shop_store_name')
                ->where('s.shop_id', $data['ord_shop_id'])
                ->first();

            if ($find_inv_data && $find_inv_data->inv_shop_code) {
                $fshop = DB::table('shop')
                    ->where('shop_code', $find_inv_data->inv_shop_code)
                    ->first();
                if ($fshop) {
                    $end_time = strtotime($fshop->shop_opening_end_time);
                    if (time() > $end_time) {
                        $end_time = time();
                    }
                    $end_time = dateSomeMonthsLater(date('Y-m-d H:i:s', $end_time),$find_inv_data->inv_gift_time);
                    $update_data['shop_opening_end_time'] = $end_time;
                    $update_res = DB::table('shop')
                        ->where('shop_code', $find_inv_data->inv_shop_code)
                        ->update($update_data);
                }
            }
        }
        return $ord_id;
    }

    /**
     * 编辑订单
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-09-11
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function editOrder($ord_id,$data)
    {
        $ord_id = WashOrder::where('ord_id', $ord_id)->update($data);
        return $ord_id;
    }

    /**
     * 其他系统下单接口
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-02
     * @param  [type]           $request [description]
     * @return [type]                 [description]
     */
    public static function placeOrder($request)
    {
        $shop_data = DB::table('shop')
            ->where('shop_code', $request['shop_code'])
            ->first();
        if (empty($shop_data)) {
            return ['code'=>500,'msg'=>'未查询到此门店','data'=>''];
        }
        $find_other_order_number = DB::table('order')
            ->where('ord_other_system_number', $request['order_number'])
            ->first();
        if ($find_other_order_number) {
            return ['code'=>500,'msg'=>'此订单已存在','data'=>''];
        }
        $request['ord_type'] = 1;//会员客户
        $user_info['adm_superior_shop_id'] = $shop_data->shop_superior_id;
        $user_info['shop_superior_id'] = $shop_data->shop_superior_id;
        $user_info['adm_shop_id'] = $shop_data->shop_id;
        $user_info['adm_cid'] = $shop_data->shop_cid;
        $user_info['adm_id'] = 0;
        $user_info['adm_name'] = '';
        $user_info['shop_versions'] = 2;
        $user_info = (object)$user_info;
        if (!empty($request['orcl_phone'])) {
            $find_member = DB::table('member')
                ->where('mem_shop_id', $shop_data->shop_id)
                ->where('mem_phone',  $request['orcl_phone'])
                ->first();
            if (empty($find_member)) {
                $add_mem['mem_shop_id'] = $shop_data->shop_id;
                $add_mem['mem_name'] = $request['orcl_name'];
                $add_mem['mem_phone'] = $request['orcl_phone'];
                $add_mem['mem_car_num'] = $request['orcl_car_num'];
                $mem_id = DB::table('member')->insertGetId($add_mem);
                $request['ord_client_id'] = $mem_id;
                WashOrderService::addFestival($mem_id,$user_info);//新增节日提醒
            } else {
                $request['ord_client_id'] = $find_member->mem_id;
            }
        } else {
            // 散户
            $request['ord_type'] = 0;
        }
        if (empty($request['goods_data'])) {
            return ['code'=>500,'msg'=>'请选择服务商品','data'=>''];
        }
        $goods_data = $request['goods_data'];
        $sepr_work_type = [];
        $goo_all_quantity = 0;
        $sepr_id = '';
        $sepr_name = '';
        foreach ($goods_data as $key => $value) {
            if ($value['goo_type'] == 2) {//服务类
                if ($value['goo_code'] == 'SP00001') {
                    $find_sepr = DB::table('service_project')
                        ->where('sepr_code', $value['goo_code'])
                        ->first();
                } else {
                    $find_sepr = DB::table('service_project')
                        ->where('sepr_shop_id', $shop_data->shop_id)
                        ->where('sepr_code', $value['goo_code'])
                        ->first();
                }
                if ($sepr_id) {
                    $sepr_id = $sepr_id.$find_sepr->sepr_id.',';
                } else {
                    $sepr_id = ','.$find_sepr->sepr_id.',';
                }
                $goods_data[$key]['goo_id'] = $find_sepr->sepr_id;
                $goods_data[$key]['goo_unta_id'] = 0;
                if (!isset($value['goo_name'])) {//没传商品名称 查询名称
                    $goods_data[$key]['goo_name'] = $find_sepr->sepr_name;
                } else {
                    if ($value['goo_code'] == 'SP00001') {
                        $remark = '下单服务为:'.$value['goo_name'];
                    }
                }
                $sepr_work_type[] = $find_sepr->sepr_work_type;
            } elseif ($value['goo_type'] == 1) {//商品
                $find_goods = DB::table('goods')
                    ->where('goo_shop_id', $shop_data->shop_id)
                    ->where('goo_goods_encode', $value['goo_code'])
                    ->where(function ($query) use ($value) {
                        if (isset($value['goo_unit'])) {
                            $query->where('goo_unit', $value['goo_unit']);
                        }
                    })
                    ->first();
                if (!$find_goods) {
                    return ['code'=>500,'msg'=>'未查询到此商品','data'=>''];
                }
                $goods_data[$key]['goo_unta_id'] = $find_goods->goo_unta_id;
                $goods_data[$key]['goo_name'] = $find_goods->goo_name;
                $goods_data[$key]['goo_unit'] = $find_goods->goo_unit;
                $goods_data[$key]['goo_id'] = $find_goods->goo_id;
            } else {
                return ['code'=>500,'msg'=>'请上传商品类型'];
            }
            $goods_data[$key]['goo_state'] = 1;
            $goods_data[$key]['goo_waon_class'] = 1;
            $goods_data[$key]['goo_inventory'] = 1;
            $goo_all_quantity += $value['goo_quantity'];
        }
        if (isset($request['ware_freight_space']) && !empty($request['ware_freight_space'])) {
            $ware_id = DB::table('warehouse')
                ->where('ware_freight_space', $request['ware_freight_space'])
                ->value('ware_id');
            if (empty($ware_id)) {
                return ['code' => 500, 'msg' => '未查询到此仓库', 'data' => ''];
            }
        } else {
            $ware_id = 0;
        }
        // 添加订单表数据
        $ord_order_number = Common::orderRule($user_info);
        //订单数据
        $ord_data['ord_cid'] = $user_info->adm_cid;
        $ord_data['ord_shop_id'] = $user_info->adm_shop_id;
        $ord_data['ord_superior_shop_id'] = $user_info->adm_shop_id;
        $ord_data['ord_order_number'] = $ord_order_number;
        $ord_data['ord_service_type'] = 1; //订单类型
        $ord_data['ord_type'] = $request['ord_type']; //三方派单
        $ord_data['ord_client_id'] = $request['ord_client_id']; //三方派单
        $ord_data['ord_is_split'] = 1; //正常订单
        $ord_data['ord_classify'] = 2; //正常订单
        $ord_data['ord_source'] = 4; //订单来源
        $ord_data['ord_other_system_number'] = $request['order_number']; //三方单号
        $ord_data['ord_ware_id'] = $ware_id; //订单来源
        $ord_data['ord_order_price'] = $request['ord_order_price'] * 100; //商品价格
        $ord_data['ord_actual_price'] = $request['ord_actual_price'] * 100; //实收金额
        if ($request['ord_payment_way'] == 0 || $request['ord_payment_way'] == 8) {
            $ord_data['ord_actual_price'] = 0; //实付金额
            $ord_data['ord_pay_state'] = 2;
        } else {
            $ord_data['ord_pay_state'] = 1;
            $ord_data['ord_state'] = 2;
        }
        $ord_data['ord_wor_state'] = 1; //7待接单
        $ord_data['ord_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
        $ord_data['ord_payment_way'] = $request['ord_payment_way']; //结算方式
        $ord_data['ord_address_type'] = $request['ord_address_type']; //施工门店类型1门店2企业客户
        $ord_data['ord_address_id'] = $request['ord_address_id']; //施工门店id
        $ord_data['ord_address'] = $request['ord_address']; //施工门店
        $ord_data['ord_explain'] = $request['ord_explain']; //施工说明
        $ord_data['ord_goods_quantity'] = $goo_all_quantity; //商品总数量
        $ord_data['ord_unique_string'] = md5(md5($ord_order_number . $user_info->adm_shop_id . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_id = self::newOrder($ord_data);
        if (isset($remark)) {//下单时默认商品添加备注
            $orre_res = orderRemark($user_info, $ord_id, 0, $remark, '订单列表');
        }
        $ord_add_work_state = 2;
        $is_goods = false;//是否有产品
        $only_goods = false;//是否只有产品
        $ord_add_work_state = 2;//是否生成工单1是2否
        if (!empty($goods_data)) {
            $goo_type = array_column($goods_data, 'goo_type');
            if (in_array(1, $goo_type)) {
                $is_goods = true;
            }
            if (!in_array(2, $goo_type)) {
                $only_goods = true;
            }
            if (in_array(1, $sepr_work_type)) {//是否生成工单
                $ord_add_work_state = 1;
            }
            $goo_all_price = 0; //商品总金额
            $goo_all_quantity = 0; //商品总数量
            $new_goo_all_quantity = 0;
            $goo_id = '';
            $goo_name = '';
            $goods_data_count = count($goods_data);
            // 新增订单商品数据
            foreach ($goods_data as $key => $value) {
                if ($value['goo_type'] == 2) {//服务类商品
                    $image_id = [];//根据服务项目确定需要上传的图片
                    $sepr_image = DB::table('sepr_img')
                        ->where('seim_sepr_id', $value['goo_id'])
                        ->select('seim_imco_id')
                        ->get()->toArray();
                    if (!empty($sepr_image)) {
                        foreach ($sepr_image as $ks => $vs) {
                            if (!in_array($vs->seim_imco_id, $image_id)) {
                                $image_id[] = $vs->seim_imco_id;
                            }
                        }
                    }
                }
                if (!isset($value['wago_id']) && $value['goo_type'] == 1 && isset($request['ware_freight_space']) && !empty($request['ware_freight_space'])) {
                    
                    $find_wago_id = DB::table('warehouse_goods')
                        ->where('wago_goo_id', $value['goo_id'])
                        ->where('wago_class', $value['goo_waon_class'])
                        ->where('wago_ware_id', $ware_id)
                        ->value('wago_id');
                    $value['wago_id'] = $find_wago_id;
                    $goods_data[$key]['wago_id'] = $find_wago_id;
                } elseif (!isset($value['wago_id']) && $value['goo_type'] == 2) {
                    $value['wago_id'] = 0;
                    $goods_data[$key]['wago_id'] = 0;
                }
                if(isset($value['wago_id']) && $value['goo_type'] == 1){
                    $find_wago_price = DB::table('warehouse_goods')
                        ->where('wago_goo_id', $value['goo_id'])
                        ->where('wago_class', $value['goo_waon_class'])
                        ->where('wago_ware_id', $ware_id)
                        ->where('wago_id', $value['wago_id'])
                        ->value('wago_goo_price');
                    $goods_price[$value['wago_id']]['price'] = $find_wago_price;//商品成本价
                    $goods_price[$value['wago_id']]['quantity'] = $value['goo_quantity'];//商品数量
                }
                if (!empty($value['goo_id'])) {
                    if (empty($value['goo_id'])  || $value['goo_quantity'] < 0  || !is_numeric($value['goo_id']) || !in_array($value['goo_state'], [1, 2]) || !is_numeric($value['goo_quantity'])) {
                        return ['code' => 500, 'msg' => 'error', 'data' => '请完善服务信息02'];
                    }
                    $orgo_data['orgo_ord_id'] = $ord_id;
                    $orgo_data['orgo_order_number'] = $ord_order_number;
                    $orgo_data['orgo_ware_id'] = isset($ware_id) ? $ware_id : 0;
                    $orgo_data['orgo_wago_id'] = isset($value['wago_id']) ? $value['wago_id'] : 0;
                    $orgo_data['orgo_goo_id'] = $value['goo_id'];
                    $orgo_data['orgo_goo_name'] = $value['goo_name'];
                    $orgo_data['orgo_goo_type'] = $value['goo_type'];
                    if ($value['goo_type'] == 1) {
                        $goo_goods_encode = DB::table('goods')
                            ->where('goo_id', $value['goo_id'])
                            ->value('goo_goods_encode');
                        $orgo_data['orgo_goo_goods_encode'] = !empty($goo_goods_encode) ? $goo_goods_encode : '';
                    }
                    $orgo_data['orgo_goo_inventory'] = 1;
                    $orgo_data['orgo_state'] = 1;
                    $orgo_data['orgo_goo_unit'] = $value['goo_unit'];
                    if ($value['goo_type'] == 2) {
                        $orgo_data['orgo_goo_unit'] = '次';
                    }
                    $orgo_data['orgo_goo_unta_id'] = $value['goo_unta_id'];
                    $orgo_data['orgo_goo_quantity'] = $value['goo_quantity'];
                    $orgo_data['orgo_goo_price'] = $value['goo_price'] * 100;
                    $orgo_data['orgo_goo_amount'] = $value['goo_quantity']*$value['goo_price'] * 100;
                    $orgo_data['orgo_can_assign_quantity'] = $value['goo_quantity'];
                    // 查询商品积分
                    if ($value['goo_type'] == 1) {// 实物商品
                        $pogo_goo_type = 2;
                    } else {
                        $pogo_goo_type = 1;
                    }
                    $orgo_goo_point = DB::table('point_goods')  
                        ->where('pogo_shop_id', $user_info->adm_shop_id)
                        ->where('pogo_goo_type', $pogo_goo_type)
                        ->where('pogo_enable', 1)
                        ->where('pogo_goo_id', $value['goo_id'])
                        ->value('pogo_goo_point');
                    $orgo_data['orgo_goo_point'] = $orgo_goo_point;
                    $orgo_data['orgo_update_time'] = date('Y-m-d H:i:s');
                    //$orgo_data['orgo_is_mem_price'] = $orgo_is_mem_price;// 20231124  pc会员价格下单暂时屏蔽
                    $orgo_id = DB::table('order_goods')->insertGetId($orgo_data);
                    $goods_data[$key]['orgo_id'] = $orgo_id; //立即派单使用
                    if ($value['goo_type'] == 1) {//实物类
                        $value['orgo_id'] = $orgo_id;
                        $new_goods_data[] = $value;
                    }
                    if ($value['goo_quantity']) {
                        $goo_all_quantity += $value['goo_quantity']; //商品总数量
                        if ($value['goo_type'] == 1) {
                            $new_goo_all_quantity += $value['goo_quantity']; //商品总数量
                        }
                    }
                }
                $goo_all_price += $value['goo_price'] * $value['goo_quantity']; //商品总金额
            }
            if ($ord_add_work_state == 1) {
                $find_imco = DB::table('image_config')
                    ->where('imco_type', 1)
                    ->get()->toArray();
                foreach ($find_imco as $kf => $vf) {
                    $add_imdata['vaca_shop_id'] = $user_info->adm_shop_id;
                    $add_imdata['vaca_ord_id'] = $ord_id;
                    $add_imdata['vaca_type'] = 1;
                    $add_imdata['vaca_name'] = $vf->imco_name;
                    $add_imdata['vaca_data_id'] = $vf->imco_id;
                    if (in_array($vf->imco_id, $image_id)) {
                        $add_imdata['vaca_must'] = 1;
                    } else {
                        $add_imdata['vaca_must'] = 2;
                    }
                    $add_imdata['vaca_create_time'] = date('Y-m-d H:i:s');
                    $add_imdata['vaca_create_id'] = $user_info->adm_id;
                    $im_res = DB::table('wash_validate_car')->insert($add_imdata);
                }

                $find_com_img = DB::table('image_config')
                    ->where('imco_type', 2)
                    ->get()->toArray();
                foreach ($find_com_img as $kf => $vf) {
                    $add_comdata['coin_shop_id'] = $user_info->adm_shop_id;
                    $add_comdata['coin_ord_id'] = $ord_id;
                    $add_comdata['coin_type'] = 3;
                    $add_comdata['coin_name'] = $vf->imco_name;
                    $add_comdata['coin_data_id'] = $vf->imco_id;
                    $add_comdata['coin_create_time'] = date('Y-m-d H:i:s');
                    $add_comdata['coin_create_id'] = $user_info->adm_id;
                    if (in_array($vf->imco_id, $image_id)) {
                        $add_comdata['coin_must'] = 1;
                        $co_res = DB::table('completion_info')->insert($add_comdata);
                    }
                }
            }
            $ord_edit_data['ord_order_price'] = $goo_all_price * 100;
            $mem_points_multiple = 1;
            $mem_price = WashOrderBasicService::mem_price($request,$user_info);
            if($mem_price['code'] == 200){
                $mem_points_multiple = $mem_price['data']['meml_points_multiple'];
            }
            if (empty($request['ord_payment_way']) || $request['ord_payment_way'] == 8) {//暂不结算或者账期
                $ord_edit_data['ord_actual_price'] = 0;
            }
            if ($request['ord_payment_way'] != 9 && !empty($request['ord_payment_way']) && $request['ord_payment_way'] != 8) {
                $ord_edit_data['ord_actual_price'] = $goo_all_price * 100; //结算金额
            }
            if ($request['ord_payment_way'] == 9) {
                if ($request['ord_actual_amout'] == $goo_all_price) {
                    $ord_edit_data['ord_state'] = 2;
                }
                $ord_edit_data['ord_actual_price'] = $request['ord_actual_amout']*100;
            }

            $ord_edit_data['ord_goods_quantity'] = $goo_all_quantity;
        } else {
            return ['code' => 500, 'msg' => '请选择产品或服务', 'data' => '请选择产品或服务'];
        }
        
        $order_client_data['orcl_ord_id'] = $ord_id; //订单id
        $order_client_data['orcl_client_id'] = $request['ord_client_id']; //订单id
        $order_client_data['orcl_name'] = $request['orcl_name']; //客户姓名
        $order_client_data['orcl_phone'] = $request['orcl_phone']; //客户电话
        $order_client_data['orcl_carowner_name'] = $request['orcl_name']; //客户姓名
        $order_client_data['orcl_carowner_phone'] = $request['orcl_phone']; //客户电话
        $order_client_data['orcl_province'] = $request['orcl_province']; //省
        $order_client_data['orcl_city'] = $request['orcl_city']; //市
        $order_client_data['orcl_county'] = $request['orcl_county']; //区县
        $order_client_data['orcl_appoint_time'] = $request['orcl_appoint_time']; //预约时间
        $order_client_data['orcl_car_num'] = $request['orcl_car_num']; //车牌号
        $order_client_data['orcl_car_vin'] = $request['orcl_car_vin']; //车牌号
        $order_client_data['orcl_car_brand_series'] = $request['orcl_car_brand_series']; //车牌号
        $order_client_data['orcl_address'] = $request['orcl_address']; //详细地址
        $order_client_data['orcl_mem_source'] = $request['orcl_mem_source']; //会员来源
        $order_client_data['orcl_order_type'] = 3; //1系统订单2外派订单3速电派单
        $orcl_id = DB::table('order_client')->insertGetid($order_client_data);
        if (!empty($request['orcl_car_num']) && $request['ord_type'] == 1 && !empty($request['ord_client_id'])) {
            $request['shop_id'] = $user_info->adm_shop_id;
            $request['weus_id'] = DB::table('user_shop')
                ->where('ussh_user_id', $request['ord_client_id'])
                ->where('ussh_shop_id', $user_info->adm_shop_id)
                ->value('ussh_weus_id');
            $request['meca_car_num'] = $request['orcl_car_num'];
            $request['meca_car_brand_series'] = isset($request['orcl_car_brand_series']) ? $request['orcl_car_brand_series'] : ''; //品牌车系
            $request['meca_car_frame'] = $request['orcl_car_vin'];
            $exist = MemberCarService::nameExists($request['meca_car_num'], $request['shop_id'], $request['weus_id']);
            if (!$exist) {
                $meca_data['meca_cid'] = $user_info->adm_cid;
                $meca_data['meca_superior_shop_id'] = $user_info->adm_superior_shop_id;
                $meca_data['meca_mem_id'] = $request['ord_client_id'];
                $meca_data['meca_shop_id'] = $request['shop_id'];
                $meca_data['meca_car_num'] = $request['meca_car_num'];
                if (!empty($request['meca_car_brand_series'])) {//品牌车系
                    $meca_data['meca_car_brand_series'] = $request['meca_car_brand_series'];
                }
                if (!empty($request['meca_car_frame'])) {//车架号
                    $meca_data['meca_car_frame'] = $request['meca_car_frame'];
                } else {
                    $meca_data['meca_car_frame'] = '';
                }
                $meca_data['meca_update_time'] = date('Y-m-d H:i:s');
                $return_car_data = DB::table('member_car')->insert($meca_data);
                // $return_car_data = MemberCarService::add($request);
            } else {
                $return_car_data = true;
            }
        } else {
            $return_car_data = true;
        }
        // 不生成工单流程
        if ($ord_add_work_state == 2) {
            // 买家类型：1门店零售2客户单位3速电派单4第三方派单5运营中心给门店派单
            // 判断是否为散户，ord_type为空值，是散户
            if (empty($request['ord_type'])) {
                // 散户开单流程
                $order_data['data']['ord_order_number'] = $ord_order_number;
                $order_data['data']['ord_id'] = $ord_id;
                $order_data['data']['shop_id'] = $user_info->adm_shop_id;
                $order_data['data']['ord_type'] = 0;
                $order_data['data']['ord_client_id'] = 0;
                if ($ware_id && $is_goods) {//选择仓库并且选择产品
                    $ord_edit_data['ord_wor_state'] = 2;//服务中
                    $request['service_shop_id'] = $user_info->adm_shop_id;
                    $dibi_data = DispatchBill::create(
                        $user_info,   //用户信息
                        $request,  //订单提交数据
                        $new_goods_data,  //提交的商品数据
                        1,  //类型：1.订单发货 2.工单发货
                        $ware_id,  //出库仓库id
                        $order_data['data']['ord_order_number'],  //原始单号，订单号/工单号
                        $order_data['data']['ord_id'],  //发货单关联的工单/订单id
                        $order_data['data']['shop_id'],  //所属总店id
                        $order_data['data']['ord_type'],  //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                        $order_data['data']['ord_client_id'],  //选择的客户id,会员id/单位id
                        $new_goo_all_quantity  //发货总数量
                    );
                    if ($dibi_data['code'] == 500) {
                        return $dibi_data;
                    }
                } else {
                    $ord_edit_data['ord_wor_state'] = 20;//已完成
                }
            } else {
                // 不是散户，未选择产品或未选择仓库，生成订单，订单状态为待评价状态
                // 不是散户，选择产品并且选择仓库，生成订单，订单状态是服务中，生成发货单
                $order_data['data']['ord_order_number'] = $ord_order_number;
                $order_data['data']['ord_id'] = $ord_id;
                $order_data['data']['shop_id'] = $user_info->adm_shop_id;
                $order_data['data']['ord_type'] = $request['ord_type'];
                $order_data['data']['ord_client_id'] = $request['ord_client_id'];
                if ($ware_id && $is_goods) {//选择仓库并且选择产品
                    $ord_edit_data['ord_wor_state'] = 2;//服务中
                    $request['service_shop_id'] = $user_info->adm_shop_id;
                    $dibi_data = DispatchBill::create(
                        $user_info,   //用户信息
                        $request,  //订单提交数据
                        $new_goods_data,  //提交的商品数据
                        1,  //类型：1.订单发货 2.工单发货
                        $ware_id,  //出库仓库id
                        $order_data['data']['ord_order_number'],  //原始单号，订单号/工单号
                        $order_data['data']['ord_id'],  //发货单关联的工单/订单id
                        $order_data['data']['shop_id'],  //所属总店id
                        $order_data['data']['ord_type'],  //买家类型：1.会员零售2.客户单位3.速电派单4.第三方派单
                        $order_data['data']['ord_client_id'],  //选择的客户id,会员id/单位id
                        $new_goo_all_quantity  //发货总数量
                    );
                    if ($dibi_data['code'] == 500) {
                        return $dibi_data;
                    }
                } else {
                    $ord_edit_data['ord_wor_state'] = 4;//待评价
                    if (empty($request['orcl_phone'])) {
                        $ord_edit_data['ord_wor_state'] = 20;//已完成
                    }
                    
                }
            }
            $ord_edit_data['ord_service_type'] = 2;//洗车-不生成工单的订单
        }
        //添加支付明细
        if(!in_array($request['ord_payment_way'], [0,8])) {
            OrderSettlementDetails::addOrderSettlementDetails($ord_id, $request['ord_type'], $request, $user_info, $ord_edit_data['ord_actual_price'], 0);
        }
        $ord_edit_data['ord_add_work_state'] = $ord_add_work_state;
        $ord_edit_data['ord_orcl_id'] = $orcl_id;
        $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_edit_data['ord_client_id'] = $request['ord_client_id'];
        $ord_edit_res = NewOrderService::editOrder($ord_id,$ord_edit_data);
        //个人会员下服务单更新会员下单时间
        if(isset($request['ord_type']) && $request['ord_type'] == 1){
            WashOrderBasicService::updateOrderCount($request['ord_client_id']);
        }
        //计算会员消费总金额
        if($request['ord_type'] == 1 && !empty($request['ord_client_id'])){
            WashOrderService::consume_money($request['ord_client_id']);
        }
        if (!empty($request['orcl_phone'])) {
            // 查询手机号是否存在
            $find_weixin_data = DB::table('user_shop')
                ->leftJoin('weixin_user','ussh_weus_id', '=', 'weus_id')
                ->where('ussh_phone', $request['orcl_phone'])
                ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
                ->first();
            if ($find_weixin_data) {
                $weus_id = $find_weixin_data->weus_id;
            } else {
                $weus_id = 0;
            }
        } else {
            $weus_id = 0;
        }
        if ($request['ord_type'] == 1) {
            if ($weus_id) {
                // 添加客户消息
                $add_data['weus_id'] = $weus_id;
                $add_data['shop_id'] = $user_info->adm_shop_id;
                $add_data['primary_id'] = $ord_id; //单据的主键id
                $add_data['primary_type'] = 1; //单据类型：1订单2工单3预约单4售后单
                $add_data['read_state'] = 1; //阅读状态：1未读2已读
                $add_data['title'] = '预约成功通知'; //消息标题
                $add_data['content'] = '您申请的服务已预约成功，我们会尽快处理，请耐心等待'; //操作内容'.$value['sepr_name'].'
                $add_data['create_adm_name'] = $user_info->adm_name; //操作人姓名
                $add_data['create_adm_id'] = $user_info->adm_id; //操作人id
                $addUserMessage_res = addUserMessage($add_data);
                unset($add_data);
            }

            if (isset($request['send']) && $request['send'] == 1) {
                // 2.给相应的客户发送短信
                if (isset($request['orcl_phone']) && !empty($request['orcl_phone'])) {
                    $phone = $request['orcl_phone'];
                    $message = '【半径服务】尊敬的客户您好，您申请的服务已预约成功，请登录(半径服务)小程序查看';
                    if (preg_match("/^1[3456789]\d{9}$/", $phone)) {
                        $find_shop_data = DB::table('shop')
                            ->where('shop_id', $user_info->adm_shop_id)
                            ->first();
                        if ($find_shop_data->shop_message_num <= 0) {
                            $send_state = 2;
                            $send_res = 0;
                        } else {
                            $msg_remind_log = DB::table('msg_remind_log')
                                ->where('mrlo_shop_id', $user_info->adm_shop_id)
                                ->where('mrlo_state', 2)
                                ->first();
                            if ($msg_remind_log) {//已提醒过
                                if ($find_shop_data->shop_message_num > $find_shop_data->shop_msg_remind) {
                                    $update_remind['mrlo_state'] = 1;
                                    $msg_remind_log = DB::table('msg_remind_log')
                                        ->where('mrlo_shop_id', $user_info->adm_shop_id)
                                        ->where('mrlo_state', 2)
                                        ->update($update_remind);
                                }
                            }
                            $msg_remind_log = DB::table('msg_remind_log')
                                ->where('mrlo_shop_id', $user_info->adm_shop_id)
                                ->where('mrlo_state', 2)
                                ->first();

                            if (($find_shop_data->shop_message_num-1) <= $find_shop_data->shop_msg_remind && empty($msg_remind_log) && $find_shop_data->shop_msg_adm_id) {
                                $adm_data = DB::table('admin')->where('adm_id', $find_shop_data->shop_msg_adm_id)->first();
                                // $wechat_msg['pushtype'] = 5; //短信预警
                                // $wechat_msg['adm_id'] = $find_shop_data->shop_msg_adm_id; //推送人
                                // $wechat_msg['user_data'] = $adm_data->adm_name; //姓名
                                // $wechat_msg['tittle'] = '剩余短信不足'.$find_shop_data->shop_msg_remind.'条，请及时充值'; //提醒消息
                                // $wechat_msg['remark'] = '短信不足预警';
                                // $CashierDesk = new CashierDesk;
                                // $wechat_msg_res = $CashierDesk->inforPush($wechat_msg);
                                $remind_phone = $adm_data->adm_phone;
                                $remind_content = '【半径服务】 您的门店短信余额不足'.$find_shop_data->shop_msg_remind.'条，请及时充值';
                                $remind_send_res = sendSmsCode($remind_phone, $remind_content);
                                if ($remind_send_res > 0) {
                                    $send_state = 1;
                                    $add_remind['mrlo_shop_id'] = $user_info->adm_shop_id;
                                    $add_remind['mrlo_state'] = 2;//未充值，
                                    $add_remind['mrlo_adm_id'] = $find_shop_data->shop_msg_adm_id;
                                    $add_remind['mrlo_num'] = $find_shop_data->shop_msg_remind;
                                    $add_remind['mrlo_create_time'] = date('Y-m-d H:i:s');
                                    $add_remind['mrlo_create_id'] = $user_info->adm_id;
                                    $reming_res = DB::table('msg_remind_log')->insertGetId($add_remind);
                                } else {
                                    $send_state = 2;
                                }
                                // 短信模块日志
                                $seme_data['seme_cid'] = $user_info->adm_cid; //公司id
                                $seme_data['seme_shop_id'] =$user_info->adm_shop_id; //门店id
                                $seme_data['seme_wor_id'] = 0; //订单id
                                $seme_data['seme_name'] = '短信不足预警'; //模板名称
                                $seme_data['seme_phone'] = $remind_phone; //手机号
                                $seme_data['seme_content'] = $remind_content; //内容
                                $seme_data['seme_row'] = 1; //条数
                                $seme_data['seme_status_code'] = $remind_send_res; //短信状态码
                                $seme_data['seme_state'] = $send_state; //状态：1成功2失败
                                $seme_data['seme_ip'] = $request['ip']; //ip地址
                                $seme_data['seme_adm_id'] = $user_info->adm_id; //创建人id
                                $seme_id = DB::table('send_message')->insert($seme_data);
                            }
                            $send_res = sendSmsCode($phone, $message);
                            if ($send_res > 0) {
                                $send_state = 1;
                                $update_shop = DB::table('shop')
                                    ->where('shop_id', $user_info->adm_shop_id)
                                    ->update(['shop_message_num'=>$find_shop_data->shop_message_num - 1]);
                            } else {
                                $send_state = 2;
                            }
                        }
                        
                        // 短信模块日志
                        $seme_data['seme_cid'] = $user_info->adm_cid; //公司id
                        $seme_data['seme_shop_id'] = $user_info->adm_shop_id; //门店id
                        $seme_data['seme_wor_id'] = $ord_id; //订单id
                        $seme_data['seme_name'] = '预约成功通知'; //模板名称
                        $seme_data['seme_phone'] = $phone; //手机号
                        $seme_data['seme_content'] = $message; //内容
                        $seme_data['seme_row'] = 1; //条数
                        $seme_data['seme_status_code'] = $send_res; //短信状态码
                        $seme_data['seme_state'] = $send_state; //状态：1成功2失败
                        $seme_data['seme_ip'] = $request['ip']; //ip地址
                        $seme_data['seme_adm_id'] = $user_info->adm_id; //创建人id
                        $seme_id = DB::table('send_message')->insert($seme_data);
                        $find_member = DB::table('member')
                            ->where('mem_shop_id', $user_info->adm_shop_id)
                            ->where('mem_phone', $phone)
                            ->first();
                        $add_log['smlo_shop_id'] = $user_info->adm_shop_id;
                        $add_log['smlo_mem_type'] = 2;//1业务人员2会员
                        $add_log['smlo_mem_id'] = $find_member->mem_id;
                        $add_log['smlo_mem_name'] = $find_member->mem_name;
                        $add_log['smlo_mem_phone'] = $phone;
                        $add_log['smlo_type'] = 2;
                        $add_log['smlo_create_time'] = date('Y-m-d H:i:s');
                        $add_log['smlo_state'] = $send_state;
                        $add_log['smlo_msg_type'] = 4;
                        $add_log['smlo_num'] = 1;
                        $add_log['smlo_content'] = $message; //内容
                        $add_log_res = DB::table('sms_log')->insertGetId($add_log);
                    }
                }
            }
        }

        if ($user_info->shop_versions == 2 && $ord_add_work_state == 1) {//企业版有排班计划
            // 添加排班计划
            $wopl_data['wopl_shop_id'] = $user_info->adm_shop_id;
            $wopl_data['wopl_ord_id'] = $ord_id;
            $wopl_data['wopl_sepr_id'] = $sepr_id;
            $wopl_data['wopl_sepr_name'] = $sepr_name;
            $wopl_data['wopl_goo_id'] = $goo_id;
            $wopl_data['wopl_goo_name'] = $goo_name;
            $wopl_data['wopl_address_id'] = $request['ord_address_id'];
            $wopl_data['wopl_address'] = $request['ord_address'];
            $wopl_data['wopl_address_type'] = $request['ord_address_type'];
            if (isset($request['orcl_sales_adm_id'])) {
                $find_adm = DB::table('admin')->where('adm_id', $request['orcl_sales_adm_id'])->value('adm_name');
            } else {
                $find_adm = '';
            }
            $wopl_data['wopl_sale_name'] = $find_adm;
            $wopl_data['wopl_sale_id'] = isset($request['orcl_sales_adm_id']) ? $request['orcl_sales_adm_id'] : '';
            $wopl_data['wopl_explain'] = isset($request['ord_explain']) ? $request['ord_explain'] : '';
            $wopl_data['wopl_time'] = isset($request['orcl_appoint_time']) ? date('H:i:s', strtotime($request['orcl_appoint_time'])) : '';
            $wopl_data['wopl_date'] = isset($request['orcl_appoint_time']) ? date('Y-m-d', strtotime($request['orcl_appoint_time'])) : '';
            // $wopl_data['wopl_service_id'] = ','.$service_adm_id.',';
            $wopl_data['wopl_create_time'] = date('Y-m-d H:i:s');
            $wopl_id = DB::table('work_plan')->insertGetId($wopl_data);
        }
        $find_ord_data = DB::table('order')
            ->where('ord_id', $ord_id)
            ->select('ord_state', 'ord_wor_state', 'ord_type')
            ->first();
        if ($find_ord_data->ord_state == 2 && ($find_ord_data->ord_wor_state == 4 || $find_ord_data->ord_wor_state == 20) && $find_ord_data->ord_type == 1) {//已结算 待评价或已完成 个人会员 添加积分
            $add_point = WashOrderBasicService::addPoint($user_info,$request['ord_client_id'],$ord_id,$mem_points_multiple);
        }
        if ($ord_id && $orcl_id && $ord_edit_res && $return_car_data) {
            $return_data['ord_id'] = $ord_id; //订单id
            $return_data['ord_order_number'] = $ord_order_number; //订单单号
            // $return_data['goods_data'] = json_encode($goods_data); //商品信息
            // $return_data['ord_type'] = $request['ord_type']; //买家类型1.会员零售2.合作商
            // $return_data['ord_client_id'] = isset($request['ord_client_id']) ? $request['ord_client_id'] : 0; //选择的客户id,会员id/单位id
            if ($only_goods && $ware_id && $is_goods) {
                //发货通知
                // 微信消息推送
                if(isset($request['orcl_sales_adm_id'])){
                    $admin = DB::table('admin')->where("adm_id",$request['orcl_sales_adm_id'])->select('adm_phone','adm_name')->first();
                    if($admin){
                        $user_data = $admin->adm_name."  ".$admin->adm_phone;
                    }else{
                        $user_data = '未选择销售人员';
                    }
                }else{
                    $user_data = '未选择销售人员';
                }
                $ware_leader_id = DB::table('warehouse')->where("ware_id",$ware_id)->value('ware_leader_id');
                if($ware_leader_id) {
                    $ware_leader_id = explode(',', $ware_leader_id);
                    foreach($ware_leader_id as $k => $v){
                        $wechat_msg['pushtype'] = 2; //发货推送
                        $wechat_msg['dego_id'] = $dibi_data['dego_id']??0; //发货推送
                        $wechat_msg['adm_id'] = $v; //推送人  ord_ware_id  ware_leader_id
                        $wechat_msg['wor_number'] = ""; //工单号
                        $wechat_msg['ord_number'] = $ord_data['ord_order_number']; //订单号
                        $wechat_msg['user_data'] = $user_data; //姓名
                        $wechat_msg['user_dress'] = $ord_data['ord_address']; //详细地址
                        $wechat_msg['tittle'] = '您有新的发货申请，请及时处理'; //手机
                        $wechat_msg['remark'] = '请确认信息，如有变动，请联系收货人';
                        $CashierDesk = new CashierDesk;
                        $wechat_msg_res = $CashierDesk->inforPush($wechat_msg);
                    }
                }
            }
            //20230724  添加订单应收应付
            $recpay_receivable_price = $goo_all_price * 100;//应收金额
            $recpay_actual_price = 0;//默认实收金额为0
            $recpay_arrears_price = $recpay_receivable_price - $recpay_actual_price;//欠收金额 = 应收金额 - 实收金额
            //支付方式为1.现金2.支付宝 3微信 4银行卡  的实收金额
            /*if (in_array($request['ord_payment_way'],[1,2,3,4])) {
                $recpay_actual_price = $goo_all_price * 100; //实收金额
                $recpay_arrears_price = 0;
            }else if(in_array($request['ord_payment_way'],[5,6])){
                $recpay_arrears_price = 0;
            }*/
            /*if(in_array($request['ord_payment_way'],[5,6])){//会员卡
                if(isset($ord_edit_data['ord_payment_money'])){
                    $recpay_actual_price = $ord_edit_data['ord_payment_money'] ;//实收金额
                }else{
                    $recpay_actual_price = 0;//实收金额
                }
                $recpay_arrears_price = 0;//欠收金额
            } elseif($request['ord_payment_way'] == 9){//部分结款
                $recpay_actual_price = $request['ord_actual_amout']*100;//实收金额
                $recpay_arrears_price = $outstanding_amount;//欠收金额
            } else*/
            if($request['ord_payment_way'] > 0 && $request['ord_payment_way'] != 9){
                if(isset($ord_edit_data['ord_payment_money'])){
                    $recpay_actual_price = $ord_edit_data['ord_payment_money'] ;//实收金额
                }else{
                    $recpay_actual_price = $recpay_receivable_price ;//实收金额
                }
                $recpay_arrears_price = 0;//欠收金额
            }
            $recpay_cost_price = 0;//成本价
            if(isset($goods_price)){
                foreach ($goods_price as $g_k => $g_v){
                    $recpay_cost_price += $g_v['price'] * $g_v['quantity'] * 100;
                }
            }
            $profit = $recpay_actual_price - $recpay_cost_price;
            if($profit > 0){
                $minus = 1;
            }else{
                $minus = 2;
                $profit = abs($profit);
            }
            //企业信息
            $type_id =isset($request['ord_client_id']) ? $request['ord_client_id'] : 0;
            $type_name = isset($request['orcl_business_name']) ? $request['orcl_business_name'] : $request['orcl_name'];
            $rece_params = [
                'recpay_type'=>1,//类型：1销售订单2充值卡
                'recpay_original_id'=>$ord_id,//订单id
                'recpay_original_number'=>$ord_order_number,//订单号
                'recpay_client_type'=>$request['ord_type'], //买家类型：0散户1门店零售2企业客户
                'recpay_cid'=>$user_info->adm_cid,
                'recpay_shop_id'=>$user_info->adm_shop_id,
                'recpay_shop_superior_id'=>$user_info->adm_shop_id,
                'recpay_client_id'=>$type_id,//
                'recpay_client_name'=>$type_name,
                'recpay_receivable_price'=>$recpay_receivable_price,//应收金额
                'recpay_arrears_price'=>$recpay_arrears_price,//欠收金额
                'recpay_actual_price'=>$recpay_actual_price,//实收金额
                'recpay_cost_price'=>$recpay_cost_price,//成本价
                /*'recpay_receivable_pay'=>0,//应付金额
                'recpay_actual_pay'=>0,//实付金额*/
                'recpay_state'=>1,//状态：1未确认2已确认
                'recpay_order_state'=>1,//订单状态：1正常2退款3取消
                'recpay_plus_minus'=>$minus,//盈利正负：1正值2负值
                'recpay_profit'=>$profit,//盈利金额
            ];
            ReceivablePayService::add($rece_params);
            return ['code' => 200, 'msg' => '新增成功', 'data' => $return_data];
        } else {
            return ['code' => 500, 'msg' => '新增失败', 'data' => '新增失败'];
        }
    }
}
