<?php

namespace App\Services\Business;

use App\Models\Business\WashOrder;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Business\WashDispatchValidator;
use App\Http\Models\Services\Dispatch;

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

    public function __construct()
    {
        $this->mainValidator = new WashDispatchValidator();
    }

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

    public static function shipments($user_info, $request)
    {
        // 验证已经发货的不能再次发货
        $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 ['code'=>500, 'msg'=>'当前发货单不存在！', 'data'=>'当前发货单不存在！'];
        }
        if ($dis_data->dego_type == 2) {
            return ['code'=>500, 'msg'=>'当前发货单已发货！', 'data'=>'当前发货单已发货！'];
        }
        if ($dis_data->dego_type == 3) {
            return ['code'=>500, 'msg'=>'当前发货单已作废！', 'data'=>'当前发货单已作废！'];
        }
        if ($dis_data->dego_type == 4) {
            return ['code'=>500, 'msg'=>'当前发货单已锁定，无法发货！', 'data'=>'当前发货单已锁定，无法发货！'];
        }

        // dego_order_type类型：1.订单发货 2.工单发货3售后单发货
        if ($dis_data->dego_order_type == 1) {
            $find_order_data = DB::table('order')
                ->where('ord_id', $dis_data->dego_wor_id)
                ->select('ord_order_number', 'ord_id')
                ->first();
            $find_ord_id = $find_order_data->ord_id; //订单id
            $find_order_number = $find_order_data->ord_order_number; //订单编号
        } elseif($dis_data->dego_order_type == 2){
            $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; //订单编号
        }

        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 ['code'=>200, 'msg'=>'success', 'data'=>$data];
        }

        $request_goods_data = json_decode($request['goodsDataList'], true); //前端提交的出库商品数据
        if (empty($request_goods_data)) {
            return ['code'=>500, 'msg'=>'请选择出库商品', '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 ['code'=>500, 'msg'=>'当前供货仓库不是固定仓库，没有发货权限！', '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 ['code'=>500, 'msg'=>'没有当前仓库的发货权限！', 'data'=>'没有当前仓库的发货权限！'];
        }

        // 更改仓库、仓位发货数量
        $shipments_retrun = Dispatch::shipments(
            $user_info, //用户信息
            $request, //用户信息
            $request_goods_data, //提交的商品数据
            $dis_data, //查询的发货单信息
            $dego_out_ware_type, //发货仓库类型
            $find_ord_id, //订单id
            $find_order_number //订单单号
        );
        if ($shipments_retrun['code'] == 500) {
            return $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);
            $new_upload_data = json_encode($request['imgs64'], true);
        } else {
            $new_upload_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);
        $update_order['ord_wor_state'] = 20;//已评价完成
        $update_order['ord_update_time'] = date('Y-m-d H:i:s');
        $order_update_res = DB::table('order')
            ->where('ord_id', $find_ord_id)
            ->update($update_order);
        if ($dispatch_res) {
            return ['code'=>200, 'msg'=>'发货成功', 'data'=>'发货成功'];
        } else {
            return ['code'=>500, 'msg'=>'发货失败', 'data'=>'发货失败'];
        }
    }

    // 获取字段数据
    public static function getFieldsById($id, $fields = '*', $shopID = 0)
    {
        $entity = WashOrder::where('ord_id', $id)
            ->where('ord_shop_id', $shopID)
            ->select($fields)
            ->first();

        return $entity;
    }
}
