<?php
namespace App\Http\Controllers\Api\Storage;

use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Exception;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Controllers\Api\Verify\Storage\VerifyWareInorderController;
use App\Http\Models\Services\WarehouseManage\WareInorder;
use App\Http\Models\Services\WarehouseManage\PurchaseOrder;

// 仓储系统 -- 出入库列表
class WareInorderController extends Controller
{
    // 出入库列表页面
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWareInorderController;
        $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->adm_shop_id;

        $where_data = $request->all();
        $page_size  = (int) $request->input('show_count', 10);
        $where_data = RemoveLineFeed($where_data);

        $cg_type = $request->input('cg_type', 1);

        $list = Db::table('purchase_order')
            ->leftjoin('ware_inorder', 'ware_inorder.cg_number', '=', 'purchase_order.cg_number')
            ->whereIn('cg_state', [2, 5, 6, 8, 11, 12])
            ->where('is_del', 1)
            ->where('purchase_order.company_id', $user_info->adm_cid)
            ->where('cg_shop_id', $shop_id)
            ->where(function ($query) use ($cg_type) {
                if ($cg_type == 2) {
                    $query->where('cg_types', 2);
                } else {
                    $query->where('cg_types', 1);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_state'])) {  //采购状态
                    $query->where('cg_state', $where_data['cg_state']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_number'])) {  //采购单号
                    $query->where('purchase_order.cg_number', 'like', '%' . $where_data['cg_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['rk_number'])) { //入库单号
                    $query->where('rk_number', 'like', '%' . $where_data['rk_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['goods_name'])) { //包含商品
                    $query->where('goods_name', 'like', '%' . $where_data['goods_name'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_wareid'])) { //仓库
                    $query->where('cg_wareid', $where_data['cg_wareid']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_creator'])) {  //创建人
                    $query->where('cg_creator', 'like', '%' . $where_data['cg_creator'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_start'])) {  //创建开始时间
                    $query->where('purchase_order.create_time', '>=', $where_data['create_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_end'])) {     //创建结束时间
                    $query->where('purchase_order.create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['dh_start'])) {  //到货开始时间
                    $query->where('dh_time', '>=', $where_data['dh_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['dh_end'])) {    //到货结束时间
                    $query->where('dh_time', '<=', $where_data['dh_end'] . ' 23:59:59');
                }
            })
            ->where(function ($query) use ($where_data) { //供货单位
                if (!empty($where_data['cg_supplyunit'])) {
                    $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                }
            })
            ->select('purchase_order.cg_number', 'contract_number', 'cg_state', 'cg_purchasetime', 'auditor_user', 'cg_wareid', 'cg_remark', 'cg_creator', 'purchase_order.create_time', 'contact_name', 'contact_phone', 'cg_paymentype', 'cg_delivertype', 'cg_invoicetype', 'cg_settlementype', 'business_type', 'rk_remarks', 'cg_supplyunit', 'puor_supplyunit_type')
            ->orderBy('purchase_order.create_time', 'desc')
            ->groupBy('purchase_order.cg_number')
            ->paginate($page_size);

        $data = $list->items();
        $page_arr = [
            'page_count' => $list->lastPage(),  //总页数
            'page' => $list->currentPage(),     //当前页
            'page_size' => $page_size,          //每页条数
            'data_count' => $list->total(),     //总条数
        ];
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);

        if ($data) {
            $data = json_decode(json_encode($data), true);

            $cg_wareid = array_unique(array_column($data, 'cg_wareid')); //仓库id
            $cg_supplyunit = array_unique(array_column($data, 'cg_supplyunit')); //供货单位id
            // 查询仓库数据
            $warehoust = Db::table('warehouse')
                ->whereIn('ware_id', $cg_wareid)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            // 查询供货单位数据
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $cg_supplyunit)
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_state', 1)
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            foreach ($data as $key => $val) {
                $data[$key]['ware_name'] = isset($warehoust[$val['cg_wareid']]) ? $warehoust[$val['cg_wareid']] : '';
                $data[$key]['chun_unit_name'] = isset($channel[$val['cg_supplyunit']]) ? $channel[$val['cg_supplyunit']] : '';
                if ($val['auditor_user'] == 0) {
                    $data[$key]['auditor_user'] = '';
                } else {
                    $data[$key]['auditor_user'] = Db::table('admin')
                        ->where('adm_id', $val['auditor_user'])
                        ->value('adm_name');
                }
                if ($val['puor_supplyunit_type'] == 3) {
                    $data[$key]['auditor_user'] = Db::connection('mysql_scm')->table('admin')
                        ->where('adm_id', $val['auditor_user'])
                        ->value('adm_name');
                }


                // 计算入库数量
                $ruku_data = Db::table('ware_inorder')
                    ->where('cg_number', $val['cg_number'])
                    ->where('rk_type', 1)
                    ->select('rk_number')
                    ->get();
                $ruku_data = json_decode(json_encode($ruku_data), true);
                $ruku_num = 0;
                if (!empty($ruku_data)) {
                    $ruku_num = (int) DB::table('storage_goods')
                        ->whereIn('relation_number', array_column($ruku_data, 'rk_number'))
                        ->sum('ruku_num');
                }

                unset($ruku_data);
                $data[$key]['ruku_num']   = $ruku_num;

                $goods = DB::table('storage_goods')
                    ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                    ->where('relation_number', $val['cg_number'])
                    ->select('goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'ruku_num', 'tax_rate', 'currency', 'estimate_time', 'company_unit', 'edit_time as dh_time', 'goods_type', 'goo_brse_id', 'goo_class', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
                    ->get();
                $goods = json_decode(json_encode($goods), true);
                // 查询系列数据
                $goo_brse_id = array_column($goods, 'goo_brse_id');
                $brse_data = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->pluck('brse_name', 'brse_id')
                    ->toArray();
                $goods_num = 0;
                foreach ($goods as $k => $v) {
                    $goods_num = $goods_num + $v['goods_num'];
                    if ($v['dh_time'] != '0000-00-00 00:00:00') {
                        $goods[$k]['dh_time'] = date("Y-m-d", strtotime($v['dh_time']));
                    } else {
                        $goods[$k]['dh_time'] = '0000-00-00';
                    }
                    // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                        if (!empty($v['goo_brse_id'])) {
                            if ($v['goo_class'] == 2) {
                                $goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                unset($goods[$k]['goo_brse_id']);
                            } else {
                                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                    $goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                    unset($goods[$k]['goo_brse_id']);
                                }
                            }
                        }
                    }
                    // 显示品牌名称
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                        if ($v['goo_class'] == 2) {
                            $goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $goods[$k]['goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $goods[$k]['goo_name'];
                            }
                        }
                    }
                }
                if ($cg_type == '2') {
                    $data[$key]['goods_count']  = '-' . $goods_num;
                } else {
                    $data[$key]['goods_count']  = $goods_num;
                }

                $data[$key]['storage_goods'] = $goods;
                $buttonData = [];
                if($cg_type == 1 && !in_array($val['cg_state'],[6,11,12])){
                    $buttonData[] = 'Warehousing';//采购入库
                }
                if($cg_type == 2 || $val['cg_state'] != 11){
                    $buttonData[] = 'delivery';//退货出库
                }
                if($cg_type == 1 || $val['cg_state'] != 5){
                    $buttonData[] = 'WareRecord';//库房记录
                }
                $buttonData[] = 'info';//查看详情
                $button = CommonService::getListButton($buttonData,$list_button);
                $data[$key]['button_one'] = $button['button_one']??[];
                $data[$key]['button_two'] = $button['button_two']??[];
                $data[$key]['button_three'] = $button['button_three']??[];
            }
        }

        // 统计各个状态下的数量
        $state_count = Db::table('purchase_order')
            ->where('company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->whereIn('cg_state', [5, 6, 8, 11])
            ->where(function ($query) use ($cg_type) {
                if ($cg_type == 2) {
                    $query->where('cg_types', 2);
                } else {
                    $query->where('cg_types', 1);
                }
            })
            ->where('is_del', 1)
            ->where('company_id', $user_info->adm_cid)
            ->groupBy('cg_state')
            ->select(DB::raw('cg_state,count(*) as num'))->get();
        $state_count = json_decode(json_encode($state_count), true);
        $state_arr = [5, 6, 8, 11];
        $key_array = array_column($state_count, 'cg_state');
        foreach ($state_arr as $key => $val) {
            if (!in_array($val, $key_array)) {
                $state_count[] = ['cg_state' => $val, 'num' => 0];
            }
        }


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

    // 入库
    public function warehousing(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWareInorderController;
        $error_message = $verify_data->warehousingShowValidator($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;

        // type类型：1获取采购单相关数据
        if ($request['type'] == 1) {
            return response()->json($this->purchaseData($user_info, $request->input('cg_number')));
        }
        // type类型：2提交采购入库数据
        // 验证提交数据
        $verify_data = new VerifyWareInorderController;
        $error_message = $verify_data->warehousingValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $goods_data = json_decode($request['goods'], true); //入库商品数据
        if (empty($goods_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请选择入库商品']);
        }

        $cg_number = $request->input('cg_number'); //采购单号
        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->select('cg_id', 'cg_number', 'cg_settlementype', 'cg_yfmoney', 'cg_moling', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time', 'is_del')
            ->first();
        // is_del 是否删除1正常2删除
        if ($cg_data->is_del != 1) {
            return response()->json(['code'=>500, 'msg'=>'当前采购单已删除，无法入库！', 'data'=>'当前采购单已删除，无法入库！']);
        }
        $cg_data = json_decode(json_encode($cg_data), true);

        // 查询采购单的商品数数据
        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $cg_number)
            ->select('goods_id', 'goods_number', 'storehouse', 'goods_name', 'cg_goodsnum', 'goods_num', 'univalence', 'ruku_num', 'company_id', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'old_univalence', 'stgo_stop')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组
        $storage_goods = array_column($storage_goods, null, 'goods_id'); //商品id当做数组键值
        $goods_id = array_unique(array_column($goods_data, 'goods_id')); //前端提交入库数据的商品id

//        if(isset($request['rk_number']) && !empty($request['rk_number'])){
//            $rk_number = $request['rk_number'];
//        }else {
            $rk_number = 'RK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //单号
//        }

        DB::beginTransaction();
        $warehousing_retrun = WareInorder::warehousing(
            $user_info, //用户信息
            $shop_id, //门店id
            $request->all(), //用户信息
            $goods_data, //提交的商品数据
            $storage_goods, //查询采购单商品信息
            $goods_id, //前端提交入库数据的商品id
            $cg_data, //查询的采购单信息
            $rk_number //入库单号
        );
        if ($warehousing_retrun['code'] != 200) {
            DB::rollBack();
            return response()->json($warehousing_retrun);
        }

        

        //采购入库修改商品单价和总价
        $amount_ret = $this->updateWagoAmountWare($storage_goods);
        if($amount_ret['code'] != 200){
            DB::rollBack();
            return response()->json($amount_ret);
        }

        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['rk_number'] = $request['rk_number'];
        $log_data['rk_type'] = '采购入库';
        $log_data['request'] = $request->all();
        $log_data['warehousing_retrun'] = $warehousing_retrun;
        Common::write_record_log($log_data, 'pc/AppletWareInorderController.txt', 'warehousing');

        // 查询自动流程
        $autoNext_data['cg_number'] = $cg_number;
        $autoNext_data['now_state'] = 3;
        $autoNext_res = PurchaseOrder::autoNext($user_info,$autoNext_data,$shop_id);
        if ($autoNext_res['code'] != 200) {
            return $autoNext_res;
        }

        if ($warehousing_retrun['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '入库列表', '采购入库', $rk_number . '成功');
            if ($request['rk_remark'] != '') {
                Common::addNote($user_info, $shop_id, $rk_number, $request['rk_remark'], '添加入库单');
            }
            return response()->json($warehousing_retrun);
        } else {
            DB::rollBack();
            return response()->json($warehousing_retrun);
        }
    }

    /* 商品库存有变化的时候，修改仓库商品得总价 20230518
     * $storage_goods 采购的商品信息
     */
    public function updateWagoAmountWare($storage_goods)
    {
        if(empty($storage_goods)){
            return ['code'=>500, 'msg'=>'仓库商品不存在', 'data'=>'仓库商品不存在1'];
        }
        $ware_id = array_unique(array_column($storage_goods,'storehouse'));//仓库id
        $good_ids = array_column($storage_goods,'goods_id');//商品id
        // 查询仓库商品信息
        $find_tror = DB::table('warehouse_goods')
            ->whereIn('wago_goo_id', $good_ids)
            ->where('wago_class', 1)
            ->whereIn('wago_ware_id', $ware_id)
            ->select('wago_id', 'wago_goo_price', 'wago_goo_amount', 'wago_stock_number', 'wago_lock_quantity', 'wago_ware_id', 'wago_goo_id')
            ->get()->toArray();

        if(empty($find_tror)){
            return ['code'=>500, 'msg'=>'仓库商品不存在', 'data'=>'仓库商品不存在2'];
        }
        //查询商品的换算单位个数
        $goo_data = DB::table('goods')
            ->whereIn('goo_id', $good_ids)
            ->select('goo_id', 'goo_name', 'goo_unit', 'goo_unta_id', 'goo_unit_conversion')
            ->get()->toArray();
        if($goo_data){
            foreach ($goo_data as $k => $v){
                $goo_data_ret[$v->goo_id] = (array)$v;
            }
        }
        foreach ($find_tror as $k => $v){
            $trod_data = [];
            $price = $storage_goods[$v->wago_goo_id]['univalence'];//采购单价
            //如果单位为卷，换算单价
            // if(isset($goo_data_ret[$v->wago_goo_id])){
            //     if ($goo_data_ret[$v->wago_goo_id]['goo_unta_id'] == 1) {//当商品单位为卷时，计算单价
            //         $price = $storage_goods[$v->wago_goo_id]['univalence'] / $goo_data_ret[$v->wago_goo_id]['goo_unit_conversion']; //采购单价
            //     }
            // }
            $trod_data['wago_goo_price'] = $price;//单价
            //仓库商品得总价 = 商品单价 * （商品库存 + 商品锁定数量）
            $amount = $price * ($v->wago_stock_number + $v->wago_lock_quantity);
            $trod_data['wago_goo_amount'] = $amount;//总价
            $trod_data['wago_update_time'] =  date('Y-m-d H:i:s'); //更新时间
            //修改仓库商品的总价
            $ware_goo_ret = DB::table('warehouse_goods')
                ->where('wago_ware_id', $v->wago_ware_id)
                ->where('wago_goo_id', $v->wago_goo_id)
                ->where('wago_class', 1)
                ->update($trod_data);
        }
        //查找仓库所有商品总价
        $find_tror_all = DB::table('warehouse_goods')
            ->whereIn('wago_ware_id', $ware_id)
            ->where('wago_class', 1)
            ->select('wago_id', 'wago_goo_amount', 'wago_ware_id')
            ->get()->toArray();
        if(empty($find_tror_all)){
            return ['code'=>500, 'msg'=>'仓库不存在', 'data'=>'仓库不存在'];
        }
        $ware_all_data = [];
        foreach ($find_tror_all as $a_k => $a_v){
            if(isset($ware_all_data[$a_v->wago_ware_id])){
                $ware_all_data[$a_v->wago_ware_id] += $a_v->wago_goo_amount;
            }else{
                $ware_all_data[$a_v->wago_ware_id] = $a_v->wago_goo_amount;
            }
        }
        foreach ($ware_all_data as $k => $v){
            //修改仓库商品的总金额
            $ware_ret = DB::table('warehouse')
                ->where('ware_id', $k)
                ->where('ware_type', 1)
                ->update(['ware_goo_amount'=>$v]);
        }
        return ['code'=>200, 'msg'=>'修改总价成功', 'data'=>'修改总价成功'];
    }

    // 出库
    public function delivery(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWareInorderController;
        $error_message = $verify_data->warehousingShowValidator($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;

        $cg_number = $request->input('cg_number');

        $cg_data = DB::table('purchase_order')
            ->where('cg_number', $cg_number)
            ->select('cg_id', 'cg_number', 'cg_original_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time')
            ->first();
        $cg_data = json_decode(json_encode($cg_data), true);
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该状态下无法操作']);
        }

        // 获取页面数据
        if ($request['type'] == 1) {
            $storage_goods = DB::table('storage_goods')
                ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                ->where('relation_number', $cg_number)
                ->select('goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'ruku_num', 'estimate_time', 'company_unit', 'goods_type', 'goo_brse_id', 'goo_class')
                ->get();
            $storage_goods = json_decode(json_encode($storage_goods), true);
            // 查询系列数据
            $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($storage_goods as $k=>$v) {
                $storage_goods[$k]['num'] = '';
                $storage_goods[$k]['estimate_time'] = date('Y-m-d');
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v['goo_brse_id'])) {
                        if ($v['goo_class'] == 2) {
                            $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                            unset($v['goo_brse_id']);
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $storage_goods[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                unset($v['goo_brse_id']);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v['goo_class'] == 2) {
                        $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $storage_goods[$k]['goo_name'];
                        }
                    }
                }
            }
            if (!in_array($cg_data['cg_state'], [6, 7, 11])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'状态已发生改变,该状态无法操作']);
            }

            unset($cg_data['cg_state']);
            // 仓库名称
            $cg_data['ware_name'] = DB::table('warehouse')
                ->where('ware_id', $cg_data['cg_wareid'])
                ->value('ware_name');
            // 供应商名称
            $cg_data['chun_unit_name'] = DB::table('channel_unit')
                ->where('chun_id', $cg_data['cg_supplyunit'])
                ->value('chun_unit_name');
            $data['cg_data'] = $cg_data;
            $data['storage_goods'] = $storage_goods;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

        if (empty($cg_data) || !in_array($cg_data['cg_state'], [6, 7])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该状态下无法出库']);
        }

        // 出库
        $goods_data = json_decode($request['goods'], true);
        if (empty($goods_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'商品数量不能为空']);
        }

        $storage_goods = DB::table('storage_goods')
            ->where('relation_number', $cg_number)
            ->select('goods_id', 'goods_number', 'storehouse', 'goods_name', 'cg_goodsnum', 'goods_num', 'univalence', 'ruku_num', 'company_id', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'goods_type', 'old_univalence')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true); //将对象转换为数组

        $storage_goods = array_column($storage_goods, null, 'goods_id');

        $rk_number = 'CK' . rand(10, 99) . date('mdHis') . rand(100000, 999999); //单号

        DB::beginTransaction();

        $delivery_retrun = WareInorder::delivery(
            $user_info, //用户信息
            $shop_id, //门店id
            $request->all(), //用户信息
            $goods_data, //提交的商品数据
            $storage_goods, //查询采购单商品信息
            $cg_data, //查询的采购单信息
            $rk_number //入库单号
        );

        // 记录日志
        $log_data['user_info'] = $user_info;
        $log_data['rk_number'] = $request['rk_number'];
        $log_data['rk_type'] = '采购退货出库';
        $log_data['request'] = $request->all();
        $log_data['delivery_retrun'] = $delivery_retrun;
        Common::write_record_log($log_data, 'pc/AppletWareInorderController.txt', 'delivery');

        if ($delivery_retrun['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '出入库列表', '采购出库', $rk_number . '成功');
            if ($request['rk_remark'] != '') {
                Common::addNote($user_info, $shop_id, $rk_number, $request['rk_remark'], '添加出库单');
            }
            return response()->json($delivery_retrun);
        } else {
            DB::rollBack();
            return response()->json($delivery_retrun);
        }
    }

    /**
     * 采购内容
     * @param [type] $cg_number 采购单号
     */
    private function purchaseData($user_info, $cg_number)
    {
        $cg_data = DB::table('purchase_order')
            ->leftjoin('channel_unit', 'chun_id', '=', 'cg_supplyunit')
            ->where('cg_number', $cg_number)
            ->where('is_del', 1)
            ->select('cg_number', 'contract_number', 'cg_state', 'cg_paymentype', 'cg_purchasetime', 'cg_wareid', 'cg_waon_class', 'cg_amount', 'cg_remark', 'cg_supplyunit', 'chun_unit_name', 'cg_delivertype', 'cg_invoicetype', 'business_type', 'contact_name', 'contact_phone', 'create_time')
            ->first();
        $cg_data = json_decode(json_encode($cg_data), true);
        if (empty($cg_data)) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'该状态下无法操作！'];
        }
        $storage_goods = DB::table('storage_goods')
            ->leftjoin('goods', 'goo_id', '=', 'goods_id')
            ->where('relation_number', $cg_number)
            ->select('id as stgo_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'ruku_num', 'estimate_time', 'company_unit', 'goods_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
            ->get()->toArray();
        $storage_goods = json_decode(json_encode($storage_goods), true);
        // 查询系列数据
        $goo_brse_id = array_column($storage_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        foreach ($storage_goods as $key => $value) {
            $storage_goods[$key]['num'] = '';
            $storage_goods[$key]['estimate_time'] = date('Y-m-d');
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                if (!empty($value['goo_brse_id'])) {
                    if ($value['goo_class'] == 2) {
                        $storage_goods[$key]['goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $value['goo_name'];
                        unset($storage_goods[$key]['goo_brse_id']);
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $storage_goods[$key]['goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $value['goo_name'];
                            unset($storage_goods[$key]['goo_brse_id']);
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($value['goo_class'] == 2) {
                    $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $storage_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $storage_goods[$key]['goo_name'];
                    }
                }
            }
            unset($storage_goods[$key]['goo_class']);
        }
        if (!in_array($cg_data['cg_state'], [2, 5, 8, 11])) {
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前状态不是未入库状态，无法操作入库！'];
        }

        unset($cg_data['cg_state']);
        $cg_data['ware_name'] = DB::table('warehouse')
            ->where('ware_id', $cg_data['cg_wareid'])
            ->value('ware_name');

        return ['code'=>200, 'msg'=>'success', 'data'=>['cg_data'=>$cg_data, 'storage_goods'=>$storage_goods]];
    }

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

        $where_data = $request->all();
        $where_data = RemoveLineFeed($where_data);

        $cg_type = $request->input('cg_type', 1);

        $data = Db::table('purchase_order')
            ->whereIn('cg_state', [5, 6, 8, 11])
            ->where('is_del', 1)
            ->where('purchase_order.company_id', $user_info->adm_cid)
            ->where('cg_superior_shop_id', $shop_id)
            ->where(function ($query) use ($cg_type) {
                if ($cg_type == 2) {
                    $query->where('cg_types', 2);
                } else {
                    $query->where('cg_types', 1);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_state'])) {  //采购状态
                    $query->where('cg_state', $where_data['cg_state']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_number'])) {  //采购单号
                    $query->where('cg_number', 'like', '%' . $where_data['cg_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['rk_number'])) { //入库单号
                    $query->where('rk_number', 'like', '%' . $where_data['rk_number'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['goods_name'])) { //包含商品
                    $query->where('goods_name', 'like', '%' . $where_data['goods_name'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_wareid'])) { //仓库
                    $query->where('cg_wareid', $where_data['cg_wareid']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['cg_creator'])) {  //创建人
                    $query->where('cg_creator', 'like', '%' . $where_data['cg_creator'] . '%');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_start'])) {  //创建开始时间
                    $query->where('create_time', '>=', $where_data['create_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['create_end'])) {     //创建结束时间
                    $query->where('create_time', '<=', $where_data['create_end'] . ' 23:59:59');
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['dh_start'])) {  //到货开始时间
                    $query->where('dh_time', '>=', $where_data['dh_start']);
                }
            })
            ->where(function ($query) use ($where_data) {
                if (!empty($where_data['dh_end'])) {    //到货结束时间
                    $query->where('dh_time', '<=', $where_data['dh_end'] . ' 23:59:59');
                }
            })
            ->where(function ($query) use ($where_data) { //供货单位
                if (!empty($where_data['cg_supplyunit'])) {
                    $query->where('cg_supplyunit', $where_data['cg_supplyunit']);
                }
            })
            ->select('cg_number', 'contract_number', 'cg_state', 'cg_purchasetime', 'cg_supplyunit', 'cg_creator', 'create_time', 'contact_name', 'contact_phone', 'cg_remark')
            ->orderBy('cg_id', 'desc')
            ->groupBy('cg_number')
            ->get()->toArray();

        if (!empty($data)) {
            // 将对象转为数组
            $data = json_decode(json_encode($data), true);
            $cg_supplyunit = array_unique(array_column($data, 'cg_supplyunit')); //供货单位id
            // 查询供货单位数据
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $cg_supplyunit)
                ->where('chun_shop_id', $user_info->adm_shop_id)
                ->where('chun_state', 1)
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            foreach ($data as $key => $value) {
                $data[$key]['cg_supplyunit'] = isset($channel[$value['cg_supplyunit']]) ? $channel[$value['cg_supplyunit']] : '';
                // 采购单状态1审核中3驳回编辑5未入库8部分入库11完成(9待结算10待审核)15申请终止17中止
                if ($value['cg_state'] == 1) {
                    $data[$key]['cg_state'] = '审核中';
                }
                if ($value['cg_state'] == 3) {
                    $data[$key]['cg_state'] = '待处理';
                }
                if ($value['cg_state'] == 5) {
                    $data[$key]['cg_state'] = '未入库';
                }
                if ($value['cg_state'] == 6) {
                    $data[$key]['cg_state'] = '未出库';
                }
                if ($value['cg_state'] == 8) {
                    $data[$key]['cg_state'] = '部分入库';
                }
                if ($value['cg_state'] == 11) {
                    $data[$key]['cg_state'] = '完成';
                }
                if ($value['cg_state'] == 17) {
                    $data[$key]['cg_state'] = '终止';
                }
            }
        } 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(1000, 9999) . '.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 info(Request $request)
    {
        $cg_number = $request->input('cg_number');
        if ($cg_number == '') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'单号不能为空']);
        }

        $user_info = Common::getUserInfo($request['api_token']);

        // 获取入库单列表
        $find_wain_data = Db::table('ware_inorder')
            ->where('cg_number', $cg_number)
            ->select('cg_number', 'rk_number', 'create_time', 'rk_wareid', 'rk_remarks')
            ->first();
        // 采购表查询
        $find_puor_data = DB::table('purchase_order')
            ->where('cg_shop_id', $user_info->adm_shop_id)
            ->where('cg_number', $cg_number)
            ->select('cg_number', 'contract_number', 'cg_purchasetime', 'cg_wareid as rk_wareid', 'create_time')
            ->first();
        if ($find_wain_data) {
            $find_wain_data->courier_number = $find_puor_data->contract_number;
            $find_wain_data->cg_purchasetime = $find_puor_data->cg_purchasetime;
            // 仓库名称
            $find_wain_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $find_wain_data->rk_wareid)
                ->value('ware_name');
            $rk_num = 0;  //采购总数
            // 获取入库单商品数据
            $ware_goods = DB::table('storage_goods')
                ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                ->where('relation_number', $find_wain_data->rk_number)
                ->where('ruku_num', '!=', 0)
                ->select('id as stgo_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'edit_time as dh_time', 'company_unit', 'goods_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
                ->get()->toArray();
        } else {
            $find_wain_data = $find_puor_data;
            $find_wain_data->courier_number = $find_puor_data->contract_number;
            $find_wain_data->cg_purchasetime = $find_puor_data->cg_purchasetime;
            // 仓库名称
            $find_wain_data->ware_name = DB::table('warehouse')
                ->where('ware_id', $find_wain_data->rk_wareid)
                ->value('ware_name');
            $rk_num = 0;  //采购总数
            // 获取入库单商品数据
            $ware_goods = DB::table('storage_goods')
                ->leftjoin('goods', 'goo_id', '=', 'goods_id')
                ->where('relation_number', $find_wain_data->cg_number)
                ->select('id as stgo_id', 'goods_id', 'goo_cate_name', 'goo_bra_name', 'goo_goods_encode', 'goods_name as goo_name', 'goods_num', 'univalence', 'ruku_num', 'tax_rate', 'currency', 'money', 'estimate_time', 'company_unit', 'edit_time as dh_time', 'goods_type', 'stgo_stop', 'goo_brse_id', 'goo_class')
                ->get()->toArray();
        }
        $ware_goods = json_decode(json_encode($ware_goods), true);
        $stgo_id = array_column($ware_goods, 'stgo_id');
        // 查询仓位商品出入库表
        $find_wfog_data = DB::table('warehouse_freight_outin_goods as wfog')
            ->leftjoin('warehouse_freight as wafr', 'wafr.wafr_id', '=', 'wfog.wfog_wafr_id')
            ->where('wfog_shop_id', $user_info->adm_shop_id)
            ->whereIn('wfog_primary_id', $stgo_id)
            ->select('wfog_id', 'wfog_wafr_id', 'wfog_primary_id', 'wafr_name', 'wfog_stock_amount')
            ->get()->toArray();
        $find_wfog_data = array_column($find_wfog_data, null, 'wfog_primary_id');
        // 查询系列数据
        $goo_brse_id = array_column($ware_goods, 'goo_brse_id');
        $brse_data = DB::table('brand_serie')
            ->whereIn('brse_id', $goo_brse_id)
            ->pluck('brse_name', 'brse_id')
            ->toArray();
        $ware_num = 0;
        foreach ($ware_goods as $key => $value) {
            $rk_num = $rk_num + $value['ruku_num'];
            $ware_num = $ware_num + $value['ruku_num'];

            if ($value['dh_time'] != '0000-00-00 00:00:00') {
                $ware_goods[$key]['dh_time'] = date("Y-m-d", strtotime($value['dh_time']));
            } else {
                $ware_goods[$key]['dh_time'] = '0000-00-00';
            }
            // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                if (!empty($value['goo_brse_id'])) {
                    if ($value['goo_class'] == 2) {
                        $ware_goods[$key]['goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $value['goo_name'];
                        unset($ware_goods[$key]['goo_brse_id']);
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $ware_goods[$key]['goo_name'] = $brse_data[$value['goo_brse_id']] . ' ' . $value['goo_name'];
                            unset($ware_goods[$key]['goo_brse_id']);
                        }
                    }
                }
            }
            // 显示品牌名称
            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                if ($value['goo_class'] == 2) {
                    $ware_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $ware_goods[$key]['goo_name'];
                } else {
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                        $ware_goods[$key]['goo_name'] = $value['goo_bra_name'] . ' ' . $ware_goods[$key]['goo_name'];
                    }
                }
            }
            if (isset($find_wfog_data[$value['stgo_id']])) {
                $ware_goods[$key]['wafr_name'] = $find_wfog_data[$value['stgo_id']]->wafr_name;
            } else {
                $ware_goods[$key]['wafr_name'] = '';
            }
            unset($ware_goods[$key]['goo_class']);
        }
        $find_wain_data->rk_num = $rk_num;

        // 获取操作备注
        $note = DB::table('note')
            ->where('note_number', $cg_number)
            ->select('note_number', 'note_content', 'note_time', 'note_type')
            ->orderBy('note_id', 'desc')
            ->get();

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

}
