<?php

namespace App\Http\Controllers\Api\SupplyChains;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SupplyChains\VerifySpoiledReplenishsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

//门店残损补货
class SpoiledReplenishsController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('damaged_replenish_bs')
                        ->where('darb_cid', $user_info->adm_cid)
                        ->where('darb_shop_id', $user_info->adm_shop_id)
                        ->where(function($query) use($search_data) {
                        //如果选择开始时间并且选择结束时间
                        if (!empty($search_data['start_time']) && !empty($search_data['end_time'])){
                            $query->whereBetween('darb_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            }else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])){
                                    $query->where('darb_create_time','>=',$search_data['start_time']);
                                }else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('darb_create_time','<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['darb_replenish_number'])) {
                                $query->where('darb_replenish_number', $search_data['darb_replenish_number']);
                            }
                        })//残损补货
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['state'])) {
                                $query->where('darb_state', $search_data['state']);
                            }
                        })//残损补货
                        ->select('darb_goo_amount', 'darb_replenish_number', 'darb_damaged_number', 'darb_delivery_amount', 'darb_remark', 'darb_state', 'darb_create_time', 'darb_id')
                        ->orderBy('darb_id', 'desc')
                        ->paginate($this->show_count);
        $state_count = DB::table('damaged_replenish_bs')
            ->where('darb_cid', $user_info->adm_cid)
            ->where('darb_shop_id', $user_info->adm_shop_id)
            ->select(DB::raw('count(*) as count, darb_state'))
            ->groupBy('darb_state')
            ->get();

        $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_data->items();                //返回数据
        $data_info['state_count'] = $state_count;

        // 获取当前列表下的按钮
        $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 details(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySpoiledReplenishsController;
        $error_message = $verify_data->detailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $data_info = DB::table('damaged_replenish_goods_bs')
            ->where('drgb_darb_id',$request['darb_id'])
            ->get(['drgb_goo_name', 'drgb_goo_encode', 'drgb_bra_name', 'drgb_cate_name', 'drgb_goo_quantity', 'drgb_delivery_quantity']);
        if($data_info) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //残损单号详情
    public function reportsDetails(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySpoiledReplenishsController;
        $error_message = $verify_data->reportsDetailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $data_info = DB::table('damaged_replenish_goods_bs')
            ->where('drgb_darb_id',$request['darb_id'])
            ->first(['drgb_goo_name', 'drgb_goo_encode', 'drgb_bra_name', 'drgb_cate_name', 'drgb_goo_quantity', 'drgb_storage_code', 'drgb_apply_time', 'drgb_discount_amount', 'drgb_result_type', 'drgb_goo_img']);
        // $darb_data = DB::table('damaged_replenish_bs')
        //     ->where('darb_id',$request['darb_id'])
        //     ->first(['darb_damaged_number']);

        // $data_info = DB::table('damaged_declare_wd as ddw')
        //     ->leftjoin('damaged_declare_goods_wd as ddgw','ddw.dadw_id','=','ddgw.ddgw_dadw_id')
        //     ->where('ddw.dadw_damaged_number',$darb_data->darb_damaged_number)
        //     ->select('ddw.dadw_damaged_amount','ddw.dadw_true_amount','ddw.dadw_total_money','ddw.dadw_plan','ddw.dadw_state','ddgw.ddgw_goo_name','ddgw.ddgw_goo_encode','ddgw.ddgw_goo_img','ddgw.ddgw_cate_name','ddgw.ddgw_bra_name','ddgw.ddgw_actual_amount')
        //     ->first();
        if($data_info) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //备注
    public function remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySpoiledReplenishsController;
        $error_message = $verify_data->remarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        //补货账单号
        $replenish_number = DB::table('damaged_replenish_bs')
            ->where('darb_id',$request['darb_id'])
            ->value('darb_replenish_number');

        $data['darb_remark'] = $request['remark'];
        $data['darb_update_time'] = date('Y-m-d H:i:s');

        $res = DB::table('damaged_replenish_bs')
            ->where('darb_id',$request['darb_id'])
            ->update($data);
        if(empty($res)) {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'添加备注失败']);
        }else{
            Common::addLog($user_info, getRealIp($request), '门店->残损补货','备注','残损单:'.$replenish_number.'添加备注为:'.$request['remark']);
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'添加备注成功']); 
        }
    }

    //收货接口
    public function takeDelivery(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySpoiledReplenishsController;
        $error_message = $verify_data->showTakeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if($request['type'] == 1){
            $list_data['list_data'] = DB::table('damaged_replenish_goods_bs')
            ->where('drgb_darb_id',$request['darb_id'])
            ->get(['drgb_goo_name','drgb_goo_encode','drgb_bra_name','drgb_cate_name','drgb_delivery_quantity','drgb_goo_quantity','drgb_id']);
            // $wd_shop_id = DB::table('damaged_replenish_bs')
            //     ->where('darb_id',$request['darb_id'])
            //     ->value('darb_shop_id');
            // $store_name = DB::table('shop')
            //     ->where('shop_id',$wd_shop_id)
            //     ->value('shop_store_name');
            $list_data['store_name'] = '';
            if($list_data) {
                return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
            }else{
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
            } 
        }
        // 验证数据
        $verify_data = new VerifySpoiledReplenishsController;
        $error_message = $verify_data->takeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        
        //验证数据
        foreach ($request['drgb_id'] as $key => $value) {
            if(!is_numeric($value) || !is_numeric($request['amount'][$key])){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误']);
            }
        }
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();
        $drgb_ids = implode(',',$request['drgb_id']);
        $drgw_data = DB::table('damaged_replenish_goods_bs')
            ->where('drgb_id',$request['drgb_id'])
            ->first(['drgb_goo_quantity','drgb_delivery_quantity','drgb_id','drgb_darb_id','drgb_goo_id','drgb_goo_name','drgb_goo_encode','drgb_bra_name','drgb_cate_name']);

        $sql = 'UPDATE `faster_damaged_replenish_goods_bs` SET ';
        $delivery_quantity = '';//已补送量
        $num = 0;
                // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if($request['amount'][0] < 1){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'签收数量不能小于1']);
        }

        $darb_replenish_number = DB::table('damaged_replenish_bs')
            ->where('darb_id',$drgw_data->drgb_darb_id)
            ->value('darb_replenish_number');

        $darb_res = DB::table('damaged_replenish_bs')
            ->where('darb_id',$drgw_data->drgb_darb_id)
            ->update(['darb_state'=>2,'darb_update_time'=>date('Y-m-d H:i:s')]);

        $dare_res = DB::connection('mysql_scm')
            ->table('damage_replenishment')
            ->where('dare_replenishment_bills_number',$darb_replenish_number)
            ->update(['dare_state'=>3,'dare_update_time'=>date('Y-m-d H:i:s')]);

        $dare_res = DB::connection('mysql_scm')
            ->table('damage_record')
            ->where('dare_replenishment_bills_number',$darb_replenish_number)
            ->update(['dare_state'=>3,'dare_update_time'=>date('Y-m-d H:i:s')]);

        $dare_data = DB::connection('mysql_scm')
            ->table('damage_record')
            ->where('dare_replenishment_bills_number',$darb_replenish_number)
            ->first(['dare_belongs_bill']);

        //获取待补商品数据
        $regw_data = DB::table('replenishment_goods_bs')
            ->where('regb_goo_id',$drgw_data->drgb_goo_id)
            ->where('regb_shop_id',$user_info->adm_shop_id)
            ->first(['regb_stock_type','regb_stock_quantity','regb_id']);
        $sd_goo_id = DB::connection('mysql_scm')
                ->table('relationship_goods')
                ->where('rego_id',$drgw_data->drgb_goo_id)
                ->value('rego_sd_goo_id');

        if(!empty($regw_data)){
            $num = 1;
            if ($regw_data->regb_stock_type == 2) {
                $data['regb_stock_quantity'] = $num + $regw_data->regb_stock_quantity;
                $data['regb_stock_type'] = 2;
            } else if($regw_data->regb_stock_type == 3){
                if ($regw_data->regb_stock_quantity > $num) {
                    $data['regb_stock_quantity'] = $regw_data->regb_stock_quantity - $num;
                    $data['regb_stock_type'] = 3;
                } else if ($regw_data->regb_stock_quantity < $num){
                    $data['regb_stock_type'] = 2;//库存类型1平2正3负
                    $data['regb_stock_quantity'] = $num - $regw_data->regb_stock_quantity;
                } else {
                    $data['regb_stock_type'] = 1;//库存类型1平2正3负
                    $data['regb_stock_quantity'] = $num - $regw_data->regb_stock_quantity;
                }
            } else if($regw_data->regb_stock_type == 1){
                $data['regb_stock_type'] = 2;
                $data['regb_stock_quantity'] = $regw_data->regb_stock_quantity + 1;
            }
            $regb_res = DB::table('replenishment_goods_bs')
                ->where('regb_id',$regw_data->regb_id)
                ->update($data);
        }else{
            
            if(empty($sd_goo_id)){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'商品信息错误']);
            }
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
            $regb_data['regb_cid'] = $user_info->adm_cid;
            $regb_data['regb_shop_id'] = $user_info->adm_shop_id;
            $regb_data['regb_shop_superior_id'] = $shop_id;
            $regb_data['regb_sd_goo_id'] = $sd_goo_id;
            $regb_data['regb_goo_id'] = $drgw_data->drgb_goo_id;
            $regb_data['regb_goo_name'] = $drgw_data->drgb_goo_name;
            $regb_data['regb_goo_encode'] = $drgw_data->drgb_goo_encode;
            $regb_data['regb_cate_name'] = $drgw_data->drgb_cate_name;
            $regb_data['regb_bra_name'] = $drgw_data->drgb_bra_name;
            $regb_data['regb_stock_type'] = 1;
            $regb_res = DB::table('replenishment_goods_bs')->insert($regb_data);
        }
        if($darb_res && $dare_res && $regb_res) {

            $bound_id = DB::connection('mysql_scm')
                ->table('channel')
                ->where('chan_shop_id',$user_info->adm_shop_id)
                ->value('chan_bound_id');
            //获取物流费
            $logistic = DB::connection('mysql_scm')
            ->table('damage_replenishment')
            ->where('dare_replenishment_bills_number',$darb_replenish_number)
            ->value('dare_logistic_total_money');

            $goods[0]['pg_id'] = $sd_goo_id;
            $goods[0]['good_name'] = $drgw_data->drgb_goo_name;
            $goods[0]['product_version'] = $drgw_data->drgb_goo_encode;
            $goods[0]['good_num'] = 1;

            $list['ser_id'] = $bound_id;
            $list['wd_id'] = 0;
            $list['distri_num'] = $darb_replenish_number;
            $list['all_price'] = $logistic;//物流费单位(分)
            $list['good_list'] = $goods;//商品数据
            $param['sd_list'] = $list;
            $param['wat_num'] = $dare_data->dare_belongs_bill;
            $param['store_list'] = [];
            $param['time'] = date('Y-m-d H:i:s');//收货时间
            $param['token'] = md5(md5($param['time'].'c883e5e641818d993a2d8d966ca450bf'));//token
            $url = config('apisystem.sd_server_name').'/index.php/get_supply_chain';
            $doPost_res = Common::doPost($param,$url);
            $doPost_res = json_decode($doPost_res);
            if($doPost_res->code != 200){
                DB::rollBack();
                DB::connection('mysql_scm')->rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
            }
            Common::addLog($user_info, getRealIp($request), '残损补货','签收','残损补货单:'.$darb_replenish_number.'签收');
            DB::commit();
            DB::connection('mysql_scm')->commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'签收成功']);
        }else{
            DB::rollBack();
            DB::connection('mysql_scm')->rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'签收失败']);
        }
    }
}
