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

use App\Models\OrderBill;
use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountManage\VerifyOrderBillController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountingSettlement;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Http\Models\Services\AccountControl\AppletOrderBill;
use App\Services\Business\WashOrderBasicService;

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

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

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->adm_shop_id;
        $page_size = $request->input('show_count', 10);
        // $post['string'] = 'ware_';
        // $post['user_info'] = $user_info;
        // $type = 1;
        // $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        // 判断是否有单号查询
        if (!empty($request['query_number'])) {
            // 根据单号查询对应的账单，查询单号有：订单号、工单号、采购单号
            $initial = substr($request['query_number'], 0, 1); //获取单号首字母
            if (in_array($initial, ['D', 'G', 'C'])) {
                if ($initial == 'D') {
                    // 查询订单对应的账单
                    $find_orbi_id = DB::table('order')
                        ->where('ord_cid', $user_info->adm_cid)
                        ->where('ord_shop_id', $user_info->adm_shop_id)
                        ->where('ord_delete', 1)
                        ->where('ord_order_number', $request['query_number'])
                        ->value('ord_orbi_id');
                    $search_data['orbi_id'] = $find_orbi_id;
                } elseif ($initial == 'G') {
                    $find_orbi_id = DB::table('work_order')
                        ->where('wor_cid', $user_info->adm_cid)
                        ->where('wor_shop_id', $user_info->adm_shop_id)
                        ->where('wor_delete', 1)
                        ->where('wor_number', $request['query_number'])
                        ->value('wor_wobi_id');
                    $search_data['orbi_id'] = $find_orbi_id;
                } elseif ($initial == 'C') {
                    $find_orbi_number = DB::table('purchase_order')
                        ->where('company_id', $user_info->adm_cid)
                        ->where('cg_shop_id', $user_info->adm_shop_id)
                        ->where('is_del', 1)
                        ->where('cg_number', $request['query_number'])
                        ->value('cg_zdnumber');
                    $search_data['orbi_number'] = $find_orbi_number;
                } else {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是系统查询单号']);
                }

                if (empty($find_orbi_id) && empty($find_orbi_number)) {
                    $data_info['current_page'] = 1;  //当前页面页码
                    $data_info['last_page'] = 1;        //表示最后一页的页码
                    $data_info['total'] = 0;               //总数据个数
                    $data_info['current_number'] = 10;        //一页显示多少个
                    $data_info['data'] = [];
                    $top_type = [['id'=>1,'name'=>'账单列表','orbi_create_type'=>1],['id'=>2,'name'=>'智配账单','orbi_create_type'=>2]];
                    $data_info['top_type'] = $top_type;                      //类型
                    $data_info['showcount'] = self::getStatusBar(true,$shop_id,$request['orbi_create_type']); //状态
                    return response()->json(['code'=>200, 'msg'=>'error', 'data'=>$data_info]);
                }
            } else {
                return response()->json(['code'=>500, 'msg'=>'不是系统单号', 'data'=>'error']);
            }
        }
        $list_data = DB::table('order_bill')
            ->leftjoin('channel_unit as cu', 'cu.chun_id', '=', 'order_bill.orbi_client_id')
            ->where('orbi_cid', $user_info->adm_cid)
            ->where('orbi_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_state']) && ($search_data['orbi_state'] == 6)) {
                    $query->whereIn('orbi_state', [1, 5]);
                } elseif (!empty($search_data['orbi_state'])) {
                    $query->where('orbi_state', $search_data['orbi_state']);
                }
            }) //账单状态
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_payment_time'])) {
                    $query->where('orbi_payment_time', 'like', '%' . $search_data['orbi_payment_time'] . '%');
                }
            }) //结款时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_number'])) {
                    $query->where('orbi_number', 'like', '%' . $search_data['orbi_number'] . '%');
                }
            }) //账单编号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_id'])) {
                    $query->where('orbi_id', $search_data['orbi_id']);
                }
            }) //账单id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_audit_adm_id'])) {
                    $query->where('orbi_audit_adm_id', $search_data['orbi_audit_adm_id']);
                }
            }) //审核人id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_payment_way'])) {
                    $query->where('orbi_payment_way', $search_data['orbi_payment_way']);
                }
            }) //结款方式
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_remark'])) {
                    $query->where('orbi_remark', 'like', '%' . $search_data['orbi_remark'] . '%');
                }
            }) //备注
            ->where(function ($query) use ($search_data) {
                if(!empty($search_data['orbi_type'])){
                    $query->where('orbi_type', $search_data['orbi_type']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if(!empty($search_data['orbi_client_id'])){
                    $query->where('orbi_client_id', $search_data['orbi_client_id']);
                }
            })
            /*->where(function ($query) use ($search_data) {
                if (!empty($search_data['orcl_channel_unit'])) {
                    $query->where('orbi_type', 2)
                        ->where('orbi_client_id', $search_data['orcl_channel_unit'])
                        ->orwhere('orbi_channel_unit', $search_data['orcl_channel_unit']);
                }
            })*/ //客户单位
            // ->where(function ($query) use ($search_data) {
            //     if (!empty($search_data['orbi_channel_unit'])) {
            //         $query->where('orbi_channel_unit', $search_data['orbi_channel_unit']);
            //     }
            // }) //客户单位
            /*->where(function ($query) use ($search_data) {
                if (!empty($search_data['orbi_create_type'])) {
                    $query->where('orbi_create_type', $search_data['orbi_create_type']);
                }
            })*/ //账单生成类型1订单账单2速电同步生成3工单账单4期初账单
            ->select('orbi_id', 'orbi_number', 'orbi_start_time', 'orbi_end_time', 'orbi_order_amount', 'orbi_bill_price', 'orbi_payment_time', 'orbi_payment_way', 'orbi_handle_adm_id', 'orbi_actual_price', 'orbi_state', 'orbi_audit_time', 'orbi_audit_adm_id', 'orbi_create_adm_id', 'orbi_remark', 'orbi_client_id', 'orbi_type', 'orbi_plus_minus', 'orbi_create_type', 'orbi_opening_time', 'orbi_create_time', 'orbi_receive_price', 'orbi_zero_price', 'orbi_receive_price')
            ->orderBy('orbi_id', 'desc')
            ->paginate($page_size);
        $list_items = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        $status_name = self::getStatsName(true);
        if ($list_items) {
            $mem_id = [];
            $channel_id = [];
            $shop_arr = [];
            $vish_id = [];
            foreach ($list_items as $key => $value) {
                $adm_id[] = $value->orbi_create_adm_id;
                $adm_id[] = $value->orbi_handle_adm_id;
                $adm_id[] = $value->orbi_audit_adm_id;

                if ($value->orbi_type == 1) {
                    // 会员
                    $mem_id[] = $value->orbi_client_id;
                    $channel_id[] = $value->orbi_client_id;
                } elseif ($value->orbi_type == 2) {
                    // 客户单位
                    $channel_id[] = $value->orbi_client_id;
                } elseif ($value->orbi_type == 3) {
                    // 加盟店
                    $shop_arr[] = $value->orbi_client_id;
                } elseif ($value->orbi_type == 4) {
                    // 虚拟加盟店
                    $vish_id[] = $value->orbi_client_id;
                }

                if (!empty($value->orbi_zero_price)) {
                    $list_items[$key]->orbi_yet_price = $value->orbi_actual_price;
                } else {
                    $list_items[$key]->orbi_yet_price = $value->orbi_receive_price;
                }
                $buttonData = [];
                $buttonData2 = [];
                if($value->orbi_state == 3){//待审核
                    $buttonData[] = 'audit';
                    $buttonData[] = 'billNumber';
                }elseif ($value->orbi_state == 1) {//未结款
                    $buttonData[] = 'settleAccounts';
                    $buttonData[] = 'billNumber';
                    $buttonData[] = 'billExport';
                }elseif ($value->orbi_state == 2) {//已结款
                    $buttonData[] = 'billNumber';
                    $buttonData[] = 'lookInfo';
                    $buttonData[] = 'moneyRecord';
                    $buttonData[] = 'billExport';
                }
                $buttonData2[] = 'billNumber';
                if($value->orbi_create_type == 2){
                    $button = CommonService::getListButton($buttonData2,$list_button);
                    $list_items[$key]->button_one = $button['button_one']??[];
                    $list_items[$key]->button_two = $button['button_two']??[];
                    $list_items[$key]->button_three = $button['button_three']??[];
                }else{
                    $button = CommonService::getListButton($buttonData,$list_button);
                    $list_items[$key]->button_one = $button['button_one']??[];
                    $list_items[$key]->button_two = $button['button_two']??[];
                    $list_items[$key]->button_three = $button['button_three']??[];
                }

                $list_items[$key]->orbi_actual_price = sprintf("%.2f",$value->orbi_actual_price / 100);
                $list_items[$key]->orbi_bill_price = sprintf("%.2f",$value->orbi_bill_price / 100);
                $list_items[$key]->orbi_receive_price = sprintf("%.2f",$value->orbi_receive_price / 100);
                $list_items[$key]->orbi_yet_price = sprintf("%.2f",$value->orbi_yet_price / 100);
                $list_items[$key]->orbi_zero_price = sprintf("%.2f",$value->orbi_zero_price / 100);
                if($value->orbi_create_type == 2){
                    $list_items[$key]->orbi_create_type_name = '智配同步生成';
                }else if($value->orbi_create_type == 1){
                    $list_items[$key]->orbi_create_type_name = '订单账单';
                }
                $list_items[$key]->orbi_state_name = $status_name[$value->orbi_state];
            }
            $adm_id = array_unique($adm_id);
            $mem_id = array_unique($mem_id);
            $shop_arr = array_unique($shop_arr);
            $vish_id = array_unique($vish_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->get(['adm_id', 'adm_name']);

            // 查找所对应的 会员信息
            $find_mem = DB::table('member')
                ->whereIn('mem_id', $mem_id)
                ->get(['mem_id', 'mem_name', 'mem_phone', 'mem_province', 'mem_city', 'mem_county', 'mem_address']);
            $channel_name = [];
            $find_channel = [];
            // 查找所对应的 客户单位信息
            /*$find_channel = DB::table('channel_unit')
                ->whereIn('chun_id', $channel_id)
                ->get(['chun_id', 'chun_unit_name', 'chun_name', 'chun_phone', 'chun_province', 'chun_city', 'chun_county', 'chun_address']);*/
            if($channel_id){
                $find_channel = DB::table('business_client')
                    ->whereIn('bucl_id', $channel_id)
                    ->select('bucl_id','bucl_name', 'bucl_user_phone', 'bucl_user_name', 'bucl_province', 'bucl_city', 'bucl_county', 'bucl_address')
                    ->get()->toArray();
                foreach ($find_channel as $k => $v) {
                    $channel_name[$v->bucl_id] = $v->bucl_name;
                }
            }
            $find_sd_chan = config('apisystem.sd_chan_info');

            $find_shop = DB::table('shop')
                ->whereIn('shop_id', $shop_arr)
                ->get(['shop_id', 'shop_store_name', 'shop_phone', 'shop_name', 'shop_province', 'shop_city', 'shop_county', 'shop_address']);

            $find_vish = DB::table('virtual_shop')
                ->whereIn('vish_id', $vish_id)
                ->get(['vish_id', 'vish_store_name', 'vish_phone', 'vish_name', 'vish_province', 'vish_city', 'vish_county', 'vish_address']);
        } else {
            $find_admin = [];
            $find_mem = [];
            $find_channel = [];
            $find_sd_chan = [];
            $find_shop = [];
            $find_vish = [];
        }

        $state_count = DB::table('order_bill')
            ->where('orbi_cid', $user_info->adm_cid)
            ->where('orbi_shop_id', $shop_id)
            ->select(DB::raw('count(*) as count, orbi_state'))
            ->groupBy('orbi_state')
            ->get();
        $orbi_state = 0;
        foreach ($state_count as $key => $value) {
            if ($value->orbi_state == 1 || $value->orbi_state == 5) {
                $orbi_state += $value->count;
            }
        }
        $state_count = json_decode(json_encode($state_count), true);
        $data['count'] = $orbi_state;
        $data['orbi_state'] = 6;
        array_push($state_count, $data);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据
        $data_info['find_admin'] = $find_admin;                  //返回数据
        $data_info['state_count'] = $state_count;                //返回数据
        $data_info['find_mem'] = $find_mem;                      //会员信息
        $data_info['find_channel'] = $find_channel;              //客户单位信息
        $data_info['find_sd_chan'] = $find_sd_chan;              //速电客户单位信息
        $data_info['find_shop'] = $find_shop;                    //加盟店
        $data_info['find_vish'] = $find_vish;                    //虚拟加盟店
        $top_type = [['id'=>1,'name'=>'账单列表','orbi_create_type'=>1],['id'=>2,'name'=>'智配账单','orbi_create_type'=>2]];
        $data_info['top_type'] = $top_type;                      //类型
        $data_info['showcount'] = self::getStatusBar(true,$shop_id,$request['orbi_create_type']); //状态


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


    /*
     * @name 状态值
     * @param string ju_ordernum
     * @retrun array
     * @author Ma 2023/8/3 19:39
     *
    */
    public function getStatsName($type=false)
    {
        $status_names = [['type'=>'1','value'=>'未结款'],['type'=>'2','value'=>'已结款'],['type'=>'3','value'=>'待审核'],['type'=>'4','value'=>'已驳回'],['type'=>'5','value'=>'部分结款']];
        if($type){
            $status_names = array_column($status_names,'value','type');
        }
        return $status_names;
    }

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

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

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

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

        $search_data = $request->all();

        $select_field = "orbi_id, orbi_number, orbi_start_time, orbi_end_time, orbi_create_time, orbi_create_adm_id, orbi_order_amount, orbi_bill_price, orbi_actual_price, orbi_type, orbi_client_id, orbi_create_type, orbi_collection_price";
        $order_bill = new AppletOrderBill();
        $return_data = $order_bill->billNumber($user_info, $request->all(), $search_data, $this->show_count, $select_field);
        return response()->json($return_data);
    }

    // 搜索预收款
    public function advanceMoney(Request $request)
    {
        $user_info = Common::getUserInfo($request['api_token']);
        if ($request['type'] == 1) {
            if (empty($request['orbi_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $data = DB::table('order_bill')
                ->whereIn('orbi_id', $request['orbi_id'])
                ->get(['orbi_client_id', 'orbi_channel_unit', 'orbi_create_type']);

            $client_id = [];
            foreach ($data as $key => $value) {
                if ($value->orbi_create_type == 3) {
                    $client_id[] = $value->orbi_channel_unit;
                } else {
                    $client_id[] = $value->orbi_client_id;
                }
            }
            // $acset_original_number = DB::table('accounting_settlement')
            //     ->where('acset_adm_cid', $user_info->adm_cid)
            //     ->where('acset_shop_id', $user_info->adm_shop_id)
            //     ->whereIn('acset_client_id', $client_id) //客户单位
            //     ->where('acset_type', 6)
            //     ->where('acset_state', 3)//已收款
            //     ->pluck('acset_original_number');
            // $acset_original_number = json_decode($acset_original_number, true);
            // 验证当前账单是否存在
            $data = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_id', $user_info->adm_shop_id)
                ->whereIn('recr_client_id', $client_id) //客户单位
                ->where('recr_type', 2)
                ->where('recr_state', 3) //已收款
                ->where('recr_actual_price', '!=', 0)
                ->where('recr_abort_time', '>=', date('Y-m-d')) //不得超过截止时间
                ->get(['recr_id', 'recr_actual_price', 'recr_original_number']);
        } elseif ($request['type'] == 2) {
            $data = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_id', $user_info->adm_shop_id)
                ->where('recr_type', 2)
                ->where('recr_state', 3) //已收款
                ->where('recr_actual_price', '!=', 0)
                ->get(['recr_id', 'recr_actual_price', 'recr_original_number']);
        } else {
            if (empty($request['client_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $acset_original_number = DB::table('accounting_settlement')
                ->where('acset_adm_cid', $user_info->adm_cid)
                ->where('acset_shop_id', $user_info->adm_shop_id)
                ->where('acset_client_id', $request['client_id']) //客户单位
                ->where('acset_type', 6)
                ->where('acset_state', 3) //已收款
                ->pluck('acset_original_number');
            $acset_original_number = json_decode($acset_original_number, true);
            // 验证当前账单是否存在
            $data = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_id', $user_info->adm_shop_id)
                ->where('recr_client_id', $request['client_id']) //客户单位
                ->whereIn('recr_original_number', $acset_original_number) //客户单位
                ->where('recr_type', 2)
                ->where('recr_state', 3) //已收款
                ->where('recr_actual_price', '!=', 0)
                ->where('recr_abort_time', '>=', date('Y-m-d')) //不得超过截止时间
                ->get(['recr_id', 'recr_actual_price', 'recr_original_number']);
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 结款提交
    public function settleAccounts(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderBillController;
        $error_message = $verify_data->getInfoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证当前账单是否存在
        $orbi_data = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->first([
                'orbi_number', 'orbi_state', 'orbi_start_time', 'orbi_end_time',
                'orbi_create_time', 'orbi_create_adm_id', 'orbi_order_amount',
                'orbi_bill_price', 'orbi_total_price', 'orbi_client_id', 'orbi_type',
                'orbi_goods_sum', 'orbi_collection_price', 'orbi_receive_price', 'orbi_img',
                'orbi_zero_price', 'orbi_plus_minus', 'orbi_actual_price', 'orbi_merge_state'
            ]);
        if (empty($orbi_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账单不存在']);
        }
        if ($orbi_data->orbi_state != 1 && $orbi_data->orbi_state != 5) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'未结算或者部分结款状态下才可以结算']);
        }

        if ($request['type'] == 1) {
            // 获取到创建人姓名
            $orbi_data->orbi_create_adm_name = DB::table('admin')
                ->where('adm_id', $orbi_data->orbi_create_adm_id)
                ->value('adm_name');
            // 结算金额 = 合计金额 - 代收金额
            $orbi_data->orbi_bill_price = $orbi_data->orbi_total_price - $orbi_data->orbi_collection_price;

            // 获取客户单位信息
            if ($orbi_data->orbi_type == 1) {
                // 会员
                $member = DB::table('member')
                    ->where('mem_id', $orbi_data->orbi_client_id)
                    ->first(['mem_name', 'mem_phone', 'mem_address']);
                $orbi_data->unit_name = '';
                $orbi_data->adm_name = $member->mem_name;
                $orbi_data->adm_phone = $member->mem_phone;
                $orbi_data->adm_address = $member->mem_address;
            } elseif ($orbi_data->orbi_type == 2) {
                // 客户单位
                $channel = DB::table('channel_unit')
                    ->where('chun_id', $orbi_data->orbi_client_id)
                    ->first(['chun_unit_name', 'chun_name', 'chun_phone', 'chun_address']);
                $orbi_data->unit_name = $channel->chun_unit_name;
                $orbi_data->adm_name = $channel->chun_name;
                $orbi_data->adm_phone = $channel->chun_phone;
                $orbi_data->adm_address = $channel->chun_address;
            } else {
                $sd_chan = config('apisystem.sd_chan_info');
                $orbi_data->unit_name = '';
                $orbi_data->adm_name = $sd_chan['name'];
                $orbi_data->adm_phone = $sd_chan['phone'];
                $orbi_data->adm_address = $sd_chan['address'];
            }
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$orbi_data]);
        }

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

        // 剩余可结款金额 = 账单的实收金额 - 账单的已收金额
        $surplus_price = $orbi_data->orbi_actual_price - $orbi_data->orbi_receive_price;

        if (!empty($request['zero_price'])) {
            $zero_price = sprintf("%.2f", substr(sprintf("%.3f", $request['zero_price']), 0, -2));
        } else {
            $zero_price = 0;
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 验证提交结款的金额是否超出账单的计算金额
        // 提交的实收金额+提交的抹零金额，不能大于剩余可结款金额
        if (($request['orbi_actual_price'] + $zero_price) * 100 > $surplus_price) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'实收金额不能大于结款金额']);
        }

        if ($request['orbi_payment_type'] == 3) {
            // 预收款抵账不用上传图片
            $img = '';
        } else {
            $few = 0;
            $img = '';
            if (!empty($request['orbi_img'])) {
                foreach ($request['orbi_img'] as $key => $value) {
                    // 调用全局函数 上传图片
                    $img .= uploadBase64Img($value) . ',';
                    $few++;
                }
            }
            if ($few > 6) {
                return response()->json(['code'=>500, 'msg'=>'最多上传六张图片', 'data'=>'{}']);
            }
        }
        // 链接上以前的图片
        $img = $orbi_data->orbi_img . ',' . $img;
        $img = trim($img, ',');

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

        // orbi_type 客户类型 1.门店零售 2.来往单位
        if ($request['orbi_type'] == 1) {
            // 获取零售客户姓名
            $client_name = DB::table('member')
                ->where('mem_id', $request['orbi_client_id'])
                ->value('mem_name');
        } elseif ($request['orbi_type'] == 2) {
            // 获取来往单位名称
            $client_name = DB::table('channel_unit')
                ->where('chun_id', $request['orbi_client_id'])
                ->value('chun_unit_name');
        } else {
            $client_name = '';
        }

        $orbi_actual_price = $request['orbi_actual_price'] * 100; //实收金额
        $zero_price = $request['zero_price'] ? $request['zero_price'] * 100 : 0; //抹零金额
        // 判断账单状态
        // 提交的实收金额+抹零金额 == 剩余可结款金额，账单已全部结款
        if (($orbi_actual_price + $zero_price) == $surplus_price) {
            // orbi_state 账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
            $orbi_state = 2;
        } else {
            $orbi_state = 5;
        }
        DB::beginTransaction();

        // 修改订单账单表
        $update_bill = DB::update('UPDATE `faster_order_bill` SET `orbi_receive_price`=`orbi_receive_price`+' . $orbi_actual_price . ', `orbi_zero_price`=`orbi_zero_price`+' . $zero_price . ',`orbi_state`= ' . $orbi_state . ' ,`orbi_remark`= "' . $request['orbi_remark'] . '" ,`orbi_payee_id`= ' . $user_info->adm_id . ' ,`orbi_img`= "' . $img . '" ,`orbi_payment_time`= "' . date('Y-m-d H:i:s') . '" ,`orbi_update_time`= "' . date('Y-m-d H:i:s') . '" WHERE `orbi_id`=?', [$request['orbi_id']]);

        // 查询出账单对应的应收账款id
        $find_recr = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_type', 3)
            ->where('recr_account_type', 5)
            ->where('recr_belongs_id', 0)
            ->where('recr_original_id', $request['orbi_id'])
            ->select('recr_id', 'recr_remark')
            ->first();
        // 6. 更改账单的应收账款金额
        $recr_edit_data['recr_actual_price'] = $orbi_actual_price; //实际金额
        $recr_edit_data['recr_zero_price'] = $zero_price; //抹零金额
        $recr_edit_data['recr_yet_receipt'] = $orbi_data->orbi_receive_price + $orbi_actual_price; //已收金额 = 订单账单已收金额 + 实收金额
        $recr_edit_data['recr_remark'] = isset($find_recr->recr_remark) ? $find_recr->recr_remark : $request->input('orbi_remark', '');
        $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
        $createBill = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_type', 3)
            ->where('recr_account_type', 5)
            ->where('recr_belongs_id', 0)
            ->where('recr_id', $find_recr->recr_id)
            ->update($recr_edit_data);

        // 添加结款明细
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,                    // [用户信息]
            2,                             // [单据类型1订单2订单账单3工单账单4采购账单5销售账单6预收款]
            $request['orbi_id'],           // [与单据类型对应的id]
            $orbi_data->orbi_number,       // [与单据类型对应的单号]
            $orbi_data->orbi_type,         // [买家类型1门店零售2来往单位]
            $orbi_data->orbi_client_id,    // [会员/客户id]
            $client_name,                  // [来往单位名称]
            $request->input('acti_id', 0),           // [会计科目id]
            $orbi_data->orbi_plus_minus,  // [类型1收入2支出]
            $orbi_actual_price,            // [实际金额](此次的实收金额)
            $surplus_price,                // [合计金额](此次的应收金额)
            $surplus_price - $orbi_actual_price - $zero_price,    // [欠收金额](此次结款后还应收金额)
            $zero_price,          // [抹零金额]
            $recr_edit_data['recr_remark'],            // [备注]
            $request['orbi_payment_type']   // [结款类型1.抹零 2.分期结款 3.预收款抵账4正常]
        );

        // 预收款抵账
        if ($request['orbi_payment_type'] == 3) {
            // 预收款金额，实际金额减少，已收金额增加
            $prepay_price = $request['orbi_actual_price'] * 100;
            $subtract = DB::update('UPDATE `faster_receivable_credit` SET `recr_actual_price`=`recr_actual_price`-' . $prepay_price . ', `recr_yet_receipt`=`recr_yet_receipt`+' . $prepay_price . ' WHERE `recr_id`=?', [$request['recr_id']]);

            $add_data['rede_advance_id'] = $request['recr_id']; //预付款的应收账款id
            $add_data['rede_recr_id'] = $find_recr->recr_id; //账单应付账款id
            $add_data['rede_acset_id'] = $AccountingSettlement; //预收款抵账的结款明细id
            $details_data = DB::table('receivable_details')->insert($add_data);
        } else {
            $subtract = true;
            $details_data = true;
        }

        if ($createBill && $update_bill && $AccountingSettlement && $subtract && $details_data) {
            Common::addLog($user_info, getRealIp($request), '订单账单', '结款', $orbi_data->orbi_number . '结款成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'结款成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结款失败']);
        }
    }

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

        // 验证当前账单是否存在
        $orbi_data = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->select('orbi_number', 'orbi_state', 'orbi_start_time', 'orbi_end_time', 'orbi_create_time', 'orbi_create_adm_id', 'orbi_order_amount', 'orbi_bill_price', 'orbi_actual_price', 'orbi_client_id', 'orbi_type',
            'orbi_goods_sum', 'orbi_collection_price', 'orbi_plus_minus', 'orbi_merge_state', 'orbi_create_type', 'orbi_opening_time')
            ->first();
        if (empty($orbi_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账单不存在']);
        }
        if ($orbi_data->orbi_state != 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'待审核状态下才可以审核']);
        }

        if ($request['type'] == 1) {
            // 获取到创建人姓名
            $orbi_data->orbi_create_adm_name = DB::table('admin')
                ->where('adm_id', $orbi_data->orbi_create_adm_id)
                ->value('adm_name');
            // 获取客户单位信息
            if ($orbi_data->orbi_type == 1) { //会员
                $member = DB::table('member')
                    ->where('mem_id', $orbi_data->orbi_client_id)
                    ->first(['mem_name', 'mem_phone', 'mem_address']);
                $orbi_data->unit_name = '';
                $orbi_data->adm_name = $member->mem_name;
                $orbi_data->adm_phone = $member->mem_phone;
                $orbi_data->adm_address = $member->mem_address;
            } elseif ($orbi_data->orbi_type == 2) { //客户单位
                /*$channel = DB::table('channel_unit')
                    ->where('chun_id', $orbi_data->orbi_client_id)
                    ->first(['chun_unit_name', 'chun_name', 'chun_phone', 'chun_address']);
                */
                $channel = DB::table('business_client')
                    ->where('bucl_id', $orbi_data->orbi_client_id)
                    ->first(['bucl_name', 'bucl_user_phone', 'bucl_user_name', 'bucl_province', 'bucl_city', 'bucl_county']);
                $orbi_data->unit_name = $channel->bucl_name;
                $orbi_data->adm_name = $channel->bucl_user_name;
                $orbi_data->adm_phone = $channel->bucl_user_phone;
                $orbi_data->adm_address = $channel->bucl_province.$channel->bucl_city.$channel->bucl_province;
            } elseif ($orbi_data->orbi_type == 4) {
                $find_vish = DB::table('virtual_shop')
                    ->where('vish_id', $orbi_data->orbi_client_id)
                    ->first(['vish_store_name', 'vish_name', 'vish_phone', 'vish_address']);
                $orbi_data->unit_name = $find_vish->vish_store_name;
                $orbi_data->adm_name = $find_vish->vish_name;
                $orbi_data->adm_phone = $find_vish->vish_phone;
                $orbi_data->adm_address = $find_vish->vish_address;
            } elseif ($orbi_data->orbi_type == 5) {
                $find_shop = DB::table('shop')
                    ->where('vish_id', $orbi_data->orbi_client_id)
                    ->first(['shop_store_name', 'shop_phone', 'shop_name', 'shop_address']);
                $orbi_data->unit_name = $find_shop->shop_store_name;
                $orbi_data->adm_name = $find_shop->shop_name;
                $orbi_data->adm_phone = $find_shop->shop_phone;
                $orbi_data->adm_address = $find_shop->shop_address;
            }

            // 订单信息
            if (in_array($orbi_data->orbi_type, [1, 2])) {
                if ($orbi_data->orbi_create_type == '5') {
                    $order_data = DB::table('purchase_order as o')
                        ->leftJoin('admin as a', 'o.cg_userid', '=', 'a.adm_id')
                        ->where('cg_zdnumber', $orbi_data->orbi_number)
                        ->select('create_time as ord_create_time', 'cg_number as ord_order_number', 'cg_userid as ord_create_id', 'cg_amount as ord_order_price', 'cg_amount as ord_actual_price', 'cg_creator as ord_create_name')
                        ->get();
                    foreach ($order_data as $k => $v) {
                        if (substr($v->ord_order_number, 0, 2) == 'TH') {
                            $order_data[$k]->ord_plus_minus = '1';
                        } else {
                            $order_data[$k]->ord_plus_minus = '2';
                        }
                        $order_data[$k]->ord_order_price = $order_data[$k]->ord_order_price * 100;
                        $order_data[$k]->ord_actual_price = $order_data[$k]->ord_actual_price * 100;
                        $order_data[$k]->ord_state = '1';
                        $order_data[$k]->ord_collection_bill = '1';
                        $order_data[$k]->ord_collection_price = '0';
                    }
                } else {
                    $order_data = DB::table('order as o')
                        ->leftJoin('admin as a', 'o.ord_create_id', '=', 'a.adm_id')
                        ->where('ord_orbi_id', $request['orbi_id'])
                        ->where('ord_collection_bill', 1)
                        ->select('ord_create_time', 'ord_order_number', 'ord_create_id',
                        'ord_order_price', 'ord_actual_price', 'ord_state', 'adm_name as ord_create_name',
                        'ord_collection_bill', 'ord_collection_price', 'ord_plus_minus')
                        ->get();
                }
            } else {
                $order_data = DB::table('work_order as o')
                    ->leftJoin('admin as a', 'o.wor_create_id', '=', 'a.adm_id')
                    ->where('wor_wobi_id', $request['orbi_id'])
                    ->where('wor_collection_bill', 1)
                    ->select('wor_create_time as ord_create_time', 'wor_number as ord_order_number', 'wor_create_id as ord_create_id', 'wor_actual_price as ord_actual_price', 'wor_account_state as ord_state', 'adm_name as ord_create_name', 'wor_collection_bill as ord_collection_bill', 'wor_collection_price as ord_collection_price', 'wor_plus_minus as ord_plus_minus')
                    ->get();
            }

            $data['orbi_data'] = $orbi_data;
            $data['order_data'] = $order_data;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$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();

        $update_data['orbi_state'] = $request['orbi_state']; //账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
        $update_data['orbi_audit_adm_id'] = $user_info->adm_id; //审核人
        $update_data['orbi_audit_time'] = date('Y-m-d H:i:s'); //审核时间
        $update_data['orbi_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->update($update_data);

        // 获取客户单位名称
        if ($orbi_data->orbi_type == 1) {
            $client_name = '';
        } elseif ($orbi_data->orbi_type == 2) {
            $client_name = DB::table('channel_unit')
                ->where('chun_id', $orbi_data->orbi_client_id)
                ->value('chun_unit_name');
        } elseif ($orbi_data->orbi_type == 4) {
            $client_name = DB::table('virtual_shop')
                ->where('vish_id', $orbi_data->orbi_client_id)
                ->value('vish_store_name');
        } elseif ($orbi_data->orbi_type == 5) {
            $client_name = DB::table('shop')
                ->where('vish_id', $orbi_data->orbi_client_id)
                ->value('shop_store_name');
        }

        if ($request['orbi_state'] == 1) {
            if (in_array($orbi_data->orbi_create_type, [1, 2])) {
                $recr_type = 1;
                $recr_account_type = 5;
            } elseif ($orbi_data->orbi_create_type == 3) {
                $recr_type = 4;
                $recr_account_type = 6;
                $orbi_data->orbi_type = 7; //虚拟加盟店
            } elseif ($orbi_data->orbi_create_type == 5) {
                $recr_type = 15;
                $recr_account_type = 22; //采购账单
            } else {
                $recr_type = 18; //期初账单
                $recr_account_type = 21; //期初账单
            }
            // 审核通过
            // 6. 生成应收账单
            /*$createBill = ReceivableBill::create(
                $user_info, //用户信息
                $recr_type, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $request['orbi_id'], //原始id(订单账单id)
                $orbi_data->orbi_number, //应收账款单号/原始号(订单账单编号)
                $orbi_data->orbi_type, //客户类型：1.门店零售 2.来往单位
                $orbi_data->orbi_client_id, //会员id/来往单位id
                $client_name, //来往单位名称
                $orbi_data->orbi_actual_price, //实收金额
                date('Y-m-d H:i:s'), //结款时间
                0, //会计科目id
                0, //实际金额
                0, //抹零金额
                1, //状态：1.未核销 2.已核销
                2, //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                0,  //已收金额
                '', //截止时间
                $orbi_data->orbi_plus_minus, //金额正负
                $recr_account_type, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款
                $orbi_data->orbi_merge_state, //是否合并代收：1是2否
                $orbi_data->orbi_create_time
            );*/
            // 账单下所有的订单为不统计状态
            // 判断订单账单是否合并代收 orbi_merge_state 是否合并代收：1是2否
            if ($orbi_data->orbi_merge_state == 2) {
                $recr_plus_minus = [1];
            } else {
                $recr_plus_minus = [1, 2];
            }
            if ($orbi_data->orbi_create_type == 4) {
                $statistics_type_update = true;
            } elseif ($orbi_data->orbi_create_type == 5) {
                $savedata = array();
                $puresult = DB::table('purchase_order')
                    ->where('cg_zdnumber', $orbi_data->orbi_number)
                    ->select('cg_number')
                    ->get();
                foreach ($puresult as $k => $v) {
                    $savedata[] = $v->cg_number;
                }
                $inorderresult = DB::table('ware_inorder')
                    ->whereIn('cg_number', $savedata)
                    ->select('rk_number')
                    ->get();
                foreach ($inorderresult as $k => $v) {
                    $savedata[] = $v->rk_number;
                }
                $statistics_type_update = DB::table('receivable_pay')
                    ->where('recpay_cid', $user_info->adm_cid)
                    ->where('recpay_shop_superior_id', $shop_id)
                    ->whereIn('recpay_original_number', $savedata)
                    ->update(['recr_statistics_type' => 2, 'recr_number_id' => $createBill, 'recr_belongs_id' => $request['orbi_id'], 'recr_state' => '2']);
            } else {
                $statistics_type_update = DB::table('receivable_pay')
                    ->where('recpay_cid', $user_info->adm_cid)
                    ->where('recpay_shop_superior_id', $shop_id)
                    ->where('recpay_type', $recr_type)
                    ->where('recpay_belongs_id', $request['orbi_id'])
                    ->update(['recpay_update_time' => date('Y-m-d H:i:s')]);
            }
        } else {
            $statistics_type_update = true;
            $createBill = true;
        }

        // 如果是订单账单
        if (in_array($orbi_data->orbi_create_type, [1, 2])) {
            // 查询出 该订单下已结算的 订单id
            $ord_id = DB::table('order')
                ->where('ord_state', 2)
                ->where('ord_orbi_id', $request['orbi_id'])
                ->get(['ord_order_number']);
            $ord_id = json_decode(json_encode($ord_id), true);
            $ord_id = array_column($ord_id, 'ord_order_number');

            // 如果代收代收订单数据有就删除
            $ord_del_data = DB::table('order')
                ->where('ord_collection_bill', 2)
                ->where('ord_orbi_id', $request['orbi_id'])
                ->value('ord_id');
            if (!empty($ord_del_data)) {
                $ord_id_del = DB::table('order')
                    ->where('ord_collection_bill', 2)
                    ->where('ord_orbi_id', $request['orbi_id'])
                    ->delete();
            } else {
                $ord_id_del = true;
            }
        } elseif ($orbi_data->orbi_create_type == 3) {
            // 如果是工单账单 查询出 该工单下已结算的 工单id
            $ord_id = DB::table('work_order')
                ->where('wor_account_state', 2)
                ->where('wor_wobi_id', $request['orbi_id'])
                ->get(['wor_number']);
            $ord_id = json_decode(json_encode($ord_id), true);
            $ord_id = array_column($ord_id, 'wor_number');

            // 如果代收代收订单数据有就删除
            $ord_del_data = DB::table('work_order')
                ->where('wor_collection_bill', 2)
                ->where('wor_wobi_id', $request['orbi_id'])
                ->value('wor_id');
            if (!empty($ord_del_data)) {
                $ord_id_del = DB::table('work_order')
                    ->where('wor_collection_bill', 2)
                    ->where('wor_wobi_id', $request['orbi_id'])
                    ->delete();
            } else {
                $ord_id_del = true;
            }
        } else {
            $ord_id_del = true;
        }

        // 已驳回
        if ($request['orbi_state'] == 4) {
            // 如果是订单账单  查询出 该订单下已结算的 订单id
            if (in_array($orbi_data->orbi_create_type, [1, 2])) {
                $find_order = DB::table('order')
                    ->where('ord_orbi_id', $request['orbi_id'])
                    ->get(['ord_order_number', 'ord_collection_price']);
                $find_order = json_decode(json_encode($find_order), true);
                // 2.解除订单与账单的绑定关系
                $update_order['ord_orbi_id'] = 0;
                $update_order['ord_state'] = 1;
                $update_order['ord_update_time'] = date('Y-m-d H:i:s');
                $ord_state = DB::table('order')
                    ->where('ord_orbi_id', $request['orbi_id'])
                    ->update($update_order);
                // 3.解除账单与应收应付的关系
                $update_rece['recpay_belongs_id'] = 0;//所属账单id
                $update_rece['recpay_update_time'] = date('Y-m-d H:i:s');
                $rec_state = DB::table('receivable_pay')
                    ->where('recpay_belongs_id', $request['orbi_id'])
                    ->update($update_rece);
            } elseif ($orbi_data->orbi_create_type == 3) {
                // 如果是工单账单 查询出 该工单下已结算的 工单id
                $find_work = DB::table('work_order')
                    ->where('wor_wobi_id', $request['orbi_id'])
                    ->get(['wor_number', 'wor_collection_price']);
                $find_work = json_decode(json_encode($find_work), true);
                $update_order['wor_wobi_id'] = 0;
                $update_order['wor_account_state'] = 1;
                $update_order['wor_update_time'] = date('Y-m-d H:i:s');
                $ord_state = DB::table('work_order')
                    ->where('wor_wobi_id', $request['orbi_id'])
                    ->update($update_order);
            } elseif ($orbi_data->orbi_create_type == 5) {
                // 如果是采购账单 查询出 该采购单下已结算的 采购单id
                $ord_state = DB::table('purchase_order')
                    ->where('cg_zdnumber', $orbi_data->orbi_number)
                    ->update(['cg_settlementype' => 2, 'cg_paytype' => 1, 'cg_zdnumber' => '', 'edit_time' => date('Y-m-d H:i:s')]);
            } else {
                $ord_state = true;
            }
            $msg = '驳回';

            // 1.删除账单表
            $del_orbi = DB::table('order_bill')
                ->where('orbi_id', $request['orbi_id'])
                ->delete();
            // $delete_state = DB::table('order')
            //         ->where('ord_orbi_id',$request['orbi_id'])
            //         ->where('ord_collection_bill',2)
            //         ->delete();
            if (!empty($find_order)) {
                // 将应收账款的订单退款的收款状态改为待收款状态
                $ord_number = [];
                foreach ($find_order as $key => $value) {
                    if ($orbi_data->orbi_merge_state == 1) {
                        if ($value['ord_collection_price'] > 0) {
                            $ord_number[] = $value['ord_order_number'];
                        }
                    }
                }
                if (!empty($ord_number)) {
                    $recr_id_one = DB::table('receivable_credit')
                        ->where('recr_cid', $user_info->adm_cid)
                        ->where('recr_shop_superior_id', $shop_id)
                        ->where('recr_type', 3)
                        ->where('recr_account_type', 2)
                        ->whereIn('recr_original_number', $ord_number)
                        ->value('recr_id');
                    if (!empty($recr_id_one)) {
                        $recr_edit_data['recr_leisurely_type'] = 2;
                        $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
                        $update_recr = DB::table('receivable_credit')
                            ->where('recr_cid', $user_info->adm_cid)
                            ->where('recr_shop_superior_id', $shop_id)
                            ->where('recr_type', 3)
                            ->where('recr_account_type', 2)
                            ->whereIn('recr_original_number', $ord_number)
                            ->update($recr_edit_data);
                    } else {
                        $update_recr = true;
                    }
                } else {
                    $update_recr = true;
                }
            } else {
                $update_recr = true;
            }

            if (!empty($find_work)) {
                $wor_number = [];
                foreach ($find_work as $key => $value) {
                    if ($orbi_data->orbi_merge_state == 1) {
                        if ($value['wor_collection_price'] > 0) {
                            $wor_number[] = $value['wor_number'];
                        }
                    }
                }
                if (!empty($wor_number)) {
                    $recr_id_two = DB::table('receivable_credit')
                        ->where('recr_cid', $user_info->adm_cid)
                        ->where('recr_shop_superior_id', $shop_id)
                        ->where('recr_type', 4)
                        ->where('recr_account_type', 3)
                        ->whereIn('recr_original_number', $wor_number)
                        ->value('recr_id');
                    if (!empty($recr_id_two)) {
                        // 将应收账款的订单退款的收款状态改为待收款状态
                        $recr_edit_data['recr_leisurely_type'] = 0;
                        $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
                        $update_wor_recr = DB::table('receivable_credit')
                            ->where('recr_cid', $user_info->adm_cid)
                            ->where('recr_shop_superior_id', $shop_id)
                            ->where('recr_type', 4)
                            ->where('recr_account_type', 3)
                            ->whereIn('recr_original_number', $wor_number)
                            ->update($recr_edit_data);
                    } else {
                        $update_wor_recr = true;
                    }
                } else {
                    $update_wor_recr = true;
                }
            } else {
                $update_wor_recr = true;
            }
        } else {
            $ord_state = true;
            $update_wor_recr = true;
            $update_recr = true;
            $del_orbi = true;
            $msg = '审核';
        }

        // 7. 将类型为销售订单  且原始id存在于账单中已结算订单id  的应收账单的应收款id 改为当前应收款id
        if (in_array($orbi_data->orbi_create_type, [1, 2])) {
            $update_recr_id = DB::table('receivable_pay')
                ->where('recpay_type', 1)
                ->whereIn('recpay_original_number', $ord_id)
                ->get(['recpay_id']);
            $update_recr_id = json_decode(json_encode($update_recr_id), true);
            if (empty($update_recr_id)) {
                // 账单中不存在已结算的订单
                $update_id = true;
            } else {
                // 账单中存在已结算的订单
                /*$recr_id = array_column($update_recr_id, 'recpay_id');
                if ($request['orbi_state'] == 1) {
                    $update_rerct['recr_number_id'] = $createBill; //应收款id
                }
                $update_rerct['recr_update_time'] = date('Y-m-d H:i:s');
                $update_id = DB::table('receivable_credit')
                    ->whereIn('recr_id', $recr_id)
                    ->update($update_rerct);*/
            }
        } else {
            $update_id = true;
        }//return response()->json(['code'=>$update_state, 'msg'=>$createBill, 'data'=>$update_id ,'data1'=>$ord_id_del,'data2'=>$statistics_type_update,'data3'=>$ord_state,'data4'=>$ord_state,'data5'=>$update_recr,'data6'=>$update_wor_recr,'data71'=>$del_orbi]);
        if ($update_state && $ord_id_del && $statistics_type_update && $ord_state && $update_recr && $update_wor_recr && $del_orbi) {
            Common::addLog($user_info, getRealIp($request), '订单账单', $msg, $orbi_data->orbi_number . $msg . '成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$msg . '成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$msg . '失败']);
        }
    }

    // 查看
    public function lookInfo(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

        $select_field = "orbi_number, orbi_state, orbi_start_time, orbi_end_time, orbi_create_time, orbi_create_adm_id, orbi_order_amount, orbi_bill_price, orbi_total_price, orbi_client_id, orbi_goods_sum, orbi_collection_price, orbi_audit_time, orbi_audit_adm_id, orbi_payment_time, orbi_payment_way, orbi_actual_price, orbi_remark, orbi_img, orbi_payee_id, orbi_type, orbi_zero_price, orbi_receive_price, orbi_plus_minus";
        $order_bill = new AppletOrderBill();
        $return_data = $order_bill->lookInfo($user_info, $request->all(), $select_field);
        return response()->json($return_data);
    }

    // 删除(做成了真删)
    public function del(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证当前账单是否存在
        $orbi_data = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->first(['orbi_number', 'orbi_state', 'orbi_type', 'orbi_client_id', 'orbi_bill_price', 'orbi_create_type', 'orbi_merge_state']);
        if (empty($orbi_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账单不存在']);
        }
        if ($orbi_data->orbi_state != 4) {
            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();

        if ($orbi_data->orbi_create_type == 3) {
            $find_work = DB::table('work_order')
                ->where('wor_wobi_id', $request['orbi_id'])
                ->get(['wor_number', 'wor_collection_price']);
            $find_work = json_decode(json_encode($find_work), true);
            $update_data['wor_wobi_id'] = 0;
            $update_data['wor_update_time'] = date('Y-m-d H:i:s');
            $update_state = DB::table('work_order')
                ->where('wor_wobi_id', $request['orbi_id'])
                ->update($update_data);
        } elseif (in_array($orbi_data->orbi_create_type, [1, 2])) {
            $find_order = DB::table('order')
                ->where('ord_orbi_id', $request['orbi_id'])
                ->get(['ord_order_number', 'ord_collection_price']);
            $find_order = json_decode(json_encode($find_order), true);
            // 2.解除订单与账单的绑定关系
            $update_data['ord_orbi_id'] = 0;
            $update_data['ord_update_time'] = date('Y-m-d H:i:s');
            $update_state = DB::table('order')
                ->where('ord_orbi_id', $request['orbi_id'])
                ->update($update_data);
        } else {
            $update_state = true;
        }

        // 1.删除账单表
        $del_orbi = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->delete();
        // $delete_state = DB::table('order')
        //         ->where('ord_orbi_id',$request['orbi_id'])
        //         ->where('ord_collection_bill',2)
        //         ->delete();
        if (!empty($find_order)) {
            // 将应收账款的订单退款的收款状态改为待收款状态
            $ord_number = [];
            foreach ($find_order as $key => $value) {
                if ($orbi_data->orbi_merge_state == 1) {
                    if ($value['ord_collection_price'] > 0) {
                        $ord_number[] = $value['ord_order_number'];
                    }
                }
            }
            if (!empty($ord_number)) {
                $recr_edit_data['recr_leisurely_type'] = 2;
                $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
                $update_recr = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    ->where('recr_type', 3)
                    ->where('recr_account_type', 2)
                    ->whereIn('recr_original_number', $ord_number)
                    ->update($recr_edit_data);
            } else {
                $update_recr = true;
            }
        } else {
            $update_recr = true;
        }

        if (!empty($find_work)) {
            $wor_number = [];
            foreach ($find_work as $key => $value) {
                if ($orbi_data->orbi_merge_state == 1) {
                    if ($value['wor_collection_price'] > 0) {
                        $wor_number[] = $value['wor_number'];
                    }
                }
            }
            if (!empty($wor_number)) {
                // 将应收账款的订单退款的收款状态改为待收款状态
                $recr_edit_data['recr_leisurely_type'] = 0;
                $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
                $update_wor_recr = DB::table('receivable_credit')
                    ->where('recr_cid', $user_info->adm_cid)
                    ->where('recr_shop_superior_id', $shop_id)
                    ->where('recr_type', 4)
                    ->where('recr_account_type', 3)
                    ->whereIn('recr_original_number', $wor_number)
                    ->update($recr_edit_data);
            } else {
                $update_wor_recr = true;
            }
        } else {
            $update_wor_recr = true;
        }

        // // 应收账单表新增数据
        // if ($request['orbi_type'] == 2) {
        //     $analyze = Common::updateAnalyze(
        //         $user_info, //用户信息
        //         $request['orbi_client_id'], //客户单位id
        //         1, //单量
        //         $request['orbi_bill_price'] * 100, //应收账款结算金额
        //         2  //类型1.编辑+ 2.编辑-
        //     );
        // } else {
        //     $analyze = true;
        // }
        if ($del_orbi && $update_state && $update_wor_recr && $update_recr) {
            Common::addLog($user_info, getRealIp($request), '账单列表', '删除', $orbi_data->orbi_number . '删除成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }

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

        // 验证当前账单是否存在
        $orbi_data = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->first(['orbi_number', 'orbi_state', 'orbi_create_type']);
        if (empty($orbi_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账单不存在']);
        }
        if ($orbi_data->orbi_state != 4 && $orbi_data->orbi_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'已驳回或者未结款的账单才可以返审核']);
        }

        // 订单账单信息更改
        $update_data['orbi_state'] = 3; // 账单状态1.未结款 2.已结款 3.待审核 4.已驳回 5.部分结款
        $update_data['orbi_update_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        // 1.修改订单账单的状态
        $update_state = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->update($update_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 (in_array($orbi_data->orbi_create_type, [1, 2])) {
            $recr_type = 1;
            $recr_account_type = 5;
        } elseif ($orbi_data->orbi_create_type == 3) {
            $recr_type = 4;
            $recr_account_type = 6;
        } elseif ($orbi_data->orbi_create_type == 5) {
            $recr_type = 15;
            $recr_account_type = 22;
        } else {
            $recr_type = 18;
            $recr_account_type = 21;
        }

        // 2. 审核通过的账单会生成订单账单应收账款，返审核应删除账单生成的应收账款
        /*$del_credit = DB::table('receivable_pay')
            ->where('recpay_cid', $user_info->adm_cid)
            ->where('recpay_shop_superior_id', $shop_id)
            ->where('recpay_type', $recr_type) //类型 3.订单账单
            ->where('recpay_account_type', $recr_account_type) //显示类型：5订单账单
            ->where('recpay_belongs_id', 0) //所属账单id为0
            ->where('recpay_original_id', $request['orbi_id']) //与类型所对应的id
            ->delete();*/

        // 3. 订单应收账款所属账单id改为0,统计状态为1
        $recr_edit_data['recpay_belongs_id'] = 0;
        $recr_edit_data['recpay_number_id'] = 0;
        $recr_edit_data['recpay_statistics_type'] = 1;
        $recr_edit_data['recpay_update_time'] = date('Y-m-d H:i:s');

        if ($orbi_data->orbi_create_type == 4) {
            $update_belongs = true;
        } elseif ($orbi_data->orbi_create_type == 5) {
            $recr_edit_data['recr_state'] = 1;
            $update_belongs = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->whereIn('recr_type', [15, 16, 17]) //类型 3.订单账单
                ->where('recr_belongs_id', $request['orbi_id'])
                ->update($recr_edit_data);
        } else {
            /*$update_belongs = DB::table('receivable_pay')
                ->where('recpay_cid', $user_info->adm_cid)
                ->where('recpay_shop_superior_id', $shop_id)
                ->where('recpay_type', $recr_type) //类型 3.订单账单
                ->where('recpay_belongs_id', $request['orbi_id'])
                ->update($recr_edit_data);*/
        }
        //if ($update_state && $del_credit && $update_belongs) {
        if ($update_state) {
            Common::addLog($user_info, getRealIp($request), '订单账单', '返审核', $orbi_data->orbi_number . '返审核成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'返审核成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'返审核失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyOrderBillController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $orbi = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->first(['orbi_state', 'orbi_create_type', 'orbi_merge_state']);
        if (($orbi->orbi_state == 2) || ($orbi->orbi_state == 5)) {
            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();
        $update_bill['orbi_goods_sum'] = 0;
        $orbi_collection_price = 0; //代收金额
        $ord_total_price = 0;
        $wor_number_one = [];
        $ord_close_price = 0; //结算金额
        // 等于三 工单账单
        if ($orbi->orbi_create_type == 3) {
            // 1.解除该订单账单与原来订单的绑定关系
            $relieve_data['wor_wobi_id'] = 0; //账单id改为0
            $relieve_data['wor_update_time'] = date('Y-m-d H:i:s');
            $relieve_relation = DB::table('work_order')
                ->where('wor_wobi_id', $request['orbi_id'])
                ->update($relieve_data);
            $ord_price = DB::table('work_order')
                ->whereIn('wor_id', $request['ord_id'])
                ->get(['wor_actual_price', 'wor_collection_price', 'wor_service_type', 'wor_plus_minus', 'wor_goo_amount', 'wor_number']);
            foreach ($ord_price as $key => $value) {
                $orbi_collection_price += $value->wor_collection_price; //代收金额
                if (($orbi->orbi_merge_state == 1) && ($value->wor_collection_price > 0)) {
                    $wor_number_one[] = $value->wor_number;
                }
                $update_bill['orbi_goods_sum'] += $value->wor_goo_amount;
                if ($value->wor_service_type == 4) { //退货单：减
                    $ord_total_price -= $value->wor_actual_price;
                } elseif ($value->wor_plus_minus == 2) { //换货单为负数：减
                    $ord_total_price -= $value->wor_actual_price;
                } else {
                    $ord_total_price += $value->wor_actual_price;
                }
            }

            // 2.重新绑定订单与账单的关系
            $sql = 'UPDATE `faster_work_order` SET ';
            $ord_orbi_id = ''; //账单id
            $update_time = ''; //更新时间
            $ord_id = "";

            foreach ($request['ord_id'] as $key => $value) {
                // 更改账单id
                $ord_orbi_id = $ord_orbi_id . ' WHEN ' . $value;
                $ord_orbi_id = $ord_orbi_id . ' THEN ' . $request['orbi_id'];
                // 更改时间
                $update_time = $update_time . ' WHEN ' . $value;
                $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
                //要更改的订单id
                $ord_id = $ord_id . $value . ',';
            }
            $sql = $sql . ' `wor_wobi_id`= CASE `wor_id` ' . $ord_orbi_id . ' END,';
            $sql = $sql . ' `wor_update_time`= CASE `wor_id` ' . $update_time . ' END';
            $sql = $sql . ' WHERE `wor_id` IN (' . trim($ord_id, ',') . ')';
            $save_order = DB::update($sql);
            $ord_close_price = $ord_total_price;
            $recr_type = 18;
        } else {
            // 1.解除该订单账单与原来订单的绑定关系
            $relieve_data['ord_orbi_id'] = 0; //账单id改为0
            $relieve_data['ord_update_time'] = date('Y-m-d H:i:s');
            $relieve_relation = DB::table('order')
                ->where('ord_orbi_id', $request['orbi_id'])
                ->update($relieve_data);
            $ord_price = DB::table('order')
                ->whereIn('ord_id', $request['ord_id'])
                ->get(['ord_actual_price', 'ord_order_price', 'ord_collection_price', 'ord_goods_quantity', 'ord_order_number', 'ord_plus_minus', 'ord_state']);


            foreach ($ord_price as $key => $value) {
                $orbi_collection_price += $value->ord_collection_price; //代收金额
                $update_bill['orbi_goods_sum'] += $value->ord_goods_quantity;
                if ($value->ord_state == 1) { //只相加未结算的订单结算金额
                    // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
                    if (($orbi->orbi_merge_state == 1) && ($value->ord_collection_price > 0)) {
                        $original_id[] = $value->ord_order_number;
                    }
                    // 计算账单总金额 ord_plus_minus 金额正负：1正值2负值
                    if ($value->ord_plus_minus == 1) {
                        $ord_total_price += $value->ord_actual_price;
                    } else {
                        $ord_total_price -= $value->ord_actual_price;
                    }
                }
            }

            // 2.重新绑定订单与账单的关系
            $sql = 'UPDATE `faster_order` SET ';
            $ord_orbi_id = ''; //账单id
            $update_time = ''; //更新时间
            $ord_id = "";

            foreach ($request['ord_id'] as $key => $value) {
                // 更改账单id
                $ord_orbi_id = $ord_orbi_id . ' WHEN ' . $value;
                $ord_orbi_id = $ord_orbi_id . ' THEN ' . $request['orbi_id'];
                // 更改时间
                $update_time = $update_time . ' WHEN ' . $value;
                $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
                //要更改的订单id
                $ord_id = $ord_id . $value . ',';
            }
            $sql = $sql . ' `ord_orbi_id`= CASE `ord_id` ' . $ord_orbi_id . ' END,';
            $sql = $sql . ' `ord_update_time`= CASE `ord_id` ' . $update_time . ' END';
            $sql = $sql . ' WHERE `ord_id` IN (' . trim($ord_id, ',') . ')';
            $save_order = DB::update($sql);
            $recr_type = 3;
            $ord_close_price = $ord_total_price;
        }

        if ($orbi->orbi_merge_state == 1) {
            // 选择合并代收金额，实收金额=结算金额-代收金额
            $ord_total_price = $ord_total_price - $orbi_collection_price; //实收金额
        }
        if ($ord_total_price >= 0) {
            $orbi_plus_minus = 1;
        } else {
            $orbi_plus_minus = 2;
        }
        // 3.修改单量 改为待审核状态
        $update_bill['orbi_order_amount'] = count($request['ord_id']); //单量
        $update_bill['orbi_state'] = 3; //3.待审核
        $update_bill['orbi_update_time'] = date('Y-m-d H:i:s');
        $update_bill['orbi_total_price'] = abs($ord_total_price);
        $update_bill['orbi_collection_price'] = abs($orbi_collection_price);
        $update_bill['orbi_actual_price'] = abs($ord_total_price);
        $update_bill['orbi_bill_price'] = abs($ord_total_price);
        $update_bill['orbi_plus_minus'] = $orbi_plus_minus;
        $bill_data = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->update($update_bill);

        if ($orbi->orbi_state == 1) {
            $credit_data = DB::table('receivable_credit')
                ->where('recr_belongs_id', $request['orbi_id'])
                ->update(['recr_belongs_id' => 0, 'recr_statistics_type' => 1, 'recr_update_time' => date('Y-m-d H:i:s')]);

            $del_data = DB::table('receivable_credit')
                ->where('recr_original_id', $request['orbi_id'])
                ->where('recr_type', $recr_type)
                ->delete();
        } else {
            $credit_data = true;
            $del_data = true;
        }

        if (!empty($wor_number_one)) {
            $recr_edit_data['recr_leisurely_type'] = 1;
            $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
            $update_recr = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', 4)
                ->where('recr_account_type', 3)
                ->whereIn('recr_original_number', $wor_number_one)
                ->update($recr_edit_data);
        } elseif (!empty($original_id)) {
            $recr_edit_data['recr_leisurely_type'] = 3;
            $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
            $update_recr = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', 3)
                ->where('recr_account_type', 2)
                ->whereIn('recr_original_number', $original_id)
                ->update($recr_edit_data);
        } else {
            $update_recr = true;
        }

        if ($relieve_relation && $save_order && $bill_data && $del_data && $credit_data && $update_recr) {
            Common::addLog($user_info, getRealIp($request), '订单账单', '编辑', $request['orbi_number'] . '编辑成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑失败']);
        }
    }

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

        $orbi_data = collect(DB::table('order_bill as ob')
            ->leftjoin('admin as a', 'ob.orbi_create_adm_id', '=', 'a.adm_id')
            ->whereIn('orbi_id', $request['orbi_id'])
            ->get(['orbi_type', 'orbi_state', 'orbi_number', 'orbi_client_id', 'orbi_receive_price', 'orbi_id', 'orbi_bill_price', 'adm_name', 'orbi_plus_minus', 'orbi_img', 'orbi_create_adm_id', 'orbi_total_price', 'orbi_collection_price', 'orbi_actual_price', 'orbi_create_type', 'orbi_sd_affirm']))
            ->keyBy('orbi_id')
            ->toArray();

        $user_info = Common::getUserInfo($request['api_token']);
        $error_orbi_number = []; //错误单号
        $orbi_type_one = []; //门店零售类型账单
        $orbi_type_three = []; //速电网单
        $orbi_type_five = []; //加盟店
        $orbi_type_two = []; //来往单位
        $orbi_type_four = []; //虚拟加盟店
        $orbi_number = []; //账单单号
        $orbi_count = count($request['orbi_id']); //账单数量
        foreach ($orbi_data as $key => $value) {
            if (in_array($value->orbi_state, [2, 3, 4])) {
                $error_orbi_number[] = $value->orbi_number;
            }
            // 门店零售类型账单
            if ($orbi_count > 1 && $value->orbi_type == 1) {
                $orbi_type_one[] = $value->orbi_number;
            }
            // 速电网单
            if ($orbi_count > 1 && $value->orbi_type == 3) {
                $orbi_type_three[] = $value->orbi_number;
            }
            // 加盟店
            if ($orbi_count > 1 && $value->orbi_type == 5) {
                $orbi_type_five[] = $value->orbi_number;
            }
            // 来往单位
            if ($orbi_count > 1 && $value->orbi_type == 2) {
                $orbi_type_two[] = $value->orbi_client_id;
            }
            // 虚拟加盟店
            if ($orbi_count > 1 && $value->orbi_type == 4) {
                $orbi_type_four[] = $value->orbi_client_id;
            }
            if ($value->orbi_create_type == 2 && $value->orbi_sd_affirm == 0) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'速电账单:' . $value->orbi_number . ',请首先到速电账单列表点击确认']);
            }
            $orbi_number[] = $value->orbi_number;
        }
        if (!empty($error_orbi_number)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账单:' . implode($error_orbi_number, ',') . '不是未结算状态']);
        }
        if ((count($orbi_type_one) > 0) && ($orbi_type_one != $orbi_count)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账单:' . implode($orbi_type_one, ',') . '不能批量结算']);
        }
        if ((count($orbi_type_three) > 0) && (count($orbi_type_three) != $orbi_count)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账单:' . implode($orbi_type_three, ',') . '不能批量结算']);
        }
        if ((count($orbi_type_five) > 0) && (count($orbi_type_five) != $orbi_count)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账单:' . implode($orbi_type_five, ',') . '不能批量结算']);
        }

        if (!empty($orbi_type_two)) {
            $orbi_type_count = array_unique($orbi_type_two);
            if (count($orbi_type_count) != 1) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'所选账单非同一客户单位，请重新选择！']);
            }
        }
        if (!empty($orbi_type_four)) {
            $orbi_type_count = array_unique($orbi_type_four);
            if (count($orbi_type_count) != 1) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'所选账单非同一客户单位，请重新选择！']);
            }
        }
        if (!empty($orbi_type_two) && !empty($orbi_type_four)) {
            $vish_chun_id = DB::table('virtual_shop')
                ->whereIn('vish_id', $orbi_type_four)
                ->value('vish_chun_id');
            if ($vish_chun_id != $orbi_type_two[0]) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'所选账单非同一客户单位，请重新选择！']);
            }
        }
        if ($request['type'] == 1) {
            $plus = [];
            $minus = [];
            foreach ($orbi_data as $key => $value) {
                $orbi_data[$key]->not_price = $value->orbi_actual_price - $value->orbi_receive_price;
                if ($value->orbi_plus_minus == 1) {
                    $plus[] = $value;
                } else {
                    $minus[] = $value;
                }
            }
            if (!empty($plus)) {
                $plus = $this->getPao($plus);
            }
            if (!empty($minus)) {
                $minus = $this->getPao($minus);
            }
            $data = array_merge($minus, $plus);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }

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

        $few = 0;
        $img = '';
        if (!empty($request['orbi_img'])) {
            foreach ($request['orbi_img'] as $key => $value) {
                // 调用全局函数 上传图片
                $img .= uploadBase64Img($value) . ',';
                $few++;
            }
            $img = trim($img, ',');
            // 链接上以前的图片
            $img = $orbi_data[$request['orbi_id'][0]]->orbi_img . ',' . $img;
            $img = trim($img, ',');
            if ($few > 6) {
                return response()->json(['code'=>500, 'msg'=>'最多上传六张图片', 'data'=>'{}']);
            }
        }

        // 结算凭证
        $acset_few = 0;
        $acset_img = '';
        if (!empty($request['acset_img'])) {
            foreach ($request['acset_img'] as $key => $value) {
                // 调用全局函数 上传图片
                $acset_img .= uploadBase64Img($value) . ',';
                $acset_few++;
            }
            $acset_img = trim($acset_img, ',');
            if ($acset_few > 6) {
                return response()->json(['code'=>500, 'msg'=>'最多上传六张图片', 'data'=>'{}']);
            }
        }

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $orbi_id = [];
        $zero_count_price = 0; //抹零总金额
        $settle_price = 0;
        DB::beginTransaction();
        $content = json_decode($request['content'], true);

        foreach ($content as $key => $value) {
            if (($value['orbi_id'] < 1) || !in_array($value['is_zero'], [1, 2]) || !is_numeric($value['settle_price']) || !is_numeric($value['zero_price'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }

            // 抹零金额 保留两位小数
            if (!empty($value['zero_price'])) {
                if (is_float($value['zero_price'])) {
                    $zero_price = round($value['zero_price'], 2);
                } else {
                    $zero_price = $value['zero_price'];
                }
            } else {
                $zero_price = 0;
            }

            // 抹零总金额
            $zero_count_price += $zero_price;
            // 结算金额
            if (is_float($value['settle_price'])) {
                $value['settle_price'] = round($value['settle_price'], 2);
            }
            // 结算总金额
            $settle_price += $value['settle_price'];
            // 已结金额
            $receive_price = $orbi_data[$value['orbi_id']]->orbi_receive_price;
            // 未结金额
            $yet_price = $orbi_data[$value['orbi_id']]->orbi_actual_price - $receive_price;

            // 抹零金额
            if ($zero_price < 0) {
                $zero_price = abs($zero_price);
                $zero_plus_minus = 2;
            } else {
                $zero_plus_minus = 1;
            }
            // is_zero  1抹零2不抹零
            if ($value['is_zero'] == 1) {
                /**
                 * 判断抹零金额正负
                 * 【门店多收，客户多付，抹零金额显示负数】,【门店少收，客户少付，抹零金额显示正数】
                 * 账单结款金额100元，实际收款150元，抹零-50元
                 * 账单金额100元，实际收款80元，抹零金额20元
                 * 数据库查询已收金额 + 当前提交的已收金额 + 抹零金额 > 结款金额,多收
                 * 数据库查询已收金额 + 当前提交的已收金额 + 抹零金额 < 结款金额,少收
                 */
                $actual_price = $orbi_data[$value['orbi_id']]->orbi_receive_price + $value['settle_price'] * 100 + $zero_price * 100;
                if ($actual_price > $orbi_data[$value['orbi_id']]->orbi_actual_price) {
                    $zero_plus_minus = 2;
                } else {
                    $zero_plus_minus = 1;
                }
            } else {
                $zero_plus_minus = 1;
            }
            $zero_price = $zero_price * 100;
            // 结算金额
            if ($value['settle_price'] < 0) {
                $value['settle_price'] = abs($value['settle_price']);
                $settle_plus_minus = 2;
            } else {
                $settle_plus_minus = 1;
            }
            $value['settle_price'] = $value['settle_price'] * 100;
            // 是否抹零  1是2否  未结金额 等于 本次结算金额
            if (($value['is_zero'] == 1) || ($yet_price == $value['settle_price'])) {
                // orbi_state 账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
                $orbi_state = 2;
            } else {
                $orbi_state = 5;
            }
            // 修改订单账单表
            $update_bill = DB::update('UPDATE `faster_order_bill` SET `orbi_receive_price`=`orbi_receive_price`+' . $value['settle_price'] . ', `orbi_zero_price`=`orbi_zero_price`+' . $zero_price . ',`orbi_state`= ' . $orbi_state . ' , `orbi_payee_id`= ' . $user_info->adm_id . ' ,`orbi_img`= "' . $img . '" ,`orbi_payment_time`= "' . date('Y-m-d H:i:s') . '" ,`orbi_update_time`= "' . date('Y-m-d H:i:s') . '" WHERE `orbi_id`=?', [$value['orbi_id']]);

            //订单结款修改
            $order_recr = DB::table('order')
                ->where('ord_orbi_id', $value['orbi_id'])
                ->select('ord_id', 'ord_order_number','ord_order_price', 'ord_type')
                ->get()->toArray();//账单id对应的所有订单id
            if($order_recr){
                $i = 1;
                foreach ($order_recr as $order_key => $order_value){
                    unset($order_params);unset($recr_edit_data);
                    $update_zero_price = $zero_price;
                    if($zero_plus_minus == 2){
                        $update_zero_price = -($zero_price);
                    }
                    $recr_edit_data['recpay_zero_plus_minus'] = 1;
                    $recr_edit_data['recpay_zero_price'] = 0;
                    $recr_edit_data['recpay_zero_remark'] = '';
                    if($i == 1 && $value['is_zero'] == 1){//需要抹零，就抹第一个订单
                        $recr_edit_data['recpay_zero_plus_minus'] = $zero_plus_minus;
                        $recr_edit_data['recpay_zero_price'] = $zero_price;
                        $recr_edit_data['recpay_zero_remark'] = '抹零金额';
                        $order_params['ord_zero_price'] = $zero_price;
                        $order_params['ord_plus_minus'] = $zero_plus_minus;
                        $order_params['ord_actual_price'] = $order_value->ord_order_price - $zero_price;//结算金额
                    }else{
                        $order_params['ord_actual_price'] = $order_value->ord_order_price;//结算金额
                    }
                    $order_id = $order_value->ord_id;//订单id
                    //一、修改订单结款
                    
                    $order_params['ord_payment_way'] = 4;//1现金、2支付宝、3微信、4银行卡
                    $order_params['ord_payment_money'] = $order_value->ord_order_price;//支付金额
                    $order_params['ord_banlance'] = 0;
                    $order_params['ord_settlement_adm_id'] = $user_info->adm_id;//结算人
                    $order_params['ord_settlement_time'] = date('Y-m-d H:i:s');//结算时间
                    $order_params['ord_state'] = 2;//结算状态1未结算2已结算
                    $order_params['ord_pay_state'] = 1;//是否支付1是2否
                    $order_params['ord_update_time'] = date('Y-m-d H:i:s');
                    $up_order = DB::table('order')
                        ->where('ord_id', $order_value->ord_id)
                        ->update($order_params);
                    $ord_data = DB::table('order')
                        ->where('ord_id', $order_id)
                        ->select('ord_state', 'ord_wor_state', 'ord_type', 'ord_client_id', 'ord_order_price')
                        ->first();
                    if ($ord_data->ord_state == 2 && ($ord_data->ord_wor_state == 4 || $ord_data->ord_wor_state == 20) && $ord_data->ord_type == 1) {//已结算 待评价或已完成 个人会员 添加积分
                        $add_point = WashOrderBasicService::addPoint($user_info,$ord_data->ord_client_id,$order_id);
                    }
                    if ($order_value->ord_type == 1) {//个人会员欠款
                        $find_mem = DB::table('member')
                            ->where('mem_id', $ord_data->ord_client_id)
                            ->select('mem_arrears')
                            ->first();
                        // 修改欠款金额
                        $update_data_mem['mem_arrears'] = $find_mem->mem_arrears - $ord_data->ord_order_price;
                        $update_data_mem['mem_update_time'] = date('Y-m-d H:i:s');
                        $update_data_mem_res = DB::table('member')->where('mem_id', $ord_data->ord_client_id)->update($update_data_mem);
                    } elseif ($order_value->ord_type == 2) {//企业会员欠款
                        $find_mem = DB::table('business_account')
                            ->leftJoin('business_client', 'bucl_id', '=', 'buac_bucl_id')
                            ->where('buac_id', $ord_data->ord_client_id)
                            ->select('buac_arrears', 'buac_bucl_id', 'bucl_arrears')
                            ->first();
                        $update_data_mem['buac_arrears'] = $find_mem->buac_arrears - $request['ord_actual_amout']*100;
                        $update_data_mem['buac_update_time'] = date('Y-m-d H:i:s');
                        $update_data_mem_res = DB::table('business_account')->where('buac_id', $ord_data->ord_client_id)->update($update_data_mem);

                        $update_bucl['bucl_arrears'] = $find_mem->bucl_arrears - $ord_data->ord_order_price;
                        $update_bucl['bucl_update_time'] = date('Y-m-d H:i:s');
                        $update_bucl_res = DB::table('business_client')->where('bucl_id', $find_mem->buac_bucl_id)->update($update_bucl);
                    }
                    //二、 修改应收应付结款
                    $find_recr = DB::table('receivable_pay')
                        ->where('recpay_cid', $user_info->adm_cid)
                        ->where('recpay_shop_superior_id', $shop_id)
                        ->where('recpay_original_id', $order_value->ord_id)
                        ->select('recpay_id', 'recpay_remark', 'recpay_original_number', 'recpay_receivable_price', 'recpay_cost_price', 'recpay_receivable_pay')
                        ->first();
                    if($find_recr){
                        //$recr_edit_data['recpay_actual_price'] = $orbi_data[$value['orbi_id']]->orbi_receive_price + $value['settle_price'];//实收金额
                        $recr_edit_data['recpay_actual_price'] = $find_recr->recpay_receivable_price - $recr_edit_data['recpay_zero_price'];//实收金额
                        $recr_edit_data['recpay_remark'] = isset($find_recr->recpay_remark) ? $find_recr->recpay_remark : '';
                        $recr_edit_data['recpay_update_time'] = date('Y-m-d H:i:s');

                        $recr_edit_data['recpay_arrears_price'] = 0;//应收 - 实收 - 抹零= 欠收金额
                        $profit = $recr_edit_data['recpay_actual_price'] - $find_recr->recpay_cost_price -  $find_recr->recpay_receivable_pay;
                        if($profit > 0){
                            $minus = 1;
                        }else{
                            $minus = 2;
                            $profit = abs($profit);
                        }
                        $recr_edit_data['recpay_plus_minus'] = $minus;
                        $recr_edit_data['recpay_profit'] = $profit;
                        $createBill = DB::table('receivable_pay')
                            ->where('recpay_id', $find_recr->recpay_id)
                            ->update($recr_edit_data);
                    }
                    $i++;
                }
            }
            //if (!$createBill && !$update_bill && !$subtract) {
            if (!$createBill && !$update_bill) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结款失败']);
            }
            if ($orbi_count == 1) {
                $acset_original_id = $value['orbi_id'];
                $acset_original_number = $orbi_data[$value['orbi_id']]->orbi_number;
                $acset_client_type = $orbi_data[$value['orbi_id']]->orbi_type; //买家类型
                $acset_client_id = $orbi_data[$value['orbi_id']]->orbi_client_id; //买家id
                // orbi_type 客户类型 1.门店零售 2.来往单位
                if ($orbi_data[$value['orbi_id']]->orbi_type == 1) {
                    // 获取零售客户姓名
                    $client_name = DB::table('member')
                        ->where('mem_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->value('mem_name');
                } elseif ($orbi_data[$value['orbi_id']]->orbi_type == 2) {
                    // 获取来往单位名称
                    /*$client_name = DB::table('channel_unit')
                        ->where('chun_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->value('chun_unit_name');*/
                    $client_name = DB::table('business_client')
                        ->where('bucl_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->value('bucl_name');
                } elseif ($orbi_data[$value['orbi_id']]->orbi_type == 5) {
                    // 获取来往单位名称
                    $client_name = DB::table('shop')
                        ->where('shop_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->value('shop_store_name');
                } elseif ($orbi_data[$value['orbi_id']]->orbi_type == 4) {
                    // 获取来往单位名称
                    $client_name = DB::table('virtual_shop')
                        ->where('vish_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->value('vish_store_name');
                } else {
                    $client_name = '速电网单';
                }
                $more_type = 1;
            } else {
                $acset_original_id = 0; //与单据类型对应的id
                $acset_original_number = 0; //与单据类型对应的单号

                if ($orbi_data[$value['orbi_id']]->orbi_type == 2) {
                    // 获取来往单位名称
                    $client = DB::table('channel_unit')
                        ->where('chun_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->first(['chun_unit_name', 'chun_id']);
                    $client_name = DB::table('business_client')
                        ->where('bucl_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->value('bucl_name');
                    //$client_name = $client->chun_unit_name;
                    $acset_client_id = $client->chun_id; //买家id
                } elseif ($orbi_data[$value['orbi_id']]->orbi_type == 3) {
                    $client_name = config('apisystem.sd_chan_info')['name'];
                    $acset_client_id = 0;
                } else {
                    // 获取来往单位名称
                    $client = DB::table('virtual_shop')
                        ->where('vish_id', $orbi_data[$value['orbi_id']]->orbi_client_id)
                        ->first(['vish_store_name', 'vish_chun_id']);
                    $client_name = $client->vish_store_name;
                    $acset_client_id = $client->vish_chun_id; //买家id
                }
                $acset_client_type = $orbi_data[$value['orbi_id']]->orbi_type; //买家类型

                $more_type = 2;
            }
            // 关联表数据添加
            $more[$key]['more_orbi_id'] = $value['orbi_id'];
            $more[$key]['more_this_settle_price'] = $value['settle_price'];
            $more[$key]['more_this_plus_minus'] = $settle_plus_minus;
            $more[$key]['more_zero_plus_minus'] = $zero_plus_minus;
            $more[$key]['more_zero_price'] = $zero_price;
            // 预收款抵账  是预收款id    否则是银行卡号
            if ($request['orbi_payment_type'] == 3) {
                $more[$key]['more_acti_id'] = $request['recr_id'];
            } else {
                $more[$key]['more_acti_id'] = $request['acti_id'];
            }
            $more[$key]['more_acti_id'] = 1;
            $more[$key]['more_type'] = $more_type;
            $more[$key]['more_recr_id'] = $find_recr->recpay_id;
            if ($orbi_state == 2) {
                $more[$key]['more_state'] = 2;
            } else {
                $more[$key]['more_state'] = 1;
            }
            // 预收款记录添加
            $add_rece[$key]['rede_advance_id'] = isset($request['recr_id']) ? $request['recr_id'] : 0; //预付款的应收账款id
            $add_rece[$key]['rede_recr_id'] = $find_recr->recpay_id; //账单应付账款id
        }
        // 合计金额
        $acset_price = $settle_price - $zero_count_price;

        // 结算金额正负值
        if ($settle_price < 0) {
            $acset_inex_type = 2;
            $settle_price = abs($settle_price);
        } else {
            $acset_inex_type = 1;
        }
        $settle_price = $settle_price * 100;
        // 抹零金额正负值
        if ($zero_count_price < 0) {
            $acset_zero_plus_minus = 2;
            $zero_count_price = abs($zero_count_price);
        } else {
            $acset_zero_plus_minus = 1;
        }

        // 如果只结一条
        if ($orbi_count == 1) {
            // 结款类型1.抹零 2.分期结款 3.预收款抵账4正常5收款6还款7批量结款
            if ($zero_count_price == 0) {
                if ($orbi_state == 2) {
                    $acset_payment_type = 4;
                } else {
                    $acset_payment_type = 2;
                }
            } else {
                $acset_payment_type = 1;
            }
            if (in_array($orbi_data[$request['orbi_id'][0]]->orbi_create_type, [1, 2])) {
                $acset_type = 2;
            } elseif ($orbi_data[$request['orbi_id'][0]]->orbi_create_type == 3) {
                $acset_type = 3;
            } elseif ($orbi_data[$request['orbi_id'][0]]->orbi_create_type == 5) {
                $acset_type = 4;
            } else {
                $acset_type = 26; //期初账单
            }
        } else {
            $acset_payment_type = 7; //批量结算
            $acset_type = 25; //批量结算
        }
        // 预收款抵账
        if ($request['orbi_payment_type'] == 3) {
            if ($acset_inex_type == 2) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'使用预收款结算金额不能为负数']);
            }
            if (empty($request['recr_id'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $rece = DB::table('receivable_pay')
                ->where('recpay_id', $request['recr_id'])
                ->where('recpay_state', 3)
                ->first(['recpay_actual_price']);
            if ($rece->recr_actual_price < (int)$settle_price) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结算金额不能大于此预收款金额']);
            }
            $acset_payment_type = 3;

            $recr_state = '';
            if ((int)$settle_price == $rece->recr_actual_price) {
                $recr_state = '`recr_state` = 2,'; //核销状态
            }
            // 预收款金额，实际金额减少，已收金额增加
            $subtract = DB::update('UPDATE `faster_receivable_pay` SET `recr_actual_price`=`recr_actual_price`-' . $settle_price . ',' . $recr_state . ' `recr_yet_receipt`=`recr_yet_receipt`+' . $settle_price . ' WHERE `recr_id`=?', [$request['recr_id']]);
        } else {
            $subtract = true;
        }

        // 结款明细表新增数据
        $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'] = $acset_type; //批量结算
        $record['acset_payment_type'] = $acset_payment_type; //结款类型 7批量结款
        $record['acset_original_id'] = $acset_original_id; //与单据类型对应的id
        $record['acset_original_number'] = $acset_original_number; //与单据类型对应的单号
        $record['acset_client_type'] = $acset_client_type; //买家类型1门店零售2来往单位
        $record['acset_client_id'] = $acset_client_id; //会员id
        $record['acset_client_name'] = $client_name; //来往单位名称
        $record['acset_with_time'] = date('Y-m-d H:i:s'); //结款时间
        if ($request['orbi_payment_type'] == 3) {
            $record['acset_acti_id'] = $request['recr_id']; //预收款id
        } else {
            $record['acset_acti_id'] = $request['acti_id']; //会计科目id
        }
        $record['acset_acti_id'] = 1; //会计科目id
        $record['acset_inex_type'] = $acset_inex_type; //类型1收入2支出
        $record['acset_actual_price'] = $settle_price; //实际金额
        $record['acset_price'] = abs($acset_price) * 100; //合计金额
        $record['acset_owe_price'] = 0; //欠收金额
        $record['acset_zero_price'] = $zero_count_price * 100; //抹零金额
        $record['acset_remark'] = $request['remark'] ?: ''; //备注
        $record['acset_update_time'] = date('Y-m-d H:i:s'); //修改时间
        $record['acset_merge_type'] = 1; //修改时间
        $record['acset_zero_plus_minus'] = $acset_zero_plus_minus; //抹零金额正负值
        $record['acset_img'] = $acset_img; //批量结算的结算凭证
        $record_add = DB::table('accounting_settlement')->insertGetId($record);

        // 预收款抵账
        if ($request['orbi_payment_type'] == 3) {
            foreach ($add_rece as $key => $value) {
                $add_rece[$key]['rede_acset_id'] = $record_add; //预收款抵账的结款明细id
            }
            $details_res = DB::table('receivable_details')->insert($add_rece);
        } else {
            $details_res = true;
        }

        // 关系表数据添加
        foreach ($more as $key => $value) {
            $more[$key]['more_acset_id'] = $record_add;
        }
        $more_res = DB::table('money_record')->insert($more);
        if ($record_add && $more_res && $subtract) {
            Common::addLog($user_info, getRealIp($request), '订单账单', '结款', implode($orbi_number, ',') . '结款成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'结款成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结款失败']);
        }
    }

    public function getPao($arr)
    {
        $len = count($arr);
        // 设置一个空数组 用来接收冒出来的泡
        for ($i = 1; $i < $len; $i++) { //该层循环用来控制每轮 冒出一个数 需要比较的次数
            for ($k = 0; $k < $len - $i; $k++) {
                if ($arr[$k]->not_price < $arr[$k + 1]->not_price) {
                    $tmp = $arr[$k + 1];
                    $arr[$k + 1] = $arr[$k];
                    $arr[$k] = $tmp;
                }
            }
        }
        return $arr;
    }

    // 结款记录
    public function moneyRecord(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (empty($request['orbi_id'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }

        $search_data = $request->all();
        $list_data = DB::table('money_record as mr')
            ->leftjoin('accounting_settlement as as', 'as.acset_id', '=', 'mr.more_acset_id')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'as.acset_adm_id')
            // ->leftjoin('account_title as at','at.acti_id','=','mr.more_acti_id')
            ->where('more_orbi_id', $request['orbi_id'])
            ->select('acset_number', 'adm_name', 'more_this_settle_price', 'more_this_plus_minus', 'more_zero_price', 'more_zero_plus_minus', 'more_type', 'acset_remark', 'more_acti_id', 'acset_payment_type','acset_img')
            ->orderBy('more_id', 'desc')
            ->paginate($this->show_count);

        $info = DB::table('order_bill as ob')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'ob.orbi_create_adm_id')
            ->where('orbi_id', $request['orbi_id'])
            ->first(['orbi_start_time', 'orbi_end_time', 'orbi_create_time', 'adm_name', 'orbi_type', 'orbi_client_id', 'orbi_total_price', 'orbi_receive_price', 'orbi_zero_price', 'orbi_plus_minus', 'orbi_actual_price']);

        if ($info->orbi_type == 2) {
            // 来往单位
            /*$info->orbi_client_name = DB::table('channel_unit')
                ->where('chun_id', $info->orbi_client_id)
                ->value('chun_unit_name');*/
            $info->orbi_client_name = DB::table('business_client')
                ->where('bucl_id', $info->orbi_client_id)
                ->value('bucl_name');
        } elseif ($info->orbi_type == 1) {
            // 客户名称
            /*$info->orbi_client_name = DB::table('admin')
                ->where('adm_id', $info->orbi_client_id)
                ->value('adm_name');*/
            $member = DB::table('member')
                ->where('mem_id', $info->orbi_client_id)
                ->first(['mem_name', 'mem_phone', 'mem_address']);
            $info->orbi_client_name = $member->mem_name;
            $info->orbi_client_phone = $member->mem_phone;
        } elseif ($info->orbi_type == 4) {
            // 虚拟加盟店
            $info->orbi_client_name = DB::table('virtual_shop')
                ->where('vish_id', $info->orbi_client_id)
                ->value('vish_store_name');
        } elseif ($info->orbi_type == 5) {
            // 加盟店
            $info->orbi_client_name = DB::table('shop')
                ->where('shop_id', $info->orbi_client_id)
                ->value('shop_store_name');
        }

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

        if (!empty($data_info['data'])) {
            foreach ($data_info['data'] as $key => $value) {
                if ($value->more_zero_price == 0) {
                    $data_info['data'][$key]->zero_type = 2;
                } else {
                    $data_info['data'][$key]->zero_type = 1;
                }
                //预收款抵账
                if ($value->acset_payment_type == 3) {
                    $course_title = DB::table('receivable_credit')
                        ->where('recr_id', $value->more_acti_id)
                        ->value('recr_original_number');
                    $data_info['data'][$key]->acti_course_title = '预收款抵账(' . $course_title . ')';
                } else {
                    $data_info['data'][$key]->acti_course_title = DB::table('account_title')
                        ->where('acti_id', $value->more_acti_id)
                        ->value('acti_course_title');
                }
                if($value->acset_img){
                    $acset_img = explode(',',$value->acset_img);
                    unset($acset_arr);
                    foreach ($acset_img as $a_k => $a_v){
                        $acset_arr[] = config('apisystem.server_name_https').'/'.$a_v;
                        //$acset_arr[] = 'http://xmtest.bluearp.com/'.$a_v;
                    }
                    $data_info['data'][$key]->acset_img = $acset_arr;
                }
            }
        }

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

    // 结款记录导出
    public function export(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (empty($request['orbi_id'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }

        $search_data = $request->all();
        $list_data = DB::table('money_record as mr')
            ->leftjoin('accounting_settlement as as', 'as.acset_id', '=', 'mr.more_acset_id')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'as.acset_adm_id')
            // ->leftjoin('account_title as at','at.acti_id','=','mr.more_acti_id')
            ->where('more_orbi_id', $request['orbi_id'])
            ->select('acset_number', 'adm_name', 'more_this_settle_price', 'more_this_plus_minus', 'more_zero_price', 'more_zero_plus_minus', 'more_type', 'acset_remark', 'acset_payment_type', 'more_acti_id')
            ->orderBy('more_id', 'desc')
            ->get();

        $info = DB::table('order_bill as ob')
            ->leftjoin('admin as a', 'a.adm_id', '=', 'ob.orbi_create_adm_id')
            ->where('orbi_id', $request['orbi_id'])
            ->first(['orbi_start_time', 'orbi_end_time', 'orbi_create_time', 'adm_name', 'orbi_type', 'orbi_client_id', 'orbi_total_price', 'orbi_receive_price', 'orbi_zero_price', 'orbi_plus_minus', 'orbi_number']);

        if ($info->orbi_type == 2) {
            // 来往单位
            $info->orbi_client_name = DB::table('channel_unit')
                ->where('chun_id', $info->orbi_client_id)
                ->value('chun_unit_name');
        } elseif ($info->orbi_type == 1) {
            // 客户名称
            $info->orbi_client_name = DB::table('admin')
                ->where('adm_id', $info->orbi_client_id)
                ->value('adm_name');
        } elseif ($info->orbi_type == 4) {
            // 虚拟加盟店
            $info->orbi_client_name = DB::table('virtual_shop')
                ->where('vish_id', $info->orbi_client_id)
                ->value('vish_store_name');
        } elseif ($info->orbi_type == 5) {
            // 加盟店
            $info->orbi_client_name = DB::table('shop')
                ->where('shop_id', $info->orbi_client_id)
                ->value('shop_store_name');
        }

        $data_info['data'] = $list_data;
        if (!empty($data_info['data'])) {
            foreach ($data_info['data'] as $key => $value) {
                if ($value->more_zero_price == 0) {
                    $data_info['data'][$key]->zero_type = '否';
                } else {
                    $data_info['data'][$key]->zero_type = '是';
                }
                if ($value->more_this_plus_minus == 1) {
                    $data_info['data'][$key]->more_this_settle_price = $value->more_this_settle_price / 100;
                } else {
                    $data_info['data'][$key]->more_this_settle_price = '-' . $value->more_this_settle_price / 100;
                }
                if ($value->more_zero_plus_minus == 1) {
                    $data_info['data'][$key]->more_zero_price = $value->more_zero_price / 100;
                } else {
                    $data_info['data'][$key]->more_zero_price = '-' . $value->more_zero_price / 100;
                }
                if ($value->more_type == 1) {
                    $data_info['data'][$key]->more_type = '独立结款';
                } else {
                    $data_info['data'][$key]->more_type = '批量结款';
                }

                // 预收款抵账
                if ($value->acset_payment_type == 3) {
                    $course_title = DB::table('receivable_credit')
                        ->where('recr_id', $value->more_acti_id)
                        ->value('recr_original_number');
                    $data_info['data'][$key]->acti_course_title = '预收款抵账(' . $course_title . ')';
                } else {
                    $data_info['data'][$key]->acti_course_title = DB::table('account_title')
                        ->where('acti_id', $value->more_acti_id)
                        ->value('acti_course_title');
                }
                unset($data_info['data'][$key]->more_this_plus_minus);
                unset($data_info['data'][$key]->more_zero_plus_minus);
                unset($data_info['data'][$key]->more_type);
                unset($data_info['data'][$key]->acset_payment_type);
                unset($data_info['data'][$key]->more_acti_id);
            }
        }

        unset($info->orbi_type);
        unset($info->orbi_client_id);
        $info->orbi_total_price = $info->orbi_total_price / 100;
        $info->orbi_receive_price = $info->orbi_receive_price / 100;
        if ($info->orbi_plus_minus == 2) {
            $info->orbi_receive_price = '合计金额:-' . $info->orbi_receive_price;
            $info->orbi_total_price = '已结金额:-' . $info->orbi_total_price;
        } else {
            $info->orbi_receive_price = '合计金额:' . $info->orbi_receive_price;
            $info->orbi_total_price = '已结金额:' . $info->orbi_total_price;
        }
        $info->orbi_client_name = '收款对象:' . $info->orbi_client_name;
        $info->adm_name = '创建人:' . $info->adm_name;
        $info->orbi_create_time = '创建时间:' . $info->orbi_create_time;
        $info->orbi_zero_price = '抹零金额:' . $info->orbi_zero_price;
        $info->time = '起止日期:' . $info->orbi_start_time . ' 至 ' . $info->orbi_end_time;
        unset($info->orbi_start_time);
        unset($info->orbi_end_time);
        unset($info->orbi_zero_price);
        unset($info->orbi_plus_minus);
        $data_info['info'] = $info;
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $where['field_name'] = ['流水号', '结款人', '结款金额', '抹零金额', '备注', '是否抹零', '发生对象'];
        $where['action_name'] = '结款记录';

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

    // 账单订单详情
    public function details(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        if ($request['ord_id']) {
            $data = DB::table('order_goods')
                ->where('orgo_ord_id', $request['ord_id'])
                ->get(['orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_quantity', 'orgo_goo_price']);
        } elseif ($request['cg_id']) {
            $pudata = DB::table('purchase_order')
                ->where('cg_id', $request['cg_id'])
                ->first(['cg_number']);
            $data = DB::table('storage_goods as stgo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'stgo.goods_id')
                ->where('relation_number', $pudata->cg_number)
                ->get(['goods_name as orgo_goo_name', 'goods_number as orgo_goo_goods_encode', 'goods_num as orgo_goo_quantity', 'univalence as orgo_goo_price', 'goo_brse_id', 'goo_class', 'goo_bra_name'])->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($data, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($data as $k => $v) {
                $data[$k]->orgo_goo_price = $data[$k]->orgo_goo_price * 100;
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v->goo_brse_id)) {
                        if ($v->goo_class == 2) {
                            $data[$k]->orgo_goo_name = $brse_data[$v->goo_brse_id] . ' ' . $v->orgo_goo_name;
                            unset($v->goo_brse_id);
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $data[$k]->orgo_goo_name = $brse_data[$v->goo_brse_id] . ' ' . $v->orgo_goo_name;
                                unset($v->goo_brse_id);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v->goo_class == 2) {
                        $data[$k]->orgo_goo_name = $v->goo_bra_name . ' ' . $data[$k]->orgo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $data[$k]->orgo_goo_name = $v->goo_bra_name . ' ' . $data[$k]->orgo_goo_name;
                        }
                    }
                }
            }
        } else {
            $data = DB::table('work_good as wogo')
                ->leftjoin('goods as goo', 'goo_id', '=', 'wogo.wogo_goo_id')
                ->where('wogo_wor_id', $request['wor_id'])
                ->get(['wogo_goo_name as orgo_goo_name', 'wogo_goo_goods_encode as orgo_goo_goods_encode', 'wogo_goo_amount as orgo_goo_quantity', 'wogo_goo_price as orgo_goo_price', 'goo_brse_id', 'goo_class', 'goo_bra_name'])->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($data, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($data as $k => $v) {
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($v->goo_brse_id)) {
                        if ($v->goo_class == 2) {
                            $data[$k]->orgo_goo_name = $brse_data[$v->goo_brse_id] . ' ' . $v->orgo_goo_name;
                            unset($v->goo_brse_id);
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $data[$k]->orgo_goo_name = $brse_data[$v->goo_brse_id] . ' ' . $v->orgo_goo_name;
                                unset($v->goo_brse_id);
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($v->goo_class == 2) {
                        $data[$k]->orgo_goo_name = $v->goo_bra_name . ' ' . $data[$k]->orgo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $data[$k]->orgo_goo_name = $v->goo_bra_name . ' ' . $data[$k]->orgo_goo_name;
                        }
                    }
                }
            }
        }
        if ($data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 账单导出
    public function billExport(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (empty($request['orbi_id'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }

        $orbi_data = DB::table('order_bill')
            ->where('orbi_id', $request['orbi_id'])
            ->first(['orbi_create_type', 'orbi_number']);
        // 等于3是工单账单
        if ($orbi_data->orbi_create_type == 3) {
            $data['data'] = DB::table('work_order as wo')
                ->leftjoin('work_good as wg', 'wo.wor_id', '=', 'wg.wogo_wor_id')
                ->leftjoin('work_client as wc', 'wc.wocl_wor_id', '=', 'wo.wor_id')
                ->where('wor_wobi_id', $request['orbi_id'])
                ->get(['wor_number', 'wor_plus_minus', 'wor_actual_price', 'wor_create_time', 'wogo_goo_name', 'wogo_goo_amount', 'wogo_goo_goods_encode', 'wogo_goo_price', 'wocl_name', 'wocl_name', 'wocl_phone', 'wor_remark']);
            $data['data'] = json_decode(json_encode($data['data']), true);
            if (empty($data['data'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
            foreach ($data['data'] as $key => $value) {
                if ($value['wor_plus_minus'] == 2) {
                    $data['data'][$key]['wor_actual_price'] = '-' . $value['wor_actual_price'] / 100;
                    $data['data'][$key]['wogo_goo_price'] = '-' . $value['wogo_goo_price'] / 100;
                } else {
                    $data['data'][$key]['wor_actual_price'] = $value['wor_actual_price'] / 100;
                    $data['data'][$key]['wogo_goo_price'] = $value['wogo_goo_price'] / 100;
                }
                unset($data['data'][$key]['wor_plus_minus']);
            }
        } elseif ($orbi_data->orbi_create_type == 5) {
            $dataarray = DB::table('purchase_order as a')
                ->leftjoin('ware_inorder as d', 'd.cg_number', '=', 'a.cg_number')
                ->leftjoin('storage_goods as b', 'b.relation_number', '=', 'd.rk_number')
                ->leftjoin('channel_unit as c', 'c.chun_id', '=', 'a.cg_supplyunit')
                ->where('cg_zdnumber', $orbi_data->orbi_number)
                ->get(['a.cg_number', 'b.create_time', 'b.goods_name', 'b.ruku_num', 'b.goods_number', 'b.univalence', 'c.chun_name', 'c.chun_phone', 'd.rk_number']);
            $dataarray = json_decode(json_encode($dataarray), true);
            if (empty($dataarray)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
            foreach ($dataarray as $key => $value) {
                $data['data'][$key]['ord_order_number'] = $value['cg_number'];
                /*if (substr($value['rk_number'],0,2) == 'CK') {
                    $data['data'][$key]['ord_actual_price'] = '-'.$value['univalence']*$value['rk_num'] / 100;
                    $orgo_goo_price = '-'.$value['univalence'] / 100;
                } else {*/
                $data['data'][$key]['ord_actual_price'] = $value['univalence'] * $value['ruku_num'] * -1;
                $orgo_goo_price = $value['univalence'] * -1;
                /// }
                $data['data'][$key]['ord_create_time'] = $value['create_time'];
                $data['data'][$key]['orgo_goo_name'] = $value['goods_name'];
                $data['data'][$key]['orgo_goo_unit'] = $value['goods_name'];
                $data['data'][$key]['orgo_goo_quantity'] = $value['ruku_num'];
                $data['data'][$key]['orgo_goo_goods_encode'] = $value['goods_number'];
                $data['data'][$key]['orgo_goo_price'] = $orgo_goo_price;
                $data['data'][$key]['orcl_name'] = $value['chun_name'];
                $data['data'][$key]['orcl_phone'] = $value['chun_phone'];
                $data['data'][$key]['ord_remark'] = '';
            }
        } else {
            $data['data'] = DB::table('order as o')
                ->leftjoin('order_goods as og', 'o.ord_id', '=', 'og.orgo_ord_id')
                ->leftjoin('order_client as oc', 'oc.orcl_ord_id', 'o.ord_id')
                ->where('ord_orbi_id', $request['orbi_id'])
                ->get(['ord_order_number', 'ord_order_plus_minus', 'ord_actual_price', 'ord_create_time', 'orgo_goo_name', 'orgo_goo_unit', 'orgo_goo_quantity', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orcl_name', 'orcl_phone', 'ord_remark','orcl_business_name','ord_type']);
            $data['data'] = json_decode(json_encode($data['data']), true);

            foreach ($data['data'] as $key => $value) {
                if ($value['ord_order_plus_minus'] == 2) {
                    $data['data'][$key]['ord_actual_price'] = '-' . $value['ord_actual_price'] / 100;
                    $data['data'][$key]['orgo_goo_price'] = '-' . $value['orgo_goo_price'] / 100;
                } else {
                    $data['data'][$key]['ord_actual_price'] = $value['ord_actual_price'] / 100;
                    $data['data'][$key]['orgo_goo_price'] = $value['orgo_goo_price'] / 100;
                }
                if($value['orcl_business_name'] != '' && $value['ord_type'] == 2){
                    $data['data'][$key]['orcl_name'] = $value['orcl_business_name'];
                }
                unset($data['data'][$key]['ord_order_plus_minus']);
                unset($data['data'][$key]['orcl_business_name']);
                unset($data['data'][$key]['ord_type']);
            }
            if ($orbi_data->orbi_create_type == 2) {
                $sdob_id = DB::table('sd_order_bill')
                    ->where('sdob_orbi_id', $request['orbi_id'])
                    ->value('sdob_id');
                $list_data = DB::table('sd_order_bill_details as so')
                    ->where('sobd_sdob_id', $sdob_id)
                    ->where('sobd_ord_order_number', '=', '')
                    ->select('sobd_order_number as ord_order_number', 'sobd_actual_price as ord_actual_price', 'sobd_create_time as ord_create_time')
                    ->get()->toArray();
                $list_data = json_decode(json_encode($list_data), true);
                foreach ($list_data as $key => $value) {
                    array_push($data['data'], $value);
                }
            }
            if (empty($data['data'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        }

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

        $where['field_name'] = ['单号', '实收金额', '添加时间', '商品名称', '商品单位', '商品数量', '商品编号', '单价', '企业名称', '客户电话', '备注'];
        $where['action_name'] = '账单详情';

        $streamFileRand = $orbi_data->orbi_number . '-' . rand(10000, 99999) . '.xls';
        $streamFilename = $pathName . '/' . $streamFileRand;
        // 调用导出的公共方法
        Common::headExport(
            $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'=>'导出失败']);
        }
    }

    // 期初账单
    public function openingBill(Request $request)
    {
        if ($request['type'] == 1) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/Template/openingBill.xlsx']);
        }
        $arr_number = [];
        $file = $request->file('file');
        if ($file->isValid()) {
            // 获取当前操作账号信息
            $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;
            //获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'文件大小不能超过5M']);
            }

            //限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'仅允许上传以xlsx结尾的后缀文件']);
            }
            if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
            }
            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            // if ($highestRow >52) {
            //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'一次最多导入50条数据']);
            // }
            $not_in = [];
            $usersExits = [];
            DB::beginTransaction();
            $i = 0;
            for ($j = 2; $j <= $highestRow; $j++) {
                $bill_add['orbi_cid'] = $user_info->adm_cid; //所属企业id
                $bill_add['orbi_shop_id'] = $user_info->adm_shop_id; //所属门店id
                $bill_add['orbi_superior_shop_id'] = $shop_id; //所属门店id
                // 客户单位名称
                $unit_name = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if (empty($unit_name)) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'客户单位名称必填']);
                }
                // if (strlen($unit_name) > 60) {
                //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'客户单位名称最多20个字符']);
                // }
                // //检索字母
                // $search_letter = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                // if (empty($search_letter)) {
                //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'检索字母必填']);
                // }

                // if (!preg_match("/^[a-zA-Z0-9\s]+$/", $search_letter)) {
                //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'检索字母由英文字母组成']);
                // }
                // 1. 判断客户单位名称是否存在
                $find_chun = DB::table('channel_unit')
                    ->where('chun_cid', $user_info->adm_cid)
                    ->where('chun_superior_shop_id', $shop_id)
                    // ->where('chun_search_letter', trim($search_letter))
                    ->where('chun_unit_name', trim($unit_name))
                    ->count();
                if ($find_chun > 1) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'重复 ' . $unit_name]);
                }
                $find_chun = DB::table('channel_unit')
                    ->where('chun_cid', $user_info->adm_cid)
                    ->where('chun_superior_shop_id', $shop_id)
                    // ->where('chun_search_letter', trim($search_letter))
                    ->where('chun_unit_name', trim($unit_name))
                    ->first(['chun_id', 'chun_unit_name']);

                if (empty($find_chun)) {
                    $not_in[] = $unit_name;
                    continue;
                }

                // 结款金额
                $actual_price = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                if (!is_numeric($actual_price)) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'客户单位类型必填']);
                }
                if ($actual_price === 0) {
                    $not_in[] = $unit_name;
                    continue;
                }
                $orbi_plus_minus = 1;
                if ($actual_price < 0) {
                    $actual_price = $actual_price * 100;
                    $orbi_plus_minus = 2;
                    $actual_price = abs($actual_price);
                } else {
                    $actual_price = $actual_price * 100;
                }

                // //期初日期
                // $opening_time = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                // if (empty($opening_time)) {
                //     return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'期初日期为空']);
                // }
                // $d = 25569;//excel和php之间相差的时间
                // $t = 24 * 60 * 60;//一天24小时
                // $opening_time = gmdate('Y-m-d', ($opening_time - $d) * $t);
                $opening_time = '2020-09-11';

                $number = 'QC' . time() . rand(10000000, 99999999);
                // 判断账单号是否重复
                $orbi_id = DB::table('order_bill')
                    ->where('orbi_number', $number)
                    ->value('orbi_id');
                if ($orbi_id) {
                    $number = 'QC' . time() . rand(10000000, 99999999);
                }
                $bill_add['orbi_number'] = $number;
                $bill_add['orbi_order_amount'] = 0;
                $bill_add['orbi_opening_time'] = $opening_time;

                $bill_add['orbi_total_price'] = $actual_price;
                $bill_add['orbi_bill_price'] = $actual_price;
                $bill_add['orbi_actual_price'] = $actual_price;
                $bill_add['orbi_state'] = 3;
                $bill_add['orbi_handle_adm_id'] = $user_info->adm_id;
                $bill_add['orbi_plus_minus'] = $orbi_plus_minus;
                $bill_add['orbi_type'] = 2;
                $bill_add['orbi_client_id'] = $find_chun->chun_id;
                $bill_add['orbi_merge_state'] = 2;
                $bill_add['orbi_create_type'] = 4; //4期初账单
                $bill_add['orbi_create_adm_id'] = $user_info->adm_id;
                // $bill_add['orbi_remark'] = '期初铺货';
                // $bill_add['orbi_remark'] = '期初应收';
                $bill_add['orbi_remark'] = '期初应付';
                $save_res = DB::table('order_bill')->insert($bill_add);
                $arr_number[] = $number;
                if (!$save_res) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'上传失败']);
                }
                $i++;
            }

            $url = storage_path() . '/logs/qichu.txt';
            $dir_name = dirname($url);
            //目录不存在就创建
            if (!file_exists($dir_name)) {
                //iconv防止中文名乱码
                mkdir(iconv("UTF-8", "GBK", $dir_name));
                chmod($dir_name, 0777);
            }
            $fp = fopen($url, "a"); //打开文件资源通道 不存在则自动创建
            date_default_timezone_set('PRC');
            flock($fp, LOCK_EX);
            if (is_array($not_in)) {
                $not_in = json_encode($not_in, JSON_UNESCAPED_UNICODE);
            }
            fwrite($fp, date("Y-m-d H:i:s") . ' ' . var_export($not_in, true) . "\r\n\r\n"); //写入文件
            flock($fp, LOCK_UN);
            fclose($fp); //关闭资源通道

            Common::addLog($user_info, getRealIp($request), '账单列表', '导入', '导入期初账单:'.implode($arr_number, ',').'成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'上传成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'上传有误,请重新上传']);
        }
    }
}
