<?php
namespace App\Http\Controllers\WeChatApplet\Technician;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Export;
use App\Http\Models\Services\Prints;
use App\Http\Models\Services\Dispatch;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Business\WashDispatchService;
use App\Services\Business\WashDispatchBasicService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use App\Services\Business\WashOrderService;
use App\Services\CommonService;

// 技师小程序-仓库发货
class WashDispatchController extends Controller
{
    public $dataService = null;

    public function __construct()
    {
        $this->dataService = $service = new WashDispatchService();
        $this->bootWithService($service);
    }

    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'index';
        logFileRecord($log_record, 'wash/WashDispatch', 2);
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->searchPage($user_info, $request->all(), 10);
        $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        if (empty($search_data['data']['data'])) {
            return response()->json($search_data);
        } else {
            if (!empty($search_data)) {
                $shipment = false;
                foreach ($list_button as $key_b => $value_b) {
                    if ($value_b['pri_operate_method'] == 'shipment' && $value_b['have_pri'] == 1) {
                        $shipment = true;
                    }
                }
                foreach ($search_data['data']['data'] as $key => $value) {
                    $buttonData = [];
                    if($value->dego_type == 1 && ($value->dego_order_type == 1 || $value->wor_service_state > 2) && $shipment){
                        $buttonData[] = 'shipment';
                        $search_data['data']['data'][$key]->is_can_shipment = 1;
                    } else {
                        $buttonData[] = 'shipmentInfo';
                        $search_data['data']['data'][$key]->is_can_shipment = 2;
                    }
                    $buttonData[] = 'deliveryList';
                    $button = CommonService::getAppletListButton($buttonData,$list_button);
                    $search_data['data']['data'][$key]->button_one = $button['button_one']??[];
                    $search_data['data']['data'][$key]->button_two = $button['button_two']??[];
                    $search_data['data']['data'][$key]->button_three = $button['button_three']??[];
                }
            }
            return response()->json($search_data);
        }
    }

    // 列表-数量统计
    public function getCount(Request $request)
    {
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'getCount';
        logFileRecord($log_record, 'wash/getCount', 2);
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $state_count = DB::table('dispatch_bill')
            ->where('dego_cid', $user_info->adm_cid)
            ->where('dego_shop_id', $user_info->adm_shop_id)
            ->select(DB::raw('count(*) as count, dego_type'))
            ->groupBy('dego_type')
            ->get();
        $rec_state_count = DB::table('recede_recycle')
            ->where('rec_cid', $user_info->adm_cid)
            ->where('rec_superior_shop_id', $user_info->adm_shop_id)
            ->select(DB::raw('count(*) as count, rec_state'))
            ->groupBy('rec_state')
            ->get();
        $data_info['state_count'] = $state_count;
        $data_info['rec_state_count'] = $rec_state_count;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
    }

    // 发货单详情
    public function info(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM,  $error_message);
        }

        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();

        $select_field = "dego_order_type, dego_wor_id, dego_count, dego_out_ware_id, dego_type, dego_pic, dego_remark";
        $dispatch_info = new Dispatch();
        $return_data = $dispatch_info->info($user_info, $request->all(), $select_field);

        $find_data = DB::table('dispatch_bill')
            ->where('dego_id', $request['dego_id'])
            ->select('dego_order_type', 'dego_original_number', 'dego_wor_id', 'dego_type')
            ->first();
        $ord_id = '';
        if (!empty($find_data)) {
            if ($find_data->dego_order_type == 1) {//类型：1.订单发货 2.工单发货3售后单发货
                $ord_id = $find_data->dego_wor_id;
                $wor_service_state = 0;
            }
            if ($find_data->dego_order_type == 2) {//类型：1.订单发货 2.工单发货3售后单发货
                $ord_id = DB::table('work_order')
                    ->where('wor_id', $find_data->dego_wor_id)
                    ->value('wor_order_id');
                $wor_service_state = DB::table('work_order')
                    ->where('wor_id', $find_data->dego_wor_id)
                    ->value('wor_service_state');
            }
            if ($find_data->dego_order_type == 3) {
                $after_data = DB::table('wash_after_sale_list as afsl')
                    ->where('afsl_id',$find_data->dego_wor_id)
                    ->first();
                $ord_id = $after_data->afsl_ord_id;
                $wor_service_state = 0;
            }
        }
        $order_client = DB::table('order_client')
            ->leftjoin('admin', 'orcl_sales_adm_id', '=', 'adm_id')
            ->leftjoin('order', 'ord_id', '=', 'order_client.orcl_ord_id')
            ->where('orcl_ord_id', $ord_id)
            ->select('orcl_phone', 'orcl_name', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'orcl_sales_adm_id', 'adm_name', 'adm_phone', 'ord_explain')
            ->first();
        $return_data['data']['order_client'] = $order_client;
        $return_data['data']['order_data']['orcl_sales_adm_name'] = $order_client->adm_name;
        $return_data['data']['order_data']['orcl_sales_adm_phone'] = $order_client->adm_phone;
        if ($find_data->dego_order_type == 2) {
            $return_data['data']['wor_data']->orcl_sales_adm_name = $order_client->adm_name;
            $return_data['data']['wor_data']->orcl_sales_adm_phone = $order_client->adm_phone;
        }
        $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        $shipment = false;
        foreach ($list_button as $key_b => $value_b) {
            if ($value_b['pri_operate_method'] == 'shipment' && $value_b['have_pri'] == 1) {
                $shipment = true;
            }
        }
        if($find_data->dego_type == 1 && (($find_data->dego_order_type == 1 || $find_data->dego_order_type == 3) || $wor_service_state > 2) && $shipment){
            $return_data['data']['is_can_shipment'] = 1;
        } else {
            $return_data['data']['is_can_shipment'] = 2;
        }
        $find_admin = DB::table('admin')
            ->leftjoin('role', 'adm_role', '=', 'rol_id')
            ->where('adm_id', $user_info->adm_id)
            ->select('rol_privilege_multiple')
            ->first();
        $order_pic = '';
        if (!empty($find_admin)) {
            $role_data = json_decode($find_admin->rol_privilege_multiple, true);
            $rol_privilege_multiple = explode(',',$role_data['applet']);
            if (in_array(27,$rol_privilege_multiple)) {
                $getorderpic = WashOrderService::getorderpic($user_info, $ord_id);
                if (!empty($getorderpic['data'])) {
                    $order_pic = $getorderpic['data'];
                }
            }
        }
        $return_data['data']['order_pic'] = $order_pic;
        return response()->json($return_data);
    }

    // 发货
    // 工单生成的发货单,状态改为已出库
    public function shipments(Request $request)
    {   
        // 验证参数
        $error_message = $this->dataService->mainValidator->shipmentsValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM,  $error_message);
        }
        request()->offsetSet('rt', 'wechat');
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'add';
        $file_name = $user_info->shop_versions.'_'.date('Ymd', strtotime('this week Monday', time()));
        logFileRecord($log_record, 'wash/WashDispatch'.$file_name, 2);

        DB::beginTransaction();
        // 判断门店版本
        if ($user_info->shop_versions == 1) {
            // 基础版功能流程
            $order_data = WashDispatchBasicService::shipments($user_info, $request->all());
        } else {
            $order_data = WashDispatchService::shipments($user_info, $request->all());
        }
        // 验证已经发货的不能再次发货
        $dis_data = DB::table('dispatch_bill')
            ->where('dego_id', $request['dego_id'])
            ->select('dego_type', 'dego_cid', 'dego_shop_id', 'dego_out_ware_id', 'dego_service_adm_id', 'dego_number', 'dego_order_type', 'dego_wor_id', 'dego_original_number', 'dego_service_shop_id', 'dego_count', 'dego_create_adm_id', 'dego_id', 'dego_client_type', 'dego_client_id', 'dego_remark')
            ->first();
        if ($dis_data->dego_order_type == 2) {
            // 查询当前工单技师的服务状态
            $wor_service_state = DB::table('work_order')
                ->where('wor_id', $dis_data->dego_wor_id)
                ->value('wor_service_state');
            // 如果技师尚未接单，不允许发货
            // 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止10锁定11速电撤销回收
            if ($wor_service_state < 2) {
                return ['code'=>500, 'msg'=>'当前技师尚未接单！', 'data'=>'当前技师尚未接单！'];
            }

            $find_order_data = DB::table('work_order as wor')
                ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                ->where('wor_id', $dis_data->dego_wor_id)
                ->select('wor_type', 'wocl_client_id', 'wor_order_id', 'wor_order_number', 'wor_create_time', 'wor_number')
                ->first();
            $find_ord_id = $find_order_data->wor_order_id; //订单id
            $find_order_number = $find_order_data->wor_order_number; //订单编号
            $work_number = $find_order_data->wor_number;
        } elseif ($dis_data->dego_order_type == 1) {
            $find_ord_id = $dis_data->dego_wor_id; //订单id
            $find_order_number = $dis_data->dego_original_number; //订单编号
            $work_number = '';
        } elseif ($dis_data->dego_order_type == 3) {
            $find_ord_id = $dis_data->dego_wor_id; //订单id
            $find_order_number = $dis_data->dego_original_number; //订单编号
            $work_number = '';
        }
        if ($order_data['code'] == 200) {
            if ($request['type'] == 2) {
                $log_data = [
                    'oplo_module'=>'仓库管理',
                    'oplo_action'=>'出库',
                    'oplo_content'=>'出库成功',
                    'oplo_ip'=>getRealIp($request),
                    'order_number'=>$find_order_number,
                    'work_number'=>$work_number,
                    'data_source'=>2,//操作来源  1 PC  2 小程序
                ];
                $log = addNewLog($user_info, $log_data);
            }
            DB::commit();
        } else {
            DB::rollBack();
        }
        return response()->json($order_data);
    }

    // 发货
    // 工单生成的发货单,状态改为已出库,扣固定仓库存
    public function newshipments(Request $request)
    {   
        // 验证数据
        $verify_data = new VerifyDispatchController;
        $error_message = $verify_data->shipmentsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证已经发货的不能再次发货
        $dis_data = DB::table('dispatch_bill')
            ->where('dego_id', $request['dego_id'])
            ->select('dego_type', 'dego_cid', 'dego_shop_id', 'dego_out_ware_id', 'dego_service_adm_id', 'dego_number', 'dego_order_type', 'dego_wor_id', 'dego_original_number', 'dego_service_shop_id', 'dego_count', 'dego_create_adm_id', 'dego_id', 'dego_client_type', 'dego_client_id', 'dego_remark')
            ->first();
        if (empty($dis_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单不存在！']);
        }
        if ($dis_data->dego_type == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单已发货！']);
        }
        if ($dis_data->dego_type == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单已作废！']);
        }
        if ($dis_data->dego_type == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前发货单已锁定，无法发货！']);
        }

        $service_ware_id = 0; //领货人技师库id
        // dego_order_type类型：1.订单发货 2.工单发货3售后单发货
        if ($dis_data->dego_order_type == 1) {
            // 订单发货，如果是订单类型为发货单的判断此订单是否审核
            $ord_wor_state = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->where('ord_order_number', $dis_data->dego_original_number)
                ->value('ord_wor_state');
            if ($ord_wor_state == 12) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此客户单位超出可欠金额、天数,请到订单列表进行审核！']);
            }

            $find_ord_id = $dis_data->dego_wor_id; //订单id
            $find_order_number = $dis_data->dego_original_number; //订单编号
        } elseif ($dis_data->dego_order_type == 2) {
            // 工单发货验证技师是否绑定了技师库
            // $service_ware_id = DB::table('warehouse')
            //     ->where('ware_type', 2) //类型：1固定仓2技师库
            //     ->where('ware_leader_id', $dis_data->dego_service_adm_id)
            //     ->value('ware_id');
            // if (empty($service_ware_id)) {
            //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师未绑定技师库,请先绑定技师库']);
            // }
            // 查询当前工单技师的服务状态
            $wor_service_state = DB::table('work_order')
                ->where('wor_id', $dis_data->dego_wor_id)
                ->value('wor_service_state');
            // 如果技师尚未接单，不允许发货
            // 服务状态：1待接单2已接单3预约4出发5抵达6完成待审核7完成已驳回8完成通过9终止10锁定11速电撤销回收
            if ($wor_service_state < 2) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师尚未接单！']);
            }

            $find_order_data = DB::table('work_order as wor')
                ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                ->where('wor_id', $dis_data->dego_wor_id)
                ->select('wor_type', 'wocl_client_id', 'wor_order_id', 'wor_order_number')
                ->first();
            $find_ord_id = $find_order_data->wor_order_id; //订单id
            $find_order_number = $find_order_data->wor_order_number; //订单编号
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'发货失败！']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        if ($request['type'] == '1') { //获取页面数据
            $digo_data = DB::table('dispatch_goods as digo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'digo.digo_goo_id')
                ->where('digo_dego_id', $request['dego_id'])
                ->where('digo_state', '!=', '2')
                ->select('digo_id', 'digo_wago_class', 'digo_goo_id', 'digo_goo_type', 'digo_goo_name', 'digo_goo_goods_encode', 'digo_goo_quantity', 'digo_is_recycle', 'digo_goo_inventory', 'digo_state', 'digo_tem_goo_name', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'digo_wago_id', 'digo_orgo_id', 'digo_goo_unit', 'digo_goo_unta_id', 'goo_unit_conversion')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($digo_data, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($digo_data as $key => $value) {
                // 查询仓位商品表中有发货商品的数据
                $digo_data[$key]->option_freight = DB::table('warehouse_freight_goods as wafg')
                    ->leftjoin('warehouse_freight as wafr', 'wafg.wafg_wafr_id', '=', 'wafr.wafr_id')
                    ->where('wafg_ware_id', $dis_data->dego_out_ware_id)
                    ->where('wafg_wago_id', $value->digo_wago_id)
                    ->where('wafg_class', $value->digo_wago_class)
                    ->where('wafg_goo_id', $value->digo_goo_id)
                    ->where(function ($query) use ($value) {
                        if ($value->digo_goo_inventory == 1) {
                            $query->where('wafg_stock_number', '>', 0);
                        } else {
                            $query->where('wafg_priority_stock_number', '>', 0);
                        }
                    })
                    ->select('wafr_id', 'wafr_name', 'wafr_rank', 'wafg_stock_number', 'wafg_priority_stock_number')
                    ->get()->toArray();

                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($value->goo_brse_id)) {
                        if ($value->goo_class == 2) {
                            $digo_data[$key]->digo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->digo_goo_name;
                            unset($digo_data[$key]->goo_brse_id);
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $digo_data[$key]->digo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->digo_goo_name;
                                unset($digo_data[$key]->goo_brse_id);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $digo_data[$key]->digo_goo_name = $value->goo_bra_name . ' ' . $value->digo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $digo_data[$key]->digo_goo_name = $value->goo_bra_name . ' ' . $value->digo_goo_name;
                        }
                    }
                }
                unset($digo_data[$key]->goo_class);
            }
            // 查询服务门店名称
            $dis_data->dego_service_shop_name = DB::table('shop')
                ->where('shop_id', $dis_data->dego_service_shop_id)
                ->value('shop_store_name');
            // 查询仓库名称
            $dis_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $dis_data->dego_out_ware_id)
                ->value('ware_name');
            // 查询领货人名称
            $dis_data->adm_name = DB::table('admin')
                ->where('adm_id', $dis_data->dego_create_adm_id)
                ->value('adm_name');
            // 订单发货
            if ($dis_data->dego_order_type == 1) {
                // 查找订单客户信息
                $order_client = DB::table('order as ord')
                    ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                    ->where('orcl_ord_id', $dis_data->dego_wor_id)
                    ->select('orcl_ord_id', 'orcl_channel_unit', 'ord_type', 'orcl_standby_battery_type', 'orcl_client_id')
                    ->first();
                $order_client->orcl_channel_unit = DB::table('channel_unit')
                    ->where('chun_id', $order_client->orcl_client_id)
                    ->value('chun_unit_name');
                unset($order_client->orcl_client_id);
            } else {
                $order_client = [];
            }

            // 工单发货
            if ($dis_data->dego_order_type == 2) {
                // 查找工单客户信息
                $work_client = DB::table('work_order as wor')
                    ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                    ->where('wocl_wor_id', $dis_data->dego_wor_id)
                    ->select('wocl_wor_id', 'wocl_channel_unit', 'wocl_name', 'wor_type', 'wocl_standby_battery_type', 'wocl_client_id')
                    ->first();
                $work_client->wocl_channel_unit = DB::table('channel_unit')
                    ->where('chun_id', $work_client->wocl_client_id)
                    ->value('chun_unit_name');
                unset($work_client->wocl_client_id);
            } else {
                $work_client = [];
            }


            $data['dis_data'] = $dis_data;
            $data['order_client'] = $order_client;
            $data['work_client'] = $work_client;
            $data['dispatch_goods'] = $digo_data;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        $request_goods_data = json_decode($request['goodsDataList'], true); //前端提交的出库商品数据
        if (empty($request_goods_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择出库商品']);
        }

        // 判断出库仓库类型，pc端不能发移动仓库的商品，只能发固定仓的，有权限的商品
        // ware_type类型：1固定仓2技师库3移动仓
        $dego_out_ware_type = DB::table('warehouse')
            ->where('ware_id', $dis_data->dego_out_ware_id)
            ->value('ware_type');
        if ($dego_out_ware_type != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前供货仓库不是固定仓库，没有发货权限！']);
        }

        // 查询当前账号所拥有的仓库权限
        $find_admin_set = DB::table('admin_set')
            ->where('adms_adm_id', $user_info->adm_id)
            ->where('adms_shop_id', $user_info->adm_shop_id)

            // ->value('adms_ware_id');
            ->value('adms_myware_id');
        $find_admin_set = explode(',', trim($find_admin_set, ','));
        if (!in_array($dis_data->dego_out_ware_id, $find_admin_set)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有当前仓库的发货权限！']);
        }

        DB::beginTransaction();

        // 更改仓库、仓位发货数量
        $shipments_retrun = Dispatch::shipments(
            $user_info, //用户信息
            $request->all(), //用户信息
            $request_goods_data, //提交的商品数据
            $dis_data, //查询的发货单信息
            $dego_out_ware_type, //发货仓库类型
            $find_ord_id, //订单id
            $find_order_number, //订单单号
            $service_ware_id //服务技师库id
        );
        if ($shipments_retrun['code'] == 500) {
            DB::rollBack();
            return response()->json($shipments_retrun);
        }

        // 发货单商品添加物料图片
        if (!empty($request['imgs64'])) {
            $upload_file = json_decode(json_encode($request['imgs64']), true);
            foreach ($upload_file as $key => $value) {
                if (!empty($value)) {
                    // 判断是否有新图片上传
                    if (strpos($value, 'data:image') === 0) {
                        // 调用全局函数 上传图片
                        $image_path = uploadBase64ImgFolder($user_info->adm_shop_id, $value, 2);
                    }
                }
                $new_data[] = $image_path;
                unset($image_path);
            }
            $new_upload_data = json_encode($new_data);
        } else {
            $new_upload_data = '';
        }

        // 发货单商品添加物料图片
        // foreach ($request_goods_data as $key => $value) {
        //     $image_path = '';
        //     if (!empty($value['digo_goo_material_pic'])) {
        //         if (strpos($value['digo_goo_material_pic'], 'data:image') === 0) {
        //             // 调用全局函数 上传图片
        //             $image_path = uploadBase64ImgFolder($user_info->adm_shop_id, $value['digo_goo_material_pic'], 2);
        //         }
        //     }
        //     $update_digo_data['digo_goo_material_pic'] = !empty($image_path) ? $image_path : '';
        //     $update_digo_data['digo_update_time'] = date('Y-m-d H:i:s');
        //     $update_digo_res = DB::table('dispatch_goods')->where('digo_id', $value['digo_id'])->update($update_digo_data);
        //     if (!$update_digo_res) {
        //         return response()->json(['code'=>500,'msg'=>'error','data'=>'发货失败，图片上传失败']);
        //     }
        // }
        // 修改发货单表的状态
        $update_data['dego_type'] = 2; //类型：1未出库2已出库
        $update_data['dego_pic'] = !empty($new_upload_data) ? $new_upload_data : ''; //发货图片
        $update_data['dego_remark'] = !empty($request['dego_remark']) ? $request['dego_remark'] : ''; //发货备注
        $update_data['dego_update_time'] = date('Y-m-d H:i:s'); //更新时间
        $dispatch_res = DB::table('dispatch_bill')
            ->where('dego_id', $request['dego_id'])
            ->update($update_data);

        // 更新订单商品表的商品成本，根据订单id,查询商品
        $find_orgo_data = DB::table('order_goods')
            ->where('orgo_ord_id', $find_ord_id)
            ->where('orgo_state', '!=', 2)
            ->select('orgo_id', 'orgo_state', 'orgo_ord_id', 'orgo_ware_id', 'orgo_waon_class', 'orgo_goo_id', 'orgo_goo_price', 'orgo_goo_quantity')
            ->get()->toArray();
        $cost_price = 0; //总成本金额
        $recycle_amount = 0; //回收商品总成本
        $now_date = date('Y-m-d H:i:s'); //当前时间
        $voucher_state = false;
        foreach ($find_orgo_data as $kkkk => $vvvv) {
            if ($vvvv->orgo_waon_class == 1 || ($vvvv->orgo_waon_class == 3 && $vvvv->orgo_goo_price != 0)) { //货物仓
                $voucher_state = true;
                // 获取当前月份商品成本价
                if (in_array($vvvv->orgo_state, [1, 5, 8])) {
                    $find_ense_end_price = DB::table('enters_sells_saves')
                        ->where('ense_goo_id', $vvvv->orgo_goo_id)
                        ->where('ense_goo_warehouse', $vvvv->orgo_ware_id)
                        ->where('ense_goo_waretype', $vvvv->orgo_waon_class)
                        ->where('ense_order_number', $find_order_number)
                        ->orderBy('ense_id', 'desc')
                        ->value('ense_end_price');
                    $find_ense_end_price = sprintf('%.2f', $find_ense_end_price);
                } else {
                    $find_ense_end_price = 0;
                }
                $cost_price += $find_ense_end_price * $vvvv->orgo_goo_quantity; //总成本金额
    
                if ($vvvv->orgo_state == 3) {
                    $recycle_amount += $vvvv->orgo_goo_price * $vvvv->orgo_goo_quantity; //回收商品成本金额
                }
                // 修改订单商品成本
                $orgo_edit_data['orgo_goo_cost'] = $find_ense_end_price * 100;
                $orgo_edit_data['orgo_update_time'] = $now_date;
                // 修改订单表的更新时间
                $orgo_edit_res = DB::table('order_goods')
                    ->where('orgo_id', $vvvv->orgo_id)
                    ->where('orgo_ord_id', $find_ord_id)
                    ->where('orgo_order_number', $find_order_number)
                    ->update($orgo_edit_data);
                unset($orgo_edit_data);
            }
        }
        if ($dis_data->dego_order_type == 1) {
            // 订单发货单 将订单状态改为完成
            $update_date['ord_wor_state'] = 4;
            $update_date['ord_update_time'] = date('Y-m-d H:i:s');
            $update_state = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->update($update_date);

            $order_client = DB::table('order_client')
                ->where('orcl_ord_id', $dis_data->dego_wor_id)
                ->first(['orcl_channel_unit', 'orcl_client_id', 'orcl_acc_subject_id', 'orcl_collect_state', 'orcl_name']);
            $ord_data = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->first(['ord_type', 'ord_actual_price', 'ord_remark', 'ord_order_number', 'ord_create_time', 'ord_service_type']);
            $ord_plus_minus = 1;
            if ($ord_data->ord_actual_price < 0) {
                $ord_plus_minus = 2;
            }
            // 生成订单应收账单
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $dis_data->dego_wor_id, //原始id(订单id)
                $dis_data->dego_original_number, //应收账款单号/原始号(订单编号)
                $ord_data->ord_type, //客户类型：1.门店零售 2.来往单位
                $order_client->orcl_client_id, //会员id/来往单位id
                $order_client->orcl_channel_unit, //来往单位名称
                abs($ord_data->ord_actual_price), //结算金额
                date('Y-m-d H:i:s'), //结款时间
                $order_client->orcl_acc_subject_id, //会计科目id
                abs($ord_data->ord_actual_price), //实际金额
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                $ord_data->ord_remark,  //备注
                0, //已收金额
                '', //截止时间
                $ord_plus_minus, //金额正负1正2负值
                1, //显示类型：1订单收款 10订单退款
                2, //是否合并代收：1是2否
                $ord_data->ord_create_time,
                $order_client->orcl_collect_state //技师是否收钱：0未选择1是2否
            );
            if (!$ord_bill || !$update_state) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'发货失败！03'];
            }

            if ($voucher_state == true) {
                // 判断门店是否使用用友u8财务系统
                if (config('apiu8cloud.CODE_STARTS') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
                    // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
                    $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
                    // 生成凭证单据
                    if ($ord_data->ord_type == '1') {
                        $order_client->orcl_channel_unit = $order_client->orcl_name;
                    } elseif ($ord_data->ord_type == '2') {
                        $order_client->orcl_channel_unit = $order_client->orcl_channel_unit;
                    } elseif ($ord_data->ord_type == '3') {
                        $order_client->orcl_channel_unit = $order_client->orcl_channel_unit;
                    }
                    $vore_data = WorkOrder::voucherReceipts($user_info, $shop_id, 1, 0, '', $dis_data->dego_wor_id, $ord_data->ord_order_number, $ord_data->ord_actual_price, $recycle_amount, 0, $cost_price, $ord_data->ord_service_type, $ord_data->ord_type, $order_client->orcl_client_id, $order_client->orcl_channel_unit);
                    if (!$vore_data) {
                        return ['code'=>500, 'msg'=>'error', 'data'=>'凭证单生成失败'];
                    }
                }
            }
        }

        if ($dis_data->dego_order_type == 4) {
            // 易损件订单发货单 将订单状态改为完成
            $update_order_data['ord_wor_state'] = 18; // 易损件订单完成状态
            $update_order_data['ord_update_time'] = date('Y-m-d H:i:s');
            $update_order_state = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->update($update_order_data);
        }

        // 仓库商品锁定表
        $wagl_id = DB::table('warehouse_goods_lock')
            ->where('wagl_original_correlation_id', $request['dego_id'])
            ->where('wagl_correlation_type', 2)
            ->value('wagl_id');
        if (!empty($wagl_id)) {
            $wagl_res = DB::table('warehouse_goods_lock')
                ->where('wagl_original_correlation_id', $request['dego_id'])
                ->where('wagl_correlation_type', 2)
                ->update(['wagl_update_time' => date('Y-m-d H:i:s'), 'wagl_state' => 2]);
        } else {
            $wagl_res =  true;
        }
        $wfgl_id = DB::table('warehouse_freight_goods_lock')
            ->where('wfgl_shop_id', $user_info->adm_shop_id)
            ->where('wfgl_original_id', $find_ord_id)
            ->where('wfgl_original_number', $find_order_number)
            ->where('wfgl_type', 1)
            ->value('wfgl_id');
        if (!empty($wfgl_id)) {
            $wfgl_res = DB::table('warehouse_freight_goods_lock')
                ->where('wfgl_shop_id', $user_info->adm_shop_id)
                ->where('wfgl_original_id', $find_ord_id)
                ->where('wfgl_original_number', $find_order_number)
                ->where('wfgl_type', 1)
                ->update(['wfgl_update_time' => date('Y-m-d H:i:s'), 'wfgl_state' => 2]);
        } else {
            $wfgl_res = true;
        }
        if ($dispatch_res && $wagl_res && $wfgl_res) {
            Common::addLog($user_info, getRealIp($request), '发货单', '发货', '发货单：' . $dis_data->dego_number . ' 发货成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'发货成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'发货失败']);
        }
    }

    // 搜索勾选过的服务门店
    public function searchShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 获取到服务门店信息
        $search_data = $request->all();

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $list_data = DB::table('shop')
            ->where('shop_superior_id', $shop_id)
            ->where('shop_cid', $user_info->adm_cid)
            ->where('shop_state', 1)
            ->where('shop_type', '<>', 3)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('shop_store_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('shop_id', 'shop_store_name')
            ->orderBy('shop_id', 'desc')
            ->get();
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    /**
     * 获取仓库
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-11-08
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getWareHouses(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getWareHousesValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM,  $error_message);
        }
        request()->offsetSet('rt', 'wechat');
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $return_data = WashDispatchService::getWareHouses($user_info, $request);
        return response()->json($return_data);
    }

    /**
     * 更换仓库
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-11-08
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function changeWare(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->changeWareValidator($request->all());
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM,  $error_message);
        }
        request()->offsetSet('rt', 'wechat');
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'changeWare';
        $file_name = $user_info->shop_versions.'_'.date('Ymd', strtotime('this week Monday', time()));
        logFileRecord($log_record, 'wash/WashDispatch'.$file_name, 2);

        $return_data = WashDispatchService::changeWare($user_info, $request);
        return response()->json($return_data);
    }
}
