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

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountControl\VerifyReceivableBillController;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\AccountTitle;
use App\Http\Models\Api\AccountSubject;

// 财务系统 -- 应收应付
class receivableBillController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

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

        $search_data = $request->all();
        if (!empty($search_data['recr_original_number']) || !empty($search_data['recr_client_id']) || !empty($search_data['recr_settle_id']) || !empty($search_data['start_time']) || !empty($search_data['end_time']) || !empty($search_data['recr_client_type']) || !empty($search_data['recr_acti_id']) || !empty($search_data['recr_remark']) || !empty($search_data['start_times']) || !empty($search_data['end_times']) || !empty($search_data['max_price']) || !empty($search_data['min_price'])) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

            // 实际金额最小钱数
            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_credit as recr')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_belongs_id', '=', 0)
                ->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_id', 'recr_original_id', 'recr_original_number', 'recr_type', 'recr_client_name', 'recr_settle_price', 'recr_settle_time', 'recr_acti_id', 'recr_actual_price', 'recr_state', 'recr_settle_id', 'recr_remark', 'recr_zero_price', 'recr_yet_receipt', 'recr_abort_time', 'recr_client_id', 'recr_client_type', 'recr_plus_minus', 'recr_number_id', 'recr_account_type', 'recr_leisurely_type', 'recr_create_time', 'recr_order_time')
                ->orderBy('recr_id', 'desc')
                ->paginate($this->show_count);
            $list_items = $list_data->items();
            if ($list_items) {
                $recr_client_id = array_unique(array_column($list_items, 'recr_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, 'recr_original_id'));
                $rec_ord_number = array_unique(array_column($list_items, 'recr_original_number'));
                $work_order = DB::table('work_order as wor')
                    ->leftjoin('receivable_credit as recr', 'recr.recr_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('recr_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) {
                    $settle_id[] = $value->recr_settle_id; //结款人id
                    $acti_id[] = $value->recr_acti_id; //科目管理id

                    unset($list_items[$key]->recr_number_id);
                    if ($value->recr_settle_time == '0000-00-00 00:00:00') {
                        $list_items[$key]->recr_settle_time = '';
                    } else {
                        $list_items[$key]->recr_settle_time = substr($list_items[$key]->recr_settle_time, 0, 10);
                    }
                    if (strpos($value->recr_original_number, 'G') === 0) {
                        $orre_wor = DB::table('order_remarks')
                            ->where('orre_wor_id', $value->recr_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->recr_original_number, 'D') === 0) {
                        $orre_order = DB::table('order_remarks')
                            ->where('orre_ord_id', $value->recr_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]->recr_remarks = array_merge($orre_order, $orre_wor);
                    // 客户单位名称
                    if (isset($channel[$value->recr_client_id])) {
                        $list_items[$key]->recr_client_name = $channel[$value->recr_client_id];
                    } else {
                        $list_items[$key]->recr_client_name = $value->recr_client_name;
                    }
                    // 订单单号
                    if (isset($wor_order_number[$value->recr_original_id])) {
                        $list_items[$key]->order_number = $wor_order_number[$value->recr_original_id];
                    } else {
                        $list_items[$key]->order_number = '';
                    }
                    if (empty($value->recr_number_id)) {
                        $list_items[$key]->recr_original_id = 0;
                    }
                }

                $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'] = $this->show_count;        //一页显示多少个
            $data_info['data'] = $list_items;                        //返回数据
            $data_info['adm_info'] = $adm_info;                      //结款人数据
            $data_info['account_info'] = $account_info;              //会计科目数据
            $data_info['bad_crop_price'] = $bad_crop;              //欠收总额
        } else {
            $data_info['data'] = [];
        }

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
    }

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

        if ($request['type'] == 1) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'YSK' . rand(10, 99) . time() . rand(10000, 99999)]);
        }

        DB::beginTransaction();

        $actual_price = $request['recr_actual_price'] * 100; //实收金额

        // 生成应收账单
        $createBill = ReceivableBill::create(
            $user_info, //用户信息
            2, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
            0, //应收账款id
            0, //原始id(无)
            $request['recr_original_number'], //应收账款单号/原始号(账单编号)
            2, //客户类型：1.门店零售 2.来往单位
            $request['recr_client_id'], //会员id/来往单位id
            $request['recr_client_name'], //来往单位名称
            $actual_price, //结算金额
            $request['recr_settle_time'], //结款时间
            $request['recr_acti_id'], //会计科目id
            $actual_price, //实际金额
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            '',  //备注
            0,   //已收金额
            $request['recr_abort_time'], //截止时间
            2, //金额正负：1正值2负值
            8, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
            1, //是否合并代收：1是2否
            date('Y-m-d H:i:s')
        );

        // 添加预收款的原始id
        $edit_data['recr_original_id'] = $createBill;
        $edit_data['recr_update_time'] = date('Y-m-d H:i:s');
        $recr_res = DB::table('receivable_credit')
            ->where('recr_id', $createBill)
            ->where('recr_type', 2)
            ->update($edit_data);

        // 添加结款明细记录
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,            // [用户信息]
            6,                     // [单据类型1订单2订单账单3工单账单4采购账单5销售账单6预收款]
            $createBill,           // [与单据类型对应的id]
            $request['recr_original_number'],          // [与单据类型对应的单号]
            2,                     // [买家类型1门店零售2来往单位]
            $request['recr_client_id'],    // [会员/客户id]
            $request['recr_client_name'],  // [来往单位名称]
            $request['recr_acti_id'],      // [会计科目id]
            1,                             // [类型1收入2支出]
            $actual_price,            // [实际金额](此次的实收金额)
            $actual_price,            // [合计金额](此次的应收金额)
            0,                        // [欠收金额](此次结款后还应收金额)
            0,                        // [抹零金额]
            '',                        // [备注]
            0,                        // [结款类型1.抹零 2.分期结款 3.预收款抵账4正常]
            date('Y-m-d H:i:s') // [创建时间]
        );

        if ($createBill && $recr_res && $AccountingSettlement) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '应收应付', '新增预收款', $request['recr_original_number'] . '新增预收款成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增预收款成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增预收款失败']);
        }
    }

    // 编辑预收款截止时间
    public function editTime(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReceivableBillController;
        $error_message = $verify_data->editTimeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $credit_data = DB::table('receivable_credit')
            ->where('recr_id', $request['recr_id'])
            ->first(['recr_type', 'recr_original_number']);
        if (empty($credit_data)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'当前预收款不存在']);
        }
        if ($credit_data->recr_type != 2) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'当前单据不是预收款类型']);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $update_data['recr_abort_time'] = $request['recr_abort_time']; //截止时间
        $update_data['recr_update_time'] = date('Y-m-d H:i:s'); //更新时间
        $update_credit = DB::table('receivable_credit')
            ->where('recr_id', $request['recr_id'])
            ->update($update_data);

        if ($update_credit) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '应收应付', '编辑预收款', $credit_data->recr_original_number . ' 编辑预收款成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑预收款成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑预收款失败']);
        }
    }

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

        $credit_data = DB::table('receivable_credit')
            ->where('recr_id', $request['recr_id'])
            ->select('recr_create_time', 'recr_original_number', 'recr_account_type', 'recr_client_name', 'recr_settle_price', 'recr_actual_price', 'recr_zero_price', 'recr_yet_receipt', 'recr_plus_minus', 'recr_original_id', 'recr_zero_plus_minus')
            ->first();
        if (empty($credit_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前应收账款不存在']);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if ($request['type'] == 1) {
            // 预收款结款记录
            $find_data = DB::table('receivable_details as a')
                ->leftJoin('receivable_credit as b', 'b.recr_id', '=', 'a.rede_recr_id')
                ->where('rede_advance_id', $request['recr_id'])
                ->get(['rede_acset_id']);
            $find_data = json_decode(json_encode($find_data), true);
            $rede_acset_id = array_column($find_data, 'rede_acset_id');

            $record_data = DB::table('accounting_settlement as a')
                ->leftJoin('admin as b', 'b.adm_id', '=', 'a.acset_adm_id')
                // ->leftJoin('account_title as c', 'c.acti_id', '=', 'a.acset_acti_id')
                ->where('acset_adm_cid', $user_info->adm_cid)
                ->where('acset_superior_shop_id', $shop_id)
                ->whereIn('acset_id', $rede_acset_id)
                ->get([
                    'acset_number', 'acset_original_number', 'acset_payment_type', 'acset_state',
                    'adm_name', 'acset_actual_price', 'acset_create_time', 'acset_with_time', 'acset_acti_id', 'acset_type'
                ]);
            if (!empty($record_data)) {
                foreach ($record_data as $key => $value) {
                    // 预收款抵账
                    if ($value->acset_payment_type == 3 && $value->acset_type != 3) {
                        $course_title = DB::table('receivable_credit')
                            ->where('recr_id', $value->acset_acti_id)
                            ->value('recr_original_number');
                        $record_data[$key]->acti_course_title = '预收款抵账(' . $course_title . ')';
                    } else {
                        $record_data[$key]->acti_course_title = DB::table('account_title')
                            ->where('acti_id', $value->acset_acti_id)
                            ->value('acti_course_title');
                    }
                }
            }
        } else {
            switch ($credit_data->recr_account_type) {
                case 5: //5订单账单
                    $acset_type = 2;
                    break;
                case 6: // 6工单账单
                    $acset_type = 3;
                    break;
                case 7: // 7销售账单
                    $acset_type = 5;
                    break;
            }

            // // 预收款结款记录
            // $find_data = DB::table('receivable_details as a')
            //         ->leftJoin('receivable_credit as b', 'b.recr_id', '=', 'a.rede_recr_id')
            //         ->where('rede_recr_id', $request['recr_id'])
            //         ->get(['rede_acset_id']);

            $find_data = DB::table('money_record')
                ->where('more_recr_id', $request['recr_id'])
                ->get(['more_acset_id']);
            $find_data = json_decode(json_encode($find_data), true);
            $rede_acset_id = array_column($find_data, 'more_acset_id');

            // 账单收款记录
            $record_data = DB::table('accounting_settlement as a')
                ->leftJoin('admin as b', 'b.adm_id', '=', 'a.acset_adm_id')
                // ->leftJoin('account_title as c', 'c.acti_id', '=', 'a.acset_acti_id')
                ->where('acset_adm_cid', $user_info->adm_cid)
                ->where('acset_superior_shop_id', $shop_id)
                // ->where('acset_type', $acset_type)//  单据类型1订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款
                // ->where('acset_original_id', $credit_data->recr_original_id)
                ->whereIn('acset_id', $rede_acset_id)
                ->select('acset_number', 'acset_original_number', 'acset_payment_type', 'acset_state', 'adm_name', 'acset_actual_price', 'acset_create_time', 'acset_with_time', 'acset_acti_id', 'acset_type')
                ->get()->toArray();
            if (!empty($record_data)) {
                foreach ($record_data as $key => $value) {
                    // 预收款抵账
                    if ($value->acset_payment_type == 3 && $value->acset_type != 3) {
                        $course_title = DB::table('receivable_credit')
                            ->where('recr_id', $value->acset_acti_id)
                            ->value('recr_original_number');
                        $record_data[$key]->acti_course_title = '预收款抵账(' . $course_title . ')';
                    } else {
                        $record_data[$key]->acti_course_title = DB::table('account_title')
                            ->where('acti_id', $value->acset_acti_id)
                            ->value('acti_course_title');
                    }
                }
            }
        }

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

    // 应收账款详情列表验证器
    public function particulars(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReceivableBillController;
        $error_message = $verify_data->particularsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $recr_type = DB::table('receivable_credit')
            ->where('recr_id', $request['recr_id'])
            ->first(['recr_type']);
        $search_data = $request->all();
        $list_data = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_number_id', $search_data['recr_id'])
            ->where('recr_id', '!=', $search_data['recr_id'])
            ->where(function ($query) use ($recr_type) {
                if ($recr_type->recr_type != 9) {
                    $query->where('recr_type', $recr_type->recr_type);
                }
            }) //单号
            ->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) {
                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', 'like', '%' . $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'])) {
                    $query->where('recr_client_type', $search_data['recr_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'] . '%');
                }
            }) //备注
            ->select('recr_id', 'recr_original_number', 'recr_account_type', 'recr_client_name', 'recr_settle_price', 'recr_settle_id', 'recr_remark', 'recr_client_type', 'recr_plus_minus', 'recr_original_id')
            ->orderBy('recr_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();

        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $settle_id[] = $value->recr_settle_id; //结款人id
                if (strpos($value->recr_original_number, 'G') === 0) {
                    $list_items[$key]->recr_remarks = DB::table('order_remarks')
                        ->where('orre_wor_id', $value->recr_original_id)
                        ->select('orre_content', 'orre_time', 'orre_create_adm_name')
                        ->orderBy('orre_id')
                        ->get();
                }
                if (strpos($value->recr_original_number, 'D') === 0) {
                    $list_items[$key]->recr_remarks = DB::table('order_remarks')
                        ->where('orre_ord_id', $value->recr_original_id)
                        ->select('orre_content', 'orre_time', 'orre_create_adm_name')
                        ->orderBy('orre_id')
                        ->get();
                }
            }
            // 查找结款人
            $adm_info = DB::table('admin')
                ->whereIn('adm_id', $settle_id)
                ->get(['adm_id', 'adm_name']);
        } else {
            $adm_info = [];
        }
        $total_data = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_id', $request['recr_id'])
            ->select('recr_settle_price', 'recr_actual_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_zero_plus_minus')
            ->first();

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据
        $data_info['adm_info'] = $adm_info;                      //结款人数据
        $data_info['total_data'] = $total_data;                   //搜索统计数据

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

    // 收款  还款
    public function leisurely(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReceivableBillController;
        $error_message = $verify_data->leisurelyValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $find_recr = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_id', $request['recr_id'])
            ->select('recr_account_type', 'recr_original_id', 'recr_original_number', 'recr_client_type', 'recr_client_id', 'recr_client_name', 'recr_settle_price', 'recr_leisurely_type', 'recr_type')
            ->first();

        DB::beginTransaction();
        if ($request['type'] == 1) {
            // recr_account_type 显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款
            // 收款
            if ($find_recr->recr_account_type != 3) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是委托代收的应收账款，无法操作！']);
            }
            // recr_leisurely_type 订单代收状态：0待收款 1收款待核对 2收款已核对/待还款 3还款待核对 4还款已核对
            if ($find_recr->recr_leisurely_type != 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前应收账款已经申请收款！']);
            }
            // recr_type 11加盟店订单收款，加盟店的订单收款，应该是向加盟店支付金额，是支出
            if ($find_recr->recr_type == 11) {
                $find_acti = DB::table('account_title')
                    ->where('acti_id', $request['acti_id'])
                    ->select('acti_closing_account')
                    ->first();
                // if ($find_recr->recr_settle_price > $find_acti->acti_closing_account) {
                //     return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前科目余额不足，无法向加盟店付款！']);
                // }
                $acset_add_data['acset_inex_type'] = 2; //类型1收入2支出
                $acset_add_data['acset_payment_type'] = 5; //收款
                $acset_add_data['acset_type'] = 16; //16加盟店订单收款
            } else {
                $acset_add_data['acset_inex_type'] = 1; //类型1收入2支出
                $acset_add_data['acset_payment_type'] = 5; //收款
                $acset_add_data['acset_type'] = 12; //12工单代收
            }

            $types = '收款';
            $recr_edit_data['recr_leisurely_type'] = 1;

            $ord_res = DB::table('work_order')
                ->where('wor_id', $find_recr->recr_original_id)
                ->update(['wor_collection_price' => 0, 'wor_update_time' => date('Y-m-d H:i:s')]);
        } else {
            // 还款
            if (!in_array($find_recr->recr_account_type, [1, 2, 10])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前应收账款不允许申请收款操作！']);
            }
            if ($find_recr->recr_leisurely_type > 2) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前应收账款已经申请还款！']);
            }

            $find_acti = DB::table('account_title')
                ->where('acti_id', $request['acti_id'])
                ->select('acti_closing_account')
                ->first();
            // if ($find_recr->recr_settle_price > $find_acti->acti_closing_account && $find_recr->recr_type != 12) {
            //     return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前科目余额不足，无法申请还款！']);
            // }

            $types = '还款';
            // recr_type 12加盟店订单代收，结款明细应该是收入
            if ($find_recr->recr_type == 12) {
                $acset_add_data['acset_inex_type'] = 1; //类型1收入2支出
            } else {
                // 其他类型的结款明细是支出
                $acset_add_data['acset_inex_type'] = 2; //类型1收入2支出
            }
            $acset_add_data['acset_payment_type'] = 6; //还款
            if ($find_recr->recr_account_type == 2) {
                // acset_type 单据类型1订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款9订单代收10采购入库单预付款11订单退款12工单代收13订单完成后结算14非实物开单15.订单冲单16.加盟店订单收款17.加盟店订单代收18.工单结算19.旧货回收20售后单结算21销售出库单22采购单23采购退货单24采购款到发货(预付款)25批量结算26期初账单
                if ($find_recr->recr_type == 12) {
                    $acset_add_data['acset_type'] = 17; //17加盟店订单代收
                } else {
                    $acset_add_data['acset_type'] = 9; //订单代收
                }
            } elseif ($find_recr->recr_account_type == 1) {
                $acset_add_data['acset_type'] = 1; //订单结算
                $ord_edit_data['ord_state'] = 4; //结算状态1未结算2已结算3已核销4已收款
            } else {
                $acset_add_data['acset_type'] = 11; //订单退款
                $ord_edit_data['ord_state'] = 4; //结算状态1未结算2已结算3已核销4已收款
            }

            $recr_edit_data['recr_leisurely_type'] = 3;

            // 订单应收账款申请还款，对应的订单的代收金额应该改为0
            $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
            $ord_edit_data['ord_collection_price'] = 0;
            $ord_res = DB::table('order')
                ->where('ord_id', $find_recr->recr_original_id)
                ->update($ord_edit_data);
        }

        // 结款明细表新增数据
        $acset_add_data['acset_adm_cid'] = $user_info->adm_cid; //公司id
        $acset_add_data['acset_shop_id'] = $user_info->adm_shop_id; //门店id
        $acset_add_data['acset_superior_shop_id'] = $shop_id; //所属总店id
        $acset_add_data['acset_adm_id'] = $user_info->adm_id; //结款人
        $acset_add_data['acset_number'] = 'JK' . rand(100, 999) . time() . rand(10000, 99999); //    结款明细单号
        $acset_add_data['acset_original_id'] = $find_recr->recr_original_id; //与单据类型对应的id
        $acset_add_data['acset_original_number'] = $find_recr->recr_original_number; //与单据类型对应的单号
        $acset_add_data['acset_client_type'] = $find_recr->recr_client_type; //买家类型1门店零售2来往单位
        $acset_add_data['acset_client_id'] = $find_recr->recr_client_id; //会员id
        $acset_add_data['acset_client_name'] = $find_recr->recr_client_name; //来往单位名称
        $acset_add_data['acset_with_time'] = date('Y-m-d H:i:s'); //结款时间
        $acset_add_data['acset_acti_id'] = $request['acti_id']; //会计科目id
        $acset_add_data['acset_actual_price'] = $find_recr->recr_settle_price; //实际金额
        $acset_add_data['acset_price'] = $find_recr->recr_settle_price; //合计金额
        $acset_add_data['acset_owe_price'] = 0; //欠收金额
        $acset_add_data['acset_zero_price'] = 0; //抹零金额
        $acset_add_data['acset_remark'] = ''; //备注
        $acset_res = DB::table('accounting_settlement')->insertGetId($acset_add_data);

        // 修改应收账款状态
        $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
        $recr_edit_data['recr_acti_id'] = $request['acti_id'];
        $recr_update = DB::table('receivable_credit')
            ->where('recr_id', $request['recr_id'])
            ->update($recr_edit_data);
        // dump($user_info->shop_versions);
        // exit;
        // if ($user_info->shop_versions == 1) {
        //     // 判断当前结款明细是否存在
        //     $settlement_data = DB::table('accounting_settlement')
        //         ->where('acset_id', $acset_res)
        //         ->first(['acset_id', 'acset_original_number', 'acset_type', 'acset_state', 'acset_original_id', 'acset_inex_type', 'acset_actual_price', 'acset_zero_price', 'acset_acti_id', 'acset_payment_type', 'acset_merge_type', 'acset_price', 'acset_number', 'acset_zero_plus_minus', 'acset_price']);
        //     if (empty($settlement_data)) {
        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前结款明细不存在']);
        //     }
        //     if ($settlement_data->acset_state == 2) {
        //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前结款明细已核对']);
        //     }

        //     // 结款明细核对需要做的有
        //     // 1. 更改状态、汇款时间、备注
        //     $update_data['acset_state'] = 2; //状态：1未核对2已核对
        //     $update_data['acset_affirm_time'] = date('Y-m-d H:i:s'); //确认时间
        //     $update_data['acset_remit_time'] = date('Y-m-d H:i:s'); //汇款时间
        //     $update_data['acset_update_time'] = date('Y-m-d H:i:s'); //更新时间
        //     $update_data['acset_adm_id'] = $user_info->adm_id;
        //     $acset_upres = DB::table('accounting_settlement')
        //         ->where('acset_id', $acset_res)
        //         ->update($update_data);
        //     // 2. 将结款明细中的金额，在对应的科目中添加/减去，是以汇款时间为准
        //     $acti_res = AccountSubject::Subject(
        //         $user_info, //用户信息
        //         $settlement_data->acset_inex_type, //类型：1借(汇入)2贷(汇出)
        //         $settlement_data->acset_actual_price, //金额
        //         !empty($request['acti_id']) ? $request['acti_id'] : $settlement_data->acset_acti_id, //科目id
        //         date('Y-m-d H:i:s') //汇款时间
        //     );
        //     if ($acti_res['code'] == 500) {
        //         DB::rollBack();
        //         return response()->json($acti_res);
        //     } else {
        //         $acti_res = true;
        //     }
        //     // dump($settlement_data->acset_type);
        //     // exit;
        //     // 如果类型是订单代收
        //     $recr_account_type = 0;
        //     switch ($settlement_data->acset_type) {
        //         case '9': //订单代收
        //             $recr_type = 3; //订单账单
        //             $recr_account_type = 2; // 2受托代收（订单代收）
        //             break;
        //         case '12': //工单代收
        //             $recr_type = 4; //4工单账单
        //             $recr_account_type = 3; //3委托代收（工单代收）
        //             break;
        //         default:
        //             DB::rollBack();
        //             return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'核对失败1']);
        //             break;
        //     }
        //     // dump($recr_type);
        //     // exit;
        //     if ($recr_type == 3) {
        //         $type = DB::table('receivable_credit')
        //             ->where('recr_original_id', $settlement_data->acset_original_id)
        //             ->where('recr_original_number', $settlement_data->acset_original_number)
        //             ->where('recr_account_type', 2)
        //             ->value('recr_leisurely_type');
        //         if ($type == 1) {
        //             $type = 2;
        //         }
        //         if ($type == 3) {
        //             $type = 4;
        //         }
        //         $leisurely_data['recr_leisurely_type'] = $type;
        //         $leisurely_data['recr_update_time'] = date('Y-m-d H:i:s');
        //         // 如果等于4把状态改为消核
        //         if ($type == 4) {
        //             $leisurely_data['recr_state'] = 2;
        //         }
        //         $recr_res = DB::table('receivable_credit')
        //             ->where('recr_original_id', $settlement_data->acset_original_id)
        //             ->where('recr_original_number', $settlement_data->acset_original_number)
        //             ->where('recr_account_type', 2)
        //             ->update($leisurely_data);
        //         // 
        //         if ($recr_account_type == 10 || $recr_account_type == 1) {
        //             // 订单退款类型核对，或者是订单完成后结算，对应的应收账款改成已核销状态，
        //             // 对应的订单改成已核销状态
        //             if ($settlement_data->acset_merge_type == 2) {
        //                 $type = [$recr_account_type, 2];
        //             } else {
        //                 $type = [$recr_account_type];
        //             }
        //             $find_recr_data = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->whereIn('recr_account_type', $type)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->select('recr_id', 'recr_settle_price')
        //                 ->get()->toArray();
        //             foreach ($find_recr_data as $key => $value) {
        //                 $recr_update_data['recr_state'] = 2; //状态：1.未核销 2.已核销
        //                 $recr_update_data['recr_yet_receipt'] = $value->recr_settle_price; //已收金额
        //                 $recr_update_data['recr_update_time'] = date('Y-m-d H:i:s');
        //                 $recr_edit_res = DB::table('receivable_credit')
        //                     ->where('recr_id', $value->recr_id)
        //                     ->update($recr_update_data);
        //             }
        //             $ord_edit_data['ord_state'] = 3; //状态：1.未核销 2.已核销
        //             $ord_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        //             $ord_res = DB::table('order')
        //                 ->where('ord_cid', $user_info->adm_cid)
        //                 ->where('ord_superior_shop_id', $shop_id)
        //                 ->where('ord_id', $settlement_data->acset_original_id)
        //                 ->where('ord_order_number', $settlement_data->acset_original_number)
        //                 ->update($ord_edit_data);
        //             if ($recr_edit_res && $ord_res) {
        //                 $recr_res = true;
        //             } else {
        //                 $recr_res = false;
        //             }
        //         } elseif ($recr_account_type == 2) {
        //             $recr_update_data['recr_yet_receipt'] = $settlement_data->acset_actual_price; //已收金额
        //             $recr_update_data['recr_state'] = 2; //状态：1.未核销 2.已核销
        //             $recr_update_data['recr_update_time'] = date('Y-m-d H:i:s');
        //             $recr_update_data['recr_settle_time'] = date('Y-m-d H:i:s'); //结款时间
        //             $recr_res = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', $recr_account_type)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->update($recr_update_data);
        //         } else {
        //             // 订单账单
        //             if ($recr_type == 3 && $recr_account_type == 0) {
        //                 $sequence_res = $this->checkSequence($settlement_data->acset_original_id, $request['acset_id'], 1);
        //                 if (!empty($sequence_res)) {
        //                     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请按照账单结款顺序进行确认']);
        //                 }
        //             }
        //             $not_price = 0;
        //             $recr = DB::table('receivable_credit')
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->orderBy('recr_id', 'desc')
        //                 ->select('recr_yet_receipt', 'recr_zero_price', 'recr_settle_price', 'recr_account_type', 'recr_id', 'recr_paid_price')
        //                 ->first();

        //             if ($settlement_data->acset_zero_plus_minus == 1) {
        //                 $not_price = $not_price - $settlement_data->acset_zero_price;
        //             } else {
        //                 $not_price = $not_price + $settlement_data->acset_zero_price;
        //             }
        //             $settle_price = $settlement_data->acset_actual_price + $recr->recr_paid_price + $not_price;
        //             $recr_update_data['recr_update_time'] = date('Y-m-d H:i:s');
        //             if ($settle_price == $recr->recr_settle_price || !empty($settlement_data->acset_zero_price)) {
        //                 $recr_update_data['recr_state'] = 2; //状态：1.未核销 2.已核销
        //                 $recr_update_data['recr_settle_time'] = $request['acset_with_time']; //结款时间
        //                 $recr_update_data['recr_paid_price'] = $recr->recr_settle_price; //已结金额
        //             }
        //             $recr_update_data['recr_paid_price'] = $recr->recr_paid_price + $settlement_data->acset_actual_price + $not_price;
        //             $recr_res = DB::table('receivable_credit')
        //                 ->where(function ($query) use ($recr_type, $settlement_data) {
        //                     $query->where('recr_type', $recr_type)
        //                         ->where('recr_original_id', $settlement_data->acset_original_id)
        //                         ->where('recr_original_number', $settlement_data->acset_original_number);
        //                 }) //账单相关的应收账款
        //                 ->orwhere(function ($query) use ($recr_type, $settlement_data) {
        //                     $query->where('recr_type', $recr_type)
        //                         ->where('recr_belongs_id', $settlement_data->acset_original_id);
        //                 }) //所属账单的订单应收账款
        //                 ->update($recr_update_data);
        //         }
        //     } elseif ($recr_type == 4) { //加盟店订单代收
        //         // 订单账单
        //         if ($recr_account_type == 0) {
        //             $sequence_res = $this->checkSequence($settlement_data->acset_original_id, $request['acset_id'], 1);
        //             if (!empty($sequence_res)) {
        //                 return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请按照账单结款顺序进行确认']);
        //             }
        //         }
        //         $not_price = 0;
        //         // 工单结算才会有2
        //         if ($settlement_data->acset_merge_type == 2) {
        //             $recr_update_data['recr_state'] = 2; //状态：1.未核销 2.已核销
        //             $recr_update_data['recr_settle_time'] = $request['acset_with_time']; //结款时间
        //             $recr_update_data['recr_update_time'] = date('Y-m-d H:i:s');
        //             $recr_update_data['recr_yet_receipt'] = $recr->recr_settle_price; //已收金额

        //             $recr_res = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', 4)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->update($recr_update_data);

        //             $recr_update_data['recr_leisurely_type'] = 2; //0待收款 1收款待核对
        //             $recr_res_two = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', 3)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->update($recr_update_data);
        //             if (empty($recr_res_two)) {
        //                 DB::rollBack();
        //                 return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'核对失败2']);
        //             }
        //         } elseif ($recr_account_type != 3) {
        //             $recr = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', 6)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->first(['recr_settle_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_zero_plus_minus', 'recr_paid_price']);

        //             if ($settlement_data->acset_zero_plus_minus == 1) {
        //                 $not_price = $not_price - $settlement_data->acset_zero_price;
        //             } else {
        //                 $not_price = $not_price + $settlement_data->acset_zero_price;
        //             }
        //             $settle_price = $settlement_data->acset_actual_price + $recr->recr_paid_price + $not_price;
        //             $recr_update_data['recr_update_time'] = date('Y-m-d H:i:s');

        //             if ($settle_price == $recr->recr_settle_price || !empty($settlement_data->acset_zero_price)) {
        //                 $recr_update_data['recr_state'] = 2; //状态：1.未核销 2.已核销
        //                 $recr_update_data['recr_settle_time'] = date('Y-m-d H:i:s'); //结款时间
        //                 $recr_update_data['recr_paid_price'] = $recr->recr_settle_price; //已结金额
        //             }
        //             $recr_update_data['recr_paid_price'] = $recr->recr_paid_price + $settlement_data->acset_actual_price + $not_price;
        //             $recr_update_data['recr_yet_receipt'] = $recr->recr_settle_price; //已收金额
        //             $recr_res = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', 6)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->update($recr_update_data);
        //         } else {
        //             $recr = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', 3)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->first(['recr_settle_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_zero_plus_minus', 'recr_paid_price']);
        //             if ($settlement_data->acset_zero_plus_minus == 1) {
        //                 $not_price = $not_price - $settlement_data->acset_zero_price;
        //             } else {
        //                 $not_price = $not_price + $settlement_data->acset_zero_price;
        //             }
        //             $settle_price = $settlement_data->acset_actual_price + $recr->recr_paid_price + $not_price;
        //             $recr_update_data['recr_update_time'] = date('Y-m-d H:i:s');

        //             if ($settle_price == $recr->recr_settle_price || !empty($settlement_data->acset_zero_price)) {
        //                 $recr_update_data['recr_state'] = 2; //状态：1.未核销 2.已核销
        //                 $recr_update_data['recr_settle_time'] = date('Y-m-d H:i:s'); //结款时间
        //                 $recr_update_data['recr_paid_price'] = $recr->recr_settle_price; //已结金额
        //             } else {
        //                 $recr_update_data['recr_paid_price'] = $recr->recr_paid_price + $settlement_data->acset_actual_price + $not_price;
        //             }
        //             $recr_update_data['recr_yet_receipt'] = $recr->recr_settle_price; //已收金额
        //             $recr_res = DB::table('receivable_credit')
        //                 ->where('recr_cid', $user_info->adm_cid)
        //                 ->where('recr_shop_superior_id', $shop_id)
        //                 ->where('recr_type', $recr_type)
        //                 ->where('recr_account_type', 3)
        //                 ->where('recr_original_id', $settlement_data->acset_original_id)
        //                 ->where('recr_original_number', $settlement_data->acset_original_number)
        //                 ->update($recr_update_data);
        //         }
        //     }
        // } else {
            $acset_upres = true;
            $recr_res = true;
        // }
        // exit;
        if ($acset_res && $recr_update && $ord_res && $acset_upres && $recr_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '应收应付', '申请' . $types, $find_recr->recr_original_number . '申请' . $types . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'申请' . $types . '成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'申请' . $types . '失败']);
        }
    }

    // 核对顺序
    // $type 1核对  2驳回
    public function checkSequence($recr_id, $acset_id, $type)
    {
        if ($type == 1) {
            $type = '<';
        } else {
            $type = '>';
        }
        $count = DB::table('money_record as mr')
            ->leftjoin('accounting_settlement as s', 's.acset_id', '=', 'mr.more_acset_id')
            ->where('more_orbi_id', $recr_id)
            ->where('more_acset_id', $type, $acset_id)
            ->where('acset_state', '!=', 2)
            ->count();
        return $count;
    }

    // 非实物开单
    public function nonphysical(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReceivableBillController;
        $error_message = $verify_data->nonphysicalValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 非实物开单提交之后就是已核销状态
        // 1. 生成应收账款，是已核销状态
        // 2. 生成结款明细是已核对状态
        // 3. 对应的会计科目id的金额要增加或减少

        // 如果金额是负数，判断科目剩余的期末金额是否足够减
        if ($request['recr_plus_minus'] == 2) {
            // 查询科目的期末余额
            $acti_closing_account = DB::table('account_title')
                ->where('acti_id', $request['recr_acti_id'])
                ->value('acti_closing_account');
            if (($request['recr_settle_price'] * 100) > $acti_closing_account) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'科目余额不足，无法提交']);
            }
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        DB::beginTransaction();
        // 1. 生成应收账款，是已核销状态
        $recr_original_number = 'FSW' . rand(10, 99) . time() . rand(10000, 99999); //非实物单号
        $receivable['recr_plus_minus'] = $request['recr_plus_minus'] ? $request['recr_plus_minus'] : 0; //金额正负：1正值2负值
        $receivable['recr_cid'] = $user_info->adm_cid;
        $receivable['recr_shop_id'] = $user_info->adm_shop_id;
        $receivable['recr_shop_superior_id'] = $shop_id;
        $receivable['recr_type'] = 8; //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单
        $receivable['recr_number_id'] = 0; //应收账单id
        $receivable['recr_original_id'] = 0; //与类型所对应的id
        $receivable['recr_original_number'] = $recr_original_number; //与类型所对应的单号
        $receivable['recr_account_type'] = $request['recr_account_type']; //显示类型：11发票 12价外费 13折扣金额抵货款
        $receivable['recr_client_type'] = $request['recr_client_type']; //客户类型：1.门店零售 2.来往单位
        $receivable['recr_client_id'] = $request['recr_client_id']; //会员id/来往单位id
        $receivable['recr_client_name'] = $request['recr_client_name']; //来往单位名称
        $receivable['recr_settle_price'] = $request['recr_settle_price'] * 100; //结算金额
        $receivable['recr_settle_time'] = $request['recr_settle_time']; //结款时间
        $receivable['recr_settle_id'] = $user_info->adm_id; //结款人
        $receivable['recr_acti_id'] = $request['recr_acti_id'] ? $request['recr_acti_id'] : 0; //会计科目id
        $receivable['recr_actual_price'] = $request['recr_settle_price'] * 100; //实际金额
        $receivable['recr_zero_price'] = 0; //抹零金额
        $receivable['recr_state'] = 2; //状态：1.未核销 2.已核销
        $receivable['recr_remark'] = $request['recr_remark'] ? $request['recr_remark'] : ''; //备注
        $receivable['recr_yet_receipt'] = $request['recr_settle_price'] * 100; //已收金额
        $recr_id = DB::table('receivable_credit')->insertGetId($receivable);

        if ($request['recr_acti_id'] && $request['recr_settle_price']) {
            // 2. 生成结款明细是已核对状态
            $record['acset_adm_cid'] = $user_info->adm_cid; //公司id
            $record['acset_shop_id'] = $user_info->adm_shop_id; //门店id
            $record['acset_superior_shop_id'] = $shop_id; //所属总店id
            $record['acset_adm_id'] = $user_info->adm_id; //结款人
            $record['acset_number'] = 'JK' . rand(100, 999) . time() . rand(10000, 99999); //结款明细单号
            $record['acset_type'] = 14; //单据类型12工单代收14非实物开单
            $record['acset_payment_type'] = 4; //结款类型1.抹零 2.分期结款 3.预收款抵账4正常
            $record['acset_original_id'] = $recr_id; //与单据类型对应的id，非实物开单对应的应收账款id
            $record['acset_original_number'] = $recr_original_number; //与单据类型对应的单号，非实物开单对应应收账款单号
            $record['acset_client_type'] = $request['recr_client_type']; //买家类型1门店零售2来往单位
            $record['acset_client_id'] = $request['recr_client_id']; //会员id/客户id
            $record['acset_client_name'] = $request['recr_client_name']; //来往单位名称
            $record['acset_with_time'] = date('Y-m-d H:i:s'); //结款时间
            $record['acset_remit_time'] = $request['recr_settle_time']; //汇款时间
            $record['acset_acti_id'] = $request['recr_acti_id']; //会计科目id
            $record['acset_inex_type'] = $request['recr_plus_minus']; //类型1收入2支出
            $record['acset_actual_price'] = $request['recr_settle_price'] * 100; //实际金额
            $record['acset_price'] = $request['recr_settle_price'] * 100; //合计金额
            $record['acset_owe_price'] = 0; //欠收金额
            $record['acset_zero_price'] = 0; //抹零金额
            $record['acset_state'] = 2; //状态：1未核对2已核对
            $record['acset_remark'] = $request['recr_remark'] ? $request['recr_remark'] : ''; //备注
            $record['acset_update_time'] = date('Y-m-d H:i:s'); //修改时间
            $record_add = DB::table('accounting_settlement')->insertGetId($record);

            // 3. 对应的会计科目id的金额要增加或减少
            $acti_return = AccountTitle::submitAccount(
                $user_info,
                $request['recr_plus_minus'],
                $request['recr_settle_price'] * 100,
                $request['recr_acti_id'],
                $request['recr_settle_time']
            );
            if ($acti_return['code'] == 500) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'非实物开单失败']);
            }
        } else {
            $record_add = true;
        }

        if ($recr_id && $record_add) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '应收应付', '非实物开单', $recr_original_number . '非实物开单成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'非实物开单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'非实物开单失败']);
        }
    }

    // 冲红账单按钮
    public function againstBill(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReceivableBillController;
        $error_message = $verify_data->showAgainstBillValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        if ($request['type'] == 1) {
            $search_data = $request->all();
            if (!empty($search_data['start_time']) || !empty($search_data['end_time'])) {
                $list_data = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    ->where('recr_belongs_id', '=', 0)
                    ->where('recr_state', 1)
                    ->whereNotIn('recr_account_type', [2, 3])
                    ->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) {
                        if (!empty($search_data['recr_client_type'])) {
                            $query->where('recr_client_type', $search_data['recr_client_type']);
                        }
                    }) //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
                    ->where(function ($query) use ($search_data) {
                        if (!empty($search_data['recr_client_id'])) {
                            $query->where('recr_client_id', $search_data['recr_client_id']);
                        }
                    }) //会员id/来往单位id/加盟店id
                    ->select('recr_id', 'recr_original_number', 'recr_type', 'recr_settle_price', 'recr_actual_price', 'recr_settle_id', 'recr_zero_price', 'recr_yet_receipt', 'recr_plus_minus', 'recr_original_id', 'recr_account_type', 'recr_create_time')
                    ->orderBy('recr_id', 'desc')
                    ->get();
                foreach ($list_data as $key => $value) {
                    // 欠收 = 结算金额 - 已收 - 抹零
                    $price = $value->recr_settle_price - $value->recr_yet_receipt - $value->recr_zero_price;
                    if ($price <= 0) {
                        unset($list_data[$key]);
                    } else {
                        $acset_res = DB::table('accounting_settlement')
                            ->where('acset_state', 1)
                            ->where('acset_original_number', $value->recr_original_number)
                            ->where('acset_original_id', $value->recr_original_id)
                            ->value('acset_id');
                        if (!empty($acset_res)) {
                            unset($list_data[$key]);
                        }
                    }
                }
                $list_items['data_list'] = $list_data;
                $settle_id = [];
                foreach ($list_items['data_list'] as $key => $value) {
                    $settle_id[] = $value->recr_settle_id; //结款人id
                }
                // 查找结款人
                $adm_info = DB::table('admin')
                    ->whereIn('adm_id', $settle_id)
                    ->get(['adm_id', 'adm_name']);
                $list_items['adm_info'] = $adm_info;
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_items]);
            } else {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>[]]);
            }
        }

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

        DB::beginTransaction();
        //正数
        $positive = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->whereIn('recr_id', $request['recr_id'])
            ->where('recr_state', 1)
            ->where('recr_plus_minus', 1)
            ->get(['recr_id', 'recr_type', 'recr_account_type', 'recr_settle_price', 'recr_zero_price', 'recr_original_number', 'recr_original_id']);
        $positive_num = 0;
        foreach ($positive as $key => $value) {
            $positive_num += $value->recr_settle_price - $value->recr_zero_price;
            $original_number[] = $value->recr_original_number;
            $original_id[] = $value->recr_original_id;

            //订单结算之后修改订单状态
            if ($value->recr_type == 1) {
                $order_update = DB::table('order')
                    ->where('ord_id', $value->recr_original_id)
                    ->where('ord_order_number', $value->recr_original_number)
                    ->update(['ord_state' => 3, 'ord_update_time' => date('Y-m-d H:i:s')]);
                if (!$order_update) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成冲红账单失败']);
                }
            }

            // 订单账单核对完之后修改此账单下订单状态
            if ($value->recr_type == 3) {
                // 工单审核生成的订单应收
                if ($value->recr_account_type == 1) {
                    $order_update = DB::table('order')
                        ->where('ord_id', $value->recr_original_id)
                        ->where('ord_order_number', $value->recr_original_number)
                        ->update(['ord_state' => 3, 'ord_update_time' => date('Y-m-d H:i:s')]);
                    if (!$order_update) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成冲红账单失败']);
                    }
                }
                // 订单账单的应收账款
                if ($value->recr_account_type == 5) {
                    $order_update = DB::table('order')
                        ->where('ord_orbi_id', $value->recr_original_id)
                        ->update(['ord_state' => 3, 'ord_update_time' => date('Y-m-d H:i:s')]);
                    if (!$order_update) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成冲红账单失败']);
                    }
                    $order_bill_update = DB::table('order_bill')
                        ->where('orbi_id', $value->recr_original_id)
                        ->where('orbi_number', $value->recr_original_number)
                        ->update(['orbi_state' => 2, 'orbi_update_time' => date('Y-m-d H:i:s')]);
                    if (!$order_bill_update) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成冲红账单失败']);
                    }
                }
            }
        }
        // 负数
        $minus = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->whereIn('recr_id', $request['recr_id'])
            ->where('recr_state', 1)
            ->where('recr_plus_minus', 2)
            ->get(['recr_id', 'recr_settle_price', 'recr_zero_price', 'recr_original_number', 'recr_original_id']);
        $minus_num = 0;
        foreach ($minus as $key => $value) {
            $minus_num += $value->recr_settle_price - $value->recr_zero_price;
            $original_number[] = $value->recr_original_number;
        }

        // 结款明细数据 已核对
        $acset_data = DB::table('accounting_settlement')
            ->where('acset_state', 2)
            ->whereIn('acset_original_number', $original_number)
            ->get(['acset_actual_price', 'acset_zero_price', 'acset_state']);
        $acset_num = 0;
        if (!empty($acset_data)) {
            foreach ($acset_data as $key => $value) {
                $acset_num += $value->acset_actual_price + $value->acset_zero_price;
            }
        }

        // 结款明细数据
        $acset_data = DB::table('accounting_settlement')
            ->where('acset_state', 1)
            ->whereIn('acset_original_number', $original_number)
            ->first(['acset_actual_price', 'acset_zero_price', 'acset_state']);
        if (!empty($acset_data)) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结款明细未核对的不允许冲红']);
        }
        // 正值-负值-已核对金额
        $total = $positive_num - $minus_num - $acset_num;
        if ($total < 0) {
            $plus_minus = 2;
        } else {
            $plus_minus = 1;
        }
        $total = abs($total);

        $number = 'CH' . rand(10, 99) . time() . rand(10000, 99999); //非实物单号
        $recr_data['recr_cid'] = $user_info->adm_cid;
        $recr_data['recr_shop_id'] = $user_info->adm_shop_id;
        $recr_data['recr_shop_superior_id'] = $shop_id;
        $recr_data['recr_type'] = 9;
        $recr_data['recr_account_type'] = 14;
        $recr_data['recr_original_number'] = $number;
        $recr_data['recr_client_type'] = $request['recr_client_type'];
        $recr_data['recr_client_id'] = $request['recr_client_id'];
        $recr_data['recr_client_name'] = $request['recr_client_name'];
        $recr_data['recr_settle_price'] = $total;
        $recr_data['recr_settle_time'] = date('Y-m-d H:i:s'); //结款时间
        $recr_data['recr_settle_id'] = $user_info->adm_id; //结款人
        $recr_data['recr_actual_price'] = $total; //实际金额
        $recr_data['recr_plus_minus'] = $plus_minus; //金额正负
        $recr_data['recr_state'] = 2; //1.未核销 2.已核销
        $recr_data['recr_leisurely_type'] = 4; //订单代收状态：0待收款 1收款待核对 2收款已核对/待还款 3还款待核对 4还款已核对
        $recr_id = DB::table('receivable_credit')->insertGetId($recr_data);
        $recr_update = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->whereIn('recr_id', $request['recr_id'])
            ->where('recr_state', 1)
            ->update(['recr_belongs_id' => $recr_id, 'recr_state' => 2]);

        $recr_info = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->whereIn('recr_belongs_id', $request['recr_id'])
            ->where('recr_state', 1)
            ->first(['recr_id']);
        if (!empty($recr_info)) {
            $recr_update_res = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->whereIn('recr_belongs_id', $request['recr_id'])
                ->where('recr_state', 1)
                ->update(['recr_state' => 2, 'recr_update_time' => date('Y-m-d H:i:s')]);
        } else {
            $recr_update_res = true;
        }

        $recr_original_res = DB::table('receivable_credit')
            ->where('recr_id', $recr_id)
            ->update(['recr_original_id' => $recr_id, 'recr_number_id' => $recr_id]);

        if ($recr_update && $recr_id && $recr_update_res && $recr_original_res) {
            Common::addLog($user_info, getRealIp($request), '应收应付', '冲红', '账单：' . trim(implode(',', $original_number), ',') . '成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'生成冲红账单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'生成冲红账单失败']);
        }
    }

    // 预付款
    public function prepayment(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyReceivableBillController;
        $error_message = $verify_data->prepaymentValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        if ($request['type'] == 1) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'YFK' . rand(10, 99) . time() . rand(10000, 99999)]);
        }

        DB::beginTransaction();

        $actual_price = $request['recr_actual_price'] * 100; //实收金额

        // 生成应付账单
        $createBill = ReceivableBill::create(
            $user_info, //用户信息
            17, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 6.销售账单 7.销售出库单 8非实物开单 9.账单冲红 10订单冲单 11.加盟店订单收款 12.加盟店订单代收13.旧货回收14售后单15采购单16采购退货单17采购款到发货(预付款)
            0, //应收账款id
            0, //原始id(无)
            $request['recr_original_number'], //应收账款单号/原始号(账单编号)
            2, //客户类型：1.门店零售 2.来往单位
            $request['recr_client_id'], //会员id/来往单位id
            $request['recr_client_name'], //来往单位名称
            $actual_price, //结算金额
            $request['recr_settle_time'], //结款时间
            $request['recr_acti_id'], //会计科目id
            $actual_price, //实际金额
            0, //抹零金额
            1,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            '',  //备注
            0,   //已收金额
            $request['recr_abort_time'], //截止时间
            2, //金额正负：1正值2负值
            20, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单 10订单退款 11发票 12价外费 13折扣金额抵货款 14.账单冲红 15.订单冲单16.旧货回收 17售后单18采购单19采购退货单20采购款到发货（预付款）
            1, //是否合并代收：1是2否
            date('Y-m-d H:i:s')
        );

        // 添加预付款的原始id
        $edit_data['recr_original_id'] = $createBill;
        $edit_data['recr_update_time'] = date('Y-m-d H:i:s');
        $recr_res = DB::table('receivable_credit')
            ->where('recr_id', $createBill)
            ->where('recr_type', 2)
            ->update($edit_data);

        // 添加结款明细记录
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,            // [用户信息]
            24,                     // [单据类型订单结算2订单账单3工单账单4采购账单5销售账单6预收款7采购入库单现金8预付款9订单代收10采购入库单预付款11订单退款12工单代收13订单完成后结算14非实物开单15.订单冲单16.加盟店订单收款17.加盟店订单代收18.工单结算19.旧货回收20售后单结算21销售出库单22采购单23采购退货单24采购款到发货(预付款)]
            $createBill,           // [与单据类型对应的id]
            $request['recr_original_number'],          // [与单据类型对应的单号]
            2,                     // [买家类型1门店零售2来往单位]
            $request['recr_client_id'],    // [会员/客户id]
            $request['recr_client_name'],  // [来往单位名称]
            $request['recr_acti_id'],      // [会计科目id]
            1,                             // [类型1收入2支出]
            $actual_price,            // [实际金额](此次的实收金额)
            0,                        // [合计金额](此次的应收金额)
            0,                        // [欠收金额](此次结款后还应收金额)
            0,                        // [抹零金额]
            '',                        // [备注]
            0,                        // [结款类型1.抹零 2.分期结款 3.预收款抵账4正常]
            $request['recr_settle_time'] // [结款时间]
        );

        if ($createBill && $recr_res && $AccountingSettlement) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '应收应付', '新增预付款', $request['recr_original_number'] . '新增预付款成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'新增预付款成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'新增预付款失败']);
        }
    }

    // 导出
    public function export(Request $request)
    {
        $search_data = $request->all();

        if (!empty($search_data['recr_original_number']) || !empty($search_data['recr_client_id']) || !empty($search_data['recr_settle_id']) || !empty($search_data['start_time']) || !empty($search_data['end_time']) || !empty($search_data['recr_client_type']) || !empty($search_data['recr_acti_id']) || !empty($search_data['recr_remark']) || !empty($search_data['start_times']) || !empty($search_data['end_times']) || !empty($search_data['max_price']) || !empty($search_data['min_price'])) {
            // 获取当前操作账号信息
            $user_info = Common::getUserInfo($request['api_token']);
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

            // 实际金额最小钱数
            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_credit as recr')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_belongs_id', '=', 0)
                ->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已核销
                    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', 'like', '%' . $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_original_number', 'recr_original_id', 'recr_client_type', 'recr_client_name', 'recr_account_type', 'recr_settle_price', 'recr_settle_id', 'recr_yet_receipt', 'recr_actual_price', 'recr_zero_price', 'recr_plus_minus', 'recr_state', 'recr_remark', 'recr_settle_time', 'recr_create_time', 'recr_order_time', 'recr_client_id')
                ->orderBy('recr_id', 'desc')
                ->get();
            $data = json_decode(json_encode($list_data), true);
            if (empty($data)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有符合搜索条件的数据！']);
            }

            $settle_id = array_unique(array_column($data, 'recr_settle_id')); //结款人id
            $recr_client_id = array_unique(array_column($data, 'recr_client_id')); //会员id/来往单位id/加盟店id/虚拟加盟店
            // 查找结款人
            $adm_info = DB::table('admin')
                ->whereIn('adm_id', $settle_id)
                ->pluck('adm_name', 'adm_id')->toArray();
            // 结款明细显示类型
            $recr_account_type = [
                1 => '订单收款',
                2 => '受托代收',
                3 => '委托代收',
                4 => '工单费用',
                5 => '订单账单',
                6 => '工单账单',
                7 => '销售账单',
                8 => '预收款',
                9 => '销售出库单',
                10 => '订单退款',
                11 => '发票',
                12 => '价外费',
                13 => '折扣金额抵货款',
                14 => '账单冲红',
                15 => '订单冲单',
                16 => '旧货回收',
                17 => '售后单',
                18 => '采购单',
                19 => '采购退货单',
                20 => '采购款到发货',
                21 => '期初账单',
                22 => '采购账单',
            ];
            // 客户类型
            $recr_client_type = [
                1 => '会员零售',
                2 => '来往单位',
                3 => '外派门店',
                4 => '会员零售',
                5 => '接单门店',
                6 => '速电派单',
                7 => '虚拟加盟店',
            ];
            // 查询客户单位
            $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($data, 'recr_original_id'));
            $rec_ord_number = array_unique(array_column($data, 'recr_original_number'));
            $work_order = DB::table('work_order as wor')
                ->leftjoin('receivable_credit as recr', 'recr.recr_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('recr_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'];
            }
            $plus_minus = ''; //正负号
            foreach ($data as $key => $value) {
                if ($value['recr_settle_id']) {
                    $data[$key]['recr_settle_id'] = $adm_info[$value['recr_settle_id']]; //结款人
                }
                $data[$key]['recr_account_type'] = $recr_account_type[$value['recr_account_type']]; //结款明细显示类型
                $data[$key]['recr_client_type'] = $recr_client_type[$value['recr_client_type']]; //客户类型
                $data[$key]['recr_state'] = $value['recr_state'] == 1 ? '未确认' : '已确认'; //状态
                // 结款时间
                if ($value['recr_settle_time'] == '0000-00-00 00:00:00') {
                    $data[$key]['recr_settle_time'] = '';
                } else {
                    $data[$key]['recr_settle_time'] = substr($data[$key]['recr_settle_time'], 0, 10);
                }
                // 金额正负：1正值2负值
                if ($value['recr_plus_minus'] == 2) {
                    $plus_minus = '-';
                }
                $data[$key]['recr_settle_price'] = $value['recr_settle_price'] / 100; //结算金额
                $recr_arrearage_price = $value['recr_settle_price'] - $value['recr_zero_price'] - $value['recr_yet_receipt'];
                $data[$key]['recr_actual_price'] = $plus_minus . $recr_arrearage_price / 100; //欠款金额
                $data[$key]['recr_zero_price'] = $plus_minus . $value['recr_zero_price'] / 100; //抹零金额
                $data[$key]['recr_yet_receipt'] = $plus_minus . $value['recr_yet_receipt'] / 100; //已收金额
                $plus_minus = '';
                // 客户单位名称
                if (isset($channel[$value['recr_client_id']])) {
                    $data[$key]['recr_client_id'] = $channel[$value['recr_client_id']];
                } else {
                    $data[$key]['recr_client_id'] = $value['recr_client_name'];
                }
                // 订单单号
                if (isset($wor_order_number[$value['recr_original_id']])) {
                    $data[$key]['recr_original_id'] = $wor_order_number[$value['recr_original_id']];
                } elseif ($value['recr_account_type'] == '1' || $value['recr_account_type'] == '2' || $value['recr_account_type'] == '10') {
                    $data[$key]['recr_original_id'] = $value['recr_original_number'];
                } else {
                    $data[$key]['recr_original_id'] = '';
                }
                unset($data[$key]['recr_plus_minus']);
                unset($data[$key]['recr_client_id']); 
            }
            $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
            // 创建文件夹
            if (!file_exists($pathName)) {
                mkdir($pathName, 0775, true);
                chmod($pathName, 0775);
            }

            $streamFileRand = '应收应付' . time() . rand(1000, 9999) . '.xls';
            // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
            $streamFilename = $pathName . '/' . $streamFileRand;
            $where['action_name'] = '应收应付';
            $where['field_name'] = ['单号', '订单单号', '客户类型', '客户名称', '类型', '结算金额', '创建人', '实际金额', '欠收金额', '抹零金额', '状态', '备注', '结款时间', '创建时间', '开单时间'];
            // 调用导出的公共方法
            export::publicExport(
                $streamFilename, //路径
                $where,    //sheet名及其每一行的标题
                $data      //导出数据
            );

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