<?php

namespace App\Http\Controllers\Api\AccountControl;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountControl\VerifyStockingSellingController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\StockingSelling;
use App\Http\Models\Api\Export;

class StockingSellingController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    //进销存查询列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStockingSellingController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $input = $request->all();
        $list_data = DB::table('stocking_selling')
                ->where('stse_cid', $user_info->adm_cid)
                ->where('stse_superior_id', $shop_id)
                //年
                ->where(function($query) use($input) {
                    if (!empty($input['stse_year'])) {
                        $query->where('stse_year', $input['stse_year']);
                    }
                }) 
                //月
                ->where(function($query) use($input) {
                    if (!empty($input['stse_month'])) {
                        $query->where('stse_month', $input['stse_month']);
                    }
                })
                //门店id
                ->where(function($query) use($input) {
                    if (!empty($input['stse_shop_id'])) {
                        $query->where('stse_shop_id', $input['stse_shop_id']);
                    }
                })
                //仓库id
                ->where(function($query) use($input) {
                    if (!empty($input['stse_ware_id'])) {
                        $query->where('stse_ware_id', $input['stse_ware_id']);
                    }
                })
                ->select('stse_id','stse_shop_name','stse_year','stse_month','stse_ware_id','stse_ware_name','stse_ware_in','stse_ware_out','stse_initial_stock','stse_closing_stock','stse_initial_cost','stse_closing_cost')
                ->orderBy('stse_id', 'desc')
                ->paginate($this->show_count);
        $list_items = $list_data->items();

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据

        if(!empty($input['stse_year']) || !empty($input['stse_month']) || !empty($input['stse_shop_id']) || !empty($input['stse_ware_id'])){
            $stics = DB::table('stocking_selling')
                ->where('stse_cid', $user_info->adm_cid)
                ->where('stse_superior_id', $shop_id)
                ->where(function($query) use($input) {
                    if (!empty($input['stse_year'])) {
                        $query->where('stse_year', $input['stse_year']);
                    }
                }) 
                //月
                ->where(function($query) use($input) {
                    if (!empty($input['stse_month'])) {
                        $query->where('stse_month', $input['stse_month']);
                    }
                })
                //门店id
                ->where(function($query) use($input) {
                    if (!empty($input['stse_shop_id'])) {
                        $query->where('stse_shop_id', $input['stse_shop_id']);
                    }
                })
                //仓库id
                ->where(function($query) use($input) {
                    if (!empty($input['stse_ware_id'])) {
                        $query->where('stse_ware_id', $input['stse_ware_id']);
                    }
                })
                ->select(DB::raw('sum(stse_ware_in) as in_ware,sum(stse_ware_out) as out_ware,sum(stse_initial_stock) as initial_stock,sum(stse_closing_stock) as closing_stock'))
                ->first();
            // $statistics['year'] = date('Y');
            // $statistics['month'] = date('m');
            $statistics['in_ware'] =isset($stics->in_ware) ? $stics->in_ware :0;//入库
            $statistics['out_ware'] =isset($stics->out_ware) ? $stics->out_ware :0;//出库
            $statistics['initial_stock'] =isset($stics->initial_stock) ? $stics->initial_stock:0;//期初库存
            $statistics['closing_stock'] =isset($stics->closing_stock) ? $stics->closing_stock:0;//期末库存
        }else{
            $statistics = '';
        }
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info, 'list_button'=>$list_button,'statistics'=>$statistics]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    // 进销存查询列表详情
    public function detail(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStockingSellingController;
        $error_message = $verify_data->detailValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $input = $request->all();
        $list_data = DB::table('stocking_selling_goods')
                ->where('sego_cid', $user_info->adm_cid)
                // ->where('sego_shop_id', $user_info->adm_shop_id)
                ->where('sego_stse_id', $input['sego_stse_id'])
                //商品名称
                ->where(function($query) use($input) {
                    if (!empty($input['sego_goo_name'])) {
                        $query->where('sego_goo_name', 'like',$input['sego_goo_name'].'%');
                    }
                }) 
                //商品编号
                ->where(function($query) use($input) {
                    if (!empty($input['sego_goo_encode'])) {
                        $query->where('sego_goo_encode', $input['sego_goo_encode']);
                    }
                })
                ->select('sego_id','sego_bra_id','sego_goo_id','sego_goo_name','sego_goo_encode','sego_initial_inventory','sego_closing_inventory','sego_closing_costing','sego_early_costing','sego_costing as sego_in_costing','sego_in_num','sego_out_num')
                ->orderBy('sego_id', 'desc')
                ->paginate($this->show_count);
        $list_items = $list_data->items();

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据

        if (!empty($data_info['data'])) {
            $sego_bra_id = [];
            foreach ($data_info['data'] as $key => $value) {
                $sego_bra_id[] = $value->sego_bra_id;
                if(empty($value->sego_bra_id)){
                    $data_info['data'][$key]->sego_bra_id = '';
                }
            }
            $res = DB::table('brand')->whereIn('bra_id',$sego_bra_id)->get(['bra_id','bra_name']);
            $data_info['brand_data'] = $res;
        }else{
            $data_info['brand_data'] = '';
        }
        // $StockingSelling  = new StockingSelling;
        // if($request['type'] == 1){
        //     $goods_id = [1,2];
        //     $num = [100,100];
        //     $costing = 10;
        //     $ware_id = 5;
        //     $type = 1;
        //     $StockingSelling->purchase($user_info,$goods_id,$num,$costing,$ware_id,$type);
        // }
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info, 'list_button'=>$list_button]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }
    //导出
    public function indexExport(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        
        $input = $request->all();
        $list_data = DB::table('stocking_selling')
                ->where('stse_cid', $user_info->adm_cid)
                ->where('stse_superior_id', $shop_id)
                //年
                ->where(function($query) use($input) {
                    if (!empty($input['stse_year'])) {
                        $query->where('stse_year', $input['stse_year']);
                    }
                }) 
                //月
                ->where(function($query) use($input) {
                    if (!empty($input['stse_month'])) {
                        $query->where('stse_month', $input['stse_month']);
                    }
                })
                //门店id
                ->where(function($query) use($input) {
                    if (!empty($input['stse_shop_id'])) {
                        $query->where('stse_shop_id', $input['stse_shop_id']);
                    }
                })
                //仓库id
                ->where(function($query) use($input) {
                    if (!empty($input['stse_ware_id'])) {
                        $query->where('stse_ware_id', $input['stse_ware_id']);
                    }
                })
                ->select('stse_shop_name','stse_year','stse_month','stse_ware_name','stse_ware_in','stse_ware_out','stse_initial_stock','stse_closing_stock','stse_initial_cost','stse_closing_cost')
                ->orderBy('stse_id', 'desc')
                ->get();
        if(empty($list_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
        if(count($list_data) > 10000){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'不能导出大于10000的数据']);
        }
        // 将对象转化为数组
        $list_data = json_decode(json_encode($list_data),true);
        foreach ($list_data as $key => $value) {
            if(!empty($value['stse_closing_cost'])){
                $list_data[$key]['stse_closing_cost']  = $value['stse_closing_cost'] / 100;
            }
            if(!empty($value['stse_initial_cost'])){
                $list_data[$key]['stse_initial_cost']  = $value['stse_initial_cost'] / 100;
            }
        }
        $pathName = storage_path()."/app/public/excel";//获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName,0775,true);
            chmod($pathName,0775);
        }

        $streamFileRand = time() . rand(10000,99999).'.xls';//
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' .$streamFileRand;

        $where['action_name'] = '进销存查询'; //
        $where['field_name'] = ['门店名称','年份','月份','仓库名称','入库数量','出库数量','期初库存','期末库存','期初成本(元)','期末成本(元)'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $list_data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if(file_exists($pathName))
        {
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    //详情导出
    public function detailExport(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $input = $request->all();

        if(empty($request['sego_stse_id'])){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        $list_data = DB::table('stocking_selling_goods')
                ->where('sego_cid', $user_info->adm_cid)
                // ->where('sego_shop_id', $user_info->adm_shop_id)
                ->where('sego_stse_id', $request['sego_stse_id'])
                //商品名称
                ->where(function($query) use($input) {
                    if (!empty($input['sego_goo_name'])) {
                        $query->where('sego_goo_name', $input['sego_goo_name']);
                    }
                }) 
                //商品编号
                ->where(function($query) use($input) {
                    if (!empty($input['sego_goo_encode'])) {
                        $query->where('sego_goo_encode', $input['sego_goo_encode']);
                    }
                })
                ->select('sego_bra_id','sego_goo_name','sego_goo_encode','sego_initial_inventory',
                         'sego_early_costing', 'sego_costing','sego_in_num',
                         'sego_out_num','sego_closing_inventory')
                ->orderBy('sego_id', 'desc')
                ->get();
        if(empty($list_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
        if(count($list_data) > 10000){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'不能导出大于10000的数据']);
        }
        // 将对象转化为数组
        $list_data = json_decode(json_encode($list_data),true);

        $sego_bra_id = [];
        foreach ($list_data as $key => $value) {
            $sego_bra_id[] = $value['sego_bra_id'];
            if(!empty($value['sego_closing_costing'])){
                $list_data[$key]['sego_closing_costing']  = $value['sego_closing_costing'] / 100;
            }
            if(!empty($value['sego_early_costing'])){
                $list_data[$key]['sego_early_costing']  = $value['sego_early_costing'] / 100;
            }
            if(!empty($value['sego_costing'])){
                $list_data[$key]['sego_costing']  = $value['sego_costing'] / 100;
            } 
        } 
        $brand = DB::table('brand')->whereIn('bra_id',$sego_bra_id)->pluck('bra_name','bra_id')->toArray();

        foreach ($list_data as $key => $value) {
            if($value['sego_bra_id'] == 0){
                $list_data[$key]['sego_bra_id'] = '';
            }else{
                $list_data[$key]['sego_bra_id'] = $brand[$value['sego_bra_id']];
            }
        }

        $pathName = storage_path()."/app/public/excel";//获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName,0775,true);
            chmod($pathName,0775);
        }

        $streamFileRand = time() . rand(10000,99999).'.xls';//
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' .$streamFileRand;

        $where['action_name'] = '进销存查询'; //
        $where['field_name'] = ['品牌','商品名称','检索编码','期初库存','期初成本','成本','入库数量','出库数量','期末库存'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $list_data      //导出数据
        );


        // 判断文件是否存在 存在则成功  不存在则失败
        if(file_exists($pathName))
        {
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

}
