<?php

namespace App\Http\Controllers\Api\AfterSaleManage;

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

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterSaleController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

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

        $search_data = $request->all();
        $list_data = DB::table('order_after_sale as a')
                        ->leftJoin('order_client as b', 'b.orcl_ord_id', '=', 'a.oras_ord_id')
                        ->leftJoin('order as c', 'c.ord_id', '=', 'a.oras_ord_id')
                        ->where('oras_cid', $user_info->adm_cid)
                        ->where('oras_superior_shop_id', $shop_id)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['ord_create_time'])) {
                                $query->where('ord_create_time', 'like', $search_data['ord_create_time'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['ord_order_number'])) {
                                $query->where('ord_order_number', 'like', $search_data['ord_order_number'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orcl_channel_unit'])) {
                                $query->where('orcl_channel_unit', 'like', '%'.$search_data['orcl_channel_unit'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orcl_name'])) {
                                $query->where('orcl_name', 'like', '%'.$search_data['orcl_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orcl_phone'])) {
                                $query->where('orcl_phone', 'like', '%'.$search_data['orcl_phone'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['orcl_car_num'])) {
                                $query->where('orcl_car_num', 'like', $search_data['orcl_car_num'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['ord_create_id'])) {
                                $query->where('ord_create_id', $search_data['ord_create_id']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['ord_state'])) {
                                $query->where('ord_state', $search_data['ord_state']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['ord_type'])) {
                                $query->where('ord_type', $search_data['ord_type']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['oras_state'])) {
                                $query->where('oras_state', $search_data['oras_state']);
                            }
                        })
                        ->select('oras_id', 'oras_state', 'oras_reason', 'ord_id', 'ord_order_number', 'ord_goods_quantity', 'ord_actual_price', 'ord_create_id', 
                            'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_service_type', 
                            'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_address', 
                            'oras_remark', 'ord_create_time', 'ord_order_price')
                        ->orderBy('ord_id', 'desc')
                        ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            // 查找订单商品
            foreach ($list_items as $key => $value) {
                $ord_id[] = $value->ord_id;
                $adm_id[] = $value->ord_create_id;
            }
            $order_goods = DB::table('order_goods')
                        ->whereIn('orgo_ord_id',$ord_id)
                        ->select('orgo_ord_id','orgo_goo_id','orgo_goo_name','orgo_goo_goods_encode','orgo_goo_price',
                            'orgo_goo_quantity','orgo_is_recycle')
                        ->get();
            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                        ->whereIn('adm_id', $adm_id)
                        ->select('adm_id', 'adm_name')
                        ->get();
        }else{
            $order_goods = [];
            $find_admin = [];
        }

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        $data_info['order_goods'] = $order_goods;                //订单商品数据
        $data_info['find_admin'] = $find_admin;                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info, 'list_button'=>$list_button]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

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

        // 查询售后订单信息
        $find_order = DB::table('order as a')
                ->leftJoin('order_client as b', 'b.orcl_ord_id', '=', 'a.ord_id')
                ->leftJoin('admin as c', 'c.adm_id', '=', 'a.ord_create_id')
                ->where('ord_id', $request['ord_id'])
                ->select( 'adm_name', 'ord_order_number', 'ord_goods_quantity', 'ord_actual_price', 'ord_order_price', 
                'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_type', 'ord_service_type',  'ord_remark', 
                'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_address')
                ->first();
        $order_goods = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->select('orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_is_recycle',
                'orgo_goo_quantity', 'orgo_can_assign_quantity')
                ->get();
        $data['find_order'] = $find_order;
        $data['order_goods'] = $order_goods;
        return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
    }

    // 取消售后
    public function cancel(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterSaleController;
        $error_message = $verify_data->cancelValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $find_oras = DB::table('order_after_sale')
                ->where('oras_id', $request['oras_id'])
                ->select('oras_state', 'oras_ord_id', 'oras_order_number')
                ->first();
        if ($find_oras->oras_state != 1) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前售后订单不是待处理状态无法取消售后']);
        }
        DB::beginTransaction();

        // 1. 删除售后订单数据
        $oras_res = DB::table('order_after_sale')
                ->where('oras_id', $request['oras_id'])
                ->delete();
        // 2. 将订单状态改为服务中
        $ord_data['ord_wor_state'] = 2;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
                    ->where('ord_id', $find_oras->oras_ord_id)
                    ->update($ord_data);
        if ($oras_res && $ord_res) {
            DB::commit();
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']); 
            Common::addLog($user_info, getRealIp($request), '订单售后','取消售后','取消售后：'.$find_oras->oras_order_number.'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'取消售后成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'取消售后失败']);
        }
    }

    // 售后完成
    public function finish(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterSaleController;
        $error_message = $verify_data->cancelValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $find_oras = DB::table('order_after_sale')
                ->where('oras_id', $request['oras_id'])
                ->select('oras_state', 'oras_ord_id', 'oras_order_number')
                ->first();
        if ($find_oras->oras_state == 1) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前售后订单尚未处理，无法完成']);
        }
        if ($find_oras->oras_state == 3) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'当前售后订单已经完成']);
        }

        DB::beginTransaction();
        // 1. 售后订单数据
        $oras_data['oras_state'] = 3;
        $oras_data['oras_update_time'] = date('Y-m-d H:i:s');
        $oras_res = DB::table('order_after_sale')
                ->where('oras_id', $request['oras_id'])
                ->update($oras_data);
        // 2. 将订单状态改为服务中
        $ord_data['ord_wor_state'] = 2;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
                    ->where('ord_id', $find_oras->oras_ord_id)
                    ->update($ord_data);
        if ($oras_res && $ord_res) {
            DB::commit();
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']); 
            Common::addLog($user_info, getRealIp($request), '订单售后','售后完成','售后完成：'.$find_oras->oras_order_number.'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'售后完成成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'售后完成失败']);
        }
    }

    // 备注
    public function remark(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterSaleController;
        $error_message = $verify_data->remarkValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $find_oras = DB::table('order_after_sale')
                ->where('oras_id', $request['oras_id'])
                ->select('oras_ord_id', 'oras_order_number')
                ->first();
        // 1. 售后订单数据
        $oras_data['oras_remark'] = $request['remark'];
        $oras_data['oras_update_time'] = date('Y-m-d H:i:s');
        $oras_res = DB::table('order_after_sale')
                ->where('oras_id', $request['oras_id'])
                ->update($oras_data);
        if ($oras_res) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']); 
            Common::addLog($user_info, getRealIp($request), '订单售后','备注','售后完成：'.$find_oras->oras_order_number.'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'备注成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'备注失败']);
        }
    }

    // 售后处理
    public function dispose(Request $request)
    {
        // 【鑫世进蓄电池救援】尊敬的客户您好，已为您安排蓄电池救援技师（***，138***)点击http://*****查看进度。
        // $message = "您的服务技师已出发，详情请查看：http://7cha.co/K5fdO09F";//短信信息
        // $message = "尊敬的客户您好，已为您安排蓄电池救援技师（姜友灿，1381521001)点击http://7cha.co/0a9K9O5c查看进度";//短信信息
        // $send_res = sendSmsCode('18514050435', $message);
        // echo $send_res;die;
        // 验证数据
        $verify_data = new VerifyOrderAfterSaleController;
        $error_message = $verify_data->disposeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if ($request['type'] == 1) {
            // 查询售后订单信息
            $find_oras = DB::table('order_after_sale as a')
                    ->leftJoin('order_client as b', 'b.orcl_ord_id', '=', 'a.oras_ord_id')
                    ->where('oras_id', $request['oras_id'])
                    ->select('oras_reason', 'oras_remark', 'oras_ord_id', 'orcl_channel_unit', 'orcl_name', 'orcl_phone')
                    ->first();
            $goods_data = DB::table('order_goods')
                    ->where('orgo_ord_id', $find_oras->oras_ord_id)
                    ->select('orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price',
                    'orgo_goo_quantity', 'orgo_can_assign_quantity')
                    ->get();
            $data['find_oras'] = $find_oras;
            $data['goods_data'] = $goods_data;
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$data]);
        }

        $goo_all_quantity = 0;//商品总数量
        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || $value < 0 || !is_numeric($request['exchange_number'][$key]) || $request['exchange_number'][$key] < 0) {
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数类型错误']);
            }
            $goo_all_quantity += $request['exchange_number'][$key];//商品总数量

            $goo_exchange[$value] = $request['exchange_number'][$key];
        }
        // 获取当前操作账号信息
        $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;

        // 订单商品数量减去对应的退货数量
        // 查询订单商品
        $goods_data = DB::table('order_goods')
                    ->where('orgo_ord_id', $request['ord_id'])
                    ->whereIn('orgo_goo_id', $request['goo_id'])
                    ->select('orgo_id', 'orgo_goo_id',  'orgo_goo_price', 'orgo_goo_quantity', 'orgo_can_assign_quantity', 
                        'orgo_goo_name', 'orgo_goo_goods_encode')
                    ->get();
        // 更新订单商品表数量
        $sql = 'UPDATE `faster_order_goods` SET ';
        $goo_quantity_sql = '';
        $actual_number_sql = '';
        $update_time_sql = '';
        $ids = '';
        $goo_price = 0;//合计金额
        foreach ($goods_data as $key => $value) {
            // 商品订单数量
            // 更改可派单商品数量
            $actual_number_sql = $actual_number_sql . ' WHEN ' .$value->orgo_id;
            $actual_number_sql = $actual_number_sql . ' THEN ' . ($value->orgo_can_assign_quantity - $goo_exchange[$value->orgo_goo_id]);
            // 更改订单数量
            $goo_quantity_sql = $goo_quantity_sql . ' WHEN ' .$value->orgo_id;
            $goo_quantity_sql = $goo_quantity_sql . ' THEN ' . ($value->orgo_goo_quantity - $goo_exchange[$value->orgo_goo_id]);

            // 更改时间
            $update_time_sql = $update_time_sql . ' WHEN ' .$value->orgo_id;
            $update_time_sql = $update_time_sql . ' THEN "' .date('Y-m-d H:i:s').'"';

            $ids = $ids . $value->orgo_id.',';
            $goo_price += $value->orgo_goo_price;
        }
        $sql = $sql .' `orgo_can_assign_quantity`=  CASE `orgo_id` '.$actual_number_sql.' END,';
        $sql = $sql .' `orgo_goo_quantity`=  CASE `orgo_id` '.$goo_quantity_sql.' END,';
        $sql = $sql .' `orgo_update_time`=  CASE `orgo_id` '.$update_time_sql.' END';
        $sql = $sql . ' WHERE `orgo_id` IN ('.trim($ids,',').')';
        DB::beginTransaction();
        $orgo_res = DB::update($sql);

        // 更改订单表的订单金额、商品总数量
        // 查询订单信息
        $find_order = DB::table('order')
                    ->where('ord_id', $request['ord_id'])
                    ->select('ord_order_number', 'ord_order_price', 'ord_goods_quantity', 'ord_type', 'ord_client_id')
                    ->first();
        $ord_data['ord_order_price'] = $find_order->ord_order_price - $goo_price;
        $ord_data['ord_goods_quantity'] = $find_order->ord_goods_quantity - $goo_all_quantity;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')->where('ord_id', $request['ord_id'])->update($ord_data);

        // 售后订单状态改为售后中
        $oras_data['oras_state'] = 2;
        $oras_data['oras_remark'] = $request['remark'] ? $request['remark'] : '';
        $oras_data['oras_update_time'] = date('Y-m-d H:i:s');
        $oras_res = DB::table('order_after_sale')
                    ->where('oras_id', $request['oras_id'])
                    ->update($oras_data);
        // 生成退货单
        // 1.退换回收单表添加数据
        $rec_number = 'TH' . rand(100, 999) . date('mdHis'). rand(100000, 999999); // 回收单号
        $add_recycle['rec_cid'] = $user_info->adm_cid; //公司id
        $add_recycle['rec_shop_id'] = $user_info->adm_shop_id; //门店id
        $add_recycle['rec_superior_shop_id'] = $shop_id; //门店id
        $add_recycle['rec_number'] = $rec_number; //回收单号
        $add_recycle['rec_create_adm_id'] = $user_info->adm_id; //创建人id
        $add_recycle['rec_date'] = date('Y-m-d'); //日期
        $add_recycle['rec_price'] = $goo_price; //回收总金额（单位：分）
        $add_recycle['rec_amount'] = $goo_all_quantity; //回收总数量
        $add_recycle['rec_state'] = 1; //回收状态 1.未回收 2.已回收
        $add_recycle['rec_type'] = $find_order->ord_type; //买家类型 1.门店零售 2.来往单位
        $add_recycle['rec_ware_id'] = $request['ware_id']; //仓库id
        $add_recycle['rec_remark'] = $request['remark'] ? $request['remark'] : ''; //备注
        $recycle_id = DB::table('recede_recycle')->insertGetId($add_recycle);

        // 2.退换回收单商品表添加数据
        foreach ($goods_data as $key => $value) {
            $rego_data[$key]['rego_rec_id'] = $recycle_id;
            $rego_data[$key]['rego_goo_id'] = $value->orgo_id;
            $rego_data[$key]['rego_goo_name'] = $value->orgo_goo_name;
            $rego_data[$key]['rego_goo_goods_encode'] = $value->orgo_goo_goods_encode;
            $rego_data[$key]['rego_goo_price'] = $value->orgo_goo_price;
            $rego_data[$key]['rego_sell_number'] = $goo_exchange[$value->orgo_goo_id];
            $rego_data[$key]['rego_recycle_number'] = $goo_exchange[$value->orgo_goo_id];
        }
        $add_goods =  DB::table('recede_goods')->insert($rego_data);

        // 3.回收单客户表添加数据
        $recl_data['recl_rec_id'] = $recycle_id; //回收单id
        $recl_data['recl_client_id'] = $find_order->ord_client_id; //来往单位id/客户id
        $recl_data['recl_name'] = $request['client_name']; //客户姓名
        $recl_data['recl_phone'] = $request['client_phone']; //联系电话
        if($find_order->ord_type == 2){
            $recl_data['recl_channel_unit'] = $request['orcl_channel_unit']; //渠道单位
            $mem_res = true;
        }else{
            // 零售类型，会员对应的退货数量加1
            $mem_res =  DB::table('member')
                    ->where('mem_id', $find_order->ord_client_id)
                    ->increment('mem_retreat_trade');
        }

        $add_client =  DB::table('recede_client')->insert($recl_data);

        if ($orgo_res && $ord_res && $oras_res && $recycle_id && $add_client && $mem_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单售后','售后处理',$find_order->ord_order_number.'售后处理成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'售后处理成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'售后处理失败']);
        }
    }
}
