<?php

namespace App\Http\Controllers\Api\AccountControl;

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

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

    // 采购明细
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementDetailController;
        $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;

        $search_data = $request->all();

        if(!empty($search_data['proc_create_time']) || !empty($search_data['proc_number']) || !empty($search_data['prgo_goo_id']) | !empty($search_data['proc_chun_id']) || !empty($search_data['chun_adm_id']) || !empty($search_data['proc_ware_id']) || !empty($search_data['shop_type']) || !empty($search_data['proc_shop_id'])){

            $list_data = DB::table('procurement_goods as g')
                ->leftjoin('procurement as p','g.prgo_proc_id','=','p.proc_id')
                ->leftjoin('channel_unit as u','p.proc_chun_id','=','u.chun_id')
                ->leftjoin('shop as s','s.shop_id','=','p.proc_shop_id')
                ->where('proc_cid',$user_info->adm_cid)
                ->where('proc_superior_shop_id',$shop_id)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_create_time'])) {
                        $query->where('proc_create_time','like','%'. $search_data['proc_create_time'].'%');
                    }
                }) //创建时间
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_number'])) {
                        $query->where('proc_number','like', '%' . $search_data['proc_number'].'%');
                    }
                }) //单号
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prgo_goo_id'])) {
                        $query->where('prgo_goo_id', $search_data['prgo_goo_id']);
                    }
                }) //商品名称
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_chun_id'])) {
                        $query->where('proc_chun_id', $search_data['proc_chun_id']);
                    }
                }) //客户单位
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['chun_adm_id'])) {
                        $query->where('chun_adm_id', $search_data['chun_adm_id']);
                    }
                }) //业务员
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_ware_id'])) {
                        $query->where('proc_ware_id', $search_data['proc_ware_id']);
                    }
                }) //仓库名称
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['shop_type'])) {
                        $query->where('shop_type', $search_data['shop_type']);
                    }
                }) //门店类型
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_shop_id'])) {
                        $query->where('proc_shop_id', $search_data['proc_shop_id']);
                    }
                }) //门店名称
                ->select('prgo_id', 'proc_create_time', 'proc_number', 'proc_shop_id', 'proc_ware_id', 
                		 'chun_unit_name', 'proc_chun_id', 'chun_adm_id', 'prgo_goo_id', 'prgo_purchase_number', 
                		 'prgo_purchase_price', 'proc_actual_price', 'shop_store_name', 'shop_type','prgo_actual_number')
                ->orderBy('prgo_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();               //总数据个数
            
            $sum_type = 2; //显示

            $sum_data = DB::table('procurement_goods as g')
                    ->leftjoin('procurement as p','g.prgo_proc_id','=','p.proc_id')
                    ->leftjoin('channel_unit as u','p.proc_chun_id','=','u.chun_id')
                    ->leftjoin('shop as s','s.shop_id','=','p.proc_shop_id')
                    ->where('proc_cid',$user_info->adm_cid)
                    ->where('proc_superior_shop_id',$shop_id)
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['proc_create_time'])) {
                            $query->where('proc_create_time','like','%'. $search_data['proc_create_time'].'%');
                        }
                    }) //创建时间
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['proc_number'])) {
                            $query->where('proc_number','like', '%' . $search_data['proc_number'].'%');
                        }
                    }) //单号
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prgo_goo_id'])) {
                            $query->where('prgo_goo_id', $search_data['prgo_goo_id']);
                        }
                    }) //商品名称
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['proc_chun_id'])) {
                            $query->where('proc_chun_id', $search_data['proc_chun_id']);
                        }
                    }) //客户单位
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['chun_adm_id'])) {
                            $query->where('chun_adm_id', $search_data['chun_adm_id']);
                        }
                    }) //业务员
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['proc_ware_id'])) {
                            $query->where('proc_ware_id', $search_data['proc_ware_id']);
                        }
                    }) //仓库名称
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['shop_type'])) {
                            $query->where('shop_type', $search_data['shop_type']);
                        }
                    }) //门店类型
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['proc_shop_id'])) {
                            $query->where('proc_shop_id', $search_data['proc_shop_id']);
                        }
                    }) //门店名称
                    ->first(array(
                            \DB::raw('SUM(prgo_purchase_number) as sum_number'),
                            \DB::raw('SUM(proc_actual_price) as sum_price')
                        ));


            if ($list_items) {
                $sum_number = 0; //商品采购总数量
                $sum_price = 0;  //总采购金额
                foreach ($list_items as $key => $value) {
                    $ware_id[] = $value->proc_ware_id; //仓库id
                    $adm_id[] = $value->chun_adm_id; //业务员id
                    $goo_id[] = $value->prgo_goo_id; //商品id
                    $list_items[$key]->total_money = $value->prgo_actual_number * $value->prgo_purchase_price ;//商品合计金额
                }
                // 仓库信息
                $ware_info = DB::table('warehouse')
                        ->whereIn('ware_id',$ware_id)
                        ->get(['ware_id','ware_name']);
                // 业务员信息
                $adm_info = DB::table('admin')
                        ->whereIn('adm_id',$adm_id)
                        ->get(['adm_id','adm_name']);
                // 商品信息
                $goo_info = DB::table('goods')
                        ->whereIn('goo_id',$goo_id)
                        ->get(['goo_id','goo_name','goo_goods_code','goo_goods_encode']);
            }else{
                $ware_info = [];
                $adm_info = [];
                $goo_info = [];
            }   
            $data_info['current_number'] = $this->show_count;        //一页显示多少个
            $data_info['ware_info'] = $ware_info;                    //单位类型数据
            $data_info['adm_info'] = $adm_info;                      //业务员/录单人数据
            $data_info['goo_info'] = $goo_info;                      //商品数据
            $data_info['sum_number'] = empty($sum_data->sum_number)?0:$sum_data->sum_number;                  //商品采购总数量
            $data_info['sum_price'] = empty($sum_data->sum_price)?0:$sum_data->sum_price;                    //总采购金额
        }else{
            $list_items = [];
            $sum_type = 1; //隐藏
        }

        $data_info['sum_type'] = $sum_type;                      //1.隐藏 2.显示
        $data_info['data'] = $list_items;                        //返回数据
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info, 'list_button'=>$list_button]);
    }

    // 导出
    public function export(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;

        $search_data = $request->all();

        $data = DB::table('procurement_goods as g')
            ->leftjoin('procurement as p','g.prgo_proc_id','=','p.proc_id')
            ->leftjoin('channel_unit as u','p.proc_chun_id','=','u.chun_id')
            ->leftjoin('shop as s','s.shop_id','=','p.proc_shop_id')
            ->where('proc_cid',$user_info->adm_cid)
            ->where('proc_superior_shop_id',$shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['proc_create_time'])) {
                    $query->where('proc_create_time','like','%'. $search_data['proc_create_time'].'%');
                }
            }) //创建时间
            ->where(function($query) use($search_data) {
                if (!empty($search_data['proc_number'])) {
                    $query->where('proc_number','like', '%' . $search_data['proc_number'].'%');
                }
            }) //单号
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prgo_goo_id'])) {
                    $query->where('prgo_goo_id', $search_data['prgo_goo_id']);
                }
            }) //商品名称
            ->where(function($query) use($search_data) {
                if (!empty($search_data['proc_chun_id'])) {
                    $query->where('proc_chun_id', $search_data['proc_chun_id']);
                }
            }) //客户单位
            ->where(function($query) use($search_data) {
                if (!empty($search_data['chun_adm_id'])) {
                    $query->where('chun_adm_id', $search_data['chun_adm_id']);
                }
            }) //业务员
            ->where(function($query) use($search_data) {
                if (!empty($search_data['proc_ware_id'])) {
                    $query->where('proc_ware_id', $search_data['proc_ware_id']);
                }
            }) //仓库名称
            ->where(function($query) use($search_data) {
                if (!empty($search_data['shop_type'])) {
                    $query->where('shop_type', $search_data['shop_type']);
                }
            }) //门店类型
            ->where(function($query) use($search_data) {
                if (!empty($search_data['proc_shop_id'])) {
                    $query->where('proc_shop_id', $search_data['proc_shop_id']);
                }
            }) //门店名称
            ->select('proc_create_time', 'proc_number', 'shop_type', 'shop_store_name', 'proc_ware_id', 
                     'chun_unit_name', 'chun_adm_id', 'prgo_goo_id', 'prgo_id','prgo_purchase_number', 
                     'prgo_purchase_price', 'proc_actual_price')
            ->orderBy('prgo_id', 'desc')
            ->get();

        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data),true);

            foreach ($data as $key => $value) {
                //仓库id
                $ware_id[] = $value['proc_ware_id'];
                //业务员id
                $adm_id[] = $value['chun_adm_id'];
                //商品id
                $goo_id[] = $value['prgo_goo_id'];
            }
            $ware_id = array_unique($ware_id);
            $adm_id = array_unique($adm_id);
            $goo_id = array_unique($goo_id);

            // 仓库信息
            $ware_info = DB::table('warehouse')->whereIn('ware_id',$ware_id)->pluck('ware_name', 'ware_id');
            // 业务员信息
            $adm_info = DB::table('admin')->whereIn('adm_id',$adm_id)->pluck('adm_name', 'adm_id');
            // 商品信息
            $goo_info = collect(DB::table('goods')->whereIn('goo_id',$goo_id)->get(['goo_name','goo_goods_code','goo_id']))->keyBy('goo_id')->toArray();
            foreach ($data as $key => $value) {
                //仓库名称
                $data[$key]['proc_ware_id'] = $ware_info[$value['proc_ware_id']];
                // 业务员姓名
                $data[$key]['chun_adm_id'] = $adm_info[$value['chun_adm_id']];
                // 商品名称/编号
                $data[$key]['prgo_goo_id'] = $goo_info[$value['prgo_goo_id']]->goo_name;
                $data[$key]['prgo_id'] = $goo_info[$value['prgo_goo_id']]->goo_goods_code;
                // 门店类型
                if($value['shop_type'] == 1){$data[$key]['shop_type'] = '总店';}
                if($value['shop_type'] == 2){$data[$key]['shop_type'] = '直营店';}
                if($value['shop_type'] == 3){$data[$key]['shop_type'] = '加盟店';}
                // 单价除100
                
                // 合计金额除100
                $data[$key]['prgo_purchase_price'] = $data[$key]['prgo_purchase_price'] / 100;
                $data[$key]['proc_actual_price'] = $data[$key]['proc_actual_price'] / 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名及其每一行的标题
            $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'=>'导出失败']);
        }
    }
}
