<?php
/**
 * 支付管理
 */

namespace App\Http\Controllers\Service;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Services\WashPayservice;
use App\Services\PayService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use BlueCity\Core\Sdk\MiscSapi;
use Illuminate\Support\Facades\DB;
use App\Services\CommonService;
use App\Models\Warehouse;
use App\Services\BmmcService;

class WarehouseController extends BaseController
{
    public function __construct()
    {
        // $service = new ServiceProviderService();
        $this->bootWithService($service);
    }

    /**
     * 仓库列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-06
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function index(Request $request) {
        $session = Request()->get('session_token');//用户信息
        $Db = new Warehouse();
        $Db = $Db->leftjoin('company', 'com_id', '=', 'company_id');
        $Db = $Db->where('com_type', 2);
        if($request->filled('shck_ckmc')){ //仓库名称
            $shck_ckmc = $request->input('shck_ckmc');
            $Db = $Db->where('shck_ckmc', 'like','%'.$shck_ckmc.'%');
        }
        if($request->filled('comapny_name')){ //仓库名称
            $comapny_name = $request->input('comapny_name');
            $Db = $Db->where('com_name', 'like','%'.$comapny_name.'%');
        }
        $page_size = $request->input('page_size',10);
        $page = $request->input('page',1);
        if ($session['admin_groupnew'] != 7) {
            $Db = $Db->where('company_id', $session['company_id']);
        }
        if($page<1){
            $page = 1;
        }
        $paginate = $Db->orderBy('id','DESC')->paginate($page_size);
        $list = self::dataToArray($paginate->items());

        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        if (empty($list)) {
            // 新增默认仓库
            $add_ware['shck_ckmc'] = '默认仓库';
            $add_ware['company_id'] = $session['company_id'];
            $ware_id = DB::table('warehouse')->insertGetId($add_ware);
        }
        $paginate = $Db->orderBy('id','DESC')->paginate($page_size);
        $list = self::dataToArray($paginate->items());
        if($list){
            foreach ($list as $k =>$v){
                $button = [];
                $list[$k]['ware_goods_num'] = DB::table('ware_goods')
                    ->where('wago_ware_id', $v['id'])
                    ->sum('wago_stock_num');
                $list[$k]['comapny_name'] = DB::table('company')
                    ->where('com_id', $v['company_id'])
                    ->value('com_name');
                if ($session['admin_groupnew'] == 7) {
                    $button = ['wareGoods', 'addGoodsNum'];
                } else {
                    $button = ['wareGoods'];
                }
                $button = BmmcService::getListButton($button,$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
            }

           $data['list'] = $list;
           $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            return $this->success('获取成功', $data);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }

    /**
     * 增加库存
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-09
     * @param  Request          $request [description]
     */
    public function addGoodsNum(Request $request) {
        if (empty($request['company_id'])) {
            return response()->json(['Data' =>'', 'ErrorMessage' => '请选择仓库', 'ErrorCode' => 2]);
        }
        if (empty($request['ware_id'])) {
            return response()->json(['Data' =>'', 'ErrorMessage' => '请选择仓库', 'ErrorCode' => 2]);
        }
        $goods_data = $request['goods_data'];
        DB::beginTransaction();
        foreach ($goods_data as $key => $value) {
            if (empty($value['goods_id'])) {
                return response()->json(['Data' =>'', 'ErrorMessage' => '请选择商品', 'ErrorCode' => 2]);
            }
            if (empty($value['goods_num'])) {
                return response()->json(['Data' =>'', 'ErrorMessage' => '请选择数量', 'ErrorCode' => 2]);
            }
            $find_goods = DB::table('pj_goods')
                ->where('pg_id', $value['goods_id'])
                ->first();
            if (empty($find_goods)) {
                return response()->json(['Data' =>'', 'ErrorMessage' => '未查询到此商品', 'ErrorCode' => 2]);
            }
            if ($find_goods['is_delect'] == 2) {
                return response()->json(['Data' =>'', 'ErrorMessage' => '此商品已停用', 'ErrorCode' => 2]);
            }
            $find_data = DB::table('ware_goods')
                ->where('wago_ware_id', $request['ware_id'])
                ->where('wago_goo_id', $value['goods_id'])
                ->first();
            if (empty($find_data)) {
                $add_data['wago_company_id'] = $request['company_id'];
                $add_data['wago_ware_id'] = $request['ware_id'];
                $add_data['wago_goo_id'] = $value['goods_id'];
                $add_data['wago_stock_num'] = $value['goods_num'];
                $add_res = DB::table('ware_goods')->insertGetId($add_data);
            } else {
                $update['wago_stock_num'] = $find_data['wago_stock_num'] + $value['goods_num'];
                $add_res = DB::table('ware_goods')
                    ->where('wago_id', $find_data['wago_id'])
                    ->update($update);
                $add_res = $find_data['wago_id'];
            }
            $add_record['goio_ware_id'] = $request['ware_id'];
            $add_record['goio_wago_id'] = $add_res;
            $add_record['goio_goo_id'] = $value['goods_id'];
            $add_record['goio_num'] = $value['goods_num'];
            $add_record['goio_type'] = '增加库存';
            $add_record_res = DB::table('goods_inout')->insert($add_record);
        }
        if ($add_res && $add_record_res) {
            DB::commit();
            return response()->json(['Data' =>'', 'ErrorMessage' => '成功', 'ErrorCode' => 1]);
        } else {
            DB::rollback();
            return response()->json(['Data' =>'', 'ErrorMessage' => '失败', 'ErrorCode' => 2]);
        }
    }

