<?php
namespace App\Http\Controllers\WeChatApplet\AppletWarehouseManage;

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\Controllers\WeChatApplet\Verify\AppletWarehouseManage\VerifyAppletWareInorderController;
use App\Http\Models\Services\WarehouseManage\WareInorder;

// 仓储系统 -- 出入库列表
class AppletWareInorderController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 出入库列表页面
    public function index(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($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();

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

        $list_data = DB::table('purchase_order as puor')
            ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'puor.cg_supplyunit')
            ->leftjoin('ware_inorder as wain', 'wain.cg_number', '=', 'puor.cg_number')
            ->where('puor.company_id', $user_info->adm_cid)
            ->where('puor.cg_superior_shop_id', $shop_id)
            ->where('puor.is_del', 1)
            ->whereIn('puor.cg_state', [2, 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(function ($query) use ($search_data) { //采购单状态：1.审核中 2.财务审核 3.驳回编辑5.未入库 6.未出库 8.部分入库 11.完成 ( 9.待结算10.待审核) 12.确认完成 14.已封账 15.申请终止17.终止 18.代发采购19.修正中
                if (!empty($search_data['cg_state'])) {
                    $query->where('cg_state', $search_data['cg_state']);
                }
            })
            ->where(function ($query) use ($search_data) { //采购单号
                if (!empty($search_data['cg_number'])) {
                    $query->where('puor.cg_number', 'like', '%' . $search_data['cg_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //入库单号
                if (!empty($search_data['rk_number'])) {
                    $query->where('rk_number', 'like', '%' . $search_data['rk_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //商品信息
                if (!empty($search_data['goods_name'])) {
                    $query->where('goods_name', 'like', '%' . $search_data['goods_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //仓库id
                if (!empty($search_data['cg_wareid'])) {
                    $query->where('cg_wareid', $search_data['cg_wareid']);
                }
            })
            ->where(function ($query) use ($search_data) { //添加人
                if (!empty($search_data['cg_creator'])) {
                    $query->where('cg_creator', 'like', '%' . $search_data['cg_creator'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //添加时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('puor.create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('puor.create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('puor.create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //到货时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['dh_time_start']) && !empty($search_data['dh_time_end'])) {
                    $query->whereBetween('puor.dh_time', [$search_data['dh_time_start'], $search_data['dh_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['dh_time_start'])) {
                        $query->where('puor.dh_time', '>=', $search_data['dh_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['dh_time_end'])) {
                            $query->where('puor.dh_time', '<=', $search_data['dh_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //供货单位
                if (!empty($search_data['cg_supplyunit'])) {
                    $query->where('chun_id', $search_data['cg_supplyunit']);
                }
            })
            ->select('puor.cg_number', 'contract_number', 'cg_state', 'cg_purchasetime', 'auditor_user', 'cg_wareid', 'cg_remark', 'chun_unit_name', 'cg_creator', 'puor.create_time', 'contact_name', 'contact_phone', 'cg_paymentype', 'cg_delivertype', 'cg_invoicetype', 'cg_settlementype', 'business_type', 'rk_remarks')
            ->orderBy('puor.create_time', 'desc')
            ->groupBy('puor.cg_number')
            ->paginate($this->show_count);

        $list_items = $list_data->items();
        if ($list_items) {
            $data = json_decode(json_encode($list_items), true);
            $cg_wareid = array_unique(array_column($data, 'cg_wareid')); //仓库id
            // 查询仓库名称
            $warehouse = DB::table('warehouse')
                ->whereIn('ware_id', $cg_wareid)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            foreach ($data as $key => $value) {
                $data[$key]['ware_name'] = $warehouse[$value['cg_wareid']];
                if ($value['auditor_user'] == 0) {
                    $data[$key]['auditor_user'] = '';
                } else {
                    $data[$key]['auditor_user'] = DB::table('admin')
                        ->where('adm_id', $value['auditor_user'])
                        ->value('adm_name');
                }

                // 计算入库数量
                $ruku_data = DB::table('ware_inorder')
                    ->where('cg_number', $value['cg_number'])
                    ->where('rk_type', 1)
                    ->select('rk_number')
                    ->get()->toArray();
                $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;

                $stgo_data = DB::table('storage_goods as stgo')
                    ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.goods_id')
                    ->where('relation_number', $value['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')
                    ->get()->toArray();
                $stgo_data = json_decode(json_encode($stgo_data), true);
                // 查询系列数据
                $goo_brse_id = array_column($stgo_data, '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 ($stgo_data as $k => $v) {
                    $goods_num = $goods_num + $v['goods_num'];
                    if ($v['dh_time'] != '0000-00-00 00:00:00') {
                        $stgo_data[$k]['dh_time'] = date("Y-m-d", strtotime($v['dh_time']));
                    } else {
                        $stgo_data[$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) {
                                $stgo_data[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                            } else {
                                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                    $stgo_data[$k]['goo_name'] = $brse_data[$v['goo_brse_id']] . ' ' . $v['goo_name'];
                                }
                            }
                        }
                    }
                    // 显示品牌名称
                    if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                        if ($v['goo_class'] == 2) {
                            $stgo_data[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $stgo_data[$k]['goo_name'];
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $stgo_data[$k]['goo_name'] = $v['goo_bra_name'] . ' ' . $stgo_data[$k]['goo_name'];
                            }
                        }
                    }
                    unset($stgo_data[$k]['goo_brse_id']);
                    unset($stgo_data[$k]['goo_class']);
                    unset($stgo_data[$k]['goo_bra_name']);
                }
                if ($cg_type == '2') { //类型1入库单2出库单
                    $data[$key]['goods_count']  = '-' . $goods_num;
                } else {
                    $data[$key]['goods_count']  = $goods_num;
                }

                $data[$key]['storage_goods'] = $stgo_data;
            }
        } else {
            $data = [];
        }

        // 统计各个状态下的数量
        $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];
            }
        }

        $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'] = $data;                        //返回数据

        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 入库
    public function warehousing(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletWareInorderController;
        $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::wechatGetUserInfo($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类型：2提交采购入库数据
        // 验证提交数据
        $verify_data = new VerifyAppletWareInorderController;
        $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)
            ->where('cg_shop_id', $user_info->adm_shop_id)
            ->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();
        if (empty($cg_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前采购单不存在']);
        }
        $cg_data = json_decode(json_encode($cg_data), true); //将对象转为数组
        // is_del 是否删除1正常2删除
        if ($cg_data['is_del'] != 1) {
            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', '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

        $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 //入库单号
        );

        // 记录日志
        $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, 'applet/AppletWareInorderController.txt', 'warehousing');

        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);
        }
    }

    // 出库
    public function delivery(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletWareInorderController;
        $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::wechatGetUserInfo($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_data = DB::table('purchase_order')
            ->where('cg_number', $request['cg_number'])
            ->where('cg_shop_id', $user_info->adm_shop_id)
            ->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 (empty($cg_data) || !in_array($cg_data['cg_state'], [6])) {
            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', $request['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, 'applet/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);
        }
    }

    // 库房记录
    public function wareRecord(Request $request)
    {
        $cg_number = $request['cg_number'];
        if (empty($cg_number)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单号不能为空']);
        }

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

        $select_field = "cg_id, cg_number, cg_yfmoney, cg_creator, contract_number, create_time, 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";
        $Ware_inorder = new WareInorder();
        $return_data = $Ware_inorder->wareRecord($user_info, $request->all(), $select_field);
        return response()->json($return_data);
    }

    // 查看详情
    public function info(Request $request)
    {
        $cg_number = $request['cg_number'];
        if (empty($cg_number)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'采购单号不能为空']);
        }

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

        $select_field = "cg_id, cg_number, cg_yfmoney, cg_creator, contract_number, create_time, 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";
        $Ware_inorder = new WareInorder();
        $return_data = $Ware_inorder->info($user_info, $request->all(), $select_field);
        return response()->json($return_data);
    }
}
