<?php
namespace App\Http\Models\Api;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\Push\PushMessageController;

use App\Http\Models\Api\StockSellStorageGoods;
use App\Http\Models\Api\SellDetail;
use App\Http\Models\Api\Warehouse;
use App\Http\Models\Services\ImageUpload;
use App\Services\Business\WashOrderService;

class Order extends Model
{
    /**
     * [createOrder 创建订单]
     * @param  [type]  $user_info [用户信息]
     * @param  [type]  $request   [订单数据]
     * @param  integer $type      [类型1生成订单2生成订单+生成工单]
     * @return [type]             [description]
     */
    public static function createOrder(
        $user_info,
        $request,
        $type = 1
    ) {
        if (empty($request['ord_unique_string'])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'生成订单验证密钥未提交，请刷新页面或重新登录系统！'];
        }
        // 判断唯一标识是否存在
        $find_unique = DB::table('order')
            ->where('ord_unique_string', $request['ord_unique_string'])
            ->value('ord_unique_string');
        if ($find_unique){
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前订单已提交，请勿重复操作！'];
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $request['orcl_phone'] = isset($request['orcl_phone']) ? $request['orcl_phone'] : '';
        // 添加订单数据
        // 1. 添加订单表数据
        $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'] = $shop_id;
        $ord_data['ord_create_id'] = $user_info->adm_id;
        // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        if (in_array($request['ord_service_type'], [4,5,6])) {
            // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成5无工单
            // 退货单、发货单、结清单 不需要技师，为无工单状态
            $ord_data['ord_wor_state'] = 5;
        }

        $ord_data['ord_ware_id'] = isset($request['ware_id']) ? $request['ware_id'] : ''; //仓库id
        $ord_data['ord_client_id'] = isset($request['ord_client_id']) ? $request['ord_client_id'] : 0; //选择客户id
        $ord_data['ord_order_number'] = $ord_order_number; //订单号
        //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
        $ord_data['ord_service_type'] = $request['ord_service_type'];
        $ord_data['ord_payment_way'] = $request['ord_payment_way']; // 结算方式1.账期 2.现结 3微信 4支付宝
        $ord_data['ord_type'] = $request['ord_type']; // 买家类型：1门店零售2渠道单位
        $ord_data['ord_remark'] = isset($request['ord_remark']) ? $request['ord_remark'] : ''; //订单备注
        if ($type == 2) {
            // 生成订单，同时生成工单
            $ord_data['ord_wor_quantity'] = 1; //工单数量
            $ord_data['ord_wor_state'] = 2; //订单的工单状态1未派工单2服务中3售后中4已完成
        }

