<?php

namespace App\Http\Controllers\Mounting\Shop;

use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Shop\PurchaseService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Services\CommonService;

// 采购单管理
class PurchaseController extends Controller
{
    public function __construct()
    {
        $this->dataService = $service = new PurchaseService();
        $this->bootWithService($service);
    }

    public function createShopCode(){
        $find_shop = DB::table('shop')->get();
        foreach ($find_shop as $key => $value) {
            $pait_number = 'S' . substr(time(),5,5)  . rand(10000, 99999);
            $createCode = $this->createCode($value->shop_id,$pait_number);
        }
    }

    function createCode($shop_id,$pait_number){
        $find_shop_data = DB::table('shop')
            ->where('shop_code', $pait_number)
            ->exists();
        if ($find_shop_data) {
            $pait_number = 'S' . substr(time(),5,5)  . rand(10000, 99999);
            $this->createCode($pait_number);
        }
        $update = DB::table('shop')->where('shop_id', $shop_id)->update(['shop_code'=>$pait_number]);
        return true;
    }

    /**
     * 获取门店信息
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-02-27
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getShop(Request $request) {
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->getShop($user_info, $request->all(), 10);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
    }

    /**
     * [getShopState description]
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-03-26
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getFshop(Request $request) {
        $user_info = LoginUserService::getUser();

        $res = $this->dataService->getFshop($user_info,$request);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$res]);
    }

    /**
     * 获取门店详细信息
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-02-27
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getShopInfo(Request $request) {
        $user_info = LoginUserService::getUser();
        if (empty($request['shop_code'])) {
            return response()->json(['code'=>500, 'msg'=>'请输入门店编号', 'data'=>'']);
        }
        $search_data = $this->dataService->getShopInfo($user_info, $request->all(), 10);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
    }

    // 详情
    public function getShopGoods(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getShopGoodsValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->getShopGoods($user_info, $request->all());
        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
        }
    }

    /**
     * 新增采购单
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-02-28
     * @param  Request          $request [description]
     */
    public function add(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->add($user_info, $request->all());
        return response()->json($search_data);
    }

    /**
     * 采购单列表-下级
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-02-28
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function index(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $request['show_count'] = isset($request['show_count']) ?$request['show_count']:10;
        $res = $this->dataService->index($user_info, $request->all(), $request['show_count']);
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'add';
        $sea_button_data = CommonService::getTopButton('',$sea_button_data,$list_button);
        // 获取当前列表下的按钮
        if (empty($res)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$res, 'searech_button'=>$sea_button_data]);
        } else {
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
            foreach ($res['list'] as $key => $value) {
                if ($list_button) {
                    foreach ($list_button as $key_b => $value_b) {
                        
                    }
                }
            }
            
            // 获取当前列表下的按钮
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$res, 'searech_button'=>$sea_button_data]);
        }
    }

    /**
     * 采购单列表-上级
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-02-28
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function wholesale(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->wholesale($user_info, $request->all(), 10);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
    }

    /**
     * 接单
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-03-01
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function receive(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->receiveValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $user_info = LoginUserService::getUser();
        $request['ip'] = getRealIp($request);
        $search_data = $this->dataService->receive($user_info, $request->all());
        return response()->json($search_data);
    }

    /**
     * 采购计划
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-31
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function purchasingPlan(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->purchasingPlanValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $user_info = LoginUserService::getUser();
        $request['ip'] = getRealIp($request);
        $request['show_count'] = isset($request['show_count']) ?$request['show_count']:10;
        $search_data = $this->dataService->purchasingPlan($user_info, $request->all(),$request['show_count']);
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        // 获取当前列表下的按钮
        if (!empty($search_data)) {
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
            foreach ($search_data['list'] as $key => $value) {
                $buttonData = [];
                if ($value->pupl_state == 2) {
                    $buttonData[] = 'quickCg';
                    $buttonData[] = 'quickDb';
                }
                $buttonData[] = 'planInfo';
                $button = CommonService::getListButton($buttonData,$list_button);
                $search_data['list'][$key]->button_one = $button['button_one']??[];
                $search_data['list'][$key]->button_two = $button['button_two']??[];
                $search_data['list'][$key]->button_three = $button['button_three']??[];
            }
        }
        //获取top按钮
        $sea_button_data = 'bulk';
        $top_button = CommonService::getTopButton('',$sea_button_data,$list_button);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data,'top_button'=>$top_button]);
    }

    public function planInfo(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->planInfoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        $user_info = LoginUserService::getUser();
        $request['ip'] = getRealIp($request);
        $search_data = $this->dataService->planInfo($user_info, $request->all());
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
    }

    /**
     * [getPlanGoods description]
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-08-01
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getPlanGoods(Request $request) {
        $user_info = LoginUserService::getUser();
        if ($request['show_count']) {
            $show_count = $request['show_count'];
        } else {
            $show_count = 10;
        }
        $list_data = DB::table('goods as g')
            ->leftJoin('purchasing_plan', 'pupl_goo_id', '=', 'goo_id')
            ->where('goo_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['goo_brse_id'])) {
                    $query->where('goo_brse_id', $request['goo_brse_id']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['goo_bra_id'])) {
                    $query->where('goo_bra_id', $request['goo_bra_id']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['goo_cate_id'])) {
                    $query->where('goo_cate_id', $request['goo_cate_id']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['goo_unta_id'])) {
                    $query->where('goo_unta_id', $request['goo_unta_id']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $request['goo_name'] . '%')
                        ->orwhere('goo_goods_encode', 'like', '%' . $request['goo_name'] . '%');
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['pupl_state'])) {
                    $query->where('pupl_state', $request['pupl_state'])
                        ->where('pupl_ware_id', $request['ware_id']);
                }
            })
            ->where('goo_delete', 1)
            ->select('g.*')
            ->orderBy('goo_id', 'desc')
            ->groupBy('goo_id')
            ->paginate($show_count);
        $data = $list_data->items();
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $plan_goods = DB::table('purchasing_plan')
                    ->where('pupl_goo_id', $value->goo_id)
                    ->where('pupl_ware_id', $request['ware_id'])
                    ->first();
                if ($plan_goods) {
                    $value = json_decode(json_encode($value,true),true);
                    $plan_goods = json_decode(json_encode($plan_goods,true),true);
                    $data[$key] = array_merge($plan_goods,$value);
                }
            }
        }
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $show_count;       //一页显示多少个
        $data_info['data'] = $data;                //返回数据
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
    }

    public function getUnit(Request $request) {
        $list_data = DB::table('unit_table')
            ->get();
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
    }
}