<?php

namespace App\Http\Controllers\Api\WarehouseManage;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\OutinRecord;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\WarehouseManage\VerifyProcurementController;

use App\Http\Models\Api\Export;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\StockingSelling;
use App\Http\Models\Api\StockSellStorageGoods;
use App\Http\Models\Api\AccountingSettlement;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $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();
        $list_data = DB::table('procurement as a')
                ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.proc_ware_id')
                ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_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_number'])) {
                        $query->where('proc_number', 'like', $search_data['proc_number'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prcl_channel_unit'])) {
                        $query->where('prcl_channel_unit', 'like', $search_data['prcl_channel_unit'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                        $query->whereBetween('proc_create_time',[$search_data['start_time'],$search_data['end_time']]);
                    }else{
                        // 如果选择开始时间
                        if (!empty($search_data['start_time'])){
                            $query->where('proc_create_time','>=',$search_data['start_time']);
                        }else{
                            // 如果选择结束时间
                            if (!empty($search_data['end_time'])) {
                                $query->where('proc_create_time','<=',$search_data['end_time']);
                            }
                        }
                    }
                }) //创建时间
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prcl_name'])) {
                        $query->where('prcl_name', 'like', '%'.$search_data['prcl_name'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prcl_phone'])) {
                        $query->where('prcl_phone', 'like', '%'.$search_data['prcl_phone'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['ware_name'])) {
                        $query->where('ware_name', 'like', $search_data['ware_name'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_state'])) {
                        $query->where('proc_state', $search_data['proc_state']);
                    }
                })
                ->select('proc_id', 'proc_number', 'proc_state', 'proc_count', 'proc_adm_id',  'proc_audit_id',
                         'proc_remark', 'proc_data', 'proc_create_time', 'prcl_channel_unit', 'prcl_name', 'prcl_phone',
                         'prcl_province', 'prcl_city', 'prcl_county', 'prcl_address', 'ware_name', 'proc_actual_price',
                         'proc_actual_count', 'proc_prbi_id', 'proc_shop_id')
                ->orderBy('proc_id', 'desc')
                ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $shop_id = [];
            // 查找账号id
            foreach ($list_items as $key => $value) {
            	if ($value->proc_adm_id) {
            		$adm_id[] = $value->proc_adm_id;
            	}
            	if ($value->proc_audit_id) {
            		$adm_id[] = $value->proc_audit_id;
            	}
                if ($value->proc_data) {
                    $value->proc_data = json_decode($value->proc_data, true);
                }
                $shop_id[] = $value->proc_shop_id;
                // 过期时间
                // if($value->proc_astrict_state == 2){
                //     $value->proc_astrict_date = date("Y-m-d",strtotime("+".$value->proc_astrict_day." day",strtotime($value->proc_create_time)));
                // }
            }
            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
    				->whereIn('adm_id', $adm_id)
        			->get(['adm_id', 'adm_name']);
            $find_shop =  DB::table('shop')
                    ->whereIn('shop_id',$shop_id)
                    ->get(['shop_id', 'shop_store_name']);
        }else{
            $find_admin = [];
            $find_shop = [];
        }
        $state_count = DB::table('procurement')
                    ->where('proc_cid', $user_info->adm_cid)
                    ->where('proc_superior_shop_id', $shop_id)
                    ->select(DB::raw('count(*) as count, proc_state'))
                    ->groupBy('proc_state')
                    ->get();
        $sum_type = 1; //隐藏
        // 判断是否有搜索条件 有搜索条件
        if(!empty($search_data['proc_number']) || !empty($search_data['prcl_channel_unit']) || !empty($search_data['start_time']) | !empty($search_data['end_time']) || !empty($search_data['prcl_name']) || !empty($search_data['prcl_phone']) || !empty($search_data['ware_name']) || !empty($search_data['proc_state'])){
            $sum_type = 2;
            $sum_data = DB::table('procurement as a')
                ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.proc_ware_id')
                ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_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_number'])) {
                        $query->where('proc_number', 'like', $search_data['proc_number'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prcl_channel_unit'])) {
                        $query->where('prcl_channel_unit', 'like', $search_data['prcl_channel_unit'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                        $query->whereBetween('proc_create_time',[$search_data['start_time'],$search_data['end_time']]);
                    }else{
                        // 如果选择开始时间
                        if (!empty($search_data['start_time'])){
                            $query->where('proc_create_time','>=',$search_data['start_time']);
                        }else{
                            // 如果选择结束时间
                            if (!empty($search_data['end_time'])) {
                                $query->where('proc_create_time','<=',$search_data['end_time']);
                            }
                        }
                    }
                }) //创建时间
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prcl_name'])) {
                        $query->where('prcl_name', 'like', '%'.$search_data['prcl_name'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prcl_phone'])) {
                        $query->where('prcl_phone', 'like', '%'.$search_data['prcl_phone'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['ware_name'])) {
                        $query->where('ware_name', 'like', $search_data['ware_name'].'%' );
                    }
                })
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_state'])) {
                        $query->where('proc_state', $search_data['proc_state']);
                    }
                })
                ->first(array(
                            \DB::raw('SUM(proc_actual_price) as sum_price'),
                            \DB::raw('SUM(proc_actual_count) as sum_count')
                        ));
        }
        
        $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;                        //返回数据
        $data_info['find_admin'] = $find_admin;                  //返回账号姓名
        $data_info['find_shop'] = $find_shop;                    //门店名称
        $data_info['state_count'] = $state_count;                //每个状态下的总数量
        $data_info['sum_type'] = $sum_type;   //返回总数量
        $data_info['sum_count'] = empty($sum_data->sum_count)?0:$sum_data->sum_count;   //返回总数量
        $data_info['sum_price'] = empty($sum_data->sum_price)?0:$sum_data->sum_price;   //返回总金额

        // 获取当前列表下的按钮
        $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 info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 采购入库单数据
        $proc_data = DB::table('procurement as a')
                ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.proc_ware_id')
                ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_id')
                ->where('proc_id', $request['proc_id'])
                ->select('proc_id', 'proc_number', 'proc_state', 'proc_count', 'proc_adm_id',  'proc_audit_id', 'proc_price', 'proc_actual_price', 
                    'proc_create_time', 'prcl_channel_unit', 'prcl_name', 'prcl_phone', 'prcl_province', 'prcl_city', 'prcl_county', 
                    'prcl_address', 'ware_name', 'proc_data', 'proc_remark', 'proc_execute_adm_id', 'proc_execute_time', 
                    'proc_audit_time','proc_actual_count')
                ->first();
        if ($proc_data->proc_execute_time == '0000-00-00 00:00:00') {
            $proc_data->proc_execute_time = '';
        }

        // 获取采购商品数据
        $find_goods = DB::table('procurement_goods as a')
                ->leftJoin('goods as b', 'a.prgo_goo_id', '=', 'b.goo_id')
                ->where('prgo_proc_id', $request['proc_id'])
                ->select('prgo_purchase_number', 'prgo_actual_number','prgo_purchase_price', 'goo_name', 'goo_type', 'goo_goods_encode')
                ->get();

        // 查询账号id对应姓名
        $adm_id = [$proc_data->proc_adm_id, $proc_data->proc_audit_id, $proc_data->proc_execute_adm_id];
        $adm_id = array_unique($adm_id);
        $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
        		->select('adm_id', 'adm_name')
                ->get();
        $data['proc_data'] = $proc_data;
        $data['goods_data'] = $find_goods;
        $data['find_admin'] = $find_admin;
        return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
    }

    // 获取采购仓库信息
    public function warehouseInfo(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或分店id
        $post['string'] = 'ware_';
        $post['user_info'] = $user_info;
        $type = 1;
        $where_data = whereFunction($post,$type);
        $list_data = DB::table('warehouse as w')
			->leftJoin('admin as a','a.adm_id' ,'=','w.ware_leader_id')
            ->where('ware_cid', $user_info->adm_cid)
            ->whereIn($where_data['string'], $where_data['shop_id'])
            // ->where('ware_superior_shop_id', $shop_id)
            ->where('ware_type', 1)
            ->where('ware_state', 1)
            ->select('ware_id', 'ware_name', 'ware_address', 'adm_name', 'adm_phone')
            ->get();
        return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
    }

    // 新增保存
    public function save(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        // 添加采购入库单数据
        $proc_return = $this->addProcurementData($request->all(), $user_info, 1);

        if ($proc_return['code'] == 200) {
        	DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购入库', '新增', '新增采购入库单：'.$proc_return['data']['proc_number'].'成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增采购入库单：成功']);
        }else{
        	DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增采购入库单：失败']);
        }
    }

    /**
     * [addProcurementData 添加采购入库单数据]
     * @param [type] $request   [提交的采购入库数据]
     * @param [type] $user_info [用户信息]
     * @param [type] $type      [入库提交类型：1保存提交2提交并清点入库]
     */
    private function addProcurementData(
        $request,
        $user_info,
        $type
    ) {
        $proc_count = 0;//采购总数量
        $proc_price = 0;//合计金额
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || 
                !is_numeric($request['goo_type'][$key]) || !in_array($request['goo_type'][$key], [1,2,3,4]) || 
                !is_numeric($request['purchase_number'][$key]) || $request['purchase_number'][$key] < 0 || 
                !is_numeric($request['purchase_price'][$key]) || $request['purchase_price'][$key] < 0) {
                return ['code'=> 500, 'msg'=>'error', 'data'=>'参数类型错误'];
            }
            $proc_price += $request['purchase_number'][$key] * $request['purchase_price'][$key];//合计金额
            $proc_count += $request['purchase_number'][$key];//采购总数量

            $prgo_data[$key]['prgo_goo_id'] = $value;
            $prgo_data[$key]['prgo_goo_type'] = $request['goo_type'][$key];
            $prgo_data[$key]['prgo_purchase_number'] = $request['purchase_number'][$key];
            $prgo_data[$key]['prgo_purchase_price'] = $request['purchase_price'][$key] * 100;
        }

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1 新增一个采购入库单数据
        $proc_number = 'CG' . rand(10, 99) . date('mdHis'). rand(100000, 999999);

        $proc_data['proc_cid'] = $user_info->adm_cid;
        $proc_data['proc_shop_id'] = $user_info->adm_shop_id;
        $proc_data['proc_superior_shop_id'] = $shop_id;
        $proc_data['proc_adm_id'] = $user_info->adm_id;
        $proc_data['proc_number'] = $proc_number;
        $proc_data['proc_state'] = $type;// 状态1提交/待审核2已通过/已入库3已驳回
        $proc_data['proc_count'] = $proc_count;
        $proc_data['proc_price'] = $proc_price * 100;
        $proc_data['proc_chun_id'] = $request['chun_id'];
        $proc_data['proc_ware_id'] = $request['proc_ware_id'];
        $proc_data['proc_actual_price'] = 0;
        $proc_data['proc_payment_way'] = $request['proc_payment_way'];
        // 结算方式1.账期 2.现结 3微信 4支付宝 5预付款
        if($request['proc_payment_way'] == 5){
            $proc_data['proc_acpa_id'] = $request['proc_acpa_id']; //预付款id
        }
        if($request['proc_payment_way'] == 2){
            $proc_data['proc_acti_id'] = $request['proc_acti_id']; //会计科目id
        }

        if ($request['proc_data']) {
            $proc_data['proc_data'] = json_encode($request['proc_data']);
        }else{
            $proc_data['proc_data'] = '';
        }
        $proc_data['proc_remark'] = $request['proc_remark'] ? $request['proc_remark'] : '';
        $proc_data['proc_waon_class'] = $request['proc_waon_class'];
        // 新增采购入库单
        $proc_res =  DB::table('procurement')->insertGetId($proc_data);

        // 2. 新增采购入库商品数据
        foreach ($prgo_data as $key => $value) {
            $prgo_data[$key]['prgo_proc_id'] = $proc_res;
            $prgo_data[$key]['prgo_update_time'] = date('Y-m-d H:i:s');
        }
        $prgo_res =  DB::table('procurement_goods')->insert($prgo_data);

        // 3. 新增采购入库客户数据
        $prcl_data['prcl_proc_id'] = $proc_res;
        $prcl_data['prcl_channel_unit'] = $request['chun_unit_name'];
        $prcl_data['prcl_name'] = $request['chun_name'];
        $prcl_data['prcl_phone'] = $request['chun_phone'];
        $prcl_data['prcl_province'] = $request['chun_province'];
        $prcl_data['prcl_city'] = $request['chun_city'];
        $prcl_data['prcl_county'] = $request['chun_county'];
        $prcl_data['prcl_address'] = $request['chun_address'];
        $prcl_data['prcl_update_time'] = date('Y-m-d H:i:s');
        $prcl_res =  DB::table('procurement_client')->insert($prcl_data);

        if ($proc_res && $prgo_res && $prcl_res) {
            return ['code'=>200, 'msg'=>'success', 'data'=>['proc_id'=>$proc_res, 'proc_number'=>$proc_number]];
        }else{
            return ['code'=>500, 'msg'=>'error', 'data'=>'新增采购入库单：失败'];
        }
    }

    // 新增提交并清点入库，生成入库单状态为待入库状态
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        // 添加采购入库单数据
        $proc_return = $this->addProcurementData($request->all(), $user_info, 2);

        if ($proc_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购入库','新增','新增采购入库单：'.$proc_return['data']['proc_number'].'成功');
            $return_data['proc_id'] = $proc_return['data']['proc_id'];
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增采购入库单：成功', 'return_data'=>$return_data]);
        }else{
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增采购入库单：失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 采购入库单数据
        $find_proc = DB::table('procurement')
                ->where('proc_id', $request['proc_id'])
                ->first(['proc_state', 'proc_number','proc_payment_way','proc_acpa_id']);
        if ($find_proc->proc_state == 2) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已通过审核无法编辑']);
        }
        if ($find_proc->proc_state == 4) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已入库无法编辑']);
        }

        if ($request['type'] == 1) {
            // 获取页面数据
	        $proc_data = DB::table('procurement as a')
	                ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_id')
	                ->where('proc_id', $request['proc_id'])
	                ->select('proc_id', 'proc_payment_way', 'proc_price', 'proc_actual_price', 'proc_data', 
                             'proc_chun_id', 'prcl_channel_unit', 'prcl_name', 'prcl_phone', 'prcl_address',
                            'prcl_province', 'prcl_city', 'prcl_county', 'proc_waon_class',
                             'proc_ware_id', 'proc_data', 'proc_remark','proc_acti_id','proc_acpa_id')
	                ->first();
            $proc_data->proc_data = json_decode($proc_data->proc_data, true);

	        // 获取客户类型信息
            $channel_type = DB::table('channel_unit as a')
                        ->leftJoin('channel_type as b','b.chty_id' ,'=','a.chun_chty_id')
                        ->where('chun_id', $proc_data->proc_chun_id)
                        ->select('chty_id', 'chty_name')
                        ->first();

            // 获取仓库信息
        	$warehouse_data = DB::table('warehouse as w')
        				->leftJoin('admin as a','a.adm_id' ,'=','w.ware_leader_id')
                        ->where('ware_id', $proc_data->proc_ware_id)
                        ->select('ware_id', 'ware_name', 'ware_address', 'adm_name', 'adm_phone')
                        ->first();

	        // 获取采购商品数据
	        $find_goods = DB::table('procurement_goods as a')
	                ->leftJoin('goods as b', 'a.prgo_goo_id', '=', 'b.goo_id')
	                ->where('prgo_proc_id', $request['proc_id'])
	                ->select('prgo_purchase_number', 'goo_name', 'goo_type', 'prgo_goo_id', 'prgo_purchase_price', 'goo_goods_encode')
	                ->get();
            $data['proc_data'] = $proc_data;
            $data['goods_data'] = $find_goods;
            $data['warehouse_data'] = $warehouse_data;
            $data['channel_type'] = $channel_type;
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
        }

        // 编辑提交数据
        // 验证数据
        $error_message = $verify_data->saveValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $proc_count = 0;//采购总数量
        $proc_price = 0;//合计金额
        foreach ($request['goo_id'] as $key => $value) {
        	if (!is_numeric($value) || $value < 0 || !is_numeric($request['purchase_number'][$key]) || $request['purchase_number'][$key] < 0  || !is_numeric($request['purchase_price'][$key]) || $request['purchase_price'][$key] < 0 ) {
            	return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数类型错误']);
        	}
        	$proc_price += $request['purchase_number'][$key] * $request['purchase_price'][$key];//合计金额
        	$proc_count += $request['purchase_number'][$key];//采购总数量

        	$prgo_data[$key]['prgo_proc_id'] = $request['proc_id'];
        	$prgo_data[$key]['prgo_update_time'] = date('Y-m-d H:i:s');
        	$prgo_data[$key]['prgo_goo_id'] = $value;
        	$prgo_data[$key]['prgo_purchase_number'] = $request['purchase_number'][$key];
        	$prgo_data[$key]['prgo_purchase_price'] = $request['purchase_price'][$key] * 100;
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 1 编辑采购入库单数据
        DB::beginTransaction();
        $proc_data['proc_state'] = 1;
        $proc_data['proc_adm_id'] = $user_info->adm_id;
        $proc_data['proc_count'] = $proc_count;
        $proc_data['proc_price'] = $proc_price * 100;
        $proc_data['proc_chun_id'] = $request['chun_id'];
        $proc_data['proc_ware_id'] = $request['proc_ware_id'];
        $proc_data['proc_actual_price'] = 0;
        $proc_data['proc_payment_way'] = $request['proc_payment_way'];
        $proc_data['proc_update_time'] = date('Y-m-d H:i:s');

        if($request['proc_payment_way'] == 1){
            $proc_data['proc_acti_id'] = 0;
        }
        if($request['proc_payment_way'] == 2){
            $proc_data['proc_acti_id'] = $request['proc_acti_id'];
        }

        if ($request['proc_data']) {
        	$proc_data['proc_data'] = json_encode($request['proc_data']);
        }else{
        	$proc_data['proc_data'] = '';
        }
        $proc_data['proc_remark'] = $request['proc_remark'] ? $request['proc_remark'] : '';

        $proc_res = DB::table('procurement')
                    ->where('proc_id', $request['proc_id'])
                    ->update($proc_data);

        // 2. 更改盘点商品表的数据
        // 2.1 删除原来盘点id对应的盘点商品数据
        $prgo_del_res = DB::table('procurement_goods')
                    ->where('prgo_proc_id', $request['proc_id'])
                    ->delete();
        // 2.2 重新添加提交的盘点商品数据
        $prgo_res =  DB::table('procurement_goods')->insert($prgo_data);

        // 3. 修改采购入库客户数据
        $prcl_data['prcl_channel_unit'] = $request['chun_unit_name'];
        $prcl_data['prcl_name'] = $request['chun_name'];
        $prcl_data['prcl_phone'] = $request['chun_phone'];
        $prcl_data['prcl_province'] = $request['chun_province'];
        $prcl_data['prcl_city'] = $request['chun_city'];
        $prcl_data['prcl_county'] = $request['chun_county'];
        $prcl_data['prcl_address'] = $request['chun_address'];
        $prcl_data['prcl_update_time'] = date('Y-m-d H:i:s');
        $prcl_res =  DB::table('procurement_client')
			        ->where('prcl_proc_id', $request['proc_id'])
			        ->update($prcl_data);

        if ($proc_res && $prgo_del_res && $prgo_res && $prcl_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购入库单','编辑','编辑采购入库单：'.$find_proc->proc_number.'成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'编辑采购入库单：成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=>500,'msg'=>'error','data'=>'编辑采购入库单：失败']);
        }
    }

    // 通过
    public function pass(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_proc = DB::table('procurement')
                    ->where('proc_id',$request['proc_id'])
                    ->first(['proc_state', 'proc_number', 'proc_ware_id', 'proc_count', 'proc_payment_way',
                             'proc_chun_id', 'proc_price', 'proc_acti_id', 'proc_remark']);
        if ($find_proc->proc_state == 2) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已通过审核']);
        }
        if ($find_proc->proc_state == 3) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已驳回']);
        }
        if ($find_proc->proc_state == 4) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已入库']);
        }

        // 获取当前操作账号信息
		$user_info = Common::getUserInfo($request['api_token']);

        // 1. 更改采购入库单数据
        $update_data['proc_state'] = 2;//状态1提交/待审核2已通过/待入库3已驳回4已入库
        $update_data['proc_audit_id'] = $user_info->adm_id;
        $update_data['proc_audit_time'] = date('Y-m-d H:i:s');
        $update_data['proc_update_time'] = date('Y-m-d H:i:s');
        $proc_res = DB::table('procurement')
                    ->where('proc_id', $request['proc_id'])
                    ->update($update_data);

        // 2. 结算方式为现结 生成一个类型为现结的预付款
        if($find_proc->proc_payment_way == 2){
            // 获取来往单位名称
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$find_proc->proc_chun_id)
                    ->value('chun_unit_name');
            // 添加结款明细记录
            $AccountingSettlement = AccountingSettlement::add(
                $user_info,            // [用户信息]
                7,                     // [单据类型1订单2订单账单3工单账单4采购账单5销售账单6预收款]
                $request['proc_id'],   // [与单据类型对应的id]
                $find_proc->proc_number,// [与单据类型对应的单号]
                2,                     // [买家类型1门店零售2来往单位]
                $find_proc->proc_chun_id,    // [会员/客户id]
                $client_name,  // [来往单位名称]
                $find_proc->proc_acti_id,      // [会计科目id]
                2,                             // [类型1收入2支出]
                $find_proc->proc_price,   // [实际金额](此次的实收金额)
                0,                        // [合计金额](此次的应收金额)
                0,                        // [欠收金额](此次结款后还应收金额)
                0,                        // [抹零金额]
                $find_proc->proc_remark   // [备注]
            );

            $createBill = ReceivableBill::addAccounts(
                $user_info, //用户信息
                3, //类型：1.预付款 2.采购账单 3.现结 4.采购入库单
                0,// $acpa_number_id, //账单的应付账款id
                $request['proc_id'], //原始id(账单id)
                $find_proc->proc_number, //应付账款单号/原始号(账单编号)
                2, //客户类型：1.门店零售 2.来往单位
                $find_proc->proc_chun_id, //会员id/来往单位id
                $client_name, //来往单位名称
                $find_proc->proc_price, //结算金额(采购入库单的合计金额)
                date('Y-m-d H:i:s'), //结款时间
                $find_proc->proc_acti_id, //会计科目id
                $find_proc->proc_price, //实际金额(采购入库单的合计金额)
                0,  //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应付账单id是否是自己 1.不是 2.是
                $find_proc->proc_remark,  //备注
                0  //已付金额
            );

            $update_data['proc_acpa_id'] = $createBill;
            $update_data['proc_update_time'] = date('Y-m-d H:i:s');
            $update_acpa =  DB::table('procurement')->where('proc_id',$request['proc_id'])->update($update_data);
        }else{
            $createBill = true;
            $update_acpa = true;
        }

        if($proc_res && $createBill && $update_acpa) {
            Common::addLog($user_info, getRealIp($request), '采购入库单','通过','采购入库单：'.$find_proc->proc_number.' 通过成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'通过成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'通过失败']);
        }
    }

    /**
     * [storageCheck 提交入库检查是否符合条件]
     * @param  [type] $proc_id [采购入库单id]
     * @param  [type] $type    [入库类型：1部分入库2入库3原单入库]
     * @return [type]          [数组，返回入库结果]
     */
    private function storageCheck($proc_id, $type)
    {
        // 查询信息
        $find_proc = DB::table('procurement')
                    ->where('proc_id', $proc_id)
                    ->first(['proc_state', 'proc_number', 'proc_ware_id', 'proc_count', 'proc_actual_count', 
                             'proc_create_time', 'proc_prbi_id', 'proc_payment_way', 'proc_acpa_id','proc_chun_id',
                             'proc_price', 'proc_acti_id', 'proc_actual_price', 'proc_waon_class']);

        if ($find_proc->proc_state == 1) {
            return ['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单未审核通过'];
        }
        if ($find_proc->proc_state == 3) {
            return ['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已驳回'];
        }
        if ($find_proc->proc_state == 4) {
            return ['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单已入库'];
        }
        // 原单入库提交，实际入库数量大于0的，不允许原单入库
        if ($find_proc->proc_actual_count > 0 && $type == 3) {
            return ['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单部分商品已入库，不允许原单入库'];
        }
        if ($find_proc->proc_prbi_id != 0) {
            return ['code'=> 500, 'msg'=>'error', 'data'=>'已经生成账单的采购入库单，不得入库'];
        }
        return ['code'=> 200, 'msg'=>'success', 'data'=>$find_proc];
    }

    /**
     * [putInStorage 入库操作，部分入库、入库、原单入库的共有代码]
     * @param  [type] $request   [入库提交的数据]
     * @param  [type] $user_info [用户信息]
     * @param  [type] $find_proc [采购入库单信息]
     * @param  [type] $type      [入库类型：1部分入库2入库3原单入库]
     * @return [type]            [数组，返回入库结果]
     */
    private function putInStorage($request, $user_info, $find_proc, $type)
    {
        // 原单入库
        if ($type == 3) {
            // 查询采购入库的商品数据
            $find_prgo_goods = DB::table('procurement_goods')
                    ->where('prgo_proc_id', $request['proc_id'])
                    ->select('prgo_id', 'prgo_goo_id', 'prgo_purchase_number', 'prgo_actual_number', 'prgo_purchase_price')
                    ->get()->toArray();
            // 原单入库只提交采购入库单id，没有提交入库商品id、入库商品数量的数组
            // 这里把采购入库单的商品id、采购数量赋值给这两个数组，下面的代码就可以执行了
            $request['goo_id'] = array_column($find_prgo_goods, 'prgo_goo_id');
            $request['proc_actual_count'] = array_column($find_prgo_goods, 'prgo_purchase_number');
        // 部分入库、入库
        }else{
            // 查询采购入库的商品数据
            $find_prgo_goods = DB::table('procurement_goods')
                    ->where('prgo_proc_id', $request['proc_id'])
                    ->whereIn('prgo_goo_id', $request['goo_id'])
                    ->select('prgo_id', 'prgo_goo_id', 'prgo_purchase_number', 'prgo_actual_number', 'prgo_purchase_price')
                    ->get()->toArray();
        }
        if (count($find_prgo_goods) != count($request['goo_id'])) {
            return ['code'=> 500, 'msg'=>'error', 'data'=>'存在不是采购入库单的商品，无法入库！'];
        }
        $goods_price = array_column($find_prgo_goods, 'prgo_purchase_price', 'prgo_goo_id');//商品id对应的采购金额

        $proc_actual_count = 0;//实际入库总数量
        $price_sum = 0;//本次实际入库金额
        $i = 0;//序号
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || 
                !is_numeric($request['proc_actual_count'][$key]) || 
                $request['proc_actual_count'][$key] < 0) {
                return ['code'=> 500, 'msg'=>'error', 'data'=>'参数类型错误'];
            }
            $proc_actual_count += $request['proc_actual_count'][$key];//实际入库总数量
            $price_sum += $request['proc_actual_count'][$key] * (isset($goods_price[$value]) ? $goods_price[$value] :0);//实际入库总金额
            //没有在采购入库单内的商品
            if(!isset($goods_price[$value])){
                $without_bill[$i]['prgo_goo_id'] = $value;
                $without_bill[$i]['prgo_actual_number'] = $request['proc_actual_count'][$key];
                $without_bill[$i]['prgo_proc_id'] = $request['proc_id'];
            }

            $goo_actual_count[$value] = $request['proc_actual_count'][$key];//商品id对应的实际入库的数量
            $purchase_goo_actual_count[$value] = $request['proc_actual_count'][$key];//进销存-商品id对应的实际入库的数量
            $purchase_goo_actual_price[$value] = $goods_price[$value] / 100;//进销存-商品id对应的实际入库的金额
            $goo_actual_id[] = $value;
            $goo_inventory[] = 1;
            $i++;
        }

        // 1. 更改采购入库单数据
        if ($type != 1) {
            $update_data['proc_state'] = 4;//状态1提交/待审核2已通过/待入库3已驳回4已入库
            $oure_type = 1;//出入库记录类型1.入库单
        }else{
            $oure_type = 7;//出入库记录类型7.部分入库
        }
        $update_data['proc_execute_adm_id'] = $user_info->adm_id;//操作人
        $update_data['proc_actual_count'] = $find_proc->proc_actual_count + $proc_actual_count;//实际入库数量
        $update_data['proc_actual_price'] = $find_proc->proc_actual_price + $price_sum;//实际入库金额
        $update_data['proc_remark'] = isset($request['proc_remark']) ? $request['proc_remark'] : '';//入库备注
        if (isset($request['proc_data'])) {
            $update_data['proc_data'] = json_encode($request['proc_data']);
        }else{
            $update_data['proc_data'] = '';
        }
        $update_data['proc_update_time'] = date('Y-m-d H:i:s');
        $update_data['proc_execute_time'] = date('Y-m-d H:i:s');
        $proc_res = DB::table('procurement')
                    ->where('proc_id', $request['proc_id'])
                    ->update($update_data);

        // 2. 查询仓库的库存数量
        $find_waon = DB::table('warehouse_onhand')
                    ->where('waon_ware_id', $find_proc->proc_ware_id)
                    ->where('waon_class', $find_proc->proc_waon_class)
                    ->first(['waon_id', 'waon_all_amount', 'waon_stock_fine_amount', 'waon_lock_fine_amount', 
                        'waon_stock_priority_amount', 'waon_lock_priority_amount', 'waon_stock_unchecked_amount']);
        // 更改仓库库存总数量
        $waon_data['waon_all_amount'] = $find_waon->waon_all_amount + $proc_actual_count;//商品总库存
        $waon_data['waon_stock_fine_amount'] = $find_waon->waon_stock_fine_amount + $proc_actual_count;//良品总库存
        $waon_res = DB::table('warehouse_onhand')
                    ->where('waon_id', $find_waon->waon_id)
                    ->update($waon_data);
        
        // 3.生成出入库记录
        $oure_res = OutinRecord::add(
            $user_info, //用户信息
            $find_proc->proc_number, //原始单号
            $find_proc->proc_ware_id, //入库仓库id
            0, //出库仓库id
            $proc_actual_count, //出库的商品总量
            $oure_type, //类型1.入库单 2.出库单 3.调货单 4.旧货回收单 5.退换回收单 6.订单出库 7.部分入库 8.部分出库 9.发货单
            $request['goo_id'], //数组，商品id
            $request['proc_actual_count'], //数组，商品数量
            $goo_inventory, //数组，出库类型1良品2优先
            3,//操作类型：1锁定库存2出库3入库4调货5发货
            $waon_data['waon_stock_fine_amount'],//良品总库存
            $find_waon->waon_lock_fine_amount,//良品锁定数量
            $find_waon->waon_stock_priority_amount,//优先总库存
            $find_waon->waon_lock_priority_amount,//优先锁定数量
            $find_waon->waon_stock_unchecked_amount,//待检测总库存
            2 //出入库类型：1出库，2入库
        );

        // 4. 在仓库商品表增加对应的商品
        // 4.1.2 更新采购入库单商品的实际入库数量
        $sql = 'UPDATE `faster_procurement_goods` SET ';
        $actual_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        $actual_goo_id  = [];//实际入库的商品id
        $actual_goo_price  = [];//实际入库的商品价格
        foreach ($find_prgo_goods as $key => $value) {
            if (in_array($value->prgo_goo_id, $goo_actual_id)) {
                $actual_goo_id[] = $value->prgo_goo_id;//盘点实际入库的商品id
                $actual_goo_price[$value->prgo_goo_id] = $value->prgo_purchase_price;//盘点实际入库的商品价格

                // 商品实际入库数量
                // 更改商品库存数量
                $actual_number_sql = $actual_number_sql . ' WHEN ' .$value->prgo_id;
                $actual_number_sql = $actual_number_sql . ' THEN ' . ($value->prgo_actual_number + $goo_actual_count[$value->prgo_goo_id]);
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' .$value->prgo_id;
                $update_time_sql = $update_time_sql . ' THEN "' .date('Y-m-d H:i:s').'"';

                $ids = $ids . $value->prgo_id.',';
            }
        }

        if(!empty($actual_number_sql)){
            $sql = $sql .' `prgo_actual_number`=  CASE `prgo_id` '.$actual_number_sql.' END,';
            $sql = $sql .' `prgo_update_time`=  CASE `prgo_id` '.$update_time_sql.' END';
            $sql = $sql . ' WHERE `prgo_id` IN ('.trim($ids,',').')';
            $prog_res = DB::update($sql);
        }else{
            $prog_res = true;
        }
        //添加采购入库单没有的商品
        if(!empty($without_bill)){
            $without_bill_res = DB::table('procurement_goods')->insert($without_bill);
        }else{
            $without_bill_res = true;
        }
        
        // 4.2 查询仓库商品库存数量
        $warehouse_goods = DB::table('warehouse_goods')
            ->where('wago_ware_id', $find_proc->proc_ware_id)
            ->where('wago_class', $find_proc->proc_waon_class)
            ->whereIn('wago_goo_id', $request['goo_id'])
            ->get(['wago_id', 'wago_stock_number', 'wago_goo_id']);
        $warehouse_goods = json_decode(json_encode($warehouse_goods), true);

        // 4.3 处理要入库的商品库存数量
        if (empty($warehouse_goods)) {
            $ware_edit_res = true;
        }else{
            // 4.4 仓库商品表中已存在的商品，更改库存数量，整理更改SQL语句
            $sql = 'UPDATE `faster_warehouse_goods` SET ';
            $stock_number_sql = '';
            $update_time_sql = '';
            $ids = '';
            foreach ($warehouse_goods as $key => $value) {
                // 要更改的商品库存数量
                $stock_number = $value['wago_stock_number'] + $goo_actual_count[$value['wago_goo_id']];

                // 更改商品库存数量
                $stock_number_sql = $stock_number_sql . ' WHEN ' .$value['wago_id'];
                $stock_number_sql = $stock_number_sql . ' THEN ' .$stock_number;
                // 更改时间
                $update_time_sql = $update_time_sql . ' WHEN ' .$value['wago_id'];
                $update_time_sql = $update_time_sql . ' THEN "' .date('Y-m-d H:i:s').'"';

                $ids = $ids . $value['wago_id'].',';
                // 删除已更改的商品数据
                unset($goo_actual_count[$value['wago_goo_id']]);
            }

            if(!empty($stock_number_sql)){
                $sql = $sql .' `wago_stock_number`=  CASE `wago_id` '.$stock_number_sql.' END,';
                $sql = $sql .' `wago_update_time`=  CASE `wago_id` '.$update_time_sql.' END';
                $sql = $sql . ' WHERE `wago_id` IN ('.trim($ids,',').')';
                $ware_edit_res = DB::update($sql);
            }else{
                $ware_edit_res = true;
            }
        }

        if (empty($goo_actual_count)) {
            $ware_add_res = true;
        }else{
            // 4.5 仓库商品表中没有的商品，新增仓库商品
            $num = 0;
            foreach ($goo_actual_count as $key => $value) {
                $ware_add_data[$num]['wago_ware_id'] = $find_proc->proc_ware_id;
                $ware_add_data[$num]['wago_class'] = $find_proc->proc_waon_class;
                $ware_add_data[$num]['wago_goo_id'] = $key;
                $ware_add_data[$num]['wago_stock_number'] = $value;
                $num++;
            }
            $ware_add_res = DB::table('warehouse_goods')->insert($ware_add_data);
        }

        // 5.进销存
        // 查询仓库类别的进销存计算方式
        $algorithm_type = DB::table('warehouse_class')
                    ->where('wacl_cid', $user_info->adm_cid)
                    ->where('wacl_shop_id', $user_info->adm_shop_id)
                    ->where('wacl_class_numerical', $find_proc->proc_waon_class)
                    ->value('wacl_sssa_id');
        $purchase_return = StockSellStorageGoods::purchaseSales(
                $user_info,//用户信息
                $algorithm_type,//进销存计算方式：1先进先出2移动加权平均法3无成本
                1,//类型：1采购，2销出，3调拨
                $find_proc->proc_ware_id,//仓库id
                $find_proc->proc_waon_class,//仓库类别
                $request['goo_id'],//数组，商品id
                $purchase_goo_actual_count,//数组，商品数量；[商品id=>商品数量]
                $purchase_goo_actual_price, //数组，商品金额，成本价(不乘以100)；[商品id=>商品金额]
                1 //进销存的移动加权平均法算法类型：1计算平均价2不计算平均价【退换回收时不计算平均价】
            );
        if ($purchase_return['code'] == 500) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'入库失败'];
        }
        return ['code'=>200, 'msg'=>'success', 'data'=>'入库成功'];
    }

    // 提交入库
    public function submitStorage(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->submitStorageValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 检查采购入库单是否符合入库条件
        $proc_return = $this->storageCheck($request['proc_id'], 2);
        if ($proc_return['code'] == 500) {
            return response()->json($proc_return);
        }

        if ($request['type'] == 1) {
            // 获取采购入库单信息
            $find_proc = DB::table('procurement as a')
                    ->leftJoin('procurement_client as b', 'b.prcl_proc_id', '=', 'a.proc_id')
                    ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.proc_ware_id')
                    ->where('proc_id',$request['proc_id'])
                    ->select('proc_state', 'proc_number', 'proc_ware_id', 'proc_count', 'prcl_channel_unit',
                    'prcl_name', 'prcl_phone', 'prcl_address', 'ware_name', 'proc_data', 'proc_remark', 
                    'proc_waon_class', 'prcl_province', 'prcl_city', 'prcl_county')
                    ->first();
            $find_proc->proc_data = json_decode($find_proc->proc_data, true);

            $find_goods = DB::table('procurement_goods as a')
                        ->leftJoin('goods as b', 'b.goo_id', '=', 'a.prgo_goo_id')
                        ->where('prgo_proc_id',$request['proc_id'])
                        ->select('prgo_purchase_number', 'goo_id', 'goo_name', 'goo_type', 'goo_goods_encode', 'prgo_actual_number')
                        ->get();
            $find_scan_record = DB::table('procurement_record')
                        ->where('prre_proc_id',$request['proc_id'])
                        ->select('prre_goo_id', 'prre_goo_name', 'prre_goo_goods_encode', 'prre_goo_quantity')
                        ->get();
            $data['find_proc'] = $find_proc;
            $data['find_goods'] = $find_goods;
            $data['find_scan_record'] = $find_scan_record;
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
        }
        
        $find_proc = $proc_return['data'];//查询的采购入库单信息

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        // 入库
        $put_in_return = $this->putInStorage($request->all(), $user_info, $find_proc, 2);

        if($put_in_return['code'] == 200) {
        	DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购入库单','入库','采购入库单：'.$find_proc->proc_number.' 入库成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'入库成功']);
        }else{
        	DB::rollBack();
            return response()->json(['code'=>500,'msg'=>'error','data'=>'入库失败']);
        }
    }

    // 部分入库
    public function partStorage(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->partStorageValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 检查采购入库单是否符合入库条件
        $proc_return = $this->storageCheck($request['proc_id'], 1);
        if ($proc_return['code'] == 500) {
            return response()->json($proc_return);
        }
        $find_proc = $proc_return['data'];

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        // 入库
        $put_in_return = $this->putInStorage($request->all(), $user_info, $find_proc, 1);

        if($put_in_return['code'] == 200) {
            $prre_del_res = DB::table('procurement_record')
                    ->where('prre_proc_id', $request['proc_id'])
                    ->delete();
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购入库单', '部分入库', '采购入库单：'.$find_proc->proc_number.' 入库成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'入库成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'入库失败']);
        }
    }

	// 原单入库
    public function originalRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 检查采购入库单是否符合入库条件
        $proc_return = $this->storageCheck($request['proc_id'], 3);
        if ($proc_return['code'] == 500) {
            return response()->json($proc_return);
        }
        $find_proc = $proc_return['data'];

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        // 入库
        $put_in_return = $this->putInStorage($request->all(), $user_info, $find_proc, 3);

        if($put_in_return['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '采购入库单', '原单入库', '采购入库单：'.$find_proc->proc_number.' 入库成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'原单入库成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'原单入库失败']);
        }
    }

    // 驳回
    public function reject(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_proc = DB::table('procurement')
                    ->where('proc_id',$request['proc_id'])
                    ->select('proc_number', 'proc_state')
                    ->first();
        if ($find_proc->proc_state != 1) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前采购入库单不是待审核状态']);
        }

        // 驳回
        $update_data['proc_state'] = 3;//状态1提交/待审核2已通过/已入库3已驳回
        $update_data['proc_update_time'] = date('Y-m-d H:i:s');
        $proc_res = DB::table('procurement')
                    ->where('proc_id', $request['proc_id'])
                    ->update($update_data);
        if($proc_res) {
	        // 获取当前操作账号信息
	        $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '采购入库单','驳回','采购入库单：'.$find_proc->proc_number.' 驳回成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'驳回成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'驳回失败']);
        }
    }

    // 扫码记录
    public function scanRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->scanRecordValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        if ($request['scan_type'] == 1) {
            // 条形码入库
            // 获取当前操作账号信息
            $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;
            // 1. 判断当前门店是否有该条形码商品
            $find_goods = DB::table('goods')
                    ->where('goo_cid', $user_info->adm_cid)
                    ->where('goo_superior_shop_id', $shop_id)
                    ->where('goo_delete', 1)
                    ->where('goo_goods_encode', $request['scan_code'])
                    ->select('goo_id', 'goo_goods_encode', 'goo_name')
                    ->first();
            if (!$find_goods) {
                return response()->json([
                            'code'=> 500, 
                            'msg'=>'error', 
                            'data'=>'当前门店未找到 '.$request['scan_code'].' 该条形码商品'
                        ]);
            }
            // 查找采购入库记录表是否添加当前扫码商品
            $find_prre = DB::table('procurement_record')
                    ->where('prre_proc_id', $request['proc_id'])
                    ->where('prre_goo_goods_encode', $find_goods->goo_goods_encode)
                    ->select('prre_id', 'prre_goo_quantity')
                    ->first();
            if ($request['type'] == 1) {
                // 扫码增加商品
                if ($find_prre) {
                    $prre_res = DB::table('procurement_record')
                                ->where('prre_id', $find_prre->prre_id)
                                ->increment('prre_goo_quantity');
                } else {
                    // 没有添加商品，增加一条商品数据
                    $prre_data['prre_proc_id'] = $request['proc_id'];
                    $prre_data['prre_goo_id'] = $find_goods->goo_id;
                    $prre_data['prre_goo_name'] = $find_goods->goo_name;
                    $prre_data['prre_goo_goods_encode'] = $find_goods->goo_goods_encode;
                    $prre_data['prre_goo_quantity'] = 1;
                    $prre_res = DB::table('procurement_record')->insert($prre_data);
                }
                // 提示文字
                $return_meg = '添加';
            } else {
                // 扫码减少商品
                if ($find_prre) {
                    if($find_prre->prre_goo_quantity == 1){
                        $prre_res = DB::table('procurement_record')
                                    ->where('prre_id', $find_prre->prre_id)
                                    ->delete();
                    }else{
                        $prre_res = DB::table('procurement_record')
                                    ->where('prre_id', $find_prre->prre_id)
                                    ->decrement('prre_goo_quantity');
                    }
                } else {
                    return response()->json([
                            'code'=> 500, 
                            'msg'=>'error', 
                            'data'=>$request['scan_code'].' 该条形码商品尚未添加扫码记录'
                        ]);
                }
                // 提示文字
                $return_meg = '删除';
            }
            if($prre_res) {
                Common::addLog($user_info, getRealIp($request), '采购入库单','扫码记录','商品条码：'.$request['scan_code'].' 扫码记录'.$return_meg.'成功');
                return response()->json(['code'=>200,'msg'=>'success','data'=>'扫码记录'.$return_meg.'成功','return_data'=>$find_goods]);
            }else{
                return response()->json(['code'=>500,'msg'=>'error','data'=>'扫码记录'.$return_meg.'失败']);
            }
        } else {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂未开通二维码扫码入库']);
        }
    }

    // 删除扫码记录
    public function deleteRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->deleteRecordValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $prre_res = DB::table('procurement_record')
                    ->where('prre_proc_id', $request['proc_id'])
                    ->where('prre_goo_id', $request['goo_id'])
                    ->delete();
        if ($prre_res) {
            return response()->json(['code'=>200,'msg'=>'success','data'=>'商品扫码记录删除成功']);
        } else {
            return response()->json(['code'=>500,'msg'=>'error','data'=>'商品扫码记录删除失败']);
        }
    }

    // 商品搜索记录
    public function searchRecord(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->searchRecordValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['proc_actual_count'][$key]) || $request['proc_actual_count'][$key] < 0 ) {
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            $goo_id[] = $value;
            $goo_quantity[$value] = $request['proc_actual_count'][$key];
        }
        $find_goods = DB::table('goods')
                    ->whereIn('goo_id', $goo_id)
                    ->select('goo_id','goo_name', 'goo_goods_encode')
                    ->get();
        foreach ($find_goods as $key => $value) {
            $prre_data[$key]['prre_proc_id'] = $request['proc_id'];
            $prre_data[$key]['prre_goo_id'] = $value->goo_id;
            $prre_data[$key]['prre_goo_name'] = $value->goo_name;
            $prre_data[$key]['prre_goo_goods_encode'] = $value->goo_goods_encode;
            $prre_data[$key]['prre_goo_quantity'] = $goo_quantity[$value->goo_id];
        }
        DB::beginTransaction();
        $find_prre = DB::table('procurement_record')
                    ->where('prre_proc_id', $request['proc_id'])
                    ->value('prre_id');
        if ($find_prre) {
            // 删除原来提交记录的数据
            $prre_del_res = DB::table('procurement_record')
                        ->where('prre_proc_id', $request['proc_id'])
                        ->delete();
        } else {
            $prre_del_res = true;
        }

        // 添加新的商品搜索记录
        $prre_add_res = DB::table('procurement_record')->insert($prre_data);

        if ($prre_add_res && $prre_del_res) {
            DB::commit();
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '采购入库单','入库记录','商品搜索记录提交成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'商品搜索记录提交成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500,'msg'=>'error','data'=>'商品搜索记录提交失败']);
        }
    }

    // 生成账单搜索
    public function searchBill(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();
        // 如果选择了单位类型 查询出该单位类型下有多少个单位
        if(!empty($search_data['unit_type'])){
            $chun_id = DB::table('channel_unit')
                    ->where('chun_chty_id', $search_data['unit_type'])
                    ->get(['chun_id'])->toArray();
            $search_data['chty_id'] = array_column($chun_id, 'chun_id');
        }

        $data = DB::table('procurement as p')
                ->leftJoin('admin as c', 'c.adm_id', '=', 'p.proc_adm_id')
                ->where('proc_cid', $user_info->adm_cid)
                ->where('proc_superior_shop_id', $shop_id)
                ->where('proc_payment_way', 1)//结算方式1.账期 2.现结 3微信 4支付宝5预付款
                ->where('proc_actual_count', '>', 0)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['prbi_id'])) {
                        // 编辑
                        $query->where('proc_prbi_id', 0)
                              ->Orwhere('proc_prbi_id', $search_data['prbi_id']);
                    } else {
                        // 新增
                        $query->where('proc_prbi_id', 0);
                    }
                })//判断是编辑还是新增
                ->where(function($query) use($search_data) {
                    //如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                        $query->whereBetween('proc_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                    }else{
                        // 如果选择开始时间
                        if (!empty($search_data['start_time'])){
                            $query->where('proc_create_time','>=',$search_data['start_time']);
                        }else{
                            // 如果选择结束时间
                            if (!empty($search_data['end_time'])) {
                                $query->where('proc_create_time','<=',$search_data['end_time'].' 23:59:59');
                            }
                        }
                    }
                }) //起止日期
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['proc_chun_id'])) {
                        $query->where('proc_chun_id', $search_data['proc_chun_id']);
                    }
                })//客户单位
                ->orderBy('proc_id', 'desc')
                ->get(['proc_id', 'proc_create_time', 'proc_number', 'proc_price', 'proc_actual_price', 'adm_name']);

        return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
    }
    
    // 生成账单
    public function createBill(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->createBillValidator($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;

        $number = 'CZ'.time().rand(1000000,9999999);
        // 1.采购账单表新增一条数据
        $add_data['prbi_cid'] = $user_info->adm_cid;
        $add_data['prbi_shop_id'] = $user_info->adm_shop_id;
        $add_data['prbi_superior_shop_id'] = $shop_id;
        $add_data['prbi_create_adm_id'] = $user_info->adm_id;
        $add_data['prbi_number'] = $number;
        $add_data['prbi_wor_amount'] = count($request['proc_id']);
        $add_data['prbi_start_time'] = $request['start_time'];
        $add_data['prbi_end_time'] = $request['end_time'];
        $add_data['prbi_state'] = 3; //待审核
        $add_data['prbi_type'] = $request['prbi_type']; //类型：1门店零售2渠道单位
        $add_data['prbi_client_id'] = $request['prbi_client_id']; //渠道/客户id
        // 获取到商品总量/合计金额/结算金额
        $add_data['prbi_total_price'] = 0; //合计金额
        $add_data['prbi_bill_price'] = 0; //结算金额
        $add_data['prbi_goods_sum'] = 0; //商品总量

        $procurement = DB::table('procurement')
                    ->whereIn('proc_id',$request['proc_id'])
                    ->get(['proc_actual_count','proc_price','proc_actual_price']);
        foreach ($procurement as $key => $value) {
            $add_data['prbi_total_price'] += $value->proc_price;
            $add_data['prbi_bill_price'] += $value->proc_actual_price;
            $add_data['prbi_goods_sum'] += $value->proc_actual_count;
        }


        DB::beginTransaction();

        $prbi_id = DB::table('procurement_bill')->insertGetId($add_data);

        // 2.修改工单表 账单id
        $sql = 'UPDATE `faster_procurement` SET ';
        $proc_prbi_id = ''; //账单id
        $update_time = ''; //调货时间
        $proc_id = "";

        foreach ($request['proc_id'] as $key => $value) {
           // 更改账单id
            $proc_prbi_id = $proc_prbi_id . ' WHEN ' .$value;
            $proc_prbi_id = $proc_prbi_id . ' THEN ' .$prbi_id;
            // 更改时间
            $update_time = $update_time . ' WHEN ' .$value;
            $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';
            //要更改的采购单id
            $proc_id = $proc_id . $value.',';
        }
        $sql = $sql .' `proc_prbi_id`= CASE `proc_id` '.$proc_prbi_id.' END,';
        $sql = $sql .' `proc_update_time`= CASE `proc_id` '.$update_time.' END';
        $sql = $sql .' WHERE `proc_id` IN ('.trim($proc_id,',').')';
        $save_procurement = DB::update($sql);

        if($prbi_id && $save_procurement){
            Common::addLog($user_info, getRealIp($request), '采购入库','生成账单','生成账单：'.$number.'成功');
            DB::commit();
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'生成账单成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'生成账单失败']);
        }
    }

    // 打印
    public function print(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 采购入库单数据
        $proc_data = DB::table('procurement as a')
                ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.proc_ware_id')
                ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_id')
                ->leftJoin('channel_info as chin', 'a.proc_chun_id', '=', 'chin.chin_chun_id')
                ->leftjoin('print_number as prnu','prnu.prnu_original_id','=','a.proc_id')
                ->where('proc_id', $request['proc_id'])
                ->select('proc_id', 'proc_number', 'proc_state', 'proc_count', 'proc_adm_id',  'proc_audit_id', 'proc_price', 'proc_actual_price', 
                    'proc_create_time', 'prcl_channel_unit', 'prcl_name', 'prcl_phone', 'prcl_address', 'ware_name', 'proc_data', 'proc_remark',
                    'proc_execute_adm_id', 'proc_execute_time', 'proc_audit_time','chin_level','prnu_print_num')
                ->first();
        
        $data['proc_price'] = num_to_rmb($proc_data->proc_actual_price / 100);
        if ($proc_data->proc_execute_time == '0000-00-00 00:00:00') {
            $proc_data->proc_execute_time = '';
        }

        // 获取采购商品数据
        $find_goods = DB::table('procurement_goods as a')
                ->leftJoin('goods as b', 'a.prgo_goo_id', '=', 'b.goo_id')
                ->where('prgo_proc_id', $request['proc_id'])
                ->select('prgo_purchase_number', 'prgo_actual_number', 'goo_name', 'goo_goods_encode','prgo_purchase_price')
                ->get();

        // 查询账号id对应姓名
        $adm_id = [$proc_data->proc_adm_id, $proc_data->proc_audit_id, $proc_data->proc_execute_adm_id];
        array_unique($adm_id);
        $find_admin = DB::table('admin')
                ->where('adm_id', $adm_id)
                ->select('adm_id', 'adm_name')
                ->first();

        $data['proc_data'] = $proc_data;
        $data['goods_data'] = $find_goods;
        $data['find_admin'] = $find_admin;

        return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
    }

    //导出
    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 as a')
            ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.proc_ware_id')
            ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_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_number'])) {
                    $query->where('proc_number', 'like', $search_data['proc_number'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prcl_channel_unit'])) {
                    $query->where('prcl_channel_unit', 'like', $search_data['prcl_channel_unit'].'%' );
                }
            })
            ->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['prcl_name'])) {
                    $query->where('prcl_name', 'like', $search_data['prcl_name'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prcl_phone'])) {
                    $query->where('prcl_phone', 'like', $search_data['prcl_phone'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['ware_name'])) {
                    $query->where('ware_name', 'like', $search_data['ware_name'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['proc_state'])) {
                    $query->where('proc_state', $search_data['proc_state']);
                }
            })
            ->get(['proc_number', 'proc_state', 'proc_count', 'proc_adm_id', 'proc_audit_id',
                'proc_remark', 'proc_data', 'proc_create_time', 'prcl_channel_unit', 'prcl_name', 'prcl_phone',
                'prcl_address', 'ware_name'])->toArray();
        if(!empty($data)){
            // 将对象转化为数组
            $data = json_decode(json_encode($data),true);
            // 查找操作人id 审核人id 物流json信息
            foreach ($data as $key => $value) {
                if ($value['proc_adm_id']) {
                    $adm_id[] = $value['proc_adm_id'];
                }
                if ($value['proc_audit_id']) {
                    $adm_id[] = $value['proc_audit_id'];
                }
            }
            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $admin = DB::table('admin')->whereIn('adm_id', $adm_id)->pluck('adm_name', 'adm_id');

            foreach ($data as $key => $value) {
                // 状态
                if($value['proc_state'] == 1){$data[$key]['proc_state'] = '待审核';}
                if($value['proc_state'] == 2){$data[$key]['proc_state'] = '待入库';}
                if($value['proc_state'] == 3){$data[$key]['proc_state'] = '已驳回';}
                if($value['proc_state'] == 4){$data[$key]['proc_state'] = '已入库';}
                // 操作人
                $data[$key]['proc_adm_id'] = $admin[$value['proc_adm_id']];
                // 审核人
                if($value['proc_audit_id'] == 0){
                    $data[$key]['proc_audit_id'] = '';
                }else{
                    $data[$key]['proc_audit_id'] = $admin[$value['proc_audit_id']];
                }
                // 物流信息json数据
                if(!empty($value['proc_data'])){
                    $value['proc_data'] = json_decode($value['proc_data'],true);

                    if($value['proc_data'][0]['type'] == 1){
                        // 1.第三方物流
                        $data[$key]['proc_data'] = '['.$value['proc_data'][0]['traffic_unit'].']
                        '.implode(",", $value['proc_data'][0]['express_waybill']);
                    } elseif ($value['proc_data'][0]['type'] == 2 || $value['proc_data'][0]['type'] == 3){
                        // 2.供货方配送 3.采购方自提
                        $data[$key]['proc_data'] = '['.$value['proc_data'][0]['traffic_unit'].'] '
                        .$value['proc_data'][0]['name'].','
                        .$value['proc_data'][0]['phone'].
                        implode(",", $value['proc_data'][0]['car_num']);
                    } elseif ($value['proc_data'][0]['type'] == 4){
                        // 4.无
                        $data[$key]['proc_data'] = $value['proc_data'][0]['remark'];
                    }
                }
                //单号
                $data[$key]['proc_number'] = "\t".$value['proc_number'];
            }
        }else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无导出数据']);
        }

        $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'=>'导出失败']);
        }
    }

    //打印次数提交
    public function printNumber(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementController;
        $error_message = $verify_data->infoValidator($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;

        //判断是否有打印数据
        $prnu_id = DB::table('print_number')
            ->where('prnu_adm_cid',$user_info->adm_cid)
            ->where('prnu_superior_shop_id',$shop_id)
            ->where('prnu_type',3)
            ->where('prnu_original_id',$request['proc_id'])
            ->select('prnu_id','prnu_print_num')
            ->first();

        $prnu_data['prnu_adm_cid'] = $user_info->adm_cid;   //公司id
        $prnu_data['prnu_shop_id'] = $user_info->adm_shop_id;   //所属门店id
        $prnu_data['prnu_superior_shop_id'] = $shop_id;   //所属总店id
        $prnu_data['prnu_type'] = 3;   //所属类型
        $prnu_data['prnu_original_id'] = $request['proc_id'];   //采购单id
        $prnu_data['prnu_update_time'] = date('Y-m-d H:i:s');

        if ($prnu_id) {
            $prnu_data['prnu_print_num'] = $prnu_id->prnu_print_num + 1;   //打印次数
            $prnu_res = DB::table('print_number')
                ->where('prnu_original_id',$request['proc_id'])
                ->update($prnu_data);
        } else {
            $prnu_data['prnu_print_num'] = 1;   //打印次数
            $prnu_res = DB::table('print_number')->insert($prnu_data);
        }
        if ($prnu_res) {
            return response()->json(['code'=>200,'msg'=>'success','data'=>"打印成功"]);
        } else {
            return response()->json(['code'=>200,'msg'=>'success','data'=>"打印失败"]);
        }
    }
}