    /**
     * 仓库商品列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-10
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function wareGoods(Request $request) {
        $session = Request()->get('session_token');//用户信息
        $page_size = $request->input('page_size',10);
        $page = $request->input('page',1);
        $paginate = DB::table('ware_goods')
            ->leftjoin('pj_goods','pg_id', '=', 'wago_goo_id')
            ->where('wago_ware_id', $request['ware_id'])
            ->where(function ($query) use ($request) {
                if (!empty($request['goods_id'])) {
                    $query->where('wago_goo_id', $request['goods_id']);
                }
            })
            ->select('ware_goods.*', 'pj_goods.pg_goodsname', 'brand_name', 'pg_series')
            ->paginate($page_size);
        $list = $paginate->items();
        if($list){
            foreach ($list as $k =>$v){
                $list[$k]['ware_goods_num'] = DB::table('ware_goods')
                    ->where('wago_ware_id', $v['id'])
                    ->sum('wago_stock_num');
                $button = [];
                $button = BmmcService::getListButton($button,$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];
            }

           $data['list'] = $list;
           $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            return $this->success('获取成功', $data);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }

    /**
     * 出入库记录
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-11
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function wareGoodsRecord(Request $request) {
        $session = Request()->get('session_token');//用户信息
        $page_size = $request->input('page_size',10);
        $page = $request->input('page',1);
        $paginate = DB::table('goods_inout as g')
            ->leftjoin('pj_goods as p', 'p.pg_id', '=', 'g.goio_goo_id')
            ->leftjoin('warehouse as w', 'g.goio_ware_id', '=', 'w.id')
            ->leftjoin('company as c','c.com_id', '=', 'w.company_id')
            ->where(function ($query) use ($request,$session) {
                if ($session['com_type'] == 2) {
                    $query->where('w.company_id', $session['company_id']);
                }
                if (!empty($request['company_id'])) {
                    $query->where('w.company_id', $request['company_id']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['pg_goodsname'])) {
                    $query->where('pg_goodsname', 'like','%'.$request['pg_goodsname'].'%');
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['goods_id'])) {
                    $query->where('goio_goo_id', $request['goods_id']);
                }
            })
            ->select('shck_ckmc', 'pg_goodsname', 'goio_num', 'goio_type', 'goio_sys_num', 'goio_serial_number', 'goio_old_num', 'goio_new_num', 'com_name')
            ->paginate($page_size);
        $list = $paginate->items();
        if($list){
            foreach ($list as $k =>$v){
                if (empty($v['goio_sys_num'])) {
                    $list[$k]['goio_sys_num'] = '--';
                }
                if (empty($v['goio_serial_number'])) {
                    $list[$k]['goio_serial_number'] = '--';
                }
                // $button = [];
                // $button = BmmcService::getListButton($button,$all_button);
                // $list[$k]['button_one'] = $button['button_one']??[];
                // $list[$k]['button_two'] = $button['button_two']??[];
                // $list[$k]['button_three'] = $button['button_three']??[];
            }

           $data['list'] = $list;
           $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
            return $this->success('获取成功', $data);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
        }
    }
}
