<?php

namespace App\Http\Controllers\Api\DistributorsManages;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\DistributorsManages\VerifyDamagedReplenishsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
//残损补货
class DamagedReplenishsController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(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();
        $list_data = DB::table('damaged_replenish_wd')
                        ->where('darw_cid', $user_info->adm_cid)
                        ->where('darw_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('darw_create_time',[$search_data['start_time'],$search_data['end_time'].' 23:59:59']);
                            }else{
                                // 如果选择开始时间
                                if (!empty($search_data['start_time'])){
                                    $query->where('darw_create_time','>=',$search_data['start_time']);
                                }else{
                                    // 如果选择结束时间
                                    if (!empty($search_data['end_time'])) {
                                        $query->where('darw_create_time','<=',$search_data['end_time'].' 23:59:59');
                                    }
                                }
                            }
                        }) //添加时间
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['darw_replenish_number'])) {
                                $query->where('darw_replenish_number', $search_data['darw_replenish_number']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['darw_state'])) {
                                $query->where('darw_state', $search_data['darw_state']);
                            }
                        })//状态
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['state'])) {
                                $query->where('darw_state', $search_data['state']);
                            }
                        })//状态
                        ->select('darw_create_time', 'darw_goo_amount', 'darw_replenish_number', 'darw_damaged_number', 'darw_delivery_amount','darw_remark','darw_state','darw_id','darw_plan','darw_total_money')
                        ->orderBy('darw_id', 'desc')
                        ->paginate($this->show_count);

        $state_count = DB::table('damaged_replenish_wd')
            ->where('darw_cid', $user_info->adm_cid)
            ->where('darw_shop_id', $user_info->adm_shop_id)
            ->select(DB::raw('count(*) as count, darw_state'))
            ->groupBy('darw_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 VerifyDamagedReplenishsController;
        $error_message = $verify_data->detailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $list_data = DB::table('damaged_replenish_goods_wd')
            ->where('drgw_darw_id',$request['darw_id'])
            ->get(['drgw_goo_name','drgw_goo_encode','drgw_bra_name','drgw_cate_name','drgw_delivery_quantity','drgw_goo_quantity']);
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        } 
    }

    //备注
    public function remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReplenishsController;
        $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_wd')
            ->where('darw_id',$request['darw_id'])
            ->value('darw_replenish_number');

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

        $rebw_res = DB::table('damaged_replenish_wd')
            ->where('darw_id',$request['darw_id'])
            ->update($data);
        if(empty($rebw_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 reportsDetails(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReplenishsController;
        $error_message = $verify_data->reportsDetailsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $dadw_id = DB::table('damaged_declare_wd')
                ->where('dadw_damaged_number',$request['damaged_number'])
                ->value('dadw_id');
        $store_name = DB::table('shop')
            ->where('shop_id',$user_info->adm_shop_id)
            ->value('shop_store_name');

        // 获取当前操作账号信息
        $data_info = DB::table('damaged_declare_goods_wd')
            ->where('ddgw_dadw_id',$dadw_id)
            ->first(['ddgw_goo_name', 'ddgw_goo_encode', 'ddgw_goo_img', 'ddgw_storage_code', 'ddgw_cate_name', 'ddgw_bra_name', 'ddgw_actual_amount','ddgw_create_time']);
        $data_info->shop_store_name = $store_name;
        if($data_info) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    //收货接口
    public function takeDelivery(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyDamagedReplenishsController;
        $error_message = $verify_data->showTakeDeliveryValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if($request['type'] == 1){    
            $shop_store_name = DB::table('shop')
                ->where('shop_id',$user_info->adm_shop_id)
                ->value('shop_store_name');
            $list_data['list_data'] = DB::table('damaged_replenish_goods_wd')
            ->where('drgw_darw_id',$request['darw_id'])
            ->get(['drgw_goo_name','drgw_goo_encode','drgw_bra_name','drgw_cate_name','drgw_goo_quantity','drgw_id']);
            $list_data['store_name'] = $shop_store_name;
            if($list_data) {
                return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
            }else{
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
            } 
        }
        
        //验证数据
        foreach ($request['drgw_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();
        $drgw_ids = implode(',',$request['drgw_id']);
        $drgw_data = DB::table('damaged_replenish_goods_wd')
            ->whereIn('drgw_id',$request['drgw_id'])
            ->get(['drgw_goo_quantity','drgw_delivery_quantity','drgw_id','drgw_darw_id','drgw_goo_id', 'drgw_goo_name','drgw_goo_encode','drgw_bra_name','drgw_cate_name']);

        $sql = 'UPDATE `faster_damaged_replenish_goods_wd` SET ';
        $delivery_quantity = '';//已补送量
        $num = 0;
        foreach ($drgw_data as $key => $value) {
            $num += $request['amount'][$key];
            //如果已补送量 + 本次签收量大于计划配送量
            if($request['amount'][$key] != $value->drgw_goo_quantity){
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'送货量必须等于签收量']);
            }
            $drgw_darw_id = $value->drgw_darw_id;
        }

        $dama = DB::table('damaged_replenish_wd')
            ->where('darw_id',$drgw_darw_id)
            ->first(['darw_damaged_number','darw_replenish_number']);

        $darw_res = DB::table('damaged_replenish_wd')
            ->where('darw_id',$drgw_darw_id)
            ->update(['darw_state'=>2,'darw_update_time'=>date('Y-m-d H:i:s')]);
        $belongs_bill = DB::table('damaged_declare_wd')
                ->where('dadw_damaged_number',$dama->darw_damaged_number)
                ->value('dadw_belongs_bill');

        $dadw_res = DB::table('damaged_declare_wd')
                ->where('dadw_damaged_number',$dama->darw_damaged_number)
                ->update(['dadw_state'=>4,'dadw_update_time'=>date('Y-m-d H:i:s')]);
        //供应链残损补货状态修改
        $dare_res = DB::connection('mysql_scm')
            ->table('damage_replenishment')
            ->where('dare_number',$dama->darw_damaged_number)
            ->update(['dare_state'=>3,'dare_update_time'=>date('Y-m-d H:i:s')]);
        $rein_data = DB::connection('mysql_scm')
                    ->table('relationship_inventory')
                    ->where('rein_shop_id', $user_info->adm_shop_id)
                    ->select('rein_id')
                    ->first();
        //配送商库存商品表
        $reid_data = DB::connection('mysql_scm')
            ->table('relationship_inventory_detail')
            ->where('reid_rein_id',$rein_data->rein_id)
            ->where('reid_rego_id',$drgw_data[0]->drgw_goo_id)
            ->select('reid_type', 'reid_stock_quantity', 'reid_rego_id', 'reid_id')
            ->first();
        $num = $request['amount'][0];
        if(!empty($reid_data)){
            if ($reid_data->reid_type == 2) {
                if ($reid_data->reid_stock_quantity > $num) {
                    $data['reid_stock_quantity'] = $reid_data->reid_stock_quantity - $num;
                    $data['reid_type'] = 2;
                } else if ($reid_data->reid_stock_quantity < $num){
                    $data['reid_type'] = 1;//盈亏类型1正2负3平
                    $data['reid_stock_quantity'] = $num - $reid_data->reid_stock_quantity;
                } else {
                    $data['reid_type'] = 3;//盈亏类型1正2负3平
                    $data['reid_stock_quantity'] = $num - $reid_data->reid_stock_quantity;
                }
            } else if($reid_data->reid_type == 3){
                $data['reid_type'] = 1;
                $data['reid_stock_quantity'] = 1;
            } else if($reid_data->reid_type == 1){
                $data['reid_stock_quantity'] = $num + $reid_data->reid_stock_quantity;
                $data['reid_type'] = 1;
            }
            $data['reid_update_time'] = date('Y-m-d H:i:s');
            $dare_add_id = DB::connection('mysql_scm')
                ->table('relationship_inventory_detail')
                ->where('reid_id', $reid_data->reid_id)
                ->update($data); 
        }else{
            $reid['reid_rego_id'] = $drgw_data[0]->drgw_goo_id;//商品id
            $reid['reid_rein_id'] = $rein_data->rein_id;//补货库存id
            $reid['reid_goo_name'] = $drgw_data[0]->drgw_goo_name;//商品名称
            $reid['reid_goo_encode'] = $drgw_data[0]->drgw_goo_encode;//商品编码
            $reid['reid_cate_name'] = $drgw_data[0]->drgw_cate_name;//品类名称
            $reid['reid_bra_name'] = $drgw_data[0]->drgw_bra_name;//品牌名称
            $reid['reid_stock_quantity'] = $num;
            $reid['reid_type'] = 1;//库存类型1正2负3平
            $dare_add_id = DB::connection('mysql_scm')
                        ->table('relationship_inventory_detail')
                        ->insert($reid);
        }

        //wd补货商品数据
        $regw_info = DB::table('replenishment_goods_wd')
            ->where('regw_goo_id',$drgw_data[0]->drgw_goo_id)
            ->where('regw_shop_id',$user_info->adm_shop_id)
            ->first(['regw_stock_type','regw_stock_quantity','regw_goo_id','regw_id','regw_enroute_amount']);
        //如果待补商品里有此数据
        if (!empty($regw_info)) {
            $num = 1;
            if ($regw_info->regw_stock_type == 2) {
                $data_regw['regw_stock_quantity'] = $num + $regw_info->regw_stock_quantity;
                $data_regw['regw_stock_type'] = 2;//库存类型1平2正3负
            } else if($regw_info->regw_stock_type == 3){
                if ($regw_info->regw_stock_quantity > $num) {
                    $data_regw['regw_stock_quantity'] = $regw_info->regw_stock_quantity - $num;
                    $data_regw['regw_stock_type'] = 3;//库存类型1平2正3负
                } else if ($regw_info->regw_stock_quantity < $num){
                    $data_regw['regw_stock_type'] = 2;//库存类型1平2正3负
                    $data_regw['regw_stock_quantity'] = $num - $regw_info->regw_stock_quantity;
                } else {
                    $data_regw['regw_stock_type'] = 1;//库存类型1平2正3负
                    $data_regw['regw_stock_quantity'] = $num - $regw_info->regw_stock_quantity;
                }
            } else if($regw_info->regw_stock_type == 1){
                $data_regw['regw_stock_type'] = 2;
                $data_regw['regw_stock_quantity'] = 1;
            }
            $data_regw['regw_enroute_amount'] = $regw_info->regw_enroute_amount - $num;
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'签收失败']);
        }
        $rrgw_update = DB::table('replenishment_goods_wd')
                ->where('regw_id',$regw_info->regw_id)
                ->update($data_regw);
        if($dare_add_id && $darw_res && $dare_res && $rrgw_update && $dadw_res) {

            $bound_id = DB::connection('mysql_scm')
                ->table('channel')
                ->where('chan_shop_id',$user_info->adm_shop_id)
                ->value('chan_bound_id');
            $sd_goo_id = DB::connection('mysql_scm')
                ->table('relationship_goods')
                ->where('rego_id',$drgw_data[0]->drgw_goo_id)
                ->value('rego_sd_goo_id');
            //获取物流费
            $logistic = DB::connection('mysql_scm')
                ->table('damage_replenishment')
                ->where('dare_number',$dama->darw_damaged_number)
                ->value('dare_logistic_total_money');

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

            $list['ser_id'] = $bound_id;
            $list['wd_id'] = 0;
            $list['distri_num'] = $dama->darw_damaged_number;
            $list['all_price'] = $logistic;//物流费单位(分)
            $list['good_list'] = $goods;//商品数据
            $param['sd_list'] = $list;
            $param['wat_num'] = $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), '残损补货','签收','残损补货单:'.$dama->darw_damaged_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'=>'签收失败']);
        }
    }
}
