<?php

namespace App\Services\ReturnGoods;

use App\Http\Controllers\Api\Verify\ReturnGoodsManage\ReturnGoodsManageController;
use App\Services\Business\WashOrderBasicService;
use App\Services\Business\WashOrderService;
use App\Services\CommonService;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;


class ReturnGoodsService extends Service
{

   /*
    * @name 退货进度
    * @retrun array
    * @author Ma 2023/9/12 15:49
    *
   */
    public static function getReturnName($type){
        $data = [['id'=>0,'name'=>'--'],['id'=>1,'name'=>'未回收'],['id'=>2,'name'=>'部分回收'],['id'=>3,'name'=>'已回收'],['id'=>4,'name'=>'供货商回收']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 退款方式
     * @retrun array
     * @author Ma 2023/9/12 15:49
     *
    */
    public static function getRefundMethodName($type){
        $data = [['id'=>0,'name'=>'--'],['id'=>1,'name'=>'线下打款'],['id'=>2,'name'=>'原账号退回']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 退款状态
     * @retrun array
     * @author Ma 2023/9/12 15:49
     *
    */
    public static function getRefundStatusName($type){
        $data = [['id'=>0,'name'=>'--'],['id'=>1,'name'=>'未退款'],['id'=>2,'name'=>'已退款']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 退款审核状态
     * @retrun array
     * @author Ma 2023/9/12 15:49
     *
    */
    public static function getStatusName($type){
        $data = [['id'=>0,'name'=>'全部'],['id'=>1,'name'=>'待审核'],['id'=>2,'name'=>'通过'],['id'=>3,'name'=>'驳回']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 仓库列表
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/14 14:04
     *
    */
    public static function wareList($user_info){
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $ware_list = DB::table('warehouse')
            ->where('ware_cid', $user_info->adm_cid)
            ->where('ware_superior_shop_id',$shop_id )
            ->where('ware_shop_id',$user_info->adm_shop_id)
            ->where('ware_state', 1)
            ->where('ware_type', '<>', 2)
            ->select('ware_id','ware_name')
            ->get()->toArray();
        $list[0] = ['ware_id'=>0,'ware_name'=>'供货商'];
        if($ware_list){
            $i = 1;
            foreach ($ware_list as $key => $value){
                $list[$i] = $value;
                $i++;
            }
        }
        return $list;
    }

    /*
     * @name 退货管理修改应收应付
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/14 14:37
     *
    */
    public static function editPay($order_id,$request,$user_info){
        $receivable_pay_res = DB::table('receivable_pay')
            ->where('recpay_original_id', $order_id)
            ->first();
        if($receivable_pay_res){
            if(isset($request['recpay_actual_price'])){//如果实收金额变了
                $recpay_actual_price = $request['recpay_actual_price'];//实收金额
                $recpay_cost_price = $receivable_pay_res->recpay_cost_price;
                $profit = $recpay_actual_price - $receivable_pay_res->recpay_cost_price;
            }
            /*if(isset($request['recpay_receivable_price'])){//如果应收金额变了
                $recpay_receivable_price = $request['recpay_receivable_price'];//应收金额
                $recpay_cost_price = 1;
            }*/

            if($profit > 0){
                $minus = 1;
            }else{
                $minus = 2;
                $profit = abs($profit);
            }
            $rece_params = [
                'recpay_actual_price'=>$recpay_actual_price,//实收金额
                'recpay_cost_price'=>$recpay_cost_price,//成本价
                'recpay_order_state'=>1,//订单状态：1正常2退款3取消
                'recpay_plus_minus'=>$minus,//盈利正负：1正值2负值
                'recpay_profit'=>$profit,//盈利金额
            ];
            $edit_res = DB::table('receivable_pay')
                ->where('recpay_original_id',$order_id)
                ->update($rece_params);

        }
        //Common::addLog($user_info, $request->getClientIp(), '修改', '修改', '修改应收应付：' . $order_id . '成功');
        return ['code'=>200, 'msg'=>'success', 'data'=>''];
    }

    //申请退货获取订单信息
    public static function getInfo($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->addValidator($request);
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if(empty($user_info)){
            $user_info = Common::wechatGetUserInfo($request['api_token']);
        }

        //订单信息
        $order_info = DB::table('order as ord')
            ->leftJoin('order_client as orcl', 'ord.ord_orcl_id', '=', 'orcl.orcl_id')
            ->where('ord_order_number', $request['order_number'])
            ->select('ord_id', 'ord_order_number', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'ord_order_price','ord_state','ord_actual_price', 'ord_explain')
            ->first();
        if (empty($order_info)) {
            return ['code'=>500, 'msg'=>'没有该订单', 'data'=>''];
        }
        $order_info->operate_name = $user_info->adm_name;
        $wareList = self::wareList($user_info);
        // 获取该订单下的商品信息
        $goods_data = DB::table('order_goods as orgo')
            ->leftjoin('goods as g', 'g.goo_id', '=', 'orgo.orgo_goo_id')
            ->where('orgo_order_number', $request['order_number'])
            ->whereIn('orgo_goo_type', [1,2])
            ->select('orgo_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_quantity as orgo_goo_quantitys', 'orgo_goo_price', 'orgo_goo_guarantee', 'orgo_goo_type', 'orgo_state', 'orgo_ord_id', 'orgo_goo_unit', 'orgo_goo_unta_id', 'goo_unit_conversion', 'orgo_goo_amount','orgo_goo_return_quantity','orgo_waon_class','orgo_goo_price','orgo_ware_id','orgo_wafr_id','orgo_new_goo_quantity')
            ->get()->toArray();
        if($goods_data){
            foreach ($goods_data as $key => $value){
                $goods_data[$key]->ware_data = $wareList;
                $goods_data[$key]->orgo_goo_quantity = $value->orgo_goo_quantity.$value->orgo_goo_unit;
                if($value->orgo_new_goo_quantity > 0 ){
                    $goods_data[$key]->max_goo_quantity = $value->orgo_new_goo_quantity;
                }else{
                    $goods_data[$key]->max_goo_quantity = $value->orgo_goo_quantitys;
                }
                //已退数量
                //$goods_data = DB::table('recede_recycle')->where('orgo_order_number', $request['order_number'])
            }
        }

        $data['order_info'] = $order_info;
        $data['goods_data'] = $goods_data??[];
        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    //添加申请退货
    public static function add($request){

        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->addValidator($request);
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if(empty($user_info)){
            $user_info = Common::wechatGetUserInfo($request['api_token']);
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;
        $superior_shop_id = $user_info->shop_superior_id;
        //如果有退款金额，生成退款单号
        $refund_number = '';
        if($request['ref_amount']){
            $ord_state = DB::table('order')
                ->where('ord_shop_id', $user_info->adm_shop_id)
                ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
                ->where('ord_classify', 2) //工单分类：1蓄电池2洗美店3易损件
                ->where('ord_is_split', '<>', 3) //订单是否拆分，1是2否
                ->where('ord_order_number', $request['order_number'])
                ->where('ord_wor_state', '!=', 11)//取消订单
                ->select('ord_state','ord_actual_price','ord_order_price')//结算状态1未结算2已结算3部分结算
                ->first();
            if($ord_state->ord_state > 1){//已结算可以退款
                $refund_number = 'TK' . rand(100, 999) . date('mdHis') . rand(100000, 999999); // 退款单号
            }else{
                return ['code'=>500, 'msg'=>'订单未结算不能退款', 'data'=>''];
            }
            if($ord_state->ord_actual_price < $request['ref_amount'] * 100){
                return ['code'=>500, 'msg'=>'输入金额不能大于实付金额', 'data'=>''];
            }
        }
        $work_data = DB::table('work_order')
            ->where('wor_order_number', $request['order_number'])
            ->select('wor_number','wor_id','wor_type','wor_ware_id')
            ->first();
        $order_data = DB::table('order')
            ->where('ord_order_number', $request['order_number'])
            ->select('ord_order_number','ord_id','ord_type','ord_ware_id','ord_order_price')
            ->first();

        //如果有退货商品，生成退货单号
        $retgo_number = '';
        $tuihuo = false;
        $number = 0;
        $goods_data = json_decode($request['goods_data'], true); //退货商品数据
        if (!empty($goods_data)) {
            foreach ($goods_data as $k => $v){
                if($v['goo_return_number'] > 0){
                    $number += $v['goo_return_number'];
                    if(!$tuihuo){
                        $tuihuo = true;
                    }
                }
            }
            $dispatch_data = DB::table('dispatch_bill as dibi')
                ->where('dego_cid', $user_info->adm_cid)
                ->where('dego_shop_id', $shop_id)
                ->where('dego_original_number', $request['order_number'])
                ->where('dego_type', 2)
                ->first();
            if(empty($dispatch_data) &&  isset($work_data->wor_number)){
                $dispatch_data = DB::table('dispatch_bill as dibi')
                    ->where('dego_cid', $user_info->adm_cid)
                    ->where('dego_shop_id', $shop_id)
                    ->where('dego_original_number',  $work_data->wor_number)
                    ->where('dego_type', 2)//已发货
                    ->first();
            }
            //有退货数量，已经发货的可以退货
            if($tuihuo && $dispatch_data){
                $retgo_number = 'TH' . rand(100, 999) . date('mdHis') . rand(100000, 999999);
            }else{
                return ['code'=>500, 'msg'=>'订单未发货不能退货', 'data'=>''];
            }
        }

        if($refund_number == '' && $retgo_number == ''){
            return ['code'=>500, 'msg'=>'您未输入退货数量或退货金额', 'data'=>''];
        }

        // 1.退货表添加数据
        $add_return['retgo_cid'] = $user_info->adm_cid; //公司id
        $add_return['retgo_shop_id'] = $user_info->adm_shop_id; //门店id
        $add_return['retgo_superior_shop_id'] = $shop_id; //所属总店id
        $add_return['retgo_number'] = $retgo_number; //退货单号
        $add_return['retgo_ref_number'] = $refund_number; //退款单号
        $add_return['retgo_order_number'] = $request['order_number']; //订单单号
        $add_return['retgo_wor_number'] = $work_data->wor_number??''; //工单号
        $add_return['retgo_reason'] = $request['retgo_reason']??''; //申请原因
        $add_return['retgo_create_time'] = date('Y-m-d H:i:s'); //时间
        $add_return['retgo_create_name'] = $user_info->adm_name; //创建人
        $add_return['retgo_create_id'] = $user_info->adm_id; //创建人id
        $add_return['retgo_return_status'] = 0; //退货进度：1未回收

        DB::beginTransaction();


        if($retgo_number){
            $return_id = DB::table('return_goods')->insertGetId($add_return);//退货
            if (!$return_id) {
                return ['code'=>500, 'msg'=>'退货失败1', 'data'=>''];
            }
            //判断是否是供货商回收
            $recede = false;
            $gonghuoshang = false;
            foreach ($goods_data as $g_key => $g_value){
                if($g_value['orgo_ware_id'] == 0){
                    $gonghuoshang = true;
                    $ghs_goods_data[] = $g_value;
                }else{
                    $recede = true;
                    $recede_goods_data[] = $g_value;
                }
            }
            if($recede){
                //添加退货
                $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'] = $superior_shop_id; //总店id
                $add_recycle['rec_date'] = date('Y-m-d'); //日期
                $add_recycle['rec_number'] = $retgo_number; //回收单号
                $add_recycle['rec_ord_id'] = $work_data->wor_id??$order_data->ord_id; //工单id
                $add_recycle['rec_ord_order_number'] = $work_data->wor_number??$order_data->ord_order_number; //工单号
                $add_recycle['rec_source_type'] = 8; //类型 4 (工单号)退货单 5技师退回 6技师拒单 7技师终止 8(订单号)退货单
                $add_recycle['rec_amount'] = $number; //退换总数量
                $add_recycle['rec_state'] = 1; //回收状态 1.未回收 2.已回收
                $add_recycle['rec_type'] = $work_data->wor_type??$order_data->ord_type; //买家类型 1.门店零售 2.来往单位
                $add_recycle['rec_ware_id'] =  $work_data->wor_ware_id??$order_data->ord_ware_id; //仓库id
                $add_recycle['rec_create_adm_id'] = $user_info->adm_id; //创建人id
                $recycle_id = DB::table('recede_recycle')->insertGetId($add_recycle);
                if (empty($recycle_id)) {
                    return ['code'=>500, 'msg'=>'商品退回失败！', 'data'=>'{}'];
                }
                $rego_key = 0;
                $kk_amount = 0;
                foreach ($recede_goods_data as $key => $value) {
                    $rego_data[$rego_key]['rego_rec_id'] = $recycle_id; //退换回收单id
                    $rego_data[$rego_key]['rego_orgo_id'] = $value['orgo_id']??''; //订单商品主键id
                    $rego_data[$rego_key]['rego_ware_id'] = $value['orgo_ware_id']??''; //仓库id
                    $orgo_ware_id = $value['orgo_ware_id']??'';
                    if(isset($value['orgo_ware_id']) && isset($value['goo_id'])){
                        $ware_good = DB::table('warehouse_freight_goods')->where('wafg_ware_id', $value['orgo_ware_id'])
                            ->where('wafg_goo_id', $value['goo_id'])
                            ->select('wafg_wafr_id','wafg_wago_id')
                            ->first();
                        if(empty($ware_good)){
                            $ware_name = '本仓库';
                            $wareList = self::wareList($user_info);
                            foreach ($wareList as $ware_key => $ware_value){
                                if($ware_key > 0){
                                    if($ware_value->ware_id == $value['orgo_ware_id']){
                                        $ware_name = $ware_value->ware_name;
                                    }
                                }
                            }
                            return ['code'=>500, 'msg'=>$ware_name.'没有该商品', 'data'=>''];
                        }
                        $rego_data[$rego_key]['rego_wafr_id'] = $ware_good->wafg_wafr_id; //仓位id
                        $rego_data[$rego_key]['rego_wago_id'] = $ware_good->wafg_wago_id; //仓库商品id
                    }
                    $rego_data[$rego_key]['rego_waon_class'] = $value['orgo_waon_class']??''; //仓库类别
                    $rego_data[$rego_key]['rego_goo_id'] = $value['goo_id']; //商品id
                    $rego_data[$rego_key]['rego_sell_number'] =  $value['goo_quantity']??''; //销售数量
                    $rego_data[$rego_key]['rego_recycle_number'] =  $value['goo_return_number']; //回收数量

                    $rego_data[$rego_key]['rego_goo_unit'] =  isset($value['goo_unit'])?$value['goo_unit']:''; //单位
                    $rego_data[$rego_key]['rego_goo_unta_id'] =  isset($value['goo_unta_id'])?$value['goo_unta_id']:''; //单位id
                    $rego_data[$rego_key]['rego_goo_name'] = $value['goo_name'];
                    $rego_data[$rego_key]['rego_goo_goods_encode'] = isset($value['orgo_goo_goods_encode']) ? $value['orgo_goo_goods_encode'] :'';
                    $rego_data[$rego_key]['rego_fine_quantity'] = $value['goo_return_number'];
                    $rego_data[$rego_key]['rego_priority_quantity'] = 0;
                    $kk_amount += $value['orgo_goo_price'] * $value['goo_return_number'];
                    $rego_key++;
                }
                $add_goods =  DB::table('recede_goods')->insert($rego_data);
                DB::table('return_goods')->where('retgo_id', $return_id)->update(['retgo_number_id'=>$recycle_id,'retgo_return_status'=>1,'retgo_amount'=>$order_data->ord_order_price-$kk_amount]);
                DB::table('recede_recycle')->where('rec_id', $recycle_id)->update(['rec_ware_id'=>$orgo_ware_id]);
                if(isset($work_data->wor_id)){
                    $work_client = DB::table('work_client')
                        ->where('wocl_wor_id', $work_data->wor_id)
                        ->select('wocl_client_id', 'wocl_bus_name', 'wocl_name', 'wocl_phone')
                        ->first();
                }

                if(!isset($work_client)){
                    $work_client = DB::table('order_client')
                        ->where('orcl_ord_id', $order_data->ord_id)
                        ->select('orcl_client_id as wocl_client_id', 'orcl_business_name as wocl_bus_name', 'orcl_name as wocl_name', 'orcl_phone as wocl_phone')
                        ->first();
                }
                // 10.3 退换回收客户表添加数据
                $recl_data['recl_rec_id'] = $recycle_id; //回收单id
                $recl_data['recl_client_id'] = $work_client->wocl_client_id; //来往单位id/客户id
                $recl_data['recl_name'] = $work_client->wocl_name; //客户姓名
                $recl_data['recl_phone'] = $work_client->wocl_phone; //联系电话
                $type = $work_data->wor_type??$order_data->ord_type;
                if ($type == 2) {
                    $recl_data['recl_channel_unit'] = $work_client->wocl_bus_name; //合作商
                }
                $add_client =  DB::table('recede_client')->insert($recl_data);
                if (empty($add_client) || empty($add_goods)) {
                    return ['code'=>500, 'msg'=>'商品退回失败！', 'data'=>'{}'];
                }
            }
            //供货商退货
            if($gonghuoshang){
                //处理订单
                $order = DB::table('order')
                    ->where('ord_shop_id', $user_info->adm_shop_id)
                    ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
                    ->where('ord_classify', 2) //工单分类：1蓄电池2洗美店3易损件
                    ->where('ord_is_split', '<>', 3) //订单是否拆分，1是2否
                    ->where('ord_order_number', $request['order_number'])
                    ->where('ord_wor_state', '!=', 11)//取消订单
                    ->select('ord_state','ord_actual_price','ord_order_price','ord_client_id','ord_type')//结算状态1未结算2已结算3部分结算
                    ->first();
                $ghs_key = 0;
                $kk_amount = 0;
                foreach ($ghs_goods_data as $ghs_key => $ghs_value) {
                    $ghs_rego_data[$ghs_key]['retgoinfo_retgo_id'] = $return_id; //退货单id
                    $ghs_rego_data[$ghs_key]['retgoinfo_retgo_number'] = $retgo_number; //退换回收单
                    $ghs_rego_data[$ghs_key]['retgoinfo_orgo_id'] = $ghs_value['orgo_id']??''; //订单商品主键id
                    $ghs_rego_data[$ghs_key]['retgoinfo_ware_id'] = $ghs_value['orgo_ware_id']??''; //仓库id
                    $ghs_rego_data[$ghs_key]['retgoinfo_goo_id'] = $ghs_value['goo_id']; //商品id
                    $ghs_rego_data[$ghs_key]['retgoinfo_sell_number'] =  $ghs_value['goo_quantity']??''; //销售数量
                    $ghs_rego_data[$ghs_key]['retgoinfo_return_number'] =  $ghs_value['goo_return_number']; //回收数量
                    $ghs_rego_data[$ghs_key]['retgoinfo_create_id'] =  $user_info->adm_id; //创建人id
                    $ghs_rego_data[$ghs_key]['retgoinfo_create_name'] =  $user_info->adm_name; //创建人
                    $ghs_rego_data[$ghs_key]['retgoinfo_create_time'] =  date('Y-m-d H:i:s'); //创建时间
                    /*if ($ghs_value['goo_unta_id'] == 1) {
                        $ghs_value['goo_unit'] = '米';
                        $ghs_value['goo_unta_id'] = 4;
                    }*/
                    $ghs_rego_data[$ghs_key]['retgoinfo_goo_unit'] =  isset($ghs_value['goo_unit'])?$ghs_value['goo_unit']:''; //单位
                    $ghs_rego_data[$ghs_key]['retgoinfo_goo_unta_id'] =  isset($ghs_value['goo_unta_id'])?$ghs_value['goo_unta_id']:''; //单位id
                    $ghs_rego_data[$ghs_key]['retgoinfo_goo_name'] = $ghs_value['goo_name'];
                    $ghs_rego_data[$ghs_key]['retgoinfo_goo_goods_encode'] = isset($ghs_value['orgo_goo_goods_encode']) ? $ghs_value['orgo_goo_goods_encode'] :'';
                    $kk_amount += $ghs_value['orgo_goo_price'] * $ghs_value['goo_return_number'];
                    $ghs_key++;
                    if($order->ord_state == 1) {//未结算,发货，数量不变，金额变
                        $order_goods_num = DB::table('order_goods')->where('orgo_order_number', $request['order_number'])
                            ->where('orgo_goo_id', $ghs_value['goo_id'])->first();
                        $up_order_goods['orgo_can_assign_quantity'] = $order_goods_num->orgo_can_assign_quantity - $ghs_value['goo_return_number'];
                        $up_order_goods['orgo_new_goo_quantity'] = $order_goods_num->orgo_new_goo_quantity - $ghs_value['goo_return_number'];
                        $up_order_goods['orgo_goo_return_quantity'] = $order_goods_num->orgo_goo_return_quantity + $ghs_value['goo_return_number'];
                        $up_order_goods['orgo_goo_amount'] = $order_goods_num->orgo_goo_amount - $ghs_value['goo_return_number'] * $order_goods_num->orgo_goo_price;
                        $order_good = DB::table('order_goods')->where('orgo_order_number',$request['order_number'])
                            ->where('orgo_goo_id', $ghs_value['goo_id'])
                            ->update($up_order_goods);
                        //工单
                        $work_order = DB::table('work_order')->where('wor_order_number', $request['order_number'])
                            ->select('wor_goo_amount','wor_new_goo_amount')->first();
                        if($work_order){
                            $up_work_order['wor_goo_amount'] = $work_order->wor_goo_amount - $ghs_value['goo_return_number'];
                            $up_work_order['wor_new_goo_amount'] = $work_order->wor_new_goo_amount - $ghs_value['goo_return_number'];
                            $order_good = DB::table('work_order')->where('wor_order_number', $request['order_number'])
                                ->update($up_work_order);
                        }
                        //工单
                        $work_order = DB::table('work_order')->where('wor_order_number', $request['order_number'])
                            ->select('wor_id','wor_goo_amount','wor_new_goo_amount')->first();
                        if($work_order){
                            $up_work_order['wor_goo_amount'] = $work_order->wor_goo_amount - $ghs_value['goo_return_number'];
                            $up_work_order['wor_new_goo_amount'] = $work_order->wor_new_goo_amount - $ghs_value['goo_return_number'];
                            $order_good = DB::table('work_order')->where('wor_order_number', $request['order_number'])
                                ->update($up_work_order);
                            $find_work_good = DB::table('work_good')->where('wogo_wor_id', $work_order->wor_id)
                                ->where('wogo_goo_id', $ghs_value['goo_id'])
                                ->first();
                            $up_work_order_goods['wogo_goo_amount'] = $find_work_good->wogo_goo_amount - $ghs_value['goo_return_number'];
                            $rec_goods_one = DB::table('recede_goods as re')
                                ->leftjoin('goods as g', 'g.goo_id', '=', 're.rego_goo_id')
                                ->where('rego_rec_id', $recycle_id)
                                ->where('rego_goo_id', $ghs_value['goo_id'])
                                ->select('rego_goo_unta_id','goo_unit_conversion')
                                ->first();
                            if($rec_goods_one && $rec_goods_one->rego_goo_unta_id == 1){
                                $wogo_new_goo_amount = $ghs_value['goo_return_number'] * $rec_goods_one->goo_unit_conversion;
                            }else{
                                $wogo_new_goo_amount = $ghs_value['goo_return_number'];
                            }
                            $up_work_order_goods['wogo_new_goo_amount'] = $find_work_good->wogo_new_goo_amount - $wogo_new_goo_amount;
                            $work_good = DB::table('work_good')->where('wogo_wor_id', $work_order->wor_id)
                                ->where('wogo_goo_id', $ghs_value['goo_id'])
                                ->update($up_work_order_goods);
                        }
                        if($order->ord_type == 1){
                            //修改会员欠收金额
                            $find_mem = DB::table('member')->where('mem_id', $order->ord_client_id)
                                ->value('mem_arrears');
                            $mem_arrears = $find_mem - ($order->ord_order_price - $ghs_value['orgo_goo_price'] * $ghs_value['goo_return_number']);//欠收金额 = 本来欠收的金额 - （订单原金额 - 订单现在的金额）
                            $update_mem = DB::table('member')->where('mem_id', $order->ord_client_id)
                                ->update(['mem_arrears'=>$mem_arrears]);
                        }else if($order->ord_type == 2){
                            //修改企业会员欠收金额
                            $find_bucl = DB::table('business_client')->where('bucl_id', $order->ord_client_id)
                                ->value('bucl_arrears');
                            $mem_arrears = $find_bucl - ($order->ord_order_price - $ghs_value['orgo_goo_price'] * $ghs_value['goo_return_number']);//欠收金额 = 本来欠收的金额 - （订单原金额 - 订单现在的金额）
                            $update_mem = DB::table('business_client')->where('bucl_id', $order->ord_client_id)
                                ->update(['bucl_arrears'=>$mem_arrears]);
                        }
                    }
                }
                $add_goods =  DB::table('return_goods_info')->insert($ghs_rego_data);

                DB::table('return_goods')->where('retgo_id', $return_id)->update(['retgo_return_status'=>4,'retgo_amount'=>$order->ord_order_price-$kk_amount]);
                if($order->ord_state == 1){//未结算,发货，数量不变，金额变
                    $order_good = DB::table('order')->where('ord_order_number', $request['order_number'])
                        ->update(['ord_order_price'=>$order->ord_order_price-$kk_amount]);

                }
            }

            //修改应收应付
            //ReturnGoodsService::editPay();
        }
        //添加退款
        if($refund_number){
            $add_refund['ref_cid'] = $user_info->adm_cid; //公司id
            $add_refund['ref_shop_id'] = $user_info->adm_shop_id; //门店id
            $add_refund['ref_superior_shop_id'] = $shop_id; //所属总店id
            $add_refund['ref_retgo_number'] = $retgo_number??''; //退货单号
            $add_refund['ref_retgo_id'] = $return_id??0; //退货单号
            $add_refund['ref_number'] = $refund_number; //退款单号
            $add_refund['ref_order_number'] = $request['order_number']; //订单单号
            $add_refund['ref_wor_number'] = $wor_number??''; //工单号
            $add_refund['ref_reason'] = $request['retgo_reason']??''; //申请原因
            $add_refund['ref_amount'] = $request['ref_amount'] * 100; //退款金额
            $add_refund['ref_refund_status'] = 1; //1未退款
            $add_refund['ref_refund_method'] = $request['ref_refund_method']??''; //退款方式
            if(isset($request['ref_refund_accoun']) && !isset($request['ref_refund_account'])){
                $request['ref_refund_account'] = $request['ref_refund_accoun'];
            }
            $add_refund['ref_refund_account'] = $request['ref_refund_account']??''; //退款账号
            $add_refund['ref_refund_name'] = $request['ref_refund_name']??''; //退款账号姓名
            $add_refund['ref_create_time'] = date('Y-m-d H:i:s'); //时间
            $add_refund['ref_create_name'] = $user_info->adm_name; //创建人
            $add_refund['ref_create_id'] = $user_info->adm_id; //创建人id
            $refund_id = DB::table('refund')->insertGetId($add_refund);//添加退款
            if (!$refund_id) {
                return ['code'=>500, 'msg'=>'退款失败3', 'data'=>''];
            }
            //修改应收应付
            //ReturnGoodsService::editPay();
        }
        //return ['工单信息'=>$work_data??[], '订单信息'=>$order_data??[], '退货表'=>$add_return,'退换货'=>$add_recycle??[],
            //'退换货商品'=>$rego_data??[],'退换货单位'=>$recl_data??[],'退款'=>$add_refund??[]];*/
        if (isset($return_id) || isset($refund_id)) {
            DB::commit();
            //Common::addLog($user_info, $request->getClientIp(), '退货', '新增', '新增退货单：' . $return_id . '成功');
            return ['code'=>200, 'msg'=>'新增退货单成功', 'data'=>'success'];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'新增退货单失败', 'data'=>'error'];
        }
    }

    //列表
    public static function index($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->indexValidator($request);
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $is_pc = 1;
        // 获取当前操作账号信息
        if(isset($request['source']) && $request['source'] == 'wechat'){
            $is_pc = 2;
            $user_info = Common::wechatGetUserInfo($request['api_token']);
        }else {
            $user_info = Common::getUserInfo($request['api_token']);
            if (empty($user_info)) {
                $is_pc = 2;
                $user_info = Common::wechatGetUserInfo($request['api_token']);
            }
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;

        if(!empty($request['retgo_number'])){
            if(mb_substr($request['retgo_number'],0,1) == 'D'){
                $request['retgo_order_number'] = $request['retgo_number'];
                $request['retgo_number'] = '';
            }
        }
        if (isset($request['show_count'])) {
            $page_size = $request['show_count'] ?$request['show_count']:10;
        } else {
            $page_size = 10;
        }
        $list_data = DB::table('return_goods as r')
            ->leftjoin('refund as e', 'e.ref_retgo_id', '=', 'r.retgo_id')
            ->where('retgo_shop_id',$shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['retgo_number'])) {
                    $query->where('retgo_number', $request['retgo_number']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['retgo_order_number'])) {
                    $query->where('retgo_order_number', $request['retgo_order_number']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['retgo_order_number'])) {
                    $query->where('retgo_order_number', $request['retgo_order_number']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['retgo_create_time']) && isset($request['retgo_create_time'][0]) && isset($request['retgo_create_time'][1])) {
                    $query->whereBetween('retgo_create_time', [$request['retgo_create_time'][0], $request['retgo_create_time'][1] . ' 23:59:59']);
                }
            })
            ->select('r.retgo_id', 'r.retgo_number', 'r.retgo_order_number', 'r.retgo_return_status','e.ref_refund_method','r.retgo_number_id','r.retgo_ref_number','e.ref_refund_status','r.retgo_status','e.ref_id','r.retgo_supplier_id','e.ref_cancel','r.retgo_reason','e.ref_img')
            ->orderBy('r.retgo_id', 'desc')
            ->paginate($page_size);
        $list = $list_data->items();
        // 获取当前列表下的按钮
        if($is_pc == 1){
            $list_button = getListButton($request['api_token'], $request['pri_id']);
        }else{
            $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        }

        $return_status = self::getReturnName(true);//回收状态
        $refund_method = self::getRefundMethodName(true);//退款方式
        $refund_status = self::getRefundStatusName(true);//退款状态

        $retgo_number_id = array_column($list, 'retgo_number_id'); //退款单号id
        $retgo_supplier_id = array_column($list, 'retgo_supplier_id'); //供货商退货id
        $ref_order_number = array_column($list, 'retgo_order_number'); //订单号

        if ($list) {
            $find_goods = DB::table('recede_goods as rego')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'rego.rego_goo_id')
                ->whereIn('rego_rec_id', $retgo_number_id)
                ->select('rego_goo_id as goo_id', 'rego_goo_name as goo_name', 'rego_goo_unit', 'rego_goo_unta_id', 'goo_unit_conversion','rego_rec_id','rego_sell_number','rego_recycle_number')
                ->get()->toArray();
            if($find_goods){
                foreach ($find_goods as $g_key => $g_value){
                    $good_data[$g_value->rego_rec_id][] = $g_value;
                }
            }
            //供货商商品
            $ghs_find_goods = DB::table('return_goods_info as rego')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'rego.retgoinfo_goo_id')
                ->whereIn('retgoinfo_retgo_id', $retgo_supplier_id)
                ->select('retgoinfo_retgo_id','retgoinfo_goo_id as goo_id', 'retgoinfo_goo_name as goo_name', 'retgoinfo_goo_unit as rego_goo_unit', 'retgoinfo_goo_unta_id as rego_goo_unta_id', 'goo_unit_conversion','retgoinfo_id as rego_rec_id','retgoinfo_sell_number as rego_sell_number')
                ->get()->toArray();
            if($ghs_find_goods){
                foreach ($ghs_find_goods as $ghs_key => $ghs_value){
                    $ghs_good_data[$ghs_value->retgoinfo_retgo_id][] = $ghs_value;
                }
            }

            foreach ($list as $key => $value) {//return [$value->retgo_id];
                $list[$key]->retgo_return_status_name = $return_status[$value->retgo_return_status];
                $list[$key]->ref_refund_method_name = $value->ref_refund_method??'';
                $list[$key]->goods = $good_data[$value->retgo_number_id]??[];
                $list[$key]->retgo_return_status_name11 = $order_goods??[];
                if(isset($ghs_good_data[$value->retgo_id])){
                    $list[$key]->goods = array_merge($list[$key]->goods,$ghs_good_data[$value->retgo_id]);
                }
                if(empty($list[$key]->goods)){
                    unset($order_good_data);
                    // 查询商品、项目信息
                    $order_goods = DB::table('order_goods as orgo')
                        ->leftjoin('goods as g', 'g.goo_id', '=', 'orgo.orgo_goo_id')
                        ->where('orgo_order_number', $value->retgo_order_number)
                        ->select('orgo_id','orgo_order_number', 'orgo_ord_id', 'orgo_goo_id as goo_id', 'orgo_goo_name as goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity as rego_sell_number', 'orgo_goo_guarantee', 'orgo_goo_type', 'orgo_state', 'orgo_goo_unit as rego_goo_unit', 'orgo_goo_unta_id as rego_goo_unta_id', 'goo_unit_conversion', 'orgo_goo_price', 'orgo_goo_amount')
                        ->get()->toArray();
                    if($order_goods){
                        foreach ($order_goods as $o_key => $o_value){
                            $order_good_data[$o_value->orgo_order_number][] = $o_value;
                        }
                    }
                }
                if(empty($list[$key]->goods) && isset($order_good_data[$value->retgo_order_number])){
                    $list[$key]->goods = $order_good_data[$value->retgo_order_number];
                }
                if(!isset($value->ref_refund_status)){
                    $list[$key]->ref_refund_method_name = '无需退款';
                }else {
                    $list[$key]->ref_refund_method_name = $refund_status[$value->ref_refund_status];
                }
                if($value->ref_cancel == 2){
                    $list[$key]->ref_refund_method_name = '已撤销';
                }
                if($value->retgo_status == 2){
                    $list[$key]->retgo_return_status_name = '已撤销';
                }
                $buttonData = [];
                if(in_array($value->retgo_return_status,[3,4])){
                    $buttonData[] = 'recyclingRecords';//回收记录
                }
                if($value->ref_refund_status == 2){
                    $buttonData[] = 'paymentRecords';//打款记录
                }
                if($value->retgo_return_status == 1 && (!isset($value->ref_refund_status) || $value->ref_refund_status == 1) && $value->retgo_status != 2){//未回收，未打款
                    $buttonData[] = 'revoke';//撤销
                }
                if($value->retgo_status == 2){
                    $buttonData = [];//撤销状态没有按钮
                }
                if($is_pc == 1){
                    $button = CommonService::getListButton($buttonData,$list_button);
                }else{
                    $button = CommonService::getAppletListButton($buttonData,$list_button);
                }
                $list[$key]->button_one = $button['button_one']??[];
                $list[$key]->button_two = $button['button_two']??[];
                $list[$key]->button_three = $button['button_three']??[];
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $page_size;        //一页显示多少个
        $data['data'] = $list;                              //返回数据

        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    /*
     * @name 打款记录
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/12 16:14
     *
    */
    public static function payment($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->payValidator($request);
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $find_data = DB::table('refund')
            ->where('ref_number', $request['ref_number'])//退款单号
            ->select('ref_refund_operate_name', 'ref_refund_time', 'ref_img')
            ->first();
        if ($find_data) {
            return ['code'=>200, 'msg'=>'success', 'data'=>$find_data];
        } else {
            return ['code'=>500, 'msg'=>'error', 'data'=>''];
        }
    }

    /*
     * @name 回收记录
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/14 10:29
     *
    */
    public static function recovery($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->recoveryValidator($request);
        if ($error_message) {
            return ['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message];
        }
        $find_recede = DB::table('recede_recycle as re')
            ->leftjoin('recede_goods as rg', 'rg.rego_rec_id', '=', 're.rec_id')
            ->leftjoin('admin as a', 'a.adm_id', '=', 're.rec_create_adm_id')
            ->leftjoin('warehouse as w', 'w.ware_id', '=', 'rg.rego_ware_id')
            ->where('rec_id', $request['retgo_number_id'])
            ->select('rec_record_adm_id','adm_name', 'rec_date', 'rego_goo_name', 'rego_recycle_number', 'rego_goo_unit','rego_ware_id','ware_name')
            ->get()->toArray();
        if ($find_recede) {
            return ['code'=>200, 'msg'=>'success', 'data'=>$find_recede];
        } else {
            $find_recede = DB::table('return_goods_info')
                ->where('retgoinfo_retgo_id', $request['retgo_id'])
                ->select('retgoinfo_create_name as adm_name', 'retgoinfo_create_time as rec_date', 'retgoinfo_goo_name as rego_goo_name', 'retgoinfo_return_number as rego_recycle_number', 'retgoinfo_goo_unit as rego_goo_unit')
                ->get()->toArray();
            if($find_recede){
                foreach ($find_recede as $key => &$value) {
                    $value->ware_name = '供货商回收';
                }
                return ['code'=>200, 'msg'=>'error', 'data'=>$find_recede];
            }else{
                return ['code'=>500, 'msg'=>'error', 'data'=>''];
            }
        }
    }

    /*
     * @name 撤销
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/14 10:29
     *
    */
    public static function revoke($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->revokeValidator($request);
        if ($error_message) {
            return ['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message];
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if(empty($user_info)){
            $user_info = Common::wechatGetUserInfo($request['api_token']);
        }
        $find_data = DB::table('return_goods')
            ->where('retgo_id', $request['retgo_id'])
            ->select('retgo_number','retgo_ref_number','retgo_number_id')
            ->first();
        DB::beginTransaction();
        if($find_data){
            $find_recede = DB::table('return_goods')
                ->where('retgo_id', $request['retgo_id'])
                ->update(['retgo_status'=>2,'retgo_return_status'=>3]);//修改为取消、已回收
        }else{
            return ['code'=>500, 'msg'=>'error', 'data'=>''];
        }
        //取消退货
        if($find_data->retgo_number_id){
            $update_recycle['rec_cancel'] = 2; //1正常2取消
            $update_recycle['rec_amount'] = 0; //回收总数量
            $update_recycle['rec_remark'] = '取消退货'; //备注
            $update_recycle['rec_state'] = 2; //回收状态 1.未回收 2.已回收
            $update_recycle['rec_date'] = date('Y-m-d H:i:s'); //日期
            $update_recycle['rec_record_adm_id'] = $user_info->adm_id; //记录人
            $update_recycle['rec_update_time'] = date("Y-m-d H:i:s"); //更新时间
            $find_recede = DB::table('recede_recycle')
                ->where('rec_number', $find_data->retgo_number)
                ->where('rec_id', $find_data->retgo_number_id)
                ->update($update_recycle);//退换货
            $update_recycle_goods['rego_recycle_number'] = 0;
            $update_recycle_goods['rego_fine_quantity'] = 0;
            $update_recycle_goods['rego_priority_quantity'] = 0;
            $find_recede = DB::table('recede_goods')
                ->where('rego_rec_id', $find_data->retgo_number_id)
                ->update($update_recycle_goods);//退换货商品表

        }

        //取消退款
        if($find_data->retgo_ref_number){
            $refund_status = DB::table('refund')
                ->where('ref_number', $find_data->retgo_ref_number)
                ->value('ref_refund_status');
            if($refund_status == 1){
                $find_recede = DB::table('refund')
                    ->where('ref_number', $find_data->retgo_ref_number)
                    ->update(['ref_cancel'=>2,'ref_status'=>3]);//修改为取消、驳回
            }
        }
        if ($find_recede) {
            DB::commit();
            //Common::addLog($user_info, $request->getClientIp(), '退货', '撤销', '撤销退货单：' . $request['retgo_id'] . '成功');
            return ['code'=>200, 'msg'=>'撤销成功', 'data'=>''];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'撤销失败', 'data'=>''];
        }
    }

    //退款列表
    public static function refundIndex($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->indexValidator($request);
        if ($error_message) {
            return ['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message];
        }
        $is_pc = 1;
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if(empty($user_info)){
            $is_pc = 2;
            $user_info = Common::wechatGetUserInfo($request['api_token']);
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $page_size = $request['show_count'] ? $request['show_count'] : 10;
        $list_data = DB::table('refund as r')
            ->leftjoin('return_goods as g', 'g.retgo_ref_number', '=', 'r.ref_number')
            ->where('ref_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['ref_order_number'])) {
                    $query->where('ref_order_number', $request['ref_order_number']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['ref_create_time']) && isset($request['ref_create_time'][0]) && isset($request['ref_create_time'][1])) {
                    $query->whereBetween('ref_create_time', [$request['ref_create_time'][0], $request['ref_create_time'][1] . ' 23:59:59']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['ref_refund_time']) && isset($request['ref_refund_time'][0]) && isset($request['ref_refund_time'][1])) {
                    $query->whereBetween('ref_refund_time', [$request['ref_refund_time'][0], $request['ref_refund_time'][1] . ' 23:59:59']);
                }
            })
            ->where(function ($query) use ($request) {
                if (!empty($request['ref_status'])) {
                    $query->where('ref_status', $request['ref_status']);
                }
            })
            ->select('r.ref_number', 'r.ref_retgo_id', 'r.ref_retgo_number', 'r.ref_order_number', 'r.ref_wor_number','r.ref_status', 'r.ref_refund_status', 'r.ref_refund_method', 'r.ref_refund_account', 'r.ref_refund_name', 'r.ref_amount', 'r.ref_create_time', 'r.ref_refund_time', 'r.ref_create_name', 'g.retgo_return_status', 'g.retgo_id','r.ref_id','r.ref_reason','r.ref_refuse_remark')
            //->select('r.*', 'e.*')
            ->orderBy('r.ref_id', 'desc')
            ->paginate($page_size);
        $list = $list_data->items();
        // 获取当前列表下的按钮
        if($is_pc ==1){
            $list_button = getListButton($request['api_token'], $request['pri_id']);
        }else{
            $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        }
        $return_status = ReturnGoodsService::getReturnName(true);//回收状态
        $refund_method = ReturnGoodsService::getRefundMethodName(true);//退款方式
        $refund_refund_status = ReturnGoodsService::getRefundStatusName(true);//退款状态
        $refund_status = ReturnGoodsService::getStatusName(true);//退款审核状态
        $order_number = array_column($list, 'ref_order_number'); //
        if ($list) {
            // 查询商品、项目信息
            $order_goods = DB::table('order_goods as orgo')
                ->leftjoin('goods as g', 'g.goo_id', '=', 'orgo.orgo_goo_id')
                ->whereIn('orgo_order_number', $order_number)
                ->whereIn('orgo_goo_type', [1,2])
                ->select('orgo_id','orgo_order_number', 'orgo_ord_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_guarantee', 'orgo_goo_type', 'orgo_state', 'orgo_goo_unit', 'orgo_goo_unta_id', 'goo_unit_conversion', 'orgo_goo_price', 'orgo_goo_amount')
                ->get()->toArray();
            if($order_goods){
                foreach ($order_goods as $g_key => $v_value){
                    $good_data[$v_value->orgo_order_number][] = $v_value;
                }
            }
            foreach ($list as $key => $value) {
                if(isset($value->retgo_return_status)){
                    $list[$key]->retgo_return_status_name = $return_status[$value->retgo_return_status];
                }else{
                    $list[$key]->retgo_return_status_name = '--';
                }
                $list[$key]->ref_refund_method_name = $value->ref_refund_method??'';
                $list[$key]->ref_refund_status_name = $refund_refund_status[$value->ref_refund_status]??'';
                $list[$key]->ref_status_name = $refund_status[$value->ref_status]??'';
                $list[$key]->operate_name = $user_info->adm_name;
                $list[$key]->ref_amount = $value->ref_amount / 100;
                $list[$key]->goods = $good_data[$value->ref_order_number]??[];
                if($value->ref_retgo_number){
                    $refund_type = '退货款';
                }else{
                    $refund_type = '仅退款';
                }
                $list[$key]->refund_type = $refund_type;
                if($list[$key]->goods){
                    foreach ($list[$key]->goods as $g_k =>$g_v){
                        $list[$key]->goods[$g_k]->orgo_goo_quantity1 = $g_v->orgo_goo_quantity;
                    }
                }
                if($value->ref_refund_time == '0000-00-00 00:00:00'){
                    $list[$key]->ref_refund_time = date('Y-m-d H:i:s');
                }
                $buttonData = [];
                if($value->ref_status == 1){
                    $buttonData[] = 'pass';//通过
                    $buttonData[] = 'reject';//驳回
                }
                if($is_pc ==1){
                    $button = CommonService::getListButton($buttonData,$list_button);
                }else{
                    $button = CommonService::getAppletListButton($buttonData,$list_button);
                }
                $list[$key]->button_one = $button['button_one']??[];
                $list[$key]->button_two = $button['button_two']??[];
                $list[$key]->button_three = $button['button_three']??[];
            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $page_size;        //一页显示多少个
        $data['data'] = $list;                              //返回数据

        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    /*
     * @name 退款编辑
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/13 9:12
     *
    */
    public static function edit($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->editValidator($request);
        if ($error_message) {
            return ['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message];
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if(empty($user_info)){
            $user_info = Common::wechatGetUserInfo($request['api_token']);
        }
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if(isset($request['ref_refund_method'])){
            $edit_data['ref_refund_method'] = $request['ref_refund_method'];//退款方式
        }
        if(isset($request['ref_refund_account'])){
            $edit_data['ref_refund_account'] = $request['ref_refund_account'];//退款账号
        }
        if(isset($request['ref_refund_name'])){
            $edit_data['ref_refund_name'] = $request['ref_refund_name'];//退款账号姓名
        }
        if(isset($request['ref_refuse_remark'])){
            $edit_data['ref_refuse_remark'] = $request['ref_refuse_remark'];//驳回备注
        }
        if(isset($request['ref_img'])){
            $edit_data['ref_img'] = $request['ref_img'];//打款凭证
        }
        if(isset($request['ref_status']) && $request['ref_status'] == 3){
            $edit_data['ref_status'] = $request['ref_status'];//状态：1待审核2通过3驳回
        }
        $edit_data['ref_update_time'] = date("Y-m-d H:i:s");//编辑时间
        DB::beginTransaction();
        if($request['ref_id'] && isset($edit_data)){
            $eidt_res = DB::table('refund')
                ->where('ref_id', $request['ref_id'])//退款id
                ->update($edit_data);
        }
        //退款数据
        $data = DB::table('refund')
            ->where('ref_id', $request['ref_id'])//退款id
            ->first();
        if(isset($request['ref_status']) && $request['ref_status'] == 2){
            $edit_data['ref_status'] = $request['ref_status'];//状态：1待审核2通过3驳回
        }
        if(isset($edit_data['ref_status']) && $edit_data['ref_status'] == 2 && $data->ref_status != $edit_data['ref_status']){//如果通过  ref_amount
            if(!$data->ref_refund_method && !$data->ref_refund_account && !$data->ref_refund_name){
                return ['code'=>500, 'msg'=>'请完善客户退款账号信息', 'data'=>'请完善客户退款账号信息'];
            }
            if(!isset($request['ref_img'])){
                return ['code'=>500, 'msg'=>'未上传打款凭证', 'data'=>'未上传打款凭证'];
            }
            $eidt_res = DB::table('refund')
                ->where('ref_id', $request['ref_id'])//退款id
                ->update(['ref_refund_status'=>2,'ref_status'=>2,'ref_refund_operate_name'=>$user_info->adm_name,'ref_refund_time'=>date('Y-m-d H:i:s')]);
            //扣款
            $order_data = DB::table('order')
                ->where('ord_order_number', $data->ref_order_number)//订单单号
                ->first();
            if($order_data->ord_actual_price >= $data->ref_amount){//实付金额 > 扣款金额
                $ord_actual_price = $order_data->ord_actual_price - $data->ref_amount; //实付金额 = 以前的实付金额 - 扣款金额
                $ord_order_price = $order_data->ord_order_price - $data->ref_amount; //订单金额 = 订单金额 - 扣款金额
                $up_order = DB::table('order')
                    ->where('ord_order_number', $data->ref_order_number)//订单单号
                    ->update(['ord_actual_price'=>$ord_actual_price]);
            }else if($order_data->ord_actual_price < $data->ref_amount){//实付金额 < 扣款金额   先扣掉实付金额，不够再扣余额
                $ord_actual_price = 0;
                $need_amount = $data->ref_amount - $order_data->ord_actual_price;//需要扣的余额
                $ord_banlance = $order_data->ord_banlance - $need_amount;
                $up_order = DB::table('order')
                    ->where('ord_order_number', $data->ref_order_number)//订单单号
                    ->update(['ord_actual_price'=>0,'ord_banlance'=>$ord_banlance]);
                
                //使用余额支付退回余额
                $find_rec_log = DB::table('rec_log')
                    ->where('relo_type', 2)
                    ->where('relo_ord_id', $request['ord_id'])
                    ->select('relo_rec_num', 'relo_gift_num', 'relo_mem_id')
                    ->first();
                if ($find_rec_log) {
                    $find_mem = DB::table('member')
                        ->where('mem_id', $find_rec_log->relo_mem_id)
                        ->select('mem_rec_banlance', 'mem_gift_banlance')
                        ->first();
                    if ($need_amount > $find_rec_log->relo_gift_num) {
                        $update_mem['mem_gift_banlance'] = $find_mem->mem_gift_banlance + $find_rec_log->relo_gift_num;
                        $relo_gift_num = $find_rec_log->relo_gift_num;
                        $relo_rec_num = $need_amount - $find_rec_log->relo_gift_num;
                        $update_mem['mem_rec_banlance'] = $find_mem->mem_rec_banlance + $relo_rec_num;
                    } else {
                        $relo_gift_num = $need_amount;
                        $relo_rec_num = 0;
                        $update_mem['mem_gift_banlance'] = $find_mem->mem_gift_banlance + $need_amount;
                    }
                    $update_mem['mem_update_time'] = date('Y-m-d H:i:s');
                    $update_mem_res = DB::table('member')
                        ->where('mem_id', $find_rec_log->relo_mem_id)
                        ->update($update_mem);

                    $add_rec_log['relo_mem_id'] = $find_rec_log->relo_mem_id;
                    $add_rec_log['relo_type'] = 4;
                    $add_rec_log['relo_remark'] = '退款';
                    $add_rec_log['relo_rec_num'] = $relo_rec_num;
                    $add_rec_log['relo_gift_num'] = $relo_gift_num;
                    $add_rec_log['relo_create_time'] = date('Y-m-d H:i:s');
                    $add_rec_log['relo_ord_id'] = $order_data->ord_id;
                    $add_rec_log['relo_create_id'] = $user_info->adm_id;
                    $rec_log_res = DB::table('rec_log')->insertGetId($add_rec_log);
                }
            }
            //应收应付修改
            ReturnGoodsService::editPay($order_data->ord_id,['recpay_actual_price'=>$ord_actual_price],$user_info);
            if($order_data->ord_type == 1){
                WashOrderBasicService::reducePoint($user_info,$order_data->ord_client_id,$order_data->ord_id, $request['ref_id']);
            }
            //如果货和款都退了就取消订单
            $params['ord_id'] = $order_data->ord_id;
            $params['ord_order_number'] = $data->ref_order_number;
            $params['remark'] = '全部退货取消订单';
            $cancel_ret = WashOrderService::cancelOrder($user_info,$params);
            if($cancel_ret['code'] != 200){
                return ['code'=>500, 'msg'=>'取消订单失败', 'data'=>''];
            }
        }
        if(!isset($eidt_res)){
            DB::rollBack();
            return ['code'=>500, 'msg'=>'未填写信息', 'data'=>'未填写信息'];
        }
        if ($eidt_res) {
            DB::commit();
            //Common::addLog($user_info, $request->getClientIp(), '退货', '编辑', '编辑退货单：' . $return_id . '成功');
            return ['code'=>200, 'msg'=>'操作成功', 'data'=>'操作成功'];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'操作成功', 'data'=>'操作失败'];
        }

    }

    /*
     * @name 退款详情 小程序的
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/9/13 9:12
     *
    */
    public static function info($request){
        // 验证数据
        $verify_data = new ReturnGoodsManageController;
        $error_message = $verify_data->editValidator($request);
        if ($error_message) {
            return ['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误', 'error_message'=>$error_message];
        }
        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $list = DB::table('refund as r')
            ->leftjoin('return_goods as g', 'g.retgo_ref_number', '=', 'r.ref_number')
            ->where('ref_id', $request['ref_id'])
            ->select('r.ref_number', 'r.ref_retgo_id', 'r.ref_retgo_number', 'r.ref_order_number', 'r.ref_wor_number','r.ref_status', 'r.ref_refund_status', 'r.ref_refund_method', 'r.ref_refund_account', 'r.ref_refund_name', 'r.ref_amount', 'r.ref_create_time', 'r.ref_refund_time', 'r.ref_create_name', 'g.retgo_return_status', 'g.retgo_id','r.ref_id','r.ref_reason','r.ref_refuse_remark')
            ->first();
        // 获取当前列表下的按钮
        $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        $return_status = ReturnGoodsService::getReturnName(true);//回收状态
        $refund_method = ReturnGoodsService::getRefundMethodName(true);//退款方式
        $refund_refund_status = ReturnGoodsService::getRefundStatusName(true);//退款状态
        $refund_status = ReturnGoodsService::getStatusName(true);//退款审核状态
        if ($list) {
            // 查询商品、项目信息
            $order_goods = DB::table('order_goods as orgo')
                ->leftjoin('goods as g', 'g.goo_id', '=', 'orgo.orgo_goo_id')
                ->where('orgo_order_number', $list->ref_order_number)
                ->whereIn('orgo_goo_type', [1,2])
                ->select('orgo_id','orgo_order_number', 'orgo_ord_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_guarantee', 'orgo_goo_type', 'orgo_state', 'orgo_goo_unit', 'orgo_goo_unta_id', 'goo_unit_conversion', 'orgo_goo_price', 'orgo_goo_amount')
                ->get()->toArray();
            if($order_goods){
                foreach ($order_goods as $g_key => $v_value){
                    $good_data[$v_value->orgo_order_number][] = $v_value;
                }
            }

                if(isset($list->retgo_return_status)){
                    $list->retgo_return_status_name = $return_status[$list->retgo_return_status];
                }else{
                    $list->retgo_return_status_name = '--';
                }
                $list->ref_refund_method_name = $list->ref_refund_method??'';
                $list->ref_refund_status_name = $refund_refund_status[$list->ref_refund_status]??'';
                $list->ref_status_name = $refund_status[$list->ref_status]??'';
                $list->operate_name = $user_info->adm_name;
                $list->ref_amount = $list->ref_amount / 100;
                $list->goods = $good_data[$list->ref_order_number]??[];
                if($list->ref_retgo_number){
                    $refund_type = '退货款';
                }else{
                    $refund_type = '仅退款';
                }
                $list->refund_type = $refund_type;
                if($list->goods){
                    foreach ($list->goods as $g_k =>$g_v){
                        if($g_v->orgo_goo_unta_id == 1 && isset($g_v->goo_unit_conversion)){
                            unset($orgo_goo_quantity);unset($orgo_goo_unit);
                            $orgo_goo_quantity = $g_v->orgo_goo_quantity.'卷';
                            $orgo_goo_unit = $g_v->orgo_goo_unit;
                            $list->goods[$g_k]->orgo_goo_quantity1 = $orgo_goo_quantity;
                            $list->goods[$g_k]->orgo_goo_unit = (int)$orgo_goo_quantity * (int)$g_v->goo_unit_conversion.'米';
                        }else{
                            $list->goods[$g_k]->orgo_goo_quantity1 = $g_v->orgo_goo_quantity;
                        }
                    }
                }
                if($list->ref_refund_time == '0000-00-00 00:00:00'){
                    $list->ref_refund_time = date('Y-m-d H:i:s');
                }
                $buttonData = [];
                if($list->ref_status == 1){
                    $buttonData[] = 'pass';//通过
                    $buttonData[] = 'reject';//驳回
                }
                $button = CommonService::getAppletListButton($buttonData,$list_button);
                $list->button_one = $button['button_one']??[];
                $list->button_two = $button['button_two']??[];
                $list->button_three = $button['button_three']??[];

        }
        $data['data'] = $list;                              //返回数据

        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

}

