<?php

namespace App\Services\ReceivablePay;
use App\Http\Controllers\Common\CommonController;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\ReceivablePay;
use App\Models\OrderBill;
use App\Models\ReceivablePay as ReceivablePayModels;
use App\Models\SettleIn;
use App\Models\SettleInSchedule;
use App\Models\SettleInSyncInformation;
use App\Services\CommonService;
use App\Services\LoginUserService;
use App\Services\ThreeApi\BaiDu\BaiDuService;
use BlueCity\Core\Service\Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use Overtrue\Pinyin\Pinyin;
use \Illuminate\Support\Facades\Validator;
use App\Services\Business\WashOrderBasicService;


class ReceivablePayService extends Service
{

    /*
     * @name 添加应收应付
     * @param array  $params 添加的数组
     * @retrun array
     * @author Ma 2023/7/24 11:28
     *
    */
    public static function add($params){
        $data_validator = self::addValidator($params);
        if($data_validator['code'] != 200){
            return response()->json($data_validator);exit;
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        //20230721  新增应收应付
        $ret = ReceivablePay::add($user_info,$params);
        if($ret['code'] == 200){
            return ['code'=>200, 'msg'=>'添加成功', 'data'=>$ret['data']];
        } else {
            return ['code'=>500, 'msg'=>'添加失败', 'data'=>'添加失败'];
        }
    }

    /*
     * @name 添加应收应付数据处理
     * @param
     * $ord_id   订单id
     * $ord_order_number   订单号
     * $orcl_id   订单客户id
     * $user_info   用户信息
     * @retrun array
     * @author Ma 2023/10/07
     *
    */
    public static function addPay($ord_id,$ord_order_number,$type,$orcl_id,$user_info,$goods_price,$request,$ord_edit_data,$outstanding_amount = NULL,$point = 1){

        $ord_order_price = $request['ord_order_price']??$ord_edit_data['ord_order_price'];//应收金额
        $recpay_receivable_price = $ord_order_price;//应收金额
        $recpay_actual_price = 0;//默认实收金额为0
        $recpay_arrears_price = $recpay_receivable_price - $recpay_actual_price;//欠收金额 = 应收金额 - 实收金额
        //支付方式为1.现金2.支付宝 3微信 4银行卡  的实收金额
        if(isset($request['ord_payment_way'])){
            if(in_array($request['ord_payment_way'],[5,6])){//会员卡
                if(isset($ord_edit_data['ord_payment_money'])){
                    $recpay_actual_price = $ord_edit_data['ord_payment_money'] ;//实收金额
                }else{
                    $recpay_actual_price = 0;//实收金额
                }
                $recpay_arrears_price = 0;//欠收金额
            } elseif($request['ord_payment_way'] == 9){//部分结款
                if(isset($request['ord_actual_amout'])){
                    $recpay_actual_price = $request['ord_actual_amout']*100;//实收金额
                }
                if($outstanding_amount){
                    $recpay_arrears_price = $outstanding_amount;//欠收金额
                }
            } elseif($request['ord_payment_way'] > 0 && $request['ord_payment_way'] != 9){
                if(isset($ord_edit_data['ord_payment_money'])){
                    $recpay_actual_price = $ord_edit_data['ord_payment_money'] ;//实收金额
                }else{
                    $recpay_actual_price = $recpay_receivable_price ;//实收金额
                }
                $recpay_arrears_price = 0;//欠收金额
            }
        }
        $recpay_cost_price = 0;//成本价
        if(isset($goods_price)){
            foreach ($goods_price as $g_k => $g_v){
                $recpay_cost_price += $g_v['price'] * $g_v['quantity'] * 100;
            }
        }
        $profit = $recpay_actual_price - $recpay_cost_price;
        if($profit > 0){
            $minus = 1;
        }else{
            $minus = 2;
            $profit = abs($profit);
        }
        $rece_params = [
            'recpay_type'=>1,//类型：1销售订单2充值卡
            'recpay_original_id'=>$ord_id,//订单id
            'recpay_original_number'=>$ord_order_number,//订单号
            'recpay_client_type'=>$type,
            'recpay_client_id'=>$request['ord_client_id']??$orcl_id,//客户id
            'recpay_client_name'=>$request['orcl_name'],
            'recpay_receivable_price'=>$ord_order_price,//应收金额
            'recpay_arrears_price'=>$recpay_arrears_price,//欠收金额
            'recpay_actual_price'=>$recpay_actual_price,//实收金额
            'recpay_cost_price'=>$recpay_cost_price,//成本价
            /*'recpay_receivable_pay'=>0,//应付金额
            'recpay_actual_pay'=>0,//实付金额*/
            'recpay_state'=>1,//状态：1未确认2已确认
            'recpay_order_state'=>1,//订单状态：1正常2退款3取消
            'recpay_plus_minus'=>$minus,//盈利正负：1正值2负值
            'recpay_profit'=>$profit,//盈利金额
            'recpay_orcl_id'=>$orcl_id,//订单客户id
            'recpay_source'=>static::getOrdsource($request),//下单来源：1pc端2车主端(车主小程序)3技师端4合作商5智配贴装
        ];
        $ord_data = DB::table('order')
            ->where('ord_id', $ord_id)
            ->select('ord_state', 'ord_wor_state', 'ord_type', 'ord_client_id')
            ->first();
        if ($point == 1 && $ord_data->ord_state == 2 && ($ord_data->ord_wor_state == 4 || $ord_data->ord_wor_state == 20) && $ord_data->ord_type == 1) {//已结算 待评价或已完成 个人会员 添加积分
            $add_point = WashOrderBasicService::addPoint($user_info,$ord_data->ord_client_id,$ord_id);
        }
        $ret = ReceivablePayService::add($rece_params);
        if($ret['code'] == 200){
            return ['code'=>200, 'msg'=>'添加成功', 'data'=>$ret['data']];
        } else {
            return ['code'=>500, 'msg'=>'添加失败', 'data'=>'添加失败'];
        }
    }

    // 来源  1 pc  2 车主小程序   3 技师
    public static function getOrdsource($request){
        $ord_source = 1;  // 来源  1 pc  2 车主小程序   3 技师
        if(isset($request['rt'])){
            if($request['rt']=='wechat'){
                $ord_source = 3;
            }elseif($request['rt']=='wechatWash'){
                $ord_source = 2;
            }
        }
        return $ord_source;
    }

    /*
     * @name 验证
     *
     */
    public static function addValidator($input){
        $message = [
            'recpay_type.required'=> '用户类型不能为空',
            'recpay_client_id.regex'=> '客户id不能为空',
            'recpay_receivable_price.required'=> '应收金额不能为空',
        ];
        $rules = [
            'recpay_type' =>'required',
            'recpay_client_id'=>'required',
            'recpay_receivable_price'=>'required',
        ];
        $Validator = Validator::make($input,$rules,$message);
        if($Validator->fails()){
            return ['data'=>'','code'=>500, 'msg'=>$Validator->errors()->first()];
        }

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

    //修改应收应付
    public static function edit($params){
        /*$data_validator = self::editValidator($params);
        if($data_validator['code'] != 200){
            return response()->json($data_validator);exit;
        }*/
        //self::info($request);
        $ret = ReceivablePay::edit($params);
        if($ret['code'] == 200){
            return ['code'=>200, 'msg'=>'修改成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'修改失败', 'data'=>'修改失败'];
        }
    }

    /*
     * @name 验证
     *
     */
    public static function editValidator($input){
        $message = [
            'recpay_id.required'=> 'id不能为空',
        ];
        $rules = [
            'recpay_id' =>'required',
        ];
        $Validator = Validator::make($input,$rules,$message);
        if($Validator->fails()){
            return ['data'=>'','code'=>500, 'msg'=>$Validator->errors()->first()];
        }

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

    //应收应付详情
    public static function info($params){
        /*$data_validator = self::editValidator($params);
        if($data_validator['code'] != 200){
            return response()->json($data_validator);exit;
        }*/
        $ret = ReceivablePay::info($params);
        $client_type = self::getRecpayClientTypeName(true);
        $ret['data']->recpay_client_type_name = $client_type[$ret['data']->recpay_client_type];
        if($ret['code'] == 200){
            return ['code'=>200, 'msg'=>'获取成功', 'data'=>$ret['data']];
        } else {
            return ['code'=>500, 'msg'=>'获取失败', 'data'=>'获取失败'];
        }
    }

    /**
     * @name 客户类型name
     * @param false $type
     * @return array
     */
    public static function getRecpayClientTypeName($type){
        $data = [['id'=>0,'name'=>'散户'],['id'=>1,'name'=>'个人会员'],['id'=>2,'name'=>'企业会员']];
        if($type){
            $data = array_column($data, 'name','id');
        }
        return $data;
    }

    /*
     * @name 列表页
     * @param string ju_ordernum 订单单号
     * @retrun array 
     * @author Ma 2023/7/25 15:24
     * 
    */
    public static function index($search_data){
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($search_data['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;
        $shop_id = $user_info->adm_shop_id;
        //if (!empty($search_data['recpay_original_number']) || !empty($search_data['recpay_client_id']) || !empty($search_data['recpay_settle_id']) || !empty($search_data['start_time']) || !empty($search_data['end_time']) || !empty($search_data['recpay_client_type']) || !empty($search_data['recpay_acti_id']) || !empty($search_data['recpay_remark']) || !empty($search_data['start_times']) || !empty($search_data['end_times']) || !empty($search_data['max_price']) || !empty($search_data['min_price'])) {
        $post['string'] = 'recpay_';
        $post['user_info'] = $user_info;
        $type = 1;
        $page_size = $search_data['show_count'] ?$search_data['show_count']:10;
        $where_data = whereFunction($post,$type);
        if( isset($search_data['recpay_client_id']) && $search_data['recpay_client_type'] == 2 && $search_data['recpay_client_id'] > 0){
            $account_unit_id = DB::table('business_account')
                ->where('buac_bucl_id', $search_data['recpay_client_id'])
                ->select('buac_id')
                ->get()->toArray();
            $all_account_ids = array_column($account_unit_id,'buac_id');
            $search_data['all_account_ids'] = $all_account_ids;
        }
        // 实际金额最小钱数
        if (!empty($search_data['min_price'])) {
            $search_data['min_price'] = $search_data['min_price'] * 100;
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            $search_data['max_price'] = $search_data['max_price'] * 100;
        }
            $list_data = DB::table('receivable_pay as recr')
                ->leftJoin('order as o', 'o.ord_id', '=', 'recr.recpay_original_id')
                ->where('recpay_cid', $user_info->adm_cid)
                ->whereIn($where_data['string'], $where_data['shop_id'])
                ->where('recpay_order_state', '!=',3)
                ->where(function ($query) use ($search_data) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                        $query->whereBetween('recpay_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['start_time'])) {
                            $query->where('recpay_create_time', '>=', $search_data['start_time']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['end_time'])) {
                                $query->where('recpay_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //状态：1未确认2已确认3已作废
                    if (!empty($search_data['recpay_state'])) {
                        $query->where('recpay_state', $search_data['recpay_state']);
                    }else{
                        $query->where('recpay_state', '<>',3);
                    }
                })
                ->where(function ($query) use ($search_data) { //单号
                    if (!empty($search_data['recpay_original_number'])) {
                        $query->where('recpay_original_number', 'like', '%' . $search_data['recpay_original_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //单位名称
                    if (!empty($search_data['recpay_client_name'])) {
                        $query->where('recpay_client_name', $search_data['recpay_client_name']);
                    }
                })
                ->where(function ($query) use ($search_data) { //结款人
                    if (!empty($search_data['recr_settle_id'])) {
                        $query->where('recr_settle_id', $search_data['recr_settle_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户类型
                    if(isset($search_data['recpay_client_type']) && $search_data['recpay_client_type'] == 0){
                        $query->where('recpay_client_type', 0);
                    }
                    if (!empty($search_data['recpay_client_type'])) {
                        if ($search_data['recpay_client_type'] == 1) {
                            $client_type = [1, 4];
                            $query->whereIn('recpay_client_type', $client_type);
                            if(isset($search_data['recpay_client_id']) && !empty($search_data['recpay_client_id'])){
                                $query->where('recpay_client_id', $search_data['recpay_client_id']);
                            }
                        } else if ($search_data['recpay_client_type'] == 2 && isset($search_data['all_account_ids']) && !empty($search_data['all_account_ids'])){
                            $query->where('recpay_client_type', 2);
                            $query->whereIn('recpay_client_id', $search_data['all_account_ids']);
                        }else if($search_data['recpay_client_type'] == 2){
                            $query->where('recpay_client_type', 2);
                        }

                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['recpay_remark'])) {
                        $query->where('recpay_remark', 'like', '%' . $search_data['recpay_remark'] . '%');
                    }
                })
                /*->where(function ($query) use ($search_data) { //开单时间(单子的创建时间)
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_times']) && !empty($search_data['end_times'])) {
                        $query->whereBetween('recr_order_time', [$search_data['start_times'], $search_data['end_times'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['start_times'])) {
                            $query->where('recr_order_time', '>=', $search_data['start_times']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['end_times'])) {
                                $query->where('recr_order_time', '<=', $search_data['end_times'] . ' 23:59:59');
                            }
                        }
                    }
                })*/
                /*->where(function ($query) use ($search_data) { //客户单位id
                    if (!empty($search_data['recpay_client_id'])) {
                        $query->where('recpay_client_id', $search_data['recpay_client_id']);
                    }
                })*/
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('recpay_profit', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('recpay_profit', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('recpay_profit', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //金额正负：1正值2负值
                    if (!empty($search_data['recpay_plus_minus'])) {
                        $query->where('recpay_plus_minus', $search_data['recpay_plus_minus']);
                    }
                })
                ->select('recpay_id', 'recpay_original_id', 'recpay_original_number', 'recpay_type', 'recpay_client_name', 'recpay_receivable_price', 'recpay_arrears_price', 'recpay_actual_price', 'recpay_cost_price', 'recpay_receivable_pay', 'recpay_actual_pay', 'recpay_plus_minus', 'recpay_profit', 'recpay_state', 'recpay_remark','recpay_client_id','recpay_order_state','recpay_create_time','recpay_client_type','recpay_zero_price','recpay_zero_remark','recpay_zero_plus_minus','ord_wor_state','ord_state','recpay_statue_pay','ord_add_work_state','recpay_orcl_id','recpay_source','ord_orcl_id','ord_type','recpay_zero_price', 'ord_openbill')
                ->orderBy('recpay_id', 'desc')
                ->paginate($page_size);
            $list_items = $list_data->items();
            // 获取当前列表下的按钮
            $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
            $status_names = self::getReceivableStatus();
            $type_names = self::getReceivableType();
            if ($list_items) {
                $recr_client_id = array_unique(array_column($list_items, 'recpay_client_id')); //客户id
                // 查询客户单位
                $channel = DB::table('channel_unit')
                    ->whereIn('chun_id', $recr_client_id)
                    ->where('chun_shop_id', $shop_id)
                    ->where('chun_state', '1')
                    ->pluck('chun_unit_name', 'chun_id')
                    ->toArray();
                // 查询订单单号
                $rec_ord_id = array_unique(array_column($list_items, 'recpay_original_id'));
                $rec_ord_number = array_unique(array_column($list_items, 'recpay_original_number'));
                $work_order = DB::table('work_order as wor')
                    ->leftjoin('receivable_pay as recr', 'recr.recpay_original_id', '=', 'wor.wor_id')
                    ->where('wor_cid', $user_info->adm_cid)
                    ->where('wor_shop_id', $shop_id)
                    ->whereIn('wor_id', $rec_ord_id)
                    ->whereIn('wor_number', $rec_ord_number)
                    //->whereIn('recpay_account_type', [3, 4])
                    ->select('wor_id', 'wor_order_id', 'wor_order_number')
                    ->get()->toArray();
                $work_order = json_decode(json_encode($work_order), true);
                foreach ($work_order as $k => $v) {
                    $wor_order_number[$v['wor_id']] = $v['wor_order_number'];
                }
                foreach ($list_items as $key => $value) {

                    unset($list_items[$key]->recpay_number_id);

                    if (strpos($value->recpay_original_number, 'G') === 0) {
                        $orre_wor = DB::table('order_remarks')
                            ->where('orre_wor_id', $value->recpay_original_id)
                            ->select('orre_content', 'orre_time', 'orre_create_adm_name')
                            ->orderBy('orre_id', 'desc')
                            ->get();
                        $orre_wor = json_decode(json_encode($orre_wor), true);
                    } else {
                        $orre_wor = [];
                    }
                    if (strpos($value->recpay_original_number, 'D') === 0) {
                        $orre_order = DB::table('order_remarks')
                            ->where('orre_ord_id', $value->recpay_original_id)
                            ->select('orre_content', 'orre_time', 'orre_create_adm_name', 'orre_module')
                            ->orderBy('orre_id', 'desc')
                            ->get();
                        $orre_order = json_decode(json_encode($orre_order), true);
                    } else {
                        $orre_order = [];
                    }
                    $list_items[$key]->recpay_remarks = array_merge($orre_order, $orre_wor);
                    $list_items[$key]->recpay_state_name = $status_names[$value->recpay_state];
                    $list_items[$key]->recpay_type_name = $type_names[$value->recpay_type];
                    // 客户单位名称
                    /*if (isset($channel[$value->recpay_client_id])) {
                        $list_items[$key]->recpay_client_name = $channel[$value->recpay_client_id];
                    } else {
                        $list_items[$key]->recpay_client_name = $value->recpay_client_name;
                    }*/
                    // 订单单号
                    /*if (isset($wor_order_number[$value->recpay_original_id])) {
                        $list_items[$key]->order_number = $wor_order_number[$value->recpay_original_id];
                    } else {
                        $list_items[$key]->order_number = '';
                    }
                    if (empty($value->recpay_number_id)) {
                        $list_items[$key]->recpay_original_id = 0;
                    }*/
                    //按钮
                    $buttonData = [];
                    if (in_array($value->recpay_order_state, [2])) {//该订单已退款
                        $buttonData[] = 'info';
                    }else if (in_array($value->recpay_order_state, [3])) {//该订单已取消
                        $buttonData[] = 'info';
                    }else if (in_array($value->recpay_state, [1])) {//未确认
                        if($value->ord_add_work_state == 1){//有工单
                            if($value->ord_wor_state > 17 && $value->ord_state >=2 && $value->recpay_statue_pay == 1 ){//已完成  已结算  绩效已结算
                                $buttonData[] = 'edit';
                            }
                        }else{//没有工单
                            if(($value->ord_wor_state == 4 || $value->ord_wor_state > 17) && $value->ord_state >=2){//已完成  已结算  显示审核按钮
                                $buttonData[] = 'edit';
                            }
                        }
                        $buttonData[] = 'info';
                        $buttonData[] = 'dedit';
                    }else if (in_array($value->recpay_state, [2])) {//已确认
                        $buttonData[] = 'info';
                    }else if (in_array($value->recpay_state, [3])) {//已作废
                        $buttonData[] = 'redit';//恢复
                        $buttonData[] = 'info';//详情
                    }
                    $button = CommonService::getListButton($buttonData,$list_button);
                    $list_items[$key]->button_one = $button['button_one']??[];
                    $list_items[$key]->button_two = $button['button_two']??[];
                    $list_items[$key]->button_three = $button['button_three']??[];
                    $list_items[$key]->recpay_receivable_price = $value->recpay_receivable_price / 100;//应收金额
                    $list_items[$key]->recpay_actual_price = $value->recpay_actual_price / 100;//实收金额
                    $list_items[$key]->recpay_arrears_price = $value->recpay_arrears_price / 100;//欠收金额
                    $list_items[$key]->recpay_cost_price = $value->recpay_cost_price / 100;//成本价
                    $list_items[$key]->recpay_actual_pay = $value->recpay_actual_pay / 100;//实付金额
                    $list_items[$key]->recpay_receivable_pay = $value->recpay_receivable_pay / 100;//应付金额
                    $list_items[$key]->recpay_zero_price = $value->recpay_zero_price / 100;//抹零金额
                    if($value->recpay_plus_minus == 2){
                        $list_items[$key]->recpay_profit = -($value->recpay_profit / 100);//盈利金额
                    }else{
                        $list_items[$key]->recpay_profit = $value->recpay_profit / 100;//盈利金额
                    }
                    if($value->recpay_source == 5 || $value->recpay_client_type == 6){//如果是智配，调用户信息
                        if($value->recpay_source == 5){
                            $orcl_id = $value->recpay_orcl_id;
                        }else{
                            $orcl_id = $value->ord_orcl_id;
                            $value->recpay_client_type = $value->ord_type;
                        }
                        $cl_name = DB::table('order_client')
                            ->where('orcl_id', $orcl_id)
                            ->value('orcl_name');
                        $list_items[$key]->recpay_client_name = $cl_name;
                    }
                }

                /*$find_price = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    ->whereRaw('`recr_settle_price` <> `recr_yet_receipt`')
                    // ->where('recr_statistics_type', 1)//1统计状态
                    ->where('recr_belongs_id', '=', 0)
                    // ->where('recr_plus_minus', 2)//金额负值
                    ->where(function ($query) use ($search_data) { //创建时间
                        // 如果选择开始时间并且选择结束时间
                        if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                            $query->whereBetween('recr_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                        } else {
                            // 如果选择开始时间
                            if (!empty($search_data['start_time'])) {
                                $query->where('recr_create_time', '>=', $search_data['start_time']);
                            } else {
                                // 如果选择结束时间
                                if (!empty($search_data['end_time'])) {
                                    $query->where('recr_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                                }
                            }
                        }
                    })
                    ->where(function ($query) use ($search_data) { //状态：1.未核销 2.已核销 3已收款
                        if (!empty($search_data['recr_state'])) {
                            $query->where('recr_state', $search_data['recr_state']);
                        }
                    })
                    ->where(function ($query) use ($search_data) { //单号
                        if (!empty($search_data['recr_original_number'])) {
                            $query->where('recr_original_number', 'like', '%' . $search_data['recr_original_number'] . '%');
                        }
                    })
                    ->where(function ($query) use ($search_data) { //单位名称
                        if (!empty($search_data['recr_client_name'])) {
                            $query->where('recr_client_name', $search_data['recr_client_name']);
                        }
                    })
                    ->where(function ($query) use ($search_data) { //结款人
                        if (!empty($search_data['recr_settle_id'])) {
                            $query->where('recr_settle_id', $search_data['recr_settle_id']);
                        }
                    })
                    ->where(function ($query) use ($search_data) { //客户类型
                        if (!empty($search_data['recr_client_type'])) {
                            if ($search_data['recr_client_type'] == 1) {
                                $client_type = [1, 4];
                            } else {
                                $client_type = [$search_data['recr_client_type']];
                            }
                            $query->whereIn('recr_client_type', $client_type);
                        }
                    })
                    ->where(function ($query) use ($search_data) { //会计科目
                        if (!empty($search_data['recr_acti_id'])) {
                            $query->where('recr_acti_id', $search_data['recr_acti_id']);
                        }
                    })
                    ->where(function ($query) use ($search_data) { //备注
                        if (!empty($search_data['recr_remark'])) {
                            $query->where('recr_remark', 'like', '%' . $search_data['recr_remark'] . '%');
                        }
                    })
                    ->where(function ($query) use ($search_data) { //开单时间(单子的创建时间)
                        // 如果选择开始时间并且选择结束时间
                        if (!empty($search_data['start_times']) && !empty($search_data['end_times'])) {
                            $query->whereBetween('recr_order_time', [$search_data['start_times'], $search_data['end_times'] . ' 23:59:59']);
                        } else {
                            // 如果选择开始时间
                            if (!empty($search_data['start_times'])) {
                                $query->where('recr_order_time', '>=', $search_data['start_times']);
                            } else {
                                // 如果选择结束时间
                                if (!empty($search_data['end_times'])) {
                                    $query->where('recr_order_time', '<=', $search_data['end_times'] . ' 23:59:59');
                                }
                            }
                        }
                    })
                    ->where(function ($query) use ($search_data) { //客户单位id
                        if (!empty($search_data['recr_client_id'])) {
                            $query->where('recr_client_id', $search_data['recr_client_id']);
                        }
                    })
                    ->where(function ($query) use ($search_data) { //实际金额区间搜索
                        // 如果选择最小钱数并且选择最大钱数
                        if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                            $query->whereBetween('recr_settle_price', [$search_data['min_price'], $search_data['max_price']]);
                        } else {
                            // 如果选择最小钱数
                            if (!empty($search_data['min_price'])) {
                                $query->where('recr_settle_price', '>=', $search_data['min_price']);
                            } else {
                                // 如果选择最大钱数
                                if (!empty($search_data['max_price'])) {
                                    $query->where('recr_settle_price', '<=', $search_data['max_price']);
                                }
                            }
                        }
                    })
                    ->where(function ($query) use ($search_data) { //金额正负：1正值2负值
                        if (!empty($search_data['recr_plus_minus'])) {
                            $query->where('recr_plus_minus', $search_data['recr_plus_minus']);
                        }
                    })
                    ->select('recr_settle_price', 'recr_actual_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_plus_minus', 'recr_zero_plus_minus')
                    ->get()->toArray();
                $bad_crop = 0; //欠收总额
                $recr_settle_price = 0; //结算金额
                $recr_yet_receipt = 0; //已收金额
                $recr_zero_price = 0; //抹零金额
                foreach ($find_price as $key => $value) {
                    // 欠收 = 结算金额 - 已收 - 抹零
                    if ($value->recr_plus_minus == 1) {
                        $recr_settle_price += $value->recr_settle_price; //结算金额
                        $recr_yet_receipt += $value->recr_yet_receipt; //已收金额
                        if ($value->recr_zero_plus_minus == 1) {
                            $recr_zero_price += $value->recr_zero_price; //抹零金额
                        } else {
                            $recr_zero_price -= $value->recr_zero_price;
                        }
                    } else {
                        $recr_settle_price -= $value->recr_settle_price;
                        $recr_yet_receipt -= $value->recr_yet_receipt;
                        if ($value->recr_zero_plus_minus == 1) {
                            $recr_zero_price -= $value->recr_zero_price; //抹零金额
                        } else {
                            $recr_zero_price += $value->recr_zero_price;
                        }
                    }
                }
                // 欠收 = 结算金额 - 已收 - 抹零
                $bad_crop = ($recr_settle_price - $recr_yet_receipt - $recr_zero_price) / 100;

                // 查找结款人
                $adm_info = DB::table('admin')
                    ->whereIn('adm_id', $settle_id)
                    ->get(['adm_id', 'adm_name']);
                // 查找会计科目
                $account_info = DB::table('account_title')
                    ->whereIn('acti_id', $acti_id)
                    ->get(['acti_id', 'acti_course_title']);*/

            } else {
                $adm_info = [];
                $account_info = [];
                $bad_crop = 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'] = $page_size;        //一页显示多少个
            $data_info['data'] = $list_items;                        //返回数据
            $count = self::getCount($user_info,$search_data);
            $data_info['showcount'] = self::getStatusBar(true,$shop_id); //状态
            //获取top按钮
            $top_button = CommonService::getTopButton('export',[],$list_button);
            $data_info['button_list'] = $top_button;
        /*} else {
            $data_info['data'] = [];
            $list_button = [];
            $count['recpay_receivable_price'] = 0;//应收金额
            $count['recpay_actual_price'] = 0;//实收金额
            $count['recpay_arrears_price'] = 0;//欠收金额
            $count['recpay_cost_price'] = 0;//成本价
            $count['recpay_receivable_pay'] = 0;//应付金额
            $count['recpay_actual_pay'] = 0;//实付金额
            $count['recpay_profit'] = 0;//盈利金额
        }*/

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'all_count'=>$count]);

    }

    /*---------------------------------------------------------------------------------
     * @name 获取顶部状态栏
     * @param string $type 查询数据类型
     * @retrun /multitype:array
     * @author dou 2023-06-06 006 下午 3:45:04
     * |---------------------------------------------------------------------------------
     */
    public static function getStatusBar ( $type = false,$shop_id){
        $showcount = [
            ['showname' => "全部", 'shownum' => '0','recpay_state'=>0],
            ['showname' => "未确认", 'shownum' => '0','recpay_state'=>1],
            ['showname' => "已确认", 'shownum' => '0','recpay_state'=>2],
            ['showname' => "作废", 'shownum' => '0','recpay_state'=>3]
        ];
        if($type){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = self::getStatusNum($v['recpay_state'],$shop_id);
            }
        }
        return $showcount;
    }

    /**
     * 获取指定状态订单数量
     * @param string $status 状态栏参数
     * @return /multitype:array
     * @author dou 2023-06-06 006 下午 3:45:04
     */
    public static function getStatusNum ( $status,$shop_id ){
        if(in_array($status,[1,2,3])){
            $db = new ReceivablePayModels();
            $where['recpay_state'] = $status;
            $where['recpay_shop_id'] = $shop_id;
            $where['recpay_order_state_noteq'] = 3;
            /*$where[] = ['recpay_state', $status];
            $where[] = ['recpay_shop_id', $shop_id];
            $where[] = ['recpay_order_state', '!=', 3];*/
            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }

    /*
     * @name 计算应收应付
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/7/25 15:43
     *
    */
    public static function getCount($user_info,$search_data){
        $shop_id = $user_info->adm_shop_id;
        if( isset($search_data['recpay_client_id']) && $search_data['recpay_client_type'] == 2 && $search_data['recpay_client_id'] > 0){
            $account_unit_id = DB::table('business_account')
                ->where('buac_bucl_id', $search_data['recpay_client_id'])
                ->select('buac_id')
                ->get()->toArray();
            $all_account_ids = array_column($account_unit_id,'buac_id');
            $search_data['all_account_ids'] = $all_account_ids;
        }
        // 实际金额最小钱数
        if (!empty($search_data['min_price'])) {
            $search_data['min_price'] = $search_data['min_price'] * 100;
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            $search_data['max_price'] = $search_data['max_price'] * 100;
        }
        $list_data = DB::table('receivable_pay as recr')
            ->leftJoin('order as o', 'o.ord_id', '=', 'recr.recpay_original_id')
            ->where('recpay_cid', $user_info->adm_cid)
            ->where('recpay_shop_superior_id', $shop_id)
            ->where('recpay_order_state', '!=',3)
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('recpay_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('recpay_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('recpay_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //状态：1未确认2已确认3已作废
                if (!empty($search_data['recpay_state'])) {
                    $query->where('recpay_state', $search_data['recpay_state']);
                }else{
                    $query->where('recpay_state', '<>',3);
                }
            })
            ->where(function ($query) use ($search_data) { //单号
                if (!empty($search_data['recpay_original_number'])) {
                    $query->where('recpay_original_number', 'like', '%' . $search_data['recpay_original_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //单位名称
                if (!empty($search_data['recpay_client_name'])) {
                    $query->where('recpay_client_name', $search_data['recpay_client_name']);
                }
            })
            ->where(function ($query) use ($search_data) { //结款人
                if (!empty($search_data['recr_settle_id'])) {
                    $query->where('recr_settle_id', $search_data['recr_settle_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户类型
                if(isset($search_data['recpay_client_type']) && $search_data['recpay_client_type'] == 0){
                    $query->where('recpay_client_type', 0);
                }
                if (!empty($search_data['recpay_client_type'])) {
                    if ($search_data['recpay_client_type'] == 1) {
                        $client_type = [1, 4];
                        $query->whereIn('recpay_client_type', $client_type);
                        if(isset($search_data['recpay_client_id']) && !empty($search_data['recpay_client_id'])){
                            $query->where('recpay_client_id', $search_data['recpay_client_id']);
                        }
                    } else if ($search_data['recpay_client_type'] == 2 && isset($search_data['all_account_ids']) && !empty($search_data['all_account_ids'])){
                        $query->where('recpay_client_type', 2);
                        $query->whereIn('recpay_client_id', $search_data['all_account_ids']);
                    }else if($search_data['recpay_client_type'] == 2){
                        $query->where('recpay_client_type', 2);
                    }

                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['recpay_remark'])) {
                    $query->where('recpay_remark', 'like', '%' . $search_data['recpay_remark'] . '%');
                }
            })
            /*->where(function ($query) use ($search_data) { //开单时间(单子的创建时间)
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_times']) && !empty($search_data['end_times'])) {
                    $query->whereBetween('recr_order_time', [$search_data['start_times'], $search_data['end_times'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_times'])) {
                        $query->where('recr_order_time', '>=', $search_data['start_times']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_times'])) {
                            $query->where('recr_order_time', '<=', $search_data['end_times'] . ' 23:59:59');
                        }
                    }
                }
            })*/
            /*->where(function ($query) use ($search_data) { //客户单位id
                if (!empty($search_data['recpay_client_id'])) {
                    $query->where('recpay_client_id', $search_data['recpay_client_id']);
                }
            })*/
            ->where(function ($query) use ($search_data) { //实际金额区间搜索
                // 如果选择最小钱数并且选择最大钱数
                if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                    $query->whereBetween('recpay_profit', [$search_data['min_price'], $search_data['max_price']]);
                } else {
                    // 如果选择最小钱数
                    if (!empty($search_data['min_price'])) {
                        $query->where('recpay_profit', '>=', $search_data['min_price']);
                    } else {
                        // 如果选择最大钱数
                        if (!empty($search_data['max_price'])) {
                            $query->where('recpay_profit', '<=', $search_data['max_price']);
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //金额正负：1正值2负值
                if (!empty($search_data['recpay_plus_minus'])) {
                    $query->where('recpay_plus_minus', $search_data['recpay_plus_minus']);
                }
            })
            ->select('recpay_id', 'recpay_receivable_price', 'recpay_actual_price', 'recpay_arrears_price', 'recpay_cost_price', 'recpay_actual_pay', 'recpay_profit','recpay_plus_minus','recpay_receivable_pay','recpay_zero_price')
            ->get()->toArray();
        $ret['recpay_receivable_price'] = 0;//应收金额
        $ret['recpay_actual_price'] = 0;//实收金额
        $ret['recpay_arrears_price'] = 0;//欠收金额
        $ret['recpay_cost_price'] = 0;//成本价
        $ret['recpay_receivable_pay'] = 0;//应付金额
        $ret['recpay_actual_pay'] = 0;//实付金额
        $ret['recpay_profit'] = 0;//盈利金额
        $ret['recpay_zero_price'] = 0;//抹零金额
            foreach ($list_data as $key => $value){
                $ret['recpay_receivable_price'] += $value->recpay_receivable_price / 100;//应收金额
                $ret['recpay_actual_price'] += $value->recpay_actual_price / 100;//实收金额
                $ret['recpay_arrears_price'] += $value->recpay_arrears_price / 100;//欠收金额
                $ret['recpay_cost_price'] += $value->recpay_cost_price / 100;//成本价
                $ret['recpay_receivable_pay'] += $value->recpay_receivable_pay / 100;//应付金额
                $ret['recpay_actual_pay'] += $value->recpay_actual_pay / 100;//实付金额
                $ret['recpay_zero_price'] += $value->recpay_zero_price / 100;//抹零金额
                if($value->recpay_plus_minus == 2){
                    $profit = -($value->recpay_profit / 100);
                }else{
                    $profit = $value->recpay_profit / 100;
                }
                $ret['recpay_profit'] += $profit;//盈利金额
            }
        $ret['recpay_receivable_price'] = sprintf("%.2f",$ret['recpay_receivable_price']);//应收金额
        $ret['recpay_actual_price'] = sprintf("%.2f",$ret['recpay_actual_price']);//实收金额
        $ret['recpay_arrears_price'] = sprintf("%.2f",$ret['recpay_arrears_price']);//欠收金额
        $ret['recpay_cost_price'] = sprintf("%.2f",$ret['recpay_cost_price']);//成本价
        $ret['recpay_receivable_pay'] = sprintf("%.2f",$ret['recpay_receivable_pay']);//应付金额
        $ret['recpay_actual_pay'] = sprintf("%.2f",$ret['recpay_actual_pay']);//实付金额
        $ret['recpay_zero_price'] = sprintf("%.2f",$ret['recpay_zero_price']);//抹零金额
        if($ret['recpay_profit'] > 0){
            $ret['recpay_plus_minus'] = 1;//盈利正负：1正值2负值
        }else{
            $ret['recpay_plus_minus'] = 2;//盈利正负：1正值2负值
        }
        $ret['recpay_profit'] = sprintf("%.2f",$ret['recpay_profit']);//盈利金额
        return $ret;
    }

    /**
     * @name 获取状态
     */
    public static function getReceivableStatus($type = true){
        $data = [['type'=>1,'name'=>'未确认'],['type'=>'2','name'=>'已确认'],['type'=>'3','name'=>'已作废']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**
     * @name 获取状态
     */
    public static function getReceivableType($type = true){
        $data = [['type'=>1,'name'=>'订单收款'],['type'=>'2','name'=>'充值卡']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /*
     * @name 列表页
     * @param array $search_data
     * @retrun array
     * @author Ma 2023/8/9 16:02
     *
    */
    public static function export($search_data){
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($search_data['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 (!empty($search_data['recpay_original_number']) || !empty($search_data['recpay_client_id']) || !empty($search_data['recpay_settle_id']) || !empty($search_data['start_time']) || !empty($search_data['end_time']) || !empty($search_data['recpay_client_type']) || !empty($search_data['recpay_acti_id']) || !empty($search_data['recpay_remark']) || !empty($search_data['start_times']) || !empty($search_data['end_times']) || !empty($search_data['max_price']) || !empty($search_data['min_price'])) {

        if( isset($search_data['recpay_client_id']) && $search_data['recpay_client_type'] == 2 && $search_data['recpay_client_id'] > 0){
            $account_unit_id = DB::table('business_account')
                ->where('buac_bucl_id', $search_data['recpay_client_id'])
                ->select('buac_id')
                ->get()->toArray();
            $all_account_ids = array_column($account_unit_id,'buac_id');
            $search_data['all_account_ids'] = $all_account_ids;
        }
        // 实际金额最小钱数
        if (!empty($search_data['min_price'])) {
            $search_data['min_price'] = $search_data['min_price'] * 100;
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            $search_data['max_price'] = $search_data['max_price'] * 100;
        }
        DB::connection()->enableQueryLog();#开启执行日志
        $list_data = DB::table('receivable_pay as recr')
            ->leftJoin('order as o', 'o.ord_id', '=', 'recr.recpay_original_id')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'o.ord_id')
            ->where('recpay_cid', $user_info->adm_cid)
            ->where('recpay_shop_superior_id', $shop_id)
            ->where('recpay_order_state', '!=',3)
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('recpay_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('recpay_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('recpay_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //状态：1未确认2已确认3已作废
                if (!empty($search_data['recpay_state'])) {
                    $query->where('recpay_state', $search_data['recpay_state']);
                }else{
                    $query->where('recpay_state', '<>',3);
                }
            })
            ->where(function ($query) use ($search_data) { //单号
                if (!empty($search_data['recpay_original_number'])) {
                    $query->where('recpay_original_number', 'like', '%' . $search_data['recpay_original_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //单位名称
                if (!empty($search_data['recpay_client_name'])) {
                    $query->where('recpay_client_name', $search_data['recpay_client_name']);
                }
            })
            ->where(function ($query) use ($search_data) { //结款人
                if (!empty($search_data['recr_settle_id'])) {
                    $query->where('recr_settle_id', $search_data['recr_settle_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //客户类型
                if(isset($search_data['recpay_client_type']) && $search_data['recpay_client_type'] == 0){
                    $query->where('recpay_client_type', 0);
                }
                if (!empty($search_data['recpay_client_type'])) {
                    if ($search_data['recpay_client_type'] == 1) {
                        $client_type = [1, 4];
                        $query->whereIn('recpay_client_type', $client_type);
                        if(isset($search_data['recpay_client_id']) && !empty($search_data['recpay_client_id'])){
                            $query->where('recpay_client_id', $search_data['recpay_client_id']);
                        }
                    } else if ($search_data['recpay_client_type'] == 2 && isset($search_data['all_account_ids']) && !empty($search_data['all_account_ids'])){
                        $query->where('recpay_client_type', 2);
                        $query->whereIn('recpay_client_id', $search_data['all_account_ids']);
                    }else if($search_data['recpay_client_type'] == 2){
                        $query->where('recpay_client_type', 2);
                    }

                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['recpay_remark'])) {
                    $query->where('recpay_remark', 'like', '%' . $search_data['recpay_remark'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //实际金额区间搜索
                // 如果选择最小钱数并且选择最大钱数
                if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                    $query->whereBetween('recpay_profit', [$search_data['min_price'], $search_data['max_price']]);
                } else {
                    // 如果选择最小钱数
                    if (!empty($search_data['min_price'])) {
                        $query->where('recpay_profit', '>=', $search_data['min_price']);
                    } else {
                        // 如果选择最大钱数
                        if (!empty($search_data['max_price'])) {
                            $query->where('recpay_profit', '<=', $search_data['max_price']);
                        }
                    }
                }
            })
            ->where(function ($query) use ($search_data) { //金额正负：1正值2负值
                if (!empty($search_data['recpay_plus_minus'])) {
                    $query->where('recpay_plus_minus', $search_data['recpay_plus_minus']);
                }
            })
            ->select('recpay_original_number', 'recpay_type', 'recpay_create_time', 'recpay_client_type', 'recpay_client_id', 'recpay_client_name' ,'recpay_receivable_price','recpay_arrears_price','recpay_actual_price','recpay_cost_price','recpay_receivable_pay','recpay_zero_price','recpay_plus_minus','recpay_profit','recpay_state','recpay_source','recpay_orcl_id','ord_orcl_id','ord_type','orcl_business_name','ord_address_type')
            ->orderBy('recpay_id', 'desc')
            /*->offset(0)
            ->limit(5000)*/
            ->get()->toArray();
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $excel = new CommonController();
        $amp_id = $search_data['amp_id']??0;
        return $excel->getExcelOut($amp_id,$user_info,$search_data['pri_id'], $sqls, $search_data['api_token']);
        $status_names = self::getReceivableStatus();
        $type_names = self::getReceivableType();
        $client_type = self::getRecpayClientTypeName(true);
        if($list_data){
             foreach ($list_data as $key => $value){
                 $list_data[$key]->recpay_type_name = $type_names[$value->recpay_type];
                 if($value->recpay_source == 5 || $value->recpay_client_type == 6){//如果是智配，调用户信息
                     if($value->recpay_source == 5){
                         $orcl_id = $value->recpay_orcl_id;
                     }else{
                         $orcl_id = $value->ord_orcl_id;
                         $value->recpay_client_type = $value->ord_type;
                     }
                     $cl_name = DB::table('order_client')
                         ->where('orcl_id', $orcl_id)
                         ->value('orcl_name');
                     $list_data[$key]->recpay_client_name = $cl_name;
                 }
                 $list_data[$key]->recpay_zero_price = $value->recpay_zero_price / 100;//抹零金额
                 if($value->recpay_plus_minus == 2){
                     $list_data[$key]->recpay_profit = -($value->recpay_profit / 100);//盈利金额
                 }else{
                     $list_data[$key]->recpay_profit = $value->recpay_profit / 100;//盈利金额
                 }
                 $list_data[$key]->recpay_client_type_name = $client_type[$list_data[$key]->recpay_client_type];
                 $list_data[$key]->recpay_state_name = $status_names[$value->recpay_state];
                 $one_arr['recpay_original_number'] = $value->recpay_original_number;//单号
                 $one_arr['recpay_type_name'] = $value->recpay_type_name;//类型
                 $one_arr['recpay_create_time'] = $value->recpay_create_time;//创建时间
                 $one_arr['recpay_client_type_name'] = $value->recpay_client_type_name;//会员类型
                 $one_arr['recpay_client_name'] = $value->recpay_client_name;//会员名称
                 $one_arr['recpay_receivable_price'] = $value->recpay_receivable_price / 100;//欠收金额
                 $one_arr['recpay_arrears_price'] = $value->recpay_arrears_price / 100;//欠收金额
                 $one_arr['recpay_actual_price'] = $value->recpay_actual_price / 100;//实收金额
                 $one_arr['recpay_cost_price'] = $value->recpay_cost_price / 100;//成本
                 $one_arr['recpay_receivable_pay'] = $value->recpay_receivable_pay / 100;//绩效
                 $one_arr['recpay_zero_price'] = $value->recpay_zero_price;//抹零
                 $one_arr['recpay_profit'] = $value->recpay_profit;//盈利
                 $one_arr['recpay_state_name'] = $value->recpay_state_name;//状态
                 if($value->ord_address_type == 2) {
                     $one_arr['orcl_business_name'] = $value->orcl_business_name;//施工门店
                 }else{
                     $one_arr['orcl_business_name'] = '本店施工';
                 }
                 $ret_arr['data'][] = $one_arr;
             }
        }

        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $where['field_name'] = ['单号', '类型', '创建时间', '会员类型', '会员名称', '应收金额', '欠收金额', '实收金额', '成本', '绩效', '抹零', '盈利', '状态','施工门店'];
        $where['action_name'] = '应收应付';

        $streamFileRand = '应收应付'. rand(10000, 99999) . '.xls';
        $streamFilename = $pathName . '/' . $streamFileRand;
        // 调用导出的公共方法
        Common::headExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $ret_arr      //导出数据
        );
        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($pathName)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }
}