        $ord_data['ord_service_adm_id'] = isset($request['service_adm_id']) ? $request['service_adm_id'] : 0; //服务技师id
        $ord_data['ord_service_sepr_id'] = isset($request['service_sepr_id']) ? $request['service_sepr_id'] : 0; //服务项目id
        // 服务门店为0的话 是当前门店id
        if ($request['service_shop_id'] == 0) {
            $ord_data['ord_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
        } else {
            $ord_data['ord_service_shop_id'] = $request['service_shop_id']; //服务门店id
        }
        $ord_data['ord_acti_id'] = isset($request['ord_acti_id']) ? $request['ord_acti_id'] : 0; //活动id
        $ord_data['ord_acti_row'] = isset($request['ord_acti_row']) ? $request['ord_acti_row'] : 0; //活动条数
        //出库方式虚拟加盟店
        if ($request['orcl_shipment_party'] == 4) {
            $ord_data['ord_form_type'] = 2;
        }
        $ord_data['ord_unique_string'] = $request['ord_unique_string'];//生成订单的唯一标识
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_id = DB::table('order')->insertGetId($ord_data);
        // 救援单的服务项目金额
        $orcl_rescue_service_price = isset($request['orcl_rescue_service_price']) ? $request['orcl_rescue_service_price'] : 0;
        // 救援单的代收金额
        $orcl_rescue_collection_price = isset($request['orcl_rescue_collection_price']) ? $request['orcl_rescue_collection_price'] : 0;
        if ($request['ord_type'] == '2') {
            $chun_adm_id = DB::table('channel_unit')
                ->where('chun_id', $request['ord_client_id'])
                ->value('chun_adm_id');
        } else {
            $chun_adm_id = 0;
        }

        // 添加订单客户表数据
        $orcl_data = [
            'orcl_ord_id' => $ord_id,
            'orcl_client_id' => isset($request['ord_client_id']) ? $request['ord_client_id'] : 0, //选择客户id
            'orcl_adm_id' => $chun_adm_id, //业务员id
            'orcl_channel_unit' => isset($request['orcl_channel_unit']) ? $request['orcl_channel_unit'] : '',
            'orcl_name' => $request['orcl_name'],
            'orcl_phone' => $request['orcl_phone'],
            'orcl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
            'orcl_province' => $request['orcl_province'],
            'orcl_city' => $request['orcl_city'],
            'orcl_county' => $request['orcl_county'],
            'orcl_address' => $request['orcl_address'],
            'orcl_chin_type' => isset($request['chin_type']) ? $request['chin_type'] : 2, //铺货类型：1是铺货 2不是铺货
            'orcl_collect_state' => isset($request['orcl_collect_state']) ? $request['orcl_collect_state'] : 0,
            // 救援单的服务项目金额 
            'orcl_rescue_service_price' => $orcl_rescue_service_price * 100,
            // 救援单的代收金额
            'orcl_rescue_collection_price' => $orcl_rescue_collection_price * 100,
            'orcl_update_time' => date('Y-m-d H:i:s'),
            'orcl_standby_battery_type' => isset($request['orcl_standby_battery_type']) ? $request['orcl_standby_battery_type'] : 2,//是否为备用电池1是2否
            'orcl_shipment_party' => isset($request['orcl_shipment_party']) ? $request['orcl_shipment_party'] : '',//出库方1仓库2直营店3加盟店
            'orcl_car_vehicle_type' => isset($request['orcl_car_vehicle_type']) ? $request['orcl_car_vehicle_type'] : '',//车型
            'orcl_junk_type' => isset($request['orcl_junk_type']) ? $request['orcl_junk_type'] : 2,//是否为旧货1是2否
            'orcl_whether_app' => isset($request['whether_app']) ? $request['whether_app'] : 1,//是否走技师流程1是2否
            'orcl_precise_lock' => isset($request['precise_lock']) ? $request['precise_lock'] : 2,//精确打卡1是 2否
        ];

        if (isset($request['orcl_rescue_assign_price'])) {
            $orcl_data['orcl_rescue_assign_price'] = $request['orcl_rescue_assign_price'] * 100;
        } else {
            $orcl_data['orcl_rescue_assign_price'] = 0;
        }
        if (isset($request['orcl_appoint_time'])) {
            $orcl_data['orcl_appoint_time'] = $request['orcl_appoint_time'];//预约时间
        }

        // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
        if (in_array($request['ord_service_type'], [1, 7])) {
            // 订单类型为服务单、救援单的有图片上传模板，根据订单类型，获取当前门店的图片上传模板
            $image_manager = new ImageUpload();
            $find_shit_id = $image_manager->getOrderTypeImageTemplate($user_info->adm_shop_id, $request['ord_service_type']);
            $orcl_data['orcl_shit_id'] = $find_shit_id;//图片模板id
        }
        $orcl_id = DB::table('order_client')->insertGetId($orcl_data);

        // 选择的客户id，对应的订单数量增加
        if ($request['ord_client_id']) {
            if ($request['ord_type'] == 1) {
                // 零售，会员表
                $client_res = DB::table('member')
                    ->where('mem_id', $request['ord_client_id'])
                    ->increment('mem_order_all');
            } else {
                $client_res = true;
            }
        } else {
            $client_res = true;
        }

        // 添加订单商品表数据
        $goo_all_quantity = 0; //商品总数量
        $goo_all_price = 0; //商品总金额
        $goo_assign_all_price = 0; //派单商品总金额
        $goo_collection_price = 0; //商品代收总金额
        $n = 0;
        $goo_state = 1; //商品状态
        $recycle_all_price = 0; //订单回收金额
        $goo_order_price = 0; //订单总金额
        // 订单类型：7救援单，查询服务项目的订单金额
        if ($request['ord_service_type'] == 7) {
            // 没有添加商品数据
            if (empty($request['goo_id'])) {
                // 4. 更改订单表客户id、订单金额
                $ord_edit_data['ord_orcl_id'] = $orcl_id;
                $ord_edit_data['ord_plus_minus'] = 1; //金额正负：1正值2负值
                $ord_edit_data['ord_order_price'] = $orcl_rescue_service_price * 100; // 订单金额（单位：分）
                $ord_edit_data['ord_actual_price'] = $orcl_rescue_service_price * 100; // 结算金额（单位：分）
                $ord_edit_data['ord_goods_quantity'] = 0; // 商品总数量
                $ord_edit_data['ord_collection_price'] = $orcl_rescue_collection_price * 100; //商品代收金额（单位：分）
                $ord_eidt_res = DB::table('order')
                    ->where('ord_id', $ord_id)
                    ->update($ord_edit_data);
                if ($ord_id && $orcl_id && $ord_eidt_res && $client_res) {
                    $return_data['ord_id'] = $ord_id;
                    $return_data['ord_order_number'] = $ord_order_number;
                    $return_data['shop_id'] = $shop_id; //总店id
                    return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
                } else {
                    return ['code'=>500, 'msg'=>'success', 'data'=>'生成订单失败'];
                }
            }
        }

        // 判断活动id是否存在,根据活动id查找对应的活动类型,商品信息
        // 判断商品id跟活动商品id是否一致,不一致,修改订单状态,审核
        if (isset($request['ord_acti_id']) && !empty($request['ord_acti_id'])) {
            $acti_res = DB::table('activity')
                ->where('acti_id', $request['ord_acti_id'])
                ->select('acti_id', 'acti_name', 'acti_activity_type')
                ->first();
            if ($acti_res->acti_activity_type == '1') { //折扣
                $acdi_goo_id = DB::table('activity_discount')
                    ->where('acdi_acti_id', $request['ord_acti_id'])
                    ->whereIn('acdi_goo_id', $request['goo_id'])
                    ->where('acdi_row', $request['ord_acti_row'])
                    ->select('acdi_id', 'acdi_goo_id', 'acdi_discount')
                    ->get();
                $acdi_goo_id = json_decode(json_encode($acdi_goo_id), true);
                $goods_id = array_column($acdi_goo_id, 'acdi_goo_id');
                $goods_data = array_column($acdi_goo_id, null, 'acdi_goo_id');
            } elseif ($acti_res->acti_activity_type == '2') { //买送
                $acdo_goo_id = DB::table('activity_donate')
                    ->where('acdo_acti_id', $request['ord_acti_id'])
                    ->whereIn('acdo_goo_id', $request['goo_id'])
                    ->where('acdo_row', $request['ord_acti_row'])
                    ->select('acdo_id', 'acdo_goo_id', 'acdo_gift_id', 'acdo_purchase_quantity', 'acdo_attached_quantity')
                    ->get();
                $acdo_goo_id = json_decode(json_encode($acdo_goo_id), true);
                $goods_id = array_column($acdo_goo_id, 'acdo_goo_id'); //商品id
                $gift_id = array_column($acdo_goo_id, 'acdo_gift_id'); //送品id
                $goods_data = array_column($acdo_goo_id, null, 'acdo_goo_id');
                $gift_data = array_column($acdo_goo_id, 'acdo_attached_quantity', 'acdo_gift_id');
            } elseif ($acti_res->acti_activity_type == '3') { //买赠
                $acdo_goo_id = DB::table('activity_donate')
                    ->where('acdo_acti_id', $request['ord_acti_id'])
                    ->whereIn('acdo_goo_id', $request['goo_id'])
                    ->where('acdo_row', $request['ord_acti_row'])
                    ->select('acdo_id', 'acdo_goo_id', 'acdo_gift_id', 'acdo_purchase_quantity', 'acdo_attached_quantity')
                    ->get();
                $acdo_goo_id = json_decode(json_encode($acdo_goo_id), true);
                $goods_id = array_column($acdo_goo_id, 'acdo_goo_id'); //商品id
                $gift_id = array_column($acdo_goo_id, 'acdo_gift_id'); //赠品id
                $goods_data = array_column($acdo_goo_id, null, 'acdo_goo_id');
                $gift_data = array_column($acdo_goo_id, 'acdo_attached_quantity', 'acdo_gift_id');
            } elseif ($acti_res->acti_activity_type == '4') { //满减
                $acdr_id = DB::table('activity_discount_reduction')
                    ->where('acdr_acti_id', $request['ord_acti_id'])
                    ->where('acdr_row', $request['ord_acti_row'])
                    ->select('acdr_id', 'acdr_reduction_price', 'acdr_credit_price')
                    ->get();
                $acdr_id = json_decode(json_encode($acdr_id), true);
                $reduction_price = array_column($acdr_id, 'acdr_reduction_price'); //满减金额(单位:分)
                $credit_price = array_column($acdr_id, 'acdr_credit_price'); //减免金额(单位:分)
            } elseif ($acti_res->acti_activity_type == '5') { //现结折扣
                $acdr_id = DB::table('activity_discount_reduction')
                    ->where('acdr_acti_id', $request['ord_acti_id'])
                    ->where('acdr_row', $request['ord_acti_row'])
                    ->select('acdr_id', 'acdr_reduction_price', 'acdr_discount')
                    ->get();
                $acdr_id = json_decode(json_encode($acdr_id), true);
                $reduction_price = array_column($acdr_id, 'acdr_reduction_price'); //满减金额(单位:分)
                $acdr_discount = array_column($acdr_id, 'acdr_discount'); //折扣
            } elseif ($acti_res->acti_activity_type == '7') { //高价回收
                $achr_goo_id = DB::table('activity_high_recycling')
                    ->where('achr_acti_id', $request['ord_acti_id'])
                    ->whereIn('achr_goo_id', $request['goo_id'])
                    ->select('achr_id', 'achr_goo_id', 'achr_recycle_quantity', 'achr_recycle_price')
                    ->get();
                $achr_goo_id = json_decode(json_encode($achr_goo_id), true);
                $goods_id = array_column($achr_goo_id, 'achr_goo_id');
                $goods_data = array_column($achr_goo_id, null, 'achr_goo_id');
            } elseif ($acti_res->acti_activity_type == '8') { //大批量采购
                $acpr_goo_id = DB::table('activity_procurement')
                    ->where('acpr_acti_id', $request['ord_acti_id'])
                    ->whereIn('acpr_goo_id', $request['goo_id'])
                    ->where('acpr_row', $request['ord_acti_row'])
                    ->select('acpr_id', 'acpr_goo_id', 'acpr_goods_quantity', 'acpr_recycle_quantity')
                    ->get();
                $acpr_goo_id = json_decode(json_encode($acpr_goo_id), true);
                $goods_id = array_column($acpr_goo_id, 'acpr_goo_id');
                $goods_data = array_column($acpr_goo_id, null, 'acpr_goo_id');
            }
        }

        if (count($request['goo_id']) != count(array_unique($request['goo_id']))) {
            if ($request['ord_service_type'] == 4) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'暂不支持换新商品与退货商品一致'];
            } else {
                return ['code'=>500, 'msg'=>'error', 'data'=>'暂不支持售卖商品跟备用电瓶一致'];
            }
        }
       
        if($request['orcl_shipment_party'] != 4 || $request['orcl_shipment_party'] != 5) {
            $request['ware_id'] = 0;
        }
        $real_data = [];//真实出库商品库存数据
        // 有商品数据
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['goo_waon_class'][$key]) || !is_numeric($request['goo_price'][$key]) || !is_numeric($request['goo_quantity'][$key]) || !in_array($request['goo_recycle'][$key], [1, 2]) || !is_numeric($request['goo_recycle_quantity'][$key]) || !is_numeric($request['goo_recycle_price'][$key]) || !in_array($request['goo_state'][$key], [1, 3, 4, 5, 6, 7, 8]) || !is_numeric($request['goo_collection_price'][$key]) || !in_array($request['goo_inventory'][$key], [1, 2])) {
                return ['code' => 500, 'msg' => 'error', 'data' => '商品参数类型错误'];
            }
            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value)
                ->select('goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price', 'goo_fid')
                ->first();

            //如果商品类型是赠品 并且不是虚拟加盟店
            if ($request['goo_state'][$key] == 5 && $request['orcl_shipment_party'] != 4) {
                $ware_return = Warehouse::obtain(
                    $request['goo_inventory'][$key],
                    $request['goo_waon_class'][$key],
                    $value,
                    $request['goo_quantity'][$key],
                    $find_goods_data->goo_fid,
                    isset($request['ware_id']) ? $request['ware_id'] : 0
                );
                if ($ware_return === false) {
                    return ['code' => 500, 'msg' => 'error', 'data' => '仓库内商品数量不足'];
                } elseif ($ware_return != $value) {
                    $request['goo_waon_class'][$key] = 1;
                    $value = $ware_return;
                    $request['goo_price'][$key] = 0;
                } else {
                    // return ['code' => 500, 'msg' => 'error', 'data' => '仓库内商品数量不足'];
                    $request['goo_waon_class'][$key];
                    $value = $ware_return;
                    $request['goo_price'][$key] = 0;
                }
            }
            if ($request['goo_recycle'][$key] == 1) {
                $recycle_all_price += $request['goo_recycle_quantity'][$key] * $request['goo_recycle_price'][$key]; //回收总金额
            }

            // 订单锁定库存，退货单、换货单的退回商品不需要判断
            if (config('apisystem.ORDER_LOCK_INVENTORY') && $request['ord_service_type'] != 4  && $request['goo_state'][$key] != 4 && $request['orcl_shipment_party'] != 4) {
                $real_stock_goods = Warehouse::getRealStockGoods(
                    $request['goo_inventory'][$key],
                    $request['goo_waon_class'][$key],
                    $value,
                    $request['goo_quantity'][$key],
                    $find_goods_data->goo_fid,
                    $request['goo_state'][$key],
                    isset($request['ware_id']) ? $request['ware_id'] : 0
                );
                if ($real_stock_goods['code'] == 500) {
                    return ['code' => 500, 'msg' => 'error', 'data' => '仓库内商品数量不足'];
                }
                $real_data[$key]['real_actual_goo_id'] = $real_stock_goods['real_stock_goods']['real_goo_id'];
                $real_data[$key]['real_wago_id'] = $real_stock_goods['real_stock_goods']['wago_id'];
                $orgo_data[$key]['orgo_actual_goo_id'] = $real_stock_goods['real_stock_goods']['real_goo_id'];//订单商品id
                $orgo_data[$key]['orgo_wago_id'] = $real_stock_goods['real_stock_goods']['wago_id'];//订单商品的仓库商品id
            } else {
                $orgo_data[$key]['orgo_actual_goo_id'] = '';//订单商品id
                $orgo_data[$key]['orgo_wago_id'] = '';//订单商品的仓库商品id
            }

            $orgo_data[$key]['orgo_ord_id'] = $ord_id;
            $orgo_data[$key]['orgo_order_number'] = $ord_order_number;
            $orgo_data[$key]['orgo_ware_id'] = $request['ware_id'];
            $orgo_data[$key]['orgo_waon_class'] = $request['goo_waon_class'][$key];
            $orgo_data[$key]['orgo_goo_id'] = $value;
            // 判断活动id是否存在,根据活动id查找对应的活动类型,商品信息
            // 判断商品id跟活动商品id是否一致,不一致,修改订单状态,审核
            if (isset($request['ord_acti_id']) && !empty($request['ord_acti_id'])) {
                if ($acti_res->acti_activity_type == '1') { //折扣
                    // 判断活动商品是否存在售卖的商品里,不存在修改订单状态
                    if (in_array($value, $goods_id)) {
                        $discount_price = $request['goo_price'][$key] * 100; //折扣
                        $request['goo_price'][$key] = $request['goo_price'][$key] * $goods_data[$value]['acdi_discount'] / 1000; //折扣
                        // 如果活动折扣价不等于商品价,修改订单状态
                        if ($discount_price != $find_goods_data->goo_price) {
                            $ord_edit_data['ord_wor_state'] = 6;
                            if ($type == 2) {
                                return ['code' => 500, 'msg' => 'error', 'data' => '活动商品价格跟订单商品价格不一致,无法派单1'];
                            }
                        }
                    }
                } elseif ($acti_res->acti_activity_type == '2') { //买送
                    // 判断活动商品是否存在售卖的商品里,不存在修改订单状态
                    // 根据商品状态判断是售卖商品还是送的goo_state商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品
                    if ($request['goo_state'][$key] == '1') { //商品状态1正常
                        if (in_array($value, $goods_id)) {
                            $purchase_quantity = $goods_data[$value]['acdo_purchase_quantity']; //购买数量
                            // 如果活动商品数量不等于商品数量,修改订单状态
                            if ($request['goo_quantity'][$key] < $purchase_quantity) {
                                $ord_edit_data['ord_wor_state'] = 6;
                                if ($type == 2) {
                                    return ['code' => 500, 'msg' => 'error', 'data' => '活动商品数量跟订单商品数量不一致,无法派单1'];
                                }
                            }
                        }
                    } elseif ($request['goo_state'][$key] == '5') { //商品状态5赠品
                        $gift[$value] = $request['goo_quantity'][$key];
                        // 判断活动赠送商品是否在存在
                        if (in_array($value, $gift_id)) {
                            $attached_quantity = $gift_data[$value]; //附送数量
                            // 如果活动商品数量不等于商品数量,修改订单状态
                            if ($request['goo_quantity'][$key] < $attached_quantity) {
                                $ord_edit_data['ord_wor_state'] = 6;
                                if ($type == 2) {
                                    return ['code' => 500, 'msg' => 'error', 'data' => '活动商品数量跟订单商品数量不一致,无法派单3'];
                                }
                            }
                        }
                    }
                } elseif ($acti_res->acti_activity_type == '3') { //买赠
                    // 判断活动商品是否存在售卖的商品里,不存在修改订单状态
                    // 根据商品状态判断是售卖商品还是赠品goo_state商品状态1.正常 2.删除3回收的商品4换货商品5赠品商品
                    if ($request['goo_state'][$key] == '1') { //商品状态为1正常
                        if (in_array($value, $goods_id)) {
                            $purchase_quantity = $goods_data[$value]['acdo_purchase_quantity']; //购买数量
                            // 如果活动商品数量不等于商品数量,修改订单状态
                            if ($request['goo_quantity'][$key] < $purchase_quantity) {
                                $ord_edit_data['ord_wor_state'] = 6;
                                if ($type == 2) {
                                    return ['code' => 500, 'msg' => 'error', 'data' => '活动商品数量跟订单商品数量不一致,无法派单1'];
                                }
                            }
                        }
                    } elseif ($request['goo_state'][$key] == '5') { //商品状态为5赠品商品
                        $gift[$value] = $request['goo_quantity'][$key];
                        // 判断活动赠送商品是否在存在
                        if (in_array($value, $gift_id)) {
                            $attached_quantity = $gift_data[$value]; //附送数量
                            // 如果活动商品数量不等于商品数量,修改订单状态
                            if ($request['goo_quantity'][$key] < $attached_quantity) {
                                $ord_edit_data['ord_wor_state'] = 6;
                                if ($type == 2) {
                                    return ['code' => 500, 'msg' => 'error', 'data' => '活动商品数量跟订单商品数量不一致,无法派单'];
                                }
                            }
                        }
                    }
                } elseif ($acti_res->acti_activity_type == '8') { //大批量采购
                    // 判断活动商品是否存在售卖的商品里,不存在修改订单状态
                    // 根据商品状态判断是售卖商品还是赠品,goo_state商品状态1正常2删除3回收的商品4换货商品5赠品尚品
                    if ($request['goo_state'][$key] == '1') {
                        if (in_array($value, $goods_id)) {
                            $goods_quantity = $goods_data[$value]['acpr_goods_quantity']; //商品数量
                            // 如果活动商品数量不等于商品数量,修改订单状态
                            if ($goods_quantity != $request['goo_quantity'][$key]) {
                                $ord_edit_data['ord_wor_state'] = 6;
                                if ($type == 2) {
                                    return ['code' => 500, 'msg' => 'error', 'data' => '活动商品数量跟订单商品数量不一致,无法派单1'];
                                }
                            }
                        }
                    }
                }
            }
            $orgo_data[$key]['orgo_goo_price'] = $request['goo_price'][$key] * 100;
            $orgo_data[$key]['orgo_goo_quantity'] = $request['goo_quantity'][$key];
            $orgo_data[$key]['orgo_recycle_quantity'] = $request['goo_recycle_quantity'][$key];
            $orgo_data[$key]['orgo_recycle_price'] = $request['goo_recycle_price'][$key] * 100;
            if ($type == 2) {
                $orgo_data[$key]['orgo_can_assign_quantity'] = 0;
            } else {
                $orgo_data[$key]['orgo_can_assign_quantity'] = $request['goo_quantity'][$key];
            }
            $orgo_data[$key]['orgo_collection_price'] = $request['goo_collection_price'][$key] * 100;
            $orgo_data[$key]['orgo_goo_inventory'] = $request['goo_inventory'][$key];
            $orgo_data[$key]['orgo_update_time'] = date('Y-m-d H:i:s');
            if (!empty($request['tem_goo_name'][$key])) {
                $tem_goo_name = $request['tem_goo_name'][$key];
            } else {
                $tem_goo_name = '';
            }
            $orgo_data[$key]['orgo_goo_name'] = $find_goods_data->goo_name;
            $orgo_data[$key]['orgo_tem_goo_name'] = $tem_goo_name;
            $orgo_data[$key]['orgo_goo_goods_encode'] = $find_goods_data->goo_goods_encode;
            $orgo_data[$key]['orgo_goo_type'] = $request['goo_type'][$key];
            $orgo_data[$key]['orgo_goo_ampere_hour'] = $find_goods_data->goo_ampere_hour;
            $orgo_data[$key]['orgo_state'] = $request['goo_state'][$key];
            if ($request['orcl_shipment_party'] == 4) {
                // if ($request['goo_price'][$key] < $request['goo_assign_price'][$key]) {
                //     return ['code'=>500, 'msg'=>'error', 'data'=>'零售金额小于派单金额，无法生成订单'];
                // }
                $orgo_data[$key]['orgo_assign_price'] = $request['goo_assign_price'][$key] * 100;
            }
            //出库方为仓库
            if ($request['orcl_shipment_party'] == 1) {
                //获取订单商品成本价
                $orgo_goo_cost = DB::table('enters_sells_saves')
                    ->where('ense_goo_warehouse',$request['ware_id'])
                    ->where('ense_goo_waretype',$request['goo_waon_class'][$key])
                    ->where('ense_goo_id',$orgo_data[$key]['orgo_actual_goo_id'] ?: $value)
                    ->orderBy('ense_id', 'desc')
                    ->value('ense_end_price');
                $orgo_goo_cost = $orgo_goo_cost ? : 0;
                $orgo_data[$key]['orgo_goo_cost'] = $orgo_goo_cost * 100;//商品成本
            }
            
            // goo_state 商品状态1.正常 2.删除3.回收的商品4.换货商品5.赠品商品6.备用电池7.临时商品8.旧货商品
            // 换货商品金额处理
            if ($request['goo_state'][$key] == 1 || $request['goo_state'][$key] == 5) {
                $orgo_data[$key]['orgo_is_recycle'] = $request['goo_recycle'][$key];
                // 订单商品
                $goo_all_price += $request['goo_price'][$key] * $request['goo_quantity'][$key];
                $goo_assign_all_price += $request['goo_assign_price'][$key] * $request['goo_quantity'][$key];

                // 判断换货单的换货商品
                $goo_id[$n] = $value;
                $goo_quantity[$n] = $request['goo_quantity'][$key];
                $goo_price[$n] = $request['goo_price'][$key];
                $n++;

                $goo_all_quantity += $request['goo_quantity'][$key]; //商品总数量
                $goo_collection_price += $request['goo_collection_price'][$key];

                if ($request['orcl_shipment_party'] != 4) {
                    // 获取商品成本价
                    $cost_price = StockSellStorageGoods::costPrice(
                        $request['ware_id'], //仓库id
                        $request['goo_waon_class'][$key], //仓库类别
                        $value //商品id
                    );

                    // 生成销售明细
                    $sell_res = SellDetail::add(
                        $user_info, //用户信息
                        $ord_order_number, //订单号
                        $request['ord_service_type'], //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                        $request['orla_id'], //订单标签id
                        $request['ware_id'], //仓库id
                        $request['ord_type'], //客户类型：1.门店零售 2.来往单位
                        $request['ord_client_id'], //会员id/来往单位id
                        $ord_data['ord_service_shop_id'], //服务门店id
                        $value, //商品id
                        $request['goo_price'][$key], //商品售价
                        $request['goo_quantity'][$key], //订单商品数量
                        $cost_price / 100, //商品成本价
                        $request['goo_inventory'][$key], //库存扣除方式1.良品 2.优先
                        $request['goo_state'][$key],  //商品状态1.正常 2.删除3回收的商品4换货商品
                        $ord_data['ord_remark'] //订单备注
                    );
                } else {
                    $cost_price = 0;
                    $sell_res = true;
                }
                
                if (!$sell_res) {
                    return ['code'=>500, 'msg'=>'success', 'data'=>'生成订单失败'];
                }
            } elseif ($request['goo_state'][$key] == 4) {//换货商品
                $orgo_data[$key]['orgo_is_recycle'] = 2;
                // 换货商品
                $goo_all_price -= $request['goo_price'][$key] * $request['goo_quantity'][$key];
                $goo_assign_all_price -= $request['goo_assign_price'][$key] * $request['goo_quantity'][$key];

                $goo_exchange[] = $value;

                if ($request['orcl_shipment_party'] != 4) {
                    // 获取商品成本价
                    $cost_price = StockSellStorageGoods::costPrice(
                        $request['ware_id'], //仓库id
                        $request['goo_waon_class'][$key], //仓库类别
                        $value //商品id
                    );
                    // 生成销售明细
                    $sell_res = SellDetail::add(
                        $user_info, //用户信息
                        $ord_order_number, //订单号
                        $request['ord_service_type'], //订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                        $request['orla_id'], //订单标签id
                        $request['ware_id'], //仓库id
                        $request['ord_type'], //客户类型：1.门店零售 2.来往单位
                        $request['ord_client_id'], //会员id/来往单位id
                        $ord_data['ord_service_shop_id'], //服务门店id
                        $value, //商品id
                        $request['goo_price'][$key], //商品售价
                        $request['goo_quantity'][$key], //订单商品数量
                        $cost_price / 100, //商品成本价
                        $request['goo_inventory'][$key], //库存扣除方式1.良品 2.优先
                        $request['goo_state'][$key],  //商品状态1.正常 2.删除3回收的商品4换货商品
                        $ord_data['ord_remark'] //订单备注
                    );
                } else {
                    $cost_price = 0;
                    $sell_res = true;
                }
                
                if (!$sell_res) {
                    return ['code'=>500, 'msg'=>'success', 'data'=>'生成订单失败'];
                }
            } elseif ($request['goo_state'][$key] == 6) {//备用电池
                $orgo_data[$key]['orgo_is_recycle'] = $request['goo_recycle'][$key];
                $goo_all_quantity += $request['goo_quantity'][$key]; //商品总数量
                $goo_all_price += $request['goo_price'][$key] * $request['goo_quantity'][$key];
                $goo_collection_price += $request['goo_collection_price'][$key];
                $orgo_data[$key]['orgo_recycle_price'] = 0;
                $orgo_data[$key]['orgo_recycle_quantity'] = 0;
            } elseif ($request['goo_state'][$key] == 7) {//临时商品
                $orgo_data[$key]['orgo_is_recycle'] = $request['goo_recycle'][$key];
                $goo_all_quantity += $request['goo_quantity'][$key]; //商品总数量
            } elseif ($request['goo_state'][$key] == 8) {//旧货商品
                $orgo_data[$key]['orgo_is_recycle'] = $request['goo_recycle'][$key];
                $goo_all_price += $request['goo_price'][$key] * $request['goo_quantity'][$key];
                $goo_assign_all_price += $request['goo_assign_price'][$key] * $request['goo_quantity'][$key];
                $goo_all_quantity += $request['goo_quantity'][$key]; //商品总数量
                $goo_collection_price += $request['goo_collection_price'][$key];//商品代收总金额
            }
        }
        if (isset($gift_data)) {
            if (isset($gift)) {
                if ($gift_data != $gift) {
                    if ($type == 2) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'没有赠品,无法派单1'];
                    }
                }
            } else {
                if ($type == 2) {
                    return ['code'=>500, 'msg'=>'error', 'data'=>'没有赠品,无法派单2'];
                }
            }
        }

        // 判断换货单是否选择换货商品
        if ($request['ord_service_type'] == 3 && empty($goo_exchange)) {
            return ['code' => 500, 'msg' => 'success', 'data' => '请点击“换货”添加退回的商品'];
        }
        if ($request['ord_service_type'] == 3 && empty($goo_id)) {
            return ['code' => 500, 'msg' => 'success', 'data' => '请添加换新的商品'];
        }

        $goo_all_price = $goo_all_price + ($orcl_rescue_service_price); //合计金额=商品总金额+服务项目的订单金额
        $goo_order_price = $goo_all_price;//订单总金额
        //合计金额 = 商品总金额 - 回收总金额
        $goo_all_price = $goo_all_price - $recycle_all_price;

        // 结算金额正负值
        if ($goo_all_price < 0 || $request['ord_service_type'] == 4) {
            // 金额小于0，或者退货单类型，金额为负
            $ord_edit_data['ord_plus_minus'] = 2; //金额正负：1正值2负值
        } else {
            $ord_edit_data['ord_plus_minus'] = 1; //金额正负：1正值2负值
        }
        // 订单金额正负值
        if ($goo_order_price < 0 || $request['ord_service_type'] == 4) {
            // 金额小于0，或者退货单类型，金额为负
            $ord_edit_data['ord_order_plus_minus'] = 2; //金额正负：1正值2负值
        } else {
            $ord_edit_data['ord_order_plus_minus'] = 1; //金额正负：1正值2负值
        }

        // 判断活动id是否存在,根据活动id查找对应的活动类型,商品信息
        // 判断商品id跟活动商品id是否一致,不一致,修改订单状态,审核
        if (isset($request['ord_acti_id']) && !empty($request['ord_acti_id'])) {
            if ($acti_res->acti_activity_type == '4') { //满减
                // 判断活动满减金额是否大于等于结算金额,是,修改订单结算金额,否,修改状态
                $goo_all_price = abs($goo_all_price) - (($credit_price[0]) / 100);
                if (abs($goo_all_price) < ($reduction_price[0] / 100)) {
                    $ord_edit_data['ord_wor_state'] = 6;
                    if ($type == 2) {
                        return ['code' => 500, 'msg' => 'error', 'data' => '合计金额不满足活动满减金额,无法派单'];
                    }
                }
            } elseif ($acti_res->acti_activity_type == '5') { //现结折扣
                // 判断活动现结折扣
                $discount_price = ($reduction_price[0] / 100) * ($acdr_discount[0] / 1000);
                $goo_all_price = abs($goo_all_price) * ($acdr_discount[0] / 1000);
                if (abs($goo_all_price) < $discount_price) {
                    $ord_edit_data['ord_wor_state'] = 6;
                    if ($type == 2) {
                        return ['code' => 500, 'msg' => 'error', 'data' => '合计金额不满足活动满减金额,无法派单'];
                    }
                }
            }
        }
        $orgo_res = DB::table('order_goods')->insert($orgo_data);

        // 4. 更改订单表客户id、订单金额
        $ord_edit_data['ord_orcl_id'] = $orcl_id;
        $ord_edit_data['ord_order_price'] = abs($goo_order_price) * 100; // 订单金额（单位：分）
        $ord_edit_data['ord_actual_price'] = abs($goo_all_price) * 100; // 结算金额（单位：分）
        $ord_edit_data['ord_goods_quantity'] = $goo_all_quantity; // 商品总数量
        $ord_edit_data['ord_collection_price'] = ($goo_collection_price + $orcl_rescue_collection_price) * 100; //商品代收金额（单位：分）
        $ord_eidt_res = DB::table('order')
            ->where('ord_id', $ord_id)
            ->update($ord_edit_data);

        if ($request['orcl_shipment_party'] == 4) {
            $goo_assign_all_price = abs($goo_assign_all_price) * 100;
            $ord_client_res = DB::table('order_client')
                ->where('orcl_id', $orcl_id)
                ->update(['orcl_assign_price'=>$goo_assign_all_price,'orcl_update_time'=>date('Y-m-d H:i:s')]);
            if ($ord_client_res || $ord_client_res===0) {
            } else {
                DB::rollBack();
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'编辑失败']);
            }
        }

        //计算会员消费总金额
        if($ord_data['ord_type'] == 1 && $ord_data['ord_client_id'] > 0){
            WashOrderService::consume_money($ord_data['ord_client_id']);
        }

        // 推送提示信息数据
        $inhi_data['inhi_original_adm_id'] = $user_info->adm_id;//原始单号创建人
        $inhi_data['inhi_original_id'] = $ord_id;//原始单id
        $inhi_data['inhi_original_number'] = $ord_data['ord_order_number'];//原始单号
        $inhi_data['inhi_original_state'] = $ord_data['ord_wor_state']??0;//原始单状态
        $inhi_data['inhi_original_operation'] = '新订单';//操作
        $inhi_data['inhi_operation_state'] = 1;//操作状态：1新订单
        $inhi_data['inhi_create_time'] = date('Y-m-d H:i:s');//操作时间

        // 第三方推送数据
        $inhi_data['modeule_type'] = 1;//模块id；单号类型:1订单2工单3速电网单
        $inhi_data['push_time'] = '';//推送触发时间,为空则表示立即推送
        $inhi_data['shop_id'] = $user_info->adm_shop_id;//门店系统门店id，有门店id就推送门店下的所有用户，没有门店id就推送用户id
        $inhi_data['target_type'] = 0;//接收端类型0=浏览器;1=移动端
        if (config('apimesssage.WHETHER_OPEN')) {
            // $push = new PushMessageController;
            // $push_return = $push->create($inhi_data);
            // if ($push_return['code'] == 500) {
            //     return ['code' => 500, 'msg' => 'success', 'data' => '消息推送失败'];
            // }
        }
        //添加新增订单信息的提示
        addInformationHint($user_info, $inhi_data, 1);

        if ($ord_id && $orgo_res  && $orcl_id && $ord_eidt_res && $client_res) {
            $return_data['ord_id'] = $ord_id;//订单id
            $return_data['ord_order_number'] = $ord_order_number;//订单单号
            $return_data['shop_id'] = $shop_id; //总店id
            $return_data['ord_type'] = $request['ord_type']; //买家类型1.会员零售2.客户单位3.速电派单4.第三方派单
            $return_data['ord_client_id'] = isset($request['ord_client_id']) ? $request['ord_client_id'] : 0; //选择的客户id,会员id/单位id
            // 修改唯一标识字段表的状态
            // $find_unique = DB::table('admin_order_time')
            //     ->where('adot_unique_string', $request['ord_unique_string'])
            //     ->where('adot_state', 1)
            //     ->update(['adot_state'=>2]);
            return ['code' => 200, 'real_data' => $real_data, 'data' => $return_data];
        } else {
            return ['code' => 500, 'msg' => 'success', 'data' => '生成订单失败'];
        }
    }
}
