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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AfterSaleManage\VerifyOrderAfterController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\Warehouse;
use App\Http\Models\Api\DispatchBill;
use App\Http\Models\Api\OutinRecord;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\SellDetail;
use App\Http\Models\Api\StockingSelling;
use App\Http\Models\Api\YongYou;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $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 as oraf')
            ->leftJoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
            ->leftJoin('order as ord', 'ord.ord_id', '=', 'oraf.oraf_ord_id')
            ->where('oraf_cid', $user_info->adm_cid)
            ->where('oraf_superior_shop_id', $shop_id)
            ->where('oraf_delete', 1)
            ->where('oraf_collection_bill', 1)//是否代收账单：1正常订单售后2代收账单售后
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('oraf_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('oraf_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('oraf_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->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['oraf_order_number'])) {
                    $query->where('oraf_number', 'like', '%' . $search_data['oraf_order_number'] . '%');
                }
            }) //售后单号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_type'])) {
                    $query->where('oraf_type', $search_data['oraf_type']);
                }
            }) //买家类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_channel_unit'])) {
                    $query->where('orac_channel_unit', 'like', '%' . $search_data['orac_channel_unit'] . '%');
                }
            }) //客户单位
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_name'])) {
                    $query->where('orac_name', 'like', '%' . $search_data['orac_name'] . '%');
                }
            }) //客户姓名
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_phone'])) {
                    $query->where('orac_phone', 'like', '%' . $search_data['orac_phone'] . '%');
                }
            }) //客户电话
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_car_num'])) {
                    $query->where('orac_car_num', 'like', '%' . $search_data['orac_car_num'] . '%');
                }
            }) //车牌号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_wor_state'])) {
                    $query->where('oraf_wor_state', $search_data['oraf_wor_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_create_id'])) {
                    $query->where('oraf_create_id', $search_data['oraf_create_id']);
                }
            })//创建人id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_service_adm_id'])) {
                    $query->where('oraf_service_adm_id', $search_data['oraf_service_adm_id']);
                }
            })//服务技师id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_order_type'])) {
                    $query->where('orac_order_type', $search_data['orac_order_type']);
                }
            })//售后服务商1我的售后2外派售后
            ->select('oraf_id', 'oraf_create_time', 'oraf_number', 'oraf_ord_id', 'oraf_order_number', 'oraf_type', 'orac_channel_unit', 'orac_name', 'orac_phone', 'orac_car_num', 'orac_province', 'orac_city', 'orac_county', 'orac_address', 'oraf_order_price', 'oraf_actual_price', 'oraf_plus_minus', 'oraf_wor_state', 'oraf_service_shop_id', 'oraf_create_id', 'orac_order_type', 'oraf_service_adm_id', 'orac_result', 'oraf_collection_price', 'oraf_state', 'oraf_after_state', 'orac_longitude', 'orac_latitude', 'ocac_feedback_state')
            ->orderBy('oraf_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $oraf_id = array_column($list_items, 'oraf_id');
            $oraf_service_shop_id = array_unique(array_column($list_items, 'oraf_service_shop_id')); //服务门店id
            $oraf_create_id = array_column($list_items, 'oraf_create_id');
            $service_adm_id = array_column($list_items, 'oraf_service_adm_id');
            $adm_id = array_unique(array_merge($oraf_create_id, $service_adm_id));
            $orag_goods = DB::table('order_after_goods')
                ->whereIn('orag_oraf_id', $oraf_id)
                ->where('orag_state', '!=', 2)
                ->select('orag_oraf_id', 'orag_goo_id', 'orag_goo_name', 'orag_goo_goods_encode', 'orag_goo_price', 'orag_goo_quantity', 'orag_is_recycle', 'orag_collection_price', 'orag_state', 'orag_actual_recycle_quantity', 'orag_goo_type', 'orag_recycle_price', 'orag_recycle_quantity')
                ->get();
            // 查找服务门店id
            $shop_name = DB::table('shop')
                ->whereIn('shop_id', $oraf_service_shop_id)
                ->select('shop_id', 'shop_store_name', 'shop_type')
                ->get();
            // 查找录单人信息
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_id', 'adm_name')
                ->get();
            // 查找操作记录
            $after_log = DB::table('order_after_log')
                ->whereIn('oral_ord_id', $oraf_id)
                ->where('oral_type', 3)
                ->select('oral_ord_id', 'oral_time', 'oral_create_adm_name', 'oral_content')
                ->orderBy('oral_id', 'desc')
                ->get();
        } else {
            $orag_goods = [];
            $find_admin = [];
            $shop_name = [];
            $after_log = [];
        }

        // 状态数量统计
        $state_count = DB::table('order_after')
            ->where('oraf_cid', $user_info->adm_cid)
            ->where('oraf_superior_shop_id', $shop_id)
            ->where('oraf_delete', 1)
            ->select(DB::raw('count(*) as count, oraf_wor_state'))
            ->groupBy('oraf_wor_state')
            ->get()->toArray();

        $state_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
        $key_array = array_column($state_count, 'oraf_wor_state');
        foreach ($state_arr as $key => $val) {
            if (!in_array($val, $key_array)) {
                $state_count[] = ['oraf_wor_state'=>$val, 'count'=>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'] = $list_items;                //返回数据
        $data_info['orag_goods'] = $orag_goods;                //订单商品数据
        $data_info['find_admin'] = $find_admin;                //返回数据
        $data_info['state_count'] = $state_count;                //返回数据
        $data_info['shop_name'] = $shop_name;                //门店名称
        $data_info['after_log'] = $after_log;                //门店名称

        // 获取当前列表下的按钮
        $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 VerifyOrderAfterController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询售后单
        $find_order_after = DB::table('order_after as oraf')
            ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
            ->leftJoin('warehouse as ware', 'ware.ware_id', '=', 'oraf.oraf_ware_id')
            ->where('oraf_id', $request['oraf_id'])
            ->select('oraf_number', 'oraf_order_number', 'orac_result', 'oraf_orla_id', 'orac_channel_unit', 'orac_name', 'orac_phone', 'orac_car_num', 'orac_province', 'orac_city', 'orac_county', 'orac_address', 'oraf_service_shop_id', 'oraf_service_adm_id', 'orac_image', 'oraf_order_price', 'oraf_actual_price', 'ware_name', 'oraf_collection_price')
            ->first();
        // 服务门店
        $find_order_after->service_shop_name = DB::table('shop')
            ->where('shop_id', $find_order_after->oraf_service_shop_id)
            ->value('shop_store_name');
        // 服务技师
        $find_order_after->service_adm_name = DB::table('admin')
            ->where('adm_id', $find_order_after->oraf_service_adm_id)
            ->value('adm_name');
        // 查询售后备注
        $find_after_label = DB::table('order_after_note')
            ->where('oran_oraf_id', $request['oraf_id'])
            ->select('oran_afla_id')
            ->get()->toArray();
        $afla_id = array_unique(array_column($find_after_label, 'oran_afla_id'));
        $find_afla_name = DB::table('after_label')
            ->whereIn('afla_id', $afla_id)
            ->select('afla_id', 'afla_name')
            ->get();
        // 查询售后商品
        $find_after_goods = DB::table('order_after_goods')
            ->where('orag_oraf_id', $request['oraf_id'])
            ->select('orag_id', 'orag_goo_id', 'orag_goo_name', 'orag_goo_goods_encode', 'orag_goo_quantity', 'orag_is_recycle', 'orag_recycle_quantity', 'orag_goo_type', 'orag_remark')
            ->get();
        
        $data['find_order_after'] = $find_order_after;
        $data['find_afla_name'] = $find_afla_name;
        $data['find_after_goods'] = $find_after_goods;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

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

        $work_data = DB::table('order_after as oraf')
            ->leftjoin('work_order as wor', 'wor.wor_order_id', '=', 'oraf.oraf_ord_id')
            ->leftJoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->leftJoin('warehouse as ware', 'ware.ware_id', '=', 'wor.wor_ware_id')
            ->where('oraf_id', $request['oraf_id'])
            ->select('wor_id', 'wor_order_number', 'wor_number', 'wor_actual_price', 'wor_plus_minus', 'wor_goo_amount', 'wor_service_type', 'wor_type', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_address', 'wor_remark', 'wor_code', 'wor_service_shop_id', 'wor_service_adm_id', 'ware_name', 'wor_img', 'wocl_join_wor_id')
            ->first();
        // 获取商品数据
        $work_goods = DB::table('work_good')
            ->where('wogo_wor_id', $work_data->wor_id)
            ->where('wogo_state', '<>', 2)
            ->select('wogo_goo_id', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_amount', 'wogo_is_recycle', 'wogo_recycle_quantity', 'wogo_actual_recycle_number', 'wogo_remark', 'wogo_goo_type', 'wogo_state')
            ->get();
        if ($work_data->wor_id == null) {
            $work_data = DB::table('order_after as oraf')
                ->leftjoin('order as ord', 'ord.ord_id', '=', 'oraf.oraf_ord_id')
                ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->leftJoin('warehouse as ware', 'ware.ware_id', '=', 'ord.ord_ware_id')
                ->where('oraf_id', $request['oraf_id'])
                ->select('ord_id as wor_id', 'ord_order_number as wor_order_number', 'ord_actual_price as wor_actual_price', 'ord_plus_minus as wor_plus_minus', 'ord_goods_quantity as wor_goo_amount', 'ord_service_type as wor_service_type', 'ord_type as wor_type', 'orcl_channel_unit as wocl_channel_unit', 'orcl_name as wocl_name', 'orcl_phone as wocl_phone', 'orcl_province as wocl_province', 'orcl_city as wocl_city', 'orcl_county as wocl_county', 'orcl_address as wocl_address', 'ord_remark as wor_remark', 'ord_service_shop_id as wor_service_shop_id', 'ord_service_sepr_id as wor_service_adm_id', 'ware_name')
                ->first();
            // 获取商品数据
            $work_goods = DB::table('order_goods')
                ->where('orgo_ord_id', $work_data->wor_id)
                ->where('orgo_state', '<>', 2)
                ->select('orgo_goo_id as wogo_goo_id', 'orgo_goo_name as wogo_goo_name', 'orgo_goo_goods_encode as wogo_goo_goods_encode', 'orgo_goo_quantity as wogo_goo_amount', 'orgo_is_recycle as wogo_is_recycle', 'orgo_recycle_quantity as wogo_recycle_quantity', 'orgo_goo_type as wogo_goo_type', 'orgo_state as wogo_state')
                ->get();
        }
        // 账号id
        $adm_id = [
            $work_data->wor_service_adm_id
        ];
        $adm_id = array_unique($adm_id);
        // 查询账号id对应的名称
        $find_admin = DB::table('admin')
            ->whereIn('adm_id', $adm_id)
            ->pluck('adm_name', 'adm_id')
            ->toArray();

        $work_data->wor_service_adm_name = isset($find_admin[$work_data->wor_service_adm_id]) ? $find_admin[$work_data->wor_service_adm_id] : '';
        
        // 查询服务门店名称
        $work_data->wor_service_shop_name = DB::table('shop')
            ->where('shop_id', $work_data->wor_service_shop_id)
            ->value('shop_store_name');

        $data['wor_data'] = $work_data;
        $data['work_goods'] = $work_goods;
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 售后备注
    public function afterNote(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->afterNoteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        $oran_data['oran_oraf_id'] = $request['oraf_id'];
        $oran_data['oran_afla_id'] = $request['oran_afla_id'];
        $oran_data['oran_adm_id'] = $user_info->adm_id;
        $oran_data['oran_adm_name'] = $user_info->adm_name;
        $oran_data['oran_content'] = $request['oran_content'] ? $request['oran_content'] : '';
        $oran_data['oran_update_time'] = date('Y-m-d H:i:s');
        $oran_id = DB::table('order_after_note')->insert($oran_data);

        if ($oran_id) {
            $oraf_number = DB::table('order_after')
                ->where('oraf_id', $request['oraf_id'])
                ->value('oraf_number');
            Common::addLog($user_info, getRealIp($request), '订单售后', '售后备注', $oraf_number . '添加售后备注成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'售后备注添加成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'售后备注添加失败']);
        }
    }

    // 售后备注列表
    public function afterNoteList(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $list_data = DB::table('order_after_note')
            ->where('oran_oraf_id', $request['oraf_id'])
            ->select('oran_id', 'oran_oraf_id', 'oran_afla_id', 'oran_adm_id', 'oran_adm_name', 'oran_content', 'oran_update_time')
            ->orderBy('oran_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();

        if ($list_items) {
            $oran_afla_id = array_unique(array_column($list_items, 'oran_afla_id')); //售后标签id
            // 查找售后标签名称
            $afla_name = DB::table('after_label')
                ->whereIn('afla_id', $oran_afla_id)
                ->select('afla_id', 'afla_name')
                ->get();
        } else {
            $afla_name = [];
        }

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

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

    // 日常反馈
    public function dailyFeedback(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->dailyFeedbackValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        $orap_data['orap_oraf_id'] = $request['oraf_id'];
        $orap_data['orap_adm_id'] = $user_info->adm_id;
        $orap_data['orap_adm_name'] = $user_info->adm_name;
        $orap_data['orap_image'] = uploadBase64Img($request['orap_image']); //调用全局函数 上传图片
        $orap_data['orap_remark'] = $request['orap_remark'] ? $request['orap_remark'] : '';
        $orap_data['orap_update_time'] = date('Y-m-d H:i:s');
        $orap_id = DB::table('order_after_pic')->insert($orap_data);

        if ($orap_id) {
            $oraf = DB::table('order_after')
                ->where('oraf_id', $request['oraf_id'])
                ->first(['oraf_number','oraf_other_system_number','oraf_type', 'oraf_service_adm_id']);
            Common::addLog($user_info, getRealIp($request), '日常反馈', '日常反馈', $oraf->oraf_number . '日常反馈添加成功');

            //如果是速电派单  并且开启推送
            if (config('apisystem.SYNC_STATE') && $oraf->oraf_type == 3) {
                if (!empty($oraf->oraf_service_adm_id)) {
                    $adm = DB::table('admin')
                        ->where('adm_id', $oraf->oraf_service_adm_id)
                        ->first(['adm_name','adm_phone']);
                    $param['install_name'] = $adm->adm_name;
                    $param['install_phone'] = $adm->adm_phone;
                } else {
                    $param['install_name'] = '';
                    $param['install_phone'] = '';
                }
                $param['after_num'] = $oraf->oraf_other_system_number;
                $param['time'] = date('Y-m-d H:i:s');
                $param['filePic'] = [config('apisystem.server_name').'/'.$orap_data['orap_image']];//图片
                $param['ip'] = getRealIp($request);
                $param['content'] = $orap_data['orap_remark'];//备注
                $param['type'] = 1;//1日常反馈2完成反馈
                $param['token'] = config('apisystem.sd_token');
                $url = config('apisystem.sd_server_name').'/index.php/Supply/feedSales';
                $doPost_res = Common::doPost($param, $url);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                }
            }
            DB::commit();  //提交
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'日常反馈添加成功']);
        } else {
            DB::rollBack();  //回滚
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'日常反馈添加失败']);
        }
    }

    // 日常反馈列表
    public function dailyFeedbackList(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $list_data = DB::table('order_after_pic')
            ->where('orap_oraf_id', $request['oraf_id'])
            ->select('orap_id', 'orap_oraf_id', 'orap_adm_id', 'orap_adm_name', 'orap_image', 'orap_remark', 'orap_update_time')
            ->orderBy('orap_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();

        $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;                //返回数据

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

    // 催单
    public function reminder(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->infoValidator($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;

        $afre_data['wore_cid'] = $user_info->adm_cid;
        $afre_data['wore_superior_shop_id'] = $shop_id;
        $afre_data['wore_shop_id'] = $user_info->adm_shop_id;
        $afre_data['wore_wor_id'] = $request['oraf_id'];
        $afre_data['wore_wor_number'] = $request['oraf_number'];
        $afre_data['wore_service_adm_id'] = $request['oraf_service_adm_id'];
        $afre_data['wore_type'] = 2;
        $afre_data['wore_state'] = 1;
        $afre_data['wore_reminder_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        // 判断该售后单有没有催单,有,更新次数,没有,新增
        $afre_id = DB::table('work_reminder')
            ->where('wore_wor_id', $request['oraf_id'])
            ->where('wore_wor_number', $request['oraf_number'])
            ->value('wore_id');
        if ($afre_id) {
            $afre_res = DB::table('work_reminder')
                ->where('wore_id', $afre_id)
                ->increment('wore_reminder_count', 1, $afre_data);
        } else {
            $afre_res = DB::table('work_reminder')->insert($afre_data);
        }

        // 生成操作记录
        $log_res = orderAfterLog($user_info, $request['oraf_id'], '3', '催单');
        if ($afre_res && $log_res) {
            $adm_phone =  DB::table('admin')
                ->where('adm_id', $request['oraf_service_adm_id'])
                ->value('adm_phone');
            $push_name['alias'][] = $adm_phone;//发送对象
            $result_push = pushMessage($push_name, '您有售后单：' . $request['oraf_number'] . ' 被催单', 2);

            DB::commit();
            Common::addLog($user_info, getRealIp($request), '售后单列表', '催单', $request['oraf_number'] . '催单成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'催单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'催单失败']);
        }
    }

    // 取消售后
    public function cancel(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->cancelValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_order_after = DB::table('order_after as oraf')
            ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
            ->where('oraf_id', $request['oraf_id'])
            ->select('oraf_number', 'oraf_ord_id', 'oraf_order_number', 'oraf_state', 'oraf_delete', 'oraf_wor_state', 'oraf_service_type', 'oraf_service_shop_id', 'orac_join_wor_id', 'orac_join_oraf_id', 'orac_order_type', 'oraf_type')
            ->first();
        if ($find_order_after->oraf_state != '1') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前售后单已结算, 无法取消']);
        }
        if ($find_order_after->oraf_delete == '2') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前售后单已取消']);
        }
        if ($find_order_after->oraf_wor_state != '1') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前售后单正在售后中，无法取消']);
        }
        if ($find_order_after->oraf_service_type == '6') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结清单无法取消']);
        }
        if ($find_order_after->oraf_type == '3') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'速电派单不允许取消']);
        }

        // 售后单数据
        $oraf_data['oraf_delete'] = 2;
        $oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');

        // 将订单状态改为已完成
        $ord_data['ord_wor_state'] = 4;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        
        DB::beginTransaction();
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_type = $user_info->shop_superior_id ? 2 : 1;

        // 删除售后订单数据
        $oraf_res = DB::table('order_after')
            ->where('oraf_id', $request['oraf_id'])
            ->update($oraf_data);
        if ($shop_type == 1) {
            if (!empty($find_order_after->orac_join_wor_id)) {
                // 加盟店售后单
                $join_oraf_res = DB::table('order_after')
                    ->where('oraf_id', $find_order_after->orac_join_wor_id)
                    ->update($oraf_data);
            } else {
                $join_oraf_res = true;
            }
        } else {
            // 取消外派售后单
            if (isset($find_order_after->orac_order_type) && $find_order_after->orac_order_type == 2) {
                $join_oraf_res = DB::table('order_after')
                    ->where('oraf_id', $find_order_after->orac_join_wor_id)
                    ->update($oraf_data);
            } else {
                $join_oraf_res = true;
            }
        }
        // 将订单状态改为已完成
        $ord_res = DB::table('order')
            ->where('ord_id', $find_order_after->oraf_ord_id)
            ->update($ord_data);
        
        // 生成操作记录
        $cancel_record = orderAfterLog($user_info, $request['oraf_id'], 3, '取消售后');

        if ($oraf_res && $join_oraf_res && $ord_res && $cancel_record) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单售后', '取消售后', '取消售后：' . $find_order_after->oraf_number . '成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'取消售后成功']);
        } else {
            DB::rollBack();
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'取消售后失败']);
        }
    }

    // 派单
    public function sendOrders(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->sendOrdersValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $ware_return = Warehouse::existMoveWarehouse($request['service_adm_id']);
        if (empty($ware_return)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前技师暂未绑定移动仓，无法派单']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        
        // 1总店2加盟店
        $shop_type = $user_info->shop_superior_id ? 2 : 1;
        DB::beginTransaction();

        // 添加售后单商品数据
        $goo_all_quantity = 0;//商品总数量

        foreach ($request['goo_id'] as $key => $value) {
            if (!is_numeric($value) || !is_numeric($request['goo_waon_class'][$key]) || !is_numeric($request['goo_quantity'][$key]) || !in_array($request['goo_state'][$key], [1, 3, 4, 5, 6]) || !in_array($request['goo_inventory'][$key], [1, 2])) {
                return ['code'=>500, 'msg'=>'error', 'data'=>'商品参数类型错误'];
            }
            // 售后单商品表数据
            $orag_data[$key]['orag_ware_id'] = $request['ware_id'];//仓库id
            $orag_data[$key]['orag_waon_class'] = $request['goo_waon_class'][$key];//仓库类别1货物仓2非货物仓3旧货仓4临时仓
            $orag_data[$key]['orag_goo_id'] = $value;//商品id

            // 搜索商品id对应的商品名称、商品编号
            $find_goods_data = DB::table('goods')
                ->where('goo_id', $value)
                ->select('goo_name', 'goo_goods_encode', 'goo_type', 'goo_ampere_hour', 'goo_price')
                ->first();
            $orag_data[$key]['orag_goo_name'] = $find_goods_data->goo_name;//商品名称
            $orag_data[$key]['orag_goo_goods_encode'] = $find_goods_data->goo_goods_encode;//商品编号
            $orag_data[$key]['orag_goo_ampere_hour'] = $find_goods_data->goo_ampere_hour;//商品安时数
            $orag_data[$key]['orag_goo_type'] = $find_goods_data->goo_type;//商品类型1正常商品2赠送商品3活动商品4旧货商品
            $orag_data[$key]['orag_state'] = $request['goo_state'][$key];//商品状态1正常2删除3回收的商品4换货商品5赠品商品6备用电池
            $orag_data[$key]['orag_goo_price'] = $request['goo_price'][$key] * 100;//商品售价
            $orag_data[$key]['orag_goo_quantity'] = $request['goo_quantity'][$key];//商品数量
            $orag_data[$key]['orag_goo_inventory'] = $request['goo_inventory'][$key];//库存扣除方式1良品2优先
            $orag_data[$key]['orag_update_time'] = date('Y-m-d H:i:s');

            $goo_all_quantity += $request['goo_quantity'][$key];
            $orag_data[$key]['orag_oraf_id'] = $request['oraf_id'];
        }

        $orag_id = DB::table('order_after_goods')->insert($orag_data);

        // 修改售后单数据
        $oraf_data['oraf_service_adm_id'] = $request['service_adm_id'];//服务技师id
        $oraf_data['oraf_ware_id'] = $request['ware_id'];//仓库id
        $oraf_data['oraf_goods_quantity'] = $goo_all_quantity;//商品总数量
        $oraf_data['oraf_wor_state'] = 2;//服务状态1未派单2待接单
        $oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');
        $oraf_id = DB::table('order_after')
            ->where('oraf_id', $request['oraf_id'])
            ->update($oraf_data);

        // 将百度经纬度 转化为高德经纬度
        // $lat_lon = Common::convert($request['latitude'], $request['longitude']);
        // $lat [纬度]
        // * @param [type] $lng [经度]
        // 修改订单售后客户信息
        $orac_data['orac_standby_battery_type']= $request['orac_standby_battery_type'];
        $orac_data['orac_longitude'] = $request['longitude'];//经度
        $orac_data['orac_latitude'] = $request['latitude'];//纬度
        $orac_data['orac_update_time']= date('Y-m-d H:i:s');
        $orac_id = DB::table('order_after_client')
            ->where('orac_oraf_id', $request['oraf_id'])
            ->update($orac_data);

        // 查询数据
        $find_oraf_id = DB::table('order_after')
            ->where('oraf_id', $request['oraf_id'])
            ->select('oraf_number', 'oraf_service_type', 'oraf_service_shop_id', 'oraf_type', 'oraf_other_system_number', 'oraf_type', 'oraf_client_id')
            ->first();
        $request['service_shop_id'] = $find_oraf_id->oraf_service_shop_id;
        // 服务门店为0的话 是当前门店id
        if ($request['service_shop_id'] == 0) {
            $oraf_data['oraf_service_shop_id'] = $user_info->adm_shop_id; //服务门店id
        } else {
            $oraf_data['oraf_service_shop_id'] = $request['service_shop_id']; //服务门店id
        }

        // 选择的仓库不为当前技师移动仓时,生成发货单
        $ware_id = DB::table('warehouse')
            ->where('ware_type', 2)//类型1固定仓2移动仓
            ->where('ware_leader_id', $request['service_adm_id'])
            ->value('ware_id');
        // 当前仓库不是技师的移动仓 且 服务类型不为退货单 且 有商品数据 生成发货单
        if ($ware_id != $request['ware_id'] && $find_oraf_id->oraf_service_type != '4' && !empty($request['goo_id'])) {
            $dibi_data = DispatchBill::add(
                $user_info,
                $request->all(),
                3,//类型1.订单发货2工单发货3售后单发货
                $request['ware_id'],//出库仓库id
                $find_oraf_id->oraf_number,//原始单号,订单号/工单号/售后单号
                $request['oraf_id'],//发货单关联的售后单/工单/订单id
                $oraf_data['oraf_service_shop_id'],//所属总店id
                $find_oraf_id->oraf_type,//买家类型：1门店零售2渠道单位3速电派单4第三方派单
                $find_oraf_id->oraf_client_id,//选择的客户id，会员id/单位id
                $goo_all_quantity//发货总数量
            );
            if ($dibi_data['code'] == 500) {
                DB::rollBack();
                return response()->json($dibi_data);
            }
        }

        // 生成操作记录
        $assign_record_res = orderAfterLog($user_info, $request['oraf_id'], 3, '派单');

        if ($orag_id && $oraf_id && $orac_id && $assign_record_res) {
            $adm_phone =  DB::table('admin')
                ->where('adm_id', $request['service_adm_id'])
                ->value('adm_phone');
            $push_name['alias'][] = $adm_phone; //发送对象
            $result_push = pushMessage($push_name, '您有新的售后单：' . $find_oraf_id->oraf_number . ' 请注意查收', 3);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '售后单列表', '派单', $find_oraf_id->oraf_number . '派单成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'派单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'派单失败']);
        }
    }

    /**
     * [editLockUnlock 售后单锁定取消锁定]
     * @param  [int] $user_info [用户信息]
     * @param  [int] $wor_id    [售后单id]
     * @param  [int] $type      [类型：4锁定 1取消锁定]
     * @return [type]         [description]
     */
    private function editLockUnlock($user_info, $oraf_id, $type)
    {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        //1总店  2加盟店
        $shop_type = $user_info->shop_superior_id ? 2 : 1;
        // 售后单状态数据
        $after_order = DB::table('order_after')
            ->where('oraf_id', $oraf_id)
            ->select('oraf_wor_state', 'oraf_ord_id')
            ->first();
        
        DB::beginTransaction();
        if ($type == '1') {
            $hint = '取消锁定';
            $orac_before_wor_state = DB::table('order_after_client')
                ->where('orac_oraf_id', $oraf_id)
                ->value('orac_before_wor_state');
            // dump($orac_before_wor_state);
            if (in_array($orac_before_wor_state, [1])) {
                $oraf_edit_data['oraf_wor_state'] = 1;
            } else {
                $oraf_edit_data['oraf_wor_state'] = stateAfterSetting($orac_before_wor_state);
            }
            // dump($oraf_edit_data);exit;
            $oraf_edit_data['oraf_update_time'] = date('Y-m-d H:i:s');
            $oraf_edit_data['orac_before_wor_state'] = $after_order->oraf_wor_state;
            $oraf_edit_data['orac_update_time'] = date('Y-m-d H:i:s');
            $edit_res = DB::table('order_after as oraf')
                ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                ->where('oraf_id', $oraf_id)
                ->update($oraf_edit_data);
            if ($shop_type == '1') {
                // 判断是否为加盟店派单
                $join_oraf_id = DB::table('order_after_client')
                    ->where('orac_oraf_id', $oraf_id)
                    ->value('orac_join_wor_id');
                if (!empty($join_oraf_id)) {
                    // 加盟店售后单
                    $join_after_info = DB::table('order_after')
                        ->where('oraf_id', $join_oraf_id)
                        ->select('oraf_wor_state', 'oraf_id')
                        ->first();
                    if (!empty($join_after_info)) {
                        $orac_state = DB::table('order_after_client')
                            ->where('orac_oraf_id', $join_after_info->oraf_id)
                            ->value('orac_before_wor_state');
                        if (in_array($orac_state, [1])) {
                            $join_oraf_data['oraf_wor_state'] = 1;
                        } else {
                            $join_oraf_data['oraf_wor_state'] = stateAfterSetting($orac_before_wor_state);
                        }
                        $join_oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');
                        $join_oraf_data['orac_before_wor_state'] = $after_order->oraf_wor_state;
                        $join_oraf_data['orac_update_time'] = date('Y-m-d H:i:s');
                        $join_oraf_res = DB::table('order_after as oraf')
                            ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                            ->where('oraf_id', $join_after_info->oraf_id)
                            ->update($join_oraf_data);
                        // 查询当前售后单的发货单状态,已发货的发货单不需要更改
                        $dego_type = 1;
                        $find_dego = DB::table('dispatch_bill')
                            ->where('dego_order_type', 3)//类型1订单发货2工单发货3售后单发货
                            ->where('dego_type', $dego_type)//类型1未出库2已出库3作废4锁定
                            ->where('dego_wor_id', $oraf_id)
                            ->select('dego_id')
                            ->orderBy('dego_id', 'desc')
                            ->first();
                        if (empty($find_dego)) {
                            $dego_res = true;
                        } else {
                            // 把未发货的发货单改成锁定状态
                            $dego_edit_data['dego_type'] = $type;
                            $dego_res = DB::table('dispatch_bill')
                                ->where('dego_id', $find_dego->dego_id)
                                ->update($dego_edit_data);
                        }
                        // dump($dego_res);
                        if (empty($dego_res)) {
                            DB::rollBack();
                            return ['code'=>500, 'msg'=>'error', 'data'=>'当前售后单' . $hint . '失败'];
                        }
                    } else {
                        $join_oraf_res = true;
                    }
                } else {
                    $join_oraf_res = true;
                }
            } else {
                // 加盟店售后单数据
                $head_oraf_info = DB::table('order_after_client')
                    ->where('orac_oraf_id', $oraf_id)
                    ->select('orac_before_wor_state', 'orac_order_type', 'orac_join_oraf_id')
                    ->first();
                // 如果是外派售后单
                if (isset($head_oraf_info->orac_order_type) && $head_oraf_info->orac_order_type == 2) {
                    if (in_array($head_oraf_info->orac_before_wor_state, [1,2,3])) {
                        $join_oraf_data['oraf_wor_state'] = 1;
                    } else {
                        $join_oraf_data['oraf_wor_state'] = stateAfterSetting($head_oraf_info->orac_before_wor_state);
                    }
                    $join_oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');
                    $join_oraf_data['orac_before_wor_state'] = $after_order->oraf_wor_state;
                    $join_oraf_data['orac_update_time'] = date('Y-m-d H:i:s');
                    $join_oraf_res = DB::table('order_after as oraf')
                        ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                        ->where('oraf_id', $head_oraf_info->orac_join_oraf_id)
                        ->update($join_oraf_data);
                } else {
                    $join_oraf_res = true;
                }
            }
        } else {
            $hint = '锁定';
            $edit_data['oraf_wor_state'] = 11;
            $edit_data['oraf_update_time'] = date('Y-m-d H:i:s');
            $edit_data['orac_before_wor_state'] = $after_order->oraf_wor_state;
            $edit_data['orac_update_time'] = date('Y-m-d H:i:s');
            $edit_res = DB::table('order_after as oraf')
                ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                ->where('oraf_id', $oraf_id)
                ->update($edit_data);
            if ($shop_type == '1') {
                // 判断是否派给加盟店加盟店派单
                $join_oraf_id = DB::table('order_after_client')
                    ->where('orac_oraf_id', $oraf_id)
                    ->value('orac_join_wor_id');
                if (!empty($join_oraf_id)) {
                    // 加盟店售后单
                    $join_after_info = DB::table('order_after')
                        ->where('oraf_id', $join_oraf_id)
                        ->select('oraf_wor_state', 'oraf_id')
                        ->first();
                    if (!empty($join_after_info)) {
                        $orac_state = DB::table('order_after_client')
                            ->where('orac_oraf_id', $join_after_info->oraf_id)
                            ->select('orac_before_wor_state', 'orac_id')
                            ->first();
                        $join_oraf_data['oraf_wor_state'] = 11;
                        $join_oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');
                        $join_oraf_data['orac_before_wor_state'] = $after_order->oraf_wor_state;
                        $join_oraf_data['orac_update_time'] = date('Y-m-d H:i:s');
                        $join_oraf_res = DB::table('order_after as oraf')
                            ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                            ->where('oraf_id', $join_after_info->oraf_id)
                            ->update($join_oraf_data);
                        
                        // 查询当前售后单的发货单状态,已发货的发货单不需要更改
                        $dego_type = 4;
                        $find_dego = DB::table('dispatch_bill')
                            ->where('dego_order_type', 3)//类型1订单发货2工单发货3售后单发货
                            ->where('dego_type', $dego_type)//类型1未出库2已出库3作废4锁定
                            ->where('dego_wor_id', $oraf_id)
                            ->select('dego_id')
                            ->orderBy('dego_id', 'desc')
                            ->first();
                        if (empty($find_dego)) {
                            $dego_res = true;
                        } else {
                            // 把未发货的发货单改成锁定状态
                            $dego_edit_data['dego_type'] = $type;
                            $dego_res = DB::table('dispatch_bill')
                                ->where('dego_id', $find_dego->dego_id)
                                ->update($dego_edit_data);
                        }
                        if (empty($dego_res)) {
                            DB::rollBack();
                            return ['code'=>500, 'msg'=>'error', 'data'=>'当前售后单' . $hint . '失败'];
                        }
                    } else {
                        $join_oraf_res = true;
                    }
                } else {
                    $join_oraf_res = true;
                }
            } else {
                // 加盟店售后单数据
                $head_oraf_info = DB::table('order_after_client')
                    ->where('orac_oraf_id', $oraf_id)
                    ->select('orac_before_wor_state', 'orac_order_type', 'orac_join_oraf_id')
                    ->first();
                // 如果是外派售后单
                if (isset($head_oraf_info->orac_order_type) && $head_oraf_info->orac_order_type == 2) {
                    $join_oraf_data['oraf_wor_state'] = 11;
                    $join_oraf_data['orac_update_time'] = date('Y-m-d H:i:s');
                    $join_orac_data['orac_before_wor_state'] = $after_order->oraf_wor_state;
                    $join_orac_data['orac_update_time'] = date('Y-m-d H:i:s');
                    $join_oraf_res = DB::table('order_after as oraf')
                        ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
                        ->where('oraf_id', $head_oraf_info->orac_join_oraf_id)
                        ->update($join_oraf_data);
                } else {
                    $join_oraf_res = true;
                }
            }
        }

        // 查询当前售后单的发货单的状态,已发货的发货单不需要更改
        $dego_type = $type == 1 ? 4 : 1;
        $find_dego = DB::table('dispatch_bill')
            ->where('dego_order_type', 3)//类型1订单发货2工单发货3售后单发货
            ->where('dego_type', $dego_type)
            ->where('dego_wor_id', $oraf_id)
            ->select('dego_id')
            ->orderBy('dego_id', 'desc')
            ->first();
        if (empty($find_dego)) {
            $dego_res = true;
        } else {
            // 未发货的发货单改成锁定状态
            $dego_edit_data['dego_type'] = $type;
            $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
            $dego_res = DB::table('dispatch_bill')
                ->where('dego_id', $find_dego->dego_id)
                ->update($dego_edit_data);
        }
        // dump($join_oraf_res);
        // dump($dego_res);
        // dump($edit_res);
        if ($join_oraf_res && $dego_res && $edit_res) {
            orderAfterLog($user_info, $oraf_id, '3', $hint);
            DB::commit();
            return ['code'=>200, 'msg'=>'success', 'data'=>'当前售后单' . $hint . '成功'];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'error', 'data'=>'当前售后单' . $hint . '失败'];
        }
    }

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

        // 锁定
        $lock_return = $this->editLockUnlock($user_info, $request['oraf_id'], 4);
        if ($lock_return['code'] == 200) {
            $oraf_number = DB::table('order_after')
                ->where('oraf_id', $request['oraf_id'])
                ->value('oraf_number');
            Common::addLog($user_info, getRealIp($request), '售后单列表', '锁定', $oraf_number . '锁定成功');
        }
        return response()->json($lock_return);
    }

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

        // 改单锁定
        $lock_return = $this->editLockUnlock($user_info, $request['oraf_id'], 1);
        if ($lock_return['code'] == 200) {
            $oraf_number = DB::table('order_after')
                ->where('oraf_id', $request['oraf_id'])
                ->value('oraf_number');
            Common::addLog($user_info, getRealIp($request), '售后单列表', '取消锁定', $oraf_number . '取消锁定成功');
        }
        return response()->json($lock_return);
    }

    // 审核
    public function pass(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->passValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 查询信息
        $find_order_after = DB::table('order_after as oraf')
            ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
            ->where('oraf_id', $request['oraf_id'])
            ->select('oraf_id', 'oraf_number', 'oraf_ord_id', 'oraf_order_number', 'oraf_wor_state', 'orac_client_id', 'oraf_collection_price', 'oraf_service_shop_id', 'oraf_service_type', 'oraf_plus_minus', 'oraf_collection_bill', 'orac_collect_state', 'orac_channel_unit', 'orac_name', 'orac_acc_subject_id', 'orac_join_oraf_id', 'orac_order_type', 'oraf_actual_price', 'oraf_state', 'oraf_type', 'oraf_client_id', 'oraf_other_system_number', 'orac_image', 'oraf_service_adm_id', 'oraf_remark', 'oraf_create_time')
            ->first();
        // oraf_wor_state 服务状态1未派单2待接单/已派单3未出发/已接单4未抵达5预约/已预约6已出发7已抵达8完成待审核9完成已驳回10已完成11锁定
        if ($find_order_after->oraf_wor_state != '8') {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前售后单服务未完成,无法审核通过']);
        }

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

        // 查询出售后单商品
        $after_goods = DB::table('order_after_goods')
            ->where('orag_oraf_id', $request['oraf_id'])
            ->select('orag_goo_id', 'orag_goo_quantity', 'orag_goo_inventory', 'orag_goo_price', 'orag_collection_price', 'orag_state', 'orag_recycle_price', 'orag_recycle_quantity')
            ->get()->toArray();

        // 服务名称
        $shop_info = DB::table('shop')
            ->where('shop_id', $find_order_after->oraf_service_shop_id)
            ->select('shop_store_name', 'shop_type')
            ->first();

        // 更改售后单信息
        $oraf_data['oraf_wor_state'] = 10;//服务状态1未派单2待接单/已派单3未出发/已接单4未抵达5预约/已预约6已出发7已抵达8完成待审核9完成已驳回10已完成11锁定
        $oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');
        $oraf_data['oraf_actual_price'] = $request['oraf_actual_price'] * 100;//客户售后结算
        //如果是速电派单
        if ($find_order_after->oraf_type == 3) {
            $oraf_data['oraf_order_state'] = 10;//10等待速电审核
        }
        DB::beginTransaction();
        $oraf_res = DB::table('order_after')
            ->where('oraf_id', $request['oraf_id'])
            ->update($oraf_data);
        $client_name = $find_order_after->orac_channel_unit ? $find_order_after->orac_channel_unit : $find_order_after->orac_name;
        // dump($find_order_after->orac_order_type);
        // dump($find_order_after->orac_order_type);
        // dump($find_order_after->orac_collect_state);
        // dump($find_order_after->oraf_collection_price);
        // dump($find_order_after->oraf_state);
        // exit;
        //如果是外派工单  加盟店审核
        if ($find_order_after->orac_order_type == 2 && $find_order_after->orac_order_type != 0) {
            $join_wor_res = DB::table('order_after')
                ->where('oraf_id', $find_order_after->orac_join_oraf_id)
                ->update($oraf_data);
            $orac_data['orac_join_audit'] = 2;//1未审核2已审核
            $orac_data['orac_join_audit_adm_id'] = $user_info->adm_id;
            $join_orac_id = DB::table('order_after_client')
                ->where('orac_oraf_id', $request['oraf_id'])
                ->update($orac_data);
            // 生成操作记录
            $edit_record = orderAfterLog($user_info, $request['oraf_id'], '3', '审核通过售后单');
            if ($oraf_res && $join_wor_res && $join_orac_id && $edit_record) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '售后单列表', '通过', $find_order_after->oraf_number . '通过成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
            }
            // 如果是速电派单
        } elseif ($find_order_after->oraf_type == 3) {
            $edit_record = orderAfterLog($user_info, $request['oraf_id'], '3', '审核通过售后单,等待第三方审核');
            if ($oraf_res && $edit_record) {
                Common::addLog($user_info, getRealIp($request), '售后单列表', '通过', $find_order_after->oraf_number . '通过成功');
                if (config('apisystem.SYNC_STATE')) {
                    if (!empty($find_order_after->oraf_service_adm_id)) {
                        $adm = DB::table('admin')
                            ->where('adm_id', $find_order_after->oraf_service_adm_id)
                            ->first(['adm_name','adm_phone']);
                        $param['install_name'] = $adm->adm_name;
                        $param['install_phone'] = $adm->adm_phone;
                    } else {
                        $param['install_name'] = '';
                        $param['install_phone'] = '';
                    }
                    $param['after_num'] = $find_order_after->oraf_other_system_number;
                    $param['time'] = date('Y-m-d H:i:s');
                    $image = json_decode($find_order_after->orac_image);
                    foreach ($image as $key => $value) {
                        if (!empty($value)) {
                            $image[$key] = config('apisystem.server_name').'/'.$value;
                        } else {
                            $image[$key] = '';
                        }
                    }
                    $param['filePic'] = $image;//图片
                    $param['ip'] = getRealIp($request);
                    $param['content'] = $find_order_after->oraf_remark;//备注
                    $param['type'] = 2;//1日常反馈2完成反馈
                    $param['token'] = config('apisystem.sd_token');
                    $url = config('apisystem.sd_server_name').'/index.php/Supply/feedSales';
                    $doPost_res = Common::doPost($param, $url);
                    $doPost_res = json_decode($doPost_res);
                    if ($doPost_res->code != 200) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                    }
                }
                DB::commit();
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
            }
            // 如果是外派工单  总店审核
        } elseif ($find_order_after->orac_order_type == 2 && $find_order_after->orac_order_type == 0) {
            // 加盟店应收账款
            // 技师代收,代收金额为0,结算方式为现结
            if ($find_order_after->orac_collect_state == '1' && $find_order_after->oraf_collection_price == 0) {
                // 生成结款明细
                $acset_id = AccountingSettlement::add(
                    $user_info, // [用户信息]
                    20,
                    $find_order_after->oraf_id, // [与单据类型对应的id]
                    $find_order_after->oraf_number, // [与单据类型对应的单号]
                    $find_order_after->oraf_type, // [买家类型1门店零售2来往单位]
                    $find_order_after->oraf_client_id, // [会员/客户id]
                    $client_name, // [来往单位名称]
                    $find_order_after->orac_acc_subject_id, // [会计科目id]
                    1, // [类型1收入2支出]
                    $request['oraf_actual_price'] * 100, // [实际金额](此次的实收金额)
                    $request['oraf_actual_price'] * 100, // [合计金额](此次的应收金额)
                    0, // [欠收金额](此次结款后还应收金额)
                    0, // [抹零金额]
                    '' //[备注]
                );
                // 售后单应收
                $ord_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    14, //类型
                    0, //应收账款id
                    $find_order_after->oraf_id, //原始id
                    $find_order_after->oraf_number, //应收账款单号/原始号
                    $find_order_after->oraf_type, //客户类型：1.门店零售 2.来往单位
                    $find_order_after->oraf_client_id, //会员id/来往单位id
                    $client_name, //来往单位名称
                    $request['oraf_actual_price'] * 100, //结算金额(应收金额)
                    '', //结款时间
                    $find_order_after->orac_acc_subject_id, //会计科目id
                    $request['oraf_actual_price'] * 100, //实际金额(应收金额)
                    0, //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    '',  //备注
                    $request['oraf_actual_price'] * 100,  //已收金额
                    '', //截止时间
                    $find_order_after->oraf_plus_minus, //金额正负1正   2负值
                    17, //显示类型
                    1, //是否合并代收：1是2否
                    $find_order_after->oraf_create_time
                );
                // 生成操作记录
                $edit_record = orderAfterLog($user_info, $request['oraf_id'], '3', '审核通过售后单');
                if ($oraf_res && $acset_id && $ord_bill) {
                    DB::commit();
                    Common::addLog($user_info, getRealIp($request), '售后单列表', '通过', $find_order_after->oraf_number . '通过成功');
                    return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
                }
            }

            if ($find_order_after->orac_collect_state == '1' && $find_order_after->oraf_collection_price > 0) {
                // 1. 售后单代收
                $ord_coll_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    14, //类型
                    0, //应收账款id
                    $find_order_after->oraf_id, //原始id(订单id)
                    $find_order_after->oraf_number, //应收账款单号/原始号(订单编号)
                    $find_order_after->oraf_type, //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                    $find_order_after->oraf_client_id, //会员id/来往单位id
                    $client_name, //来往单位名称
                    $find_order_after->oraf_collection_price, //结算金额(代收金额)
                    '', //结款时间
                    $find_order_after->orac_acc_subject_id, //会计科目id
                    $find_order_after->oraf_collection_price, //实际金额(未结算:0，已结算：代收金额)
                    0, //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    '',  //备注
                    $find_order_after->oraf_collection_price,  //已收金额
                    '', //截止时间
                    2, //金额正负1正   2负值
                    17, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $find_order_after->oraf_create_time
                );

                // 判断是否生成结款明细，让技师收款，就生成结款明细
                if ($find_order_after->orac_collect_state == 1) {
                    // 生成结款明细
                    $acset_id = AccountingSettlement::add(
                        $user_info, // [用户信息]
                    20, // [单据类型1订单结算2订单账单3工单账单11订单退款12工单代收]
                    $find_order_after->oraf_id, // [与单据类型对应的id]
                    $find_order_after->oraf_number, // [与单据类型对应的单号]
                    $find_order_after->oraf_type, // [买家类型1门店零售2来往单位]
                    $find_order_after->oraf_client_id, // [会员/客户id]
                    $client_name, // [来往单位名称]
                    $find_order_after->orac_acc_subject_id, // [会计科目id]
                    1, // [类型1收入2支出]
                    $request['oraf_actual_price'] * 100, // [实际金额](此次的实收金额)
                    $request['oraf_actual_price'] * 100, // [合计金额](此次的应收金额)
                    0, // [欠收金额](此次结款后还应收金额)
                    0, // [抹零金额]
                    '' //[备注]
                    );
                } else {
                    $acset_id = true;
                }
            } else {
                $ord_coll_bill = true;
                $acset_id = true;
            }
            // 判断是否应该生成应收账款、结款明细
            if ($find_order_after->oraf_state == 1) {
                if ($shop_info->shop_type == 3 && $find_order_after->orac_order_type == 2) {
                    $after_bill = ReceivableBill::create(
                        $user_info, //用户信息
                        14, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                        0, //应收账款id
                        $find_order_after->oraf_id, //原始id(工单id)
                        $find_order_after->oraf_number, //应收账款单号/原始号(工单编号)
                        3, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                        $find_order_after->oraf_service_shop_id, //派单门店id
                        $shop_info->shop_store_name, //派单门店名称
                        $request['oraf_actual_price'] * 100, //结算金额
                        '', //结款时间
                        $find_order_after->orac_acc_subject_id, //会计科目id
                        $request['oraf_actual_price'] * 100, //实际金额
                        0,  //抹零金额
                        1,  //状态：1.未核销 2.已核销
                        1,  //应收账单id是否是自己 1.不是 2.是
                        '',  //备注
                        $request['oraf_actual_price'] * 100,  //已收金额
                        '', //截止时间
                        2, //金额正负1正   2负值
                        17, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                        1, //是否合并代收：1是2否
                        $find_order_after->oraf_create_time
                    );
                } else {
                    $after_bill = true;
                }
            } else {
                $after_bill = true;
            }
            $join_wor_res = true;
            $join_orac_id = true;
        } else {
            $join_wor_res = true;
            $join_orac_id = true;
        }
        // 技师代收,代收金额为0,结算方式为现结
        if ($find_order_after->orac_collect_state == '1' && $find_order_after->oraf_collection_price == 0) {
            // 售后单应收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                14, //类型
                0, //应收账款id
                $find_order_after->oraf_id, //原始id
                $find_order_after->oraf_number, //应收账款单号/原始号
                $find_order_after->oraf_type, //客户类型：1.门店零售 2.来往单位
                $find_order_after->oraf_client_id, //会员id/来往单位id
                $client_name, //来往单位名称
                $request['oraf_actual_price'] * 100, //结算金额(应收金额)
                '', //结款时间
                $find_order_after->orac_acc_subject_id, //会计科目id
                $request['oraf_actual_price'] * 100, //实际金额(应收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                $request['oraf_actual_price'] * 100,  //已收金额
                '', //截止时间
                $find_order_after->oraf_plus_minus, //金额正负1正   2负值
                17, //显示类型
                1, //是否合并代收：1是2否
                $find_order_after->oraf_create_time
            );
            
            // 生成操作记录
            $edit_record = orderAfterLog($user_info, $request['oraf_id'], '3', '审核通过售后单');
            if ($oraf_res && $ord_bill) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '售后单列表', '通过', $find_order_after->oraf_number . '通过成功');
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
            }
        }

        if ($find_order_after->orac_collect_state == '1' && $find_order_after->oraf_collection_price > 0) {
            // 1. 售后单代收
            $ord_bill = ReceivableBill::create(
                $user_info, //用户信息
                14, //类型
                0, //应收账款id
                $find_order_after->oraf_id, //原始id(订单id)
                $find_order_after->oraf_number, //应收账款单号/原始号(订单编号)
                $find_order_after->oraf_type, //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                $find_order_after->oraf_client_id, //会员id/来往单位id
                $client_name, //来往单位名称
                $request['oraf_actual_price'] * 100, //结算金额(代收金额)
                '', //结款时间
                $find_order_after->orac_acc_subject_id, //会计科目id
                0, //实际金额(未结算:0，已结算：代收金额)
                0, //抹零金额
                1,  //状态：1.未核销 2.已核销
                1,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                0,  //已收金额
                '', //截止时间
                2, //金额正负1正   2负值
                17, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                1, //是否合并代收：1是2否
                $find_order_after->oraf_create_time
            );
        } else {
            $ord_bill = true;
            $acset_id = true;
        }
        // 判断是否应该生成应收账款、结款明细
        if ($find_order_after->oraf_state == 1) {
            if ($shop_info->shop_type == 3 && $find_order_after->orac_order_type == 2) {
                $after_bill = ReceivableBill::create(
                    $user_info, //用户信息
                    14, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    0, //应收账款id
                    $find_order_after->oraf_id, //原始id(工单id)
                    $find_order_after->oraf_number, //应收账款单号/原始号(工单编号)
                    3, //客户类型：1.门店零售 2.来往单位3.外派门店（加盟店或总店）
                    $find_order_after->oraf_service_shop_id, //派单门店id
                    $shop_info->shop_store_name, //派单门店名称
                    $request['oraf_actual_price'] * 100, //结算金额
                    '', //结款时间
                    $find_order_after->orac_acc_subject_id, //会计科目id
                    $request['oraf_actual_price'] * 100, //实际金额
                    0,  //抹零金额
                    1,  //状态：1.未核销 2.已核销
                    1,  //应收账单id是否是自己 1.不是 2.是
                    '',  //备注
                    $request['oraf_actual_price'] * 100,  //已收金额
                    '', //截止时间
                    2, //金额正负1正   2负值
                    17, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                    1, //是否合并代收：1是2否
                    $find_order_after->oraf_create_time
                );
            } else {
                $after_bill = true;
            }
        } else {
            $after_bill = true;
        }

        // 判断门店是否使用用友u8财务系统
        if (config('apiu8cloud.CODE_START') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
            // $request_voucher['voucher_cost'] = $voucher_cost;//销售成本总额，换货单换新商品成本总额
            // $request_voucher['voucher_sell_total_price'] = $$request['oraf_actual_price'];//换货单，销售总额
            // // $request_voucher['voucher_refund_total_price'] = $voucher_refund_total_price;//换货单，退货总额
            // // $request_voucher['refund_voucher_cost'] = $refund_voucher_cost;//换货单，换新商品成本总额
            // $u8_return = YongYou::apiAfterOrder($user_info, $find_order_after, $request_voucher);//调用u8接口
            // if ($u8_return['code'] == 500) {
            //     DB::rollBack();
            //     // 如果凭证添加失败，凭证号自动加1
            //     YongYou::insertVoucher($userinfo, $u8_return['vou_data'], 1);
            //     return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'U8财务系统凭证上传失败！']);
            // }
        }
        // 生成操作记录
        $edit_record = orderAfterLog($user_info, $request['oraf_id'], 3, '审核通过售后单');
        if ($oraf_res && $join_wor_res && $join_orac_id && $after_bill) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '售后单列表', '通过', $find_order_after->oraf_number . '通过成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'通过成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'通过失败']);
        }
    }

    // 结算
    public function settlement(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->settlementValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $find_after_order = DB::table('order_after as oraf')
            ->leftjoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
            ->where('oraf_id', $request['oraf_id'])
            ->select('oraf_number', 'oraf_state', 'oraf_type', 'oraf_client_id', 'oraf_service_shop_id', 'oraf_order_price', 'oraf_actual_price', 'oraf_wor_state', 'oraf_collection_bill', 'oraf_orbi_id', 'oraf_plus_minus', 'oraf_payment_way', 'oraf_goods_quantity', 'oraf_collection_price', 'oraf_remark', 'oraf_service_type', 'oraf_ware_id', 'oraf_orla_id', 'orac_result', 'oraf_ord_id')
            ->first();
        // if ($find_after_order->oraf_state != '1') {
        //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前售后单不是待结算状态,无法结算']);
        // }
        // if (!empty($find_after_order->oraf_orbi_id)) {
        //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该售后单已经生成账单,无法结算']);
        // }
        // if ($find_after_order->oraf_wor_state != 10) {
        //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前售后单尚未完成,无法结算']);
        // }

        // 订单售后表修改状态
        $oraf_data['oraf_state'] = 2;//结算状态1未结算2已结算
        $oraf_data['oraf_update_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        $oraf_res = DB::table('order_after')
            ->where('oraf_id', $request['oraf_id'])
            ->update($oraf_data);
        // 订单售后客户表修改结算凭证 会计科目
        $orac_data['orac_acc_subject_id'] = $request['orac_acc_subject_id'];
        // 判断是否有图片需要上传
        if (!empty($request['orac_img'])) {
            foreach ($request['orac_img'] as $key => $value) {
                // 调用全局函数 上传图片
                $image[] = uploadBase64Img($value);
            }
            $image = implode(",", $image);
        } else {
            $image = '';
        }
        $orac_data['orac_img'] = $image;
        $orac_data['orac_update_time'] = date('Y-m-d H:i:s');
        $orac_res = DB::table('order_after_client')
            ->where('orac_oraf_id', $request['oraf_id'])
            ->update($orac_data);
        // 查询订单客户信息
        $find_orac_data = DB::table('order_after_client')
            ->where('orac_oraf_id', $request['oraf_id'])
            ->select('orac_channel_unit', 'orac_collect_state', 'orac_order_type', 'orac_name')
            ->first();

        // 获取当前操作账号信息
        $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;

        //判断服务门店id是否当前账号的门店id一样，一样的是当前门店的订单，不一样的是加盟店的订单
        if ($find_after_order->oraf_service_shop_id == $user_info->adm_shop_id) {
            // 查询客户名称
            if ($find_after_order->oraf_type == 2) {
                // 查询出单位名称
                $client_name = $find_orac_data->orac_channel_unit;
            } else {
                //如果等于0是临时会员
                if ($find_after_order->oraf_client_id == 0) {
                    $client_name = $find_orac_data->orcl_name;
                } else {
                    $client_name = DB::table('member')
                        ->where('mem_id', $request['oraf_id'])
                        ->value('mem_name');
                }
            }
            $service_shop_type = 1;//服务门店类型 1总店
        } else {
            $service_shop_type = 3;//服务门店类型 3加盟店
            // 跟来往单位结算
            $client_name = $find_orac_data->orac_channel_unit;
            $find_after_order->oraf_type = 3;//客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
            $find_after_order->oraf_client_id = $find_after_order->ord_service_shop_id;//加盟店id
        }
        if ($request['merge_collection'] == 1 && $find_after_order->oraf_collection_price > 0) {
            $merge_collection = 2; //1不合并2合并
        } else {
            $merge_collection = 1;
            $request->offsetSet('merge_collection', 2);
        }

        // 添加结款明细
        $acset_res = AccountingSettlement::add(
            $user_info,                         // [用户信息]
            20,                        // [单据类型1订单结算2订单账单11订单退款13订单完成后结算]
            $request['oraf_id'],                 // [与单据类型对应的id]
            $find_after_order->oraf_number,      // [与单据类型对应的单号]
            $find_after_order->oraf_type,              // [买家类型1门店零售2来往单位]
            $find_after_order->oraf_client_id,         // [会员/客户id]
            $client_name,                       // [来往单位名称]
            $request['orac_acc_subject_id'],    // [会计科目id]
            $find_after_order->oraf_plus_minus,        // [类型1收入2支出]
            $find_after_order->oraf_actual_price,      // [实际金额](此次的实收金额)
            $find_after_order->oraf_actual_price,      // [合计金额](此次的应收金额)
            0,                                  // [欠收金额](此次结款后还应收金额)
            0,                                  // [抹零金额]
            '',                                  // [备注]
            0,                                  // [结款类型1.抹零 2.分期结款 3.预收款抵账4正常]
            date('Y-m-d H:i:s'),     // [结款时间]
            $merge_collection
        );
        // 查询售后商品数据
        $after_goods = DB::table('order_after_goods')
            ->where('orag_oraf_id', $request['oraf_id'])
            ->select('orag_goo_id', 'orag_goo_price', 'orag_goo_quantity', 'orag_goo_inventory')
            ->get();
        // 查询订单商品数据
        $order_goods = DB::table('order_goods')
            ->where('orgo_ord_id', $find_after_order->oraf_ord_id)
            ->select('orgo_goo_id', 'orgo_goo_price', 'orgo_goo_quantity', 'orgo_goo_inventory')
            ->get();
        // 退货
        if ($find_after_order->orac_result == '3') {
            foreach ($order_goods as $key => $value) {
                // 获取当前月份商品成本价
                $cost_price = StockingSelling::costPrice($find_after_order->oraf_ware_id, $value->orgo_goo_id);
                // 添加销售明细
                $sell_detail_res = SellDetail::add(
                    $user_info, //用户信息
                    $find_after_order->oraf_number, //原始s单号
                    $find_after_order->oraf_service_type,//售后单类型
                    $find_after_order->oraf_orla_id, //订单标签id
                    $find_after_order->oraf_ware_id, //仓库id
                    $find_after_order->oraf_type, //[客户类型：1.门店零售 2.来往单位]
                    $find_after_order->oraf_client_id,
                    $user_info->adm_shop_id, //服务门店id
                    $value->orgo_goo_id, //商品id
                    ($value->orgo_goo_price) / 100, //商品价格
                    $value->orgo_goo_quantity, //商品数量
                    $cost_price, //成本单价
                    $value->orgo_goo_inventory,
                    3 //商品状态1.正常 2.删除3回收的商品4换货商品
                );
            }
        }
        foreach ($after_goods as $key => $value) {
            // 获取当前月份商品成本价
            $cost_price = StockingSelling::costPrice($find_after_order->oraf_ware_id, $value->orag_goo_id);
            // 添加销售明细
            $sell_detail_res = SellDetail::add(
                $user_info, //用户信息
                $find_after_order->oraf_number, //原始s单号
                $find_after_order->oraf_service_type,//售后单类型
                $find_after_order->oraf_orla_id, //订单标签id
                $find_after_order->oraf_ware_id, //仓库id
                $find_after_order->oraf_type, //[客户类型：1.门店零售 2.来往单位]
                $find_after_order->oraf_client_id,
                $user_info->adm_shop_id, //服务门店id
                $value->orag_goo_id, //商品id
                ($value->orag_goo_price) / 100, //商品价格
                $value->orag_goo_quantity, //商品数量
                $cost_price, //成本单价
                $value->orag_goo_inventory,
                1 //商品状态1.正常 2.删除3回收的商品4换货商品
            );
        }
        $recr_del = true;
        if ($oraf_res && $orac_res && $recr_del && $acset_res && $sell_detail_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '售后单列表', '结算售后单', '结算售后单：'.$find_after_order->oraf_number.'成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'结算成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结算失败']);
        }
    }

    // 行驶路线
    public function runningRoute(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->runningRouteValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }
        
        if ($request['oraf_service_adm_id'] == 0) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'无技师无法查看路径']);
        }
        $user_info = Common::getUserInfo($request['api_token']);
        // 获取当前服务技师的公司id
        $adm_cid = DB::table('admin_shop_role')
            ->where('adm_id', $request['oraf_service_adm_id'])
            ->where('shop_id', $user_info->adm_shop_ip)
            ->value('shop_cid as adm_cid');

        // 获取当前年月
        $now_time = substr(date("Ym"), -4);

        $table_name = DB::table('table_link_after')
            ->where([
                'tala_codeid' => '5000' . $adm_cid,
                'tala_yemo' => $now_time,
            ])
            ->value('tala_table_name');
        // 获取技师当前售后单出发之后和抵达的经纬度
        $state = [3, 4, 5];//服务状态1空闲2预约3出发4抵达5完成
        $locaion = DB::table($table_name . '_location_after')
            ->where([
                'loaf_oraf_id' => $request['oraf_id'],
                'loaf_adm_id' => $request['oraf_service_adm_id'],
            ])
            ->whereIn('loaf_ord_state', $state)
            ->orderBy('loaf_id', 'asc')
            ->select('loaf_id', 'loaf_longitude', 'loaf_latitude')
            ->paginate(300);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$locaion->items()]);
    }

    // 导出
    public function export(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();
        $data = DB::table('order_after as oraf')
            ->leftJoin('order_after_client as orac', 'orac.orac_oraf_id', '=', 'oraf.oraf_id')
            ->leftJoin('order_after_goods as orag', 'orag.orag_oraf_id', '=', 'oraf.oraf_id')
            ->where('oraf_cid', $user_info->adm_cid)
            ->where('oraf_superior_shop_id', $shop_id)
            ->where('oraf_delete', 1)
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('oraf_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('oraf_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('oraf_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->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['oraf_order_number'])) {
                    $query->where('oraf_order_number', 'like', '%' . $search_data['oraf_order_number'] . '%');
                }
            }) //售后单号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_type'])) {
                    $query->where('oraf_type', $search_data['oraf_type']);
                }
            }) //买家类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_channel_unit'])) {
                    $query->where('orac_channel_unit', 'like', '%' . $search_data['orac_channel_unit'] . '%');
                }
            }) //客户单位
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_name'])) {
                    $query->where('orac_name', 'like', '%' . $search_data['orac_name'] . '%');
                }
            }) //客户姓名
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_phone'])) {
                    $query->where('orac_phone', 'like', '%' . $search_data['orac_phone'] . '%');
                }
            }) //客户电话
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orac_car_num'])) {
                    $query->where('orac_car_num', 'like', '%' . $search_data['orac_car_num'] . '%');
                }
            }) //车牌号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_wor_state'])) {
                    $query->where('oraf_wor_state', $search_data['oraf_wor_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['oraf_create_id'])) {
                    $query->where('oraf_create_id', $search_data['oraf_create_id']);
                }
            })
            ->select('oraf_create_time', 'oraf_number', 'oraf_order_number', 'orag_goo_name', 'orag_goo_goods_encode', 'orag_goo_price', 'orag_goo_quantity', 'oraf_actual_price', 'oraf_wor_state', 'oraf_type', 'orac_channel_unit', 'orac_name', 'orac_phone', 'orac_car_num', 'orac_address', 'oraf_order_price', 'oraf_create_id')
            ->orderBy('oraf_id', 'desc')
            ->get()->toArray();
        if (!empty($data)) {
            // 将对象转为数组
            $data = json_decode(json_encode($data), true);
            $adm_id = array_unique(array_column($data, 'oraf_create_id'));
            // 查找账号id对应的账号姓名
            $admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id');
            foreach ($data as $key => $value) {
                $data[$key]['orag_goo_price'] = $value['orag_goo_price'] / 100;
                $data[$key]['oraf_order_price'] = $value['oraf_order_price'] / 100;
                $data[$key]['oraf_actual_price'] = $value['oraf_actual_price'] / 100;
                // 服务状态
                if ($value['oraf_wor_state'] == '1') {
                    $data[$key]['oraf_wor_state'] = '未派单';
                }
                if ($value['oraf_wor_state'] == '2') {
                    $data[$key]['oraf_wor_state'] = '待接单';
                }
                if ($value['oraf_wor_state'] == '3') {
                    $data[$key]['oraf_wor_state'] = '未出发';
                }
                if ($value['oraf_wor_state'] == '4') {
                    $data[$key]['oraf_wor_state'] = '未抵达';
                }
                if ($value['oraf_wor_state'] == '5') {
                    $data[$key]['oraf_wor_state'] = '已预约';
                }
                if ($value['oraf_wor_state'] == '6') {
                    $data[$key]['oraf_wor_state'] = '已出发';
                }
                if ($value['oraf_wor_state'] == '7') {
                    $data[$key]['oraf_wor_state'] = '已抵达';
                }
                if ($value['oraf_wor_state'] == '8') {
                    $data[$key]['oraf_wor_state'] = '完成待审核';
                }
                if ($value['oraf_wor_state'] == '9') {
                    $data[$key]['oraf_wor_state'] = '完成已驳回';
                }
                if ($value['oraf_wor_state'] == '10') {
                    $data[$key]['oraf_wor_state'] = '已完成';
                }
                if ($value['oraf_wor_state'] == '11') {
                    $data[$key]['oraf_wor_state'] = '锁定';
                }
                // 订单类型
                if ($value['oraf_type'] == '1') {
                    $data[$key]['oraf_type'] = '会员零售';
                }
                if ($value['oraf_type'] == '2') {
                    $data[$key]['oraf_type'] = '客户单位';
                }
                if ($value['oraf_type'] == '3') {
                    $data[$key]['oraf_type'] = '速电派单';
                }
                if ($value['oraf_type'] == '4') {
                    $data[$key]['oraf_type'] = '第三方派单';
                }
                //商品编号
                $data[$key]['orag_goo_goods_encode'] = "\t" . $value['orag_goo_goods_encode'];
                // 操作人
                $data[$key]['oraf_create_id'] = $admin[$value['oraf_create_id']];
            }
        } 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(10000, 99999) . '.xls'; //
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '售后单列表'; //
        $where['field_name'] = ['创建时间', '售后单号', '订单号', '商品名称', '商品编号', '单价', '商品数量', '结算金额', '服务状态', '买家类型', '客户单位', '客户姓名', '客户电话', '车牌号', '地址', '订单金额', '录单员'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($streamFilename)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    //售后处理
    public function feedback(Request $request)
    {
        // 使用验证器 验证数据
        $verify_data = new VerifyOrderAfterController;
        $error_message = $verify_data->feedbackValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'{}']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        DB::beginTransaction();
        $order['ocac_feedback_state'] = 1;
        $order['orac_update_time'] = date('Y-m-d H:i:s');

        $ord_data = DB::table('order_after')
            ->where('oraf_id', $request['oraf_id'])
            ->first(['oraf_order_number','oraf_type','oraf_other_system_number']);

        $order_res = DB::table('order_after_client')
            ->where('orac_oraf_id', $request['oraf_id'])
            ->update($order);
        if ($order_res) {
            orderLog($user_info, $request['oraf_id'], 0, '售后处理');
            Common::addLog($user_info, getRealIp($request), '订单列表', '售后处理', '订单'.$ord_data->oraf_order_number.'售后处理:'.$ord_data->oraf_order_number);

            if (config('apisystem.SYNC_STATE') && $ord_data->oraf_type == 3) {
                $url = config('apisystem.sd_server_name').'/index.php/Supply/immedAfter';
                $param['after_num'] = $ord_data->oraf_other_system_number;//第三方工单号
                $param['sin_bid'] = $request['label_id'];
                $param['sin_bcentent'] = $request['label_name'];
                $param['content'] = $request['remark'] ? $request['remark'] :'';
                $param['time'] = date('Y-m-d H:i:s');//收货时间
                $param['ip'] = getRealIp($request);
                $param['token'] = md5(md5($param['time'].config('apisystem.sd_token')));//token
                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                }
            }
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'处理成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'处理失败']);
        }
    }
}
