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

use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountManage\VerifyBillContrastController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Models\Api\YongYou;
use App\Services\ReceivablePay\ReceivablePayService;

// 财务系统 -- 速电账单
class BillContrastController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

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

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        $search_data = $request->all();
        $list_data = DB::table('sd_order_bill')
            ->where('sdob_cid', $user_info->adm_cid)
            ->where('sdob_superior_shop_id', $shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['sd_bill_bumber'])) {
                    $query->where('sdob_sd_bill_bumber', 'like', '%' . $search_data['sd_bill_bumber'] . '%');
                }
            }) //账单状态
            ->where(function ($query) use ($search_data) {
                if (is_numeric($search_data['sdob_state'])) {
                    $query->where('sdob_state', $search_data['sdob_state']);
                }
            }) //账单状态
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('sdob_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('sdob_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('sdob_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->select('sdob_id', 'sdob_start_time', 'sdob_end_time', 'sdob_bill_price', 'sdob_create_time', 'sdob_state', 'sdob_orbi_number', 'sdob_sd_bill_price', 'sdob_sd_bill_bumber', 'sdob_shop_name', 'sdob_stl_ticket')
            ->orderBy('sdob_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        $status_name = self::getStatsName(true);
        foreach ($list_items as $key => $value) {
            $buttonData = [];
            if($value->sdob_state == 0){//未确认
                $buttonData[] = 'audit';
            }
            $buttonData[] = 'look';
            $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]->sdob_state_name = $status_name[$value->sdob_state];
            $list_items[$key]->sdob_nvoicingi_amount = $value->sdob_sd_bill_price - $value->sdob_stl_ticket;//开票金额
        }

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

        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'=>'0','value'=>'未确认'],['type'=>'1','value'=>'结算中'],['type'=>'3','value'=>'已结款'],['type'=>'2','value'=>'已撤销']];
        if($type){
            $status_names = array_column($status_names,'value','type');
        }
        return $status_names;
    }
    // 确认
    public function affirm(Request $request)
    {
        if (empty($request['sdob_id']) || empty($request['type']) || !in_array($request['type'], [1, 2])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        if ($request['type'] == 1) {
            $sd_bill = DB::table('sd_order_bill')
                ->where('sdob_id', $request['sdob_id'])
                ->first(['sdob_sd_bill_bumber', 'sdob_start_time', 'sdob_end_time', 'sdob_bill_price', 'sdob_orbi_id', 'sdob_shop_name']);

            $data['sd_order'] = DB::table('sd_order_bill_details')
                ->where('sobd_sdob_id', $request['sdob_id'])
                ->get(['sobd_order_number', 'sobd_actual_price', 'sobd_relative_price', 'sobd_ord_id', 'sobd_details_price', 'sobd_car_owner_name']);
            foreach ($data['sd_order'] as $key => $value) {
                $data['sd_order'][$key]->sobd_details_price = json_decode($value->sobd_details_price);
            }
            $data['mk_order'] = DB::table('order')
                ->where('ord_orbi_id', $sd_bill->sdob_orbi_id)
                ->get(['ord_order_number', 'ord_actual_price', 'ord_id']);
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
        $bill_data = DB::table('sd_order_bill')
            ->where('sdob_id', $request['sdob_id'])
            ->first(['sdob_sd_bill_bumber', 'sdob_sd_bill_price', 'sdob_orbi_id', 'sdob_start_time', 'sdob_end_time', 'sdob_bill_price', 'sdob_orbi_number']);
        // 获取当前操作账号信息
        $user_infos = Common::getUserInfo($request['api_token']);
        $user_info = CommonService::dataToArray($user_infos);
        $shop_id = $user_info['shop_superior_id'] ??$user_info['adm_shop_id'];
        if($shop_id == 0){
            $shop_id = $user_info['adm_shop_id'];
        }

        DB::beginTransaction();

        $orbi_id = DB::table('sd_order_bill')
            ->where('sdob_id', $request['sdob_id'])
            ->value('sdob_orbi_id');

        if(empty($orbi_id)){
            // 2.订单账单表新增一条数据
            // $number = 'DZ' . time() . rand(10000000, 99999999);
            $number = $bill_data->sdob_orbi_number;
            $data['sdob_orbi_id'] = $number;//本系统账单id
            $add_data['orbi_cid'] = $user_info['adm_cid'];
            $add_data['orbi_shop_id'] = $user_info['adm_shop_id'];
            $add_data['orbi_superior_shop_id'] = $shop_id;
            $add_data['orbi_number'] = $number;//账单编号
            $add_data['orbi_start_time'] = $bill_data->sdob_start_time;//开始日期
            $add_data['orbi_end_time'] = $bill_data->sdob_end_time;//结束日期
            $add_data['orbi_state'] = 3; //待审核
            $add_data['orbi_type'] = 3; //类型：1会员零售2客户单位3速电网单4虚拟加盟店5加盟店
            $add_data['orbi_create_type'] = 2; //账单生成类型1手动生成2速电同步生成
            $order_number = [];//订单号(速电派工单号)
            // 查询速电同步账单详情表
            $sobd_id = DB::table('sd_order_bill_details')
                ->where('sobd_sdob_id', $request['sdob_id'])
                ->select('sobd_id', 'sobd_sdob_id', 'sobd_order_number', 'sobd_ord_order_number', 'sobd_ord_id', 'sobd_actual_price')
                ->get()->toArray();
            $sobd_id = json_decode(json_encode($sobd_id), true);
            foreach ($sobd_id as $key => $value) {
                $order_number[] = $value['sobd_order_number'];//订单号(速电派工单号)
                $sd_order_detail[$value['sobd_order_number']] = $value;
            }
            $order_count = count($sobd_id);
            $add_data['orbi_order_amount'] = $order_count;
            // 根据速电工单号(第三方系统单号)查询订单数据
            $order_info = DB::table('order')
                ->whereIn('ord_other_system_number', $order_number)
                ->where('ord_delete', 1)
                // ->where('ord_state', 1) //未结算
                ->whereIn('ord_wor_state', [4, 5, 8]) //无工单 已完成  撤销订单
                ->select('ord_goods_quantity', 'ord_collection_price', 'ord_actual_price', 'ord_state', 'ord_service_type', 'ord_plus_minus', 'ord_id', 'ord_other_system_number', 'ord_order_number')
                ->get()->toArray();
            $order_info = json_decode(json_encode($order_info), true);
            $add_data['orbi_collection_price'] = 0; //代收金额
            $add_data['orbi_goods_sum'] = 0; // 商品总量
            $original_number = []; //原始id，更改应收账款数据使用
            $ord_id = [];
            $sys_order_number = [];
            foreach ($order_info as $key => $value) {
                $ord_id[] = $value['ord_id'];
                $sys_order_number[] = $value['ord_other_system_number'];
                $add_data['orbi_collection_price'] += $value['ord_collection_price']; //代收金额
                $add_data['orbi_goods_sum'] += $value['ord_goods_quantity'];//商品总量
                foreach ($sobd_id as $k => $v) {
                    if ($value['ord_other_system_number'] == $v['sobd_order_number']) {
                        $sobd_id[$k]['order_number'] = $value['ord_order_number']; //本系统的订单单号
                        $sobd_id[$k]['order_id'] = $value['ord_id']; //本系统的订单id
                    }
                }
            }
            // 结算金额
            $goods_price = $bill_data->sdob_bill_price;
            // 如果是正数
            if ($goods_price >= 0) {
                $plus_minus = 1;
            } else {
                $plus_minus = 2;
            }

            $add_data['orbi_collection_price'] = 0; //代收金额为0
            $add_data['orbi_plus_minus'] = $plus_minus; //正数
            $add_data['orbi_state'] = 1; //账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
            $add_data['orbi_merge_state'] = 2; //1是2否
            $add_data['orbi_total_price'] = $goods_price; //合计金额（单位：分）订单的结算
            $add_data['orbi_bill_price'] = $goods_price; //结算金额（单位：分）订单结算金额：商品总金额-回收总金额
            $add_data['orbi_actual_price'] = $goods_price; //实收金额（单位：分）订单结算金额-代收金额，实际应收金额
            $add_data['orbi_sd_affirm'] = 1; //速电账单确认状态 0未确认  1已确认
            $orbi_id = DB::table('order_bill')->insertGetId($add_data);

            if (!empty($order_info)) {
                // 3.修改订单表 账单id
                $sql = 'UPDATE `faster_order` SET ';
                $ord_orbi_id = ''; //账单id
                $ord_state = ''; //更改结算状态
                $update_time = ''; //调货时间
                $ord_id_str = "";
                foreach ($ord_id as $key => $value) {
                    // 更改账单id
                    $ord_orbi_id = $ord_orbi_id . ' WHEN ' . $value;
                    $ord_orbi_id = $ord_orbi_id . ' THEN ' . $orbi_id;
                    // 更改结算状态
                    $ord_state = $ord_state . ' WHEN ' . $value;
                    $ord_state = $ord_state . ' THEN 2';
                    // 更改时间
                    $update_time = $update_time . ' WHEN ' . $value;
                    $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
                    //要更改的订单id
                    $ord_id_str = $ord_id_str . $value . ',';
                }
                $sql = $sql . ' `ord_orbi_id`= CASE `ord_id` ' . $ord_orbi_id . ' END,';
                $sql = $sql . ' `ord_state`= CASE `ord_id` ' . $ord_state . ' END,';
                $sql = $sql . ' `ord_update_time`= CASE `ord_id` ' . $update_time . ' END';
                $sql = $sql . ' WHERE `ord_id` IN (' . trim($ord_id_str, ',') . ')';
                $save_order = DB::update($sql);
            } else {
                $save_order = true;
            }

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

            // 6.账单下所有的订单为不统计状态
            /*$statistics_type_update = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', 3)
                ->where('recr_belongs_id', $orbi_id)
                ->update(['recr_statistics_type' => 2, 'recr_update_time' => date('Y-m-d H:i:s')]);
            if ($statistics_type_update || $statistics_type_update === 0) {
            } else {
                DB::rollBack();
                return response()->json(['code'=>203, 'msg'=>'生成账单失败']);
            }*/

            // 判断是否有本系统不存在的订单
            $diff_number = array_diff($order_number, $sys_order_number);
            if (!empty($diff_number)) {
                foreach ($diff_number as $key => $value) {
                    $price  = 0;
                    foreach ($sobd_id as $k => $v) {
                        if ($v['sobd_order_number'] == $value) {
                            $price = $v['sobd_actual_price'];
                        }
                    }
                    $rece[$key]['recr_cid'] = $user_info['adm_cid'];
                    $rece[$key]['recr_shop_id'] = $user_info['adm_shop_id'];
                    $rece[$key]['recr_shop_superior_id'] = $shop_id;
                    $rece[$key]['recr_type'] = 3; //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    $rece[$key]['recr_account_type'] = 5;
                    //$rece[$key]['recr_number_id'] = $createBill; //应收账单id
                    $rece[$key]['recr_belongs_id'] = $orbi_id; //应收账单id
                    // $rece[$key]['recr_original_id'] = $recr_original_id; //与类型所对应的id
                    $rece[$key]['recr_original_number'] = $value; //与类型所对应的单号
                    $rece[$key]['recr_client_type'] = 6; //客户类型：1.门店零售 2.来往单位
                    $rece[$key]['recr_client_id'] = 0; //会员id/来往单位id
                    $rece[$key]['recr_client_name'] = config('apisystem.sd_chan_info')['name']; //来往单位名称
                    $rece[$key]['recr_settle_price'] = $price; //结算金额
                    $rece[$key]['recr_actual_price'] = $price; //实际金额
                    $rece[$key]['recr_state'] = 1; //状态：1.未核销 2.已核销
                    $rece[$key]['recr_plus_minus'] = 1; //金额正负值
                    $rece[$key]['recr_bill_type'] = 2; //1系统单  2非系统单
                }
                //$recr_res = DB::table('receivable_credit')->insert($rece);
                $recr_res = true;
            } else {
                $recr_res = true;
            }
        }else{
            $recr_res = true;
            $save_order = true;
            $createBill = DB::table('order_bill')
                ->where('orbi_id',$orbi_id)
                ->update(['orbi_sd_affirm'=>1,'orbi_update_time'=>date('Y-m-d H:i:s')]);
        }

        // 1.修改速电同步账单表状态
        $data['sdob_state'] = 1;//对比状态0未处理1已对比  2已撤销
        $data['sdob_update_time'] = date('Y-m-d H:i:s');
        $data['sdob_orbi_id'] = $orbi_id;//本系统账单id

        // 1.修改速电同步账单表状态
        $res = DB::table('sd_order_bill')
            ->where('sdob_id', $request['sdob_id'])
            ->update($data);

        //20230724  修改订单应收应付  //1现金、2支付宝、3微信、4银行卡
        $sd_detail_ret = DB::table('sd_order_bill_details')
            ->where('sobd_sdob_id', $request['sdob_id'])
            ->get()->toArray();
        foreach ($sd_detail_ret as $key => $value) {
            $sobd_order_number[] = $value->sobd_order_number;
            $sd_order_detail[$value->sobd_order_number] = $value;
        }
        if(isset($sobd_order_number)){
            $order_info = DB::table('order')
                ->whereIn('ord_other_system_number', $sobd_order_number)
                ->where('ord_delete', 1)
                ->select('ord_order_number','ord_other_system_number')
                ->get()->toArray();
            if($order_info){
                $order_info = CommonService::dataToArray($order_info);
                $order_number_arr = CommonService::jointArrayKey($order_info,'ord_other_system_number');
                foreach ($sobd_order_number as $number_key => $number_value){
                    $rec_info = DB::table('receivable_pay')
                        ->where('recpay_original_number', $order_number_arr[$number_value]['ord_order_number'])
                        ->first();
                    if($rec_info){
                        $sd_info = $sd_order_detail[$number_value];
                        //$rece_params['recpay_original_number'] = $number_value;//订单id
                        $rece_params['recpay_original_number'] = $order_number_arr[$number_value]['ord_order_number'];//订单id
                        $rece_params['recpay_receivable_price'] = $sd_info->sobd_actual_price / 100;//应收金额
                        $rece_params['recpay_actual_price'] = $sd_info->sobd_actual_price / 100;//实收金额
                        $rece_params['recpay_arrears_price'] = 0;//欠收金额
                        $rece_params['recpay_cost_price'] = 0;//成本
                        $rece_params['recpay_plus_minus'] = 1;
                        $rece_params['recpay_profit'] = $sd_info->sobd_actual_price / 100;//盈利金额
                        $rece_params['recpay_state'] = 2;
                        $rt = ReceivablePayService::edit($rece_params);
                        $rec_info = DB::table('order')
                            ->where('ord_order_number', $order_number_arr[$number_value]['ord_order_number'])
                            ->update(['ord_state'=>2,'ord_actual_price'=>$sd_info->sobd_actual_price,'ord_settlement_time'=>date('Y-m-d H:i:s'),'ord_payment_money'=>$sd_info->sobd_actual_price]);
                    }
                }
            }
        }
        if ($res && $orbi_id && $recr_res && $save_order) {
            Common::addLog($user_infos, getRealIp($request), '账单对比', '确认', '速电账单确认：' . $bill_data->sdob_sd_bill_bumber . '成功');
            if (config('apisystem.SYNC_STATE')) {
                //$url = config('apisystem.sd_server_name') . '/index.php/Supply/dealWith';
                $url = config('apiconnect.ZPTZ_URL') . '/index.php/api/supplychain/SupplyMz/dealWith';
                $param['time'] = date('Y-m-d H:i:s'); //收货时间
                $param['ip'] = getRealIp($request);
                $param['apply_note'] = ''; //拒单备注
                //$param['token'] = md5(md5($param['time'] . config('apisystem.sd_token'))); //token
                $param['token'] = md5(md5($param['time'] . config('apiconnect.ZPTZ_TOKEN'))); //token
                $param['wat_num'] = $bill_data->sdob_sd_bill_bumber; //速电账单号
                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'fail']);
                }
            }
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'账单确认成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账单确认失败']);
        }
    }

    // //驳回
    // public function reject(Request $request)
    // {
    //     if(empty($request['sdob_id'])){
    //         return response()->json(['code'=> 500,'msg'=>'error','data'=>'参数错误']);
    //     }
    //     return response()->json(['code'=> 500,'msg'=>'error','data'=>'此功能暂时废弃']);
    //     $sd_data = DB::table('sd_order_bill')
    //         ->where('sdob_id',$request['sdob_id'])
    //         ->first(['sdob_sd_bill_bumber','sdob_orbi_id']);
    //     // 获取当前操作账号信息
    //     $user_info = Common::getUserInfo($request['api_token']);
    //     $data['sdob_update_time'] = date('Y-m-d H:i:s');
    //     $data['sdob_state'] = 1;

    //     $orbi_info = DB::table('order_bill')
    //         ->where('orbi_id', $sd_data->sdob_orbi_id)
    //         ->first(['orbi_state','orbi_type']);
    //     if($orbi_info->orbi_state != 1){
    //         return response()->json(['code'=> 500,'msg'=>'error','data'=>'此账单已结款不能驳回']);
    //     }
    //     $more_id = DB::table('money_record')
    //         ->where('more_orbi_id',$sd_data->sdob_orbi_id)
    //         ->value('more_id');
    //     if(!empty($more_id)){
    //         return response()->json(['code'=> 500,'msg'=>'error','data'=>'此账单已结款不能驳回']);
    //     }
    //     DB::beginTransaction();
    //     //删除速电账单
    //     $sdob_res = DB::table('sd_order_bill')
    //         ->where('sdob_id',$request['sdob_id'])
    //         ->delete();
    //     $sobd_res = DB::table('sd_order_bill_details')
    //         ->where('sobd_sdob_id',$request['sdob_id'])
    //         ->delete();
    //     //删除该账单
    //     $orbi_res = DB::table('order_bill')
    //         ->where('orbi_id', $sd_data->sdob_orbi_id)
    //         ->delete();
    //     //删除已生成的应收账单
    //     $rece_res = DB::table('receivable_credit')
    //         ->where('recr_original_id', $sd_data->sdob_orbi_id)
    //         ->delete();
    //     //把所属账单id修改成0
    //     $rece_two = DB::table('receivable_credit')
    //         ->where('recr_belongs_id', $sd_data->sdob_orbi_id)
    //         ->update(['recr_belongs_id'=>0,'recr_update_time'=>date('Y-m-d H:i:s')]);

    //     $order_data['ord_update_time'] = date('Y-m-d H:i:s');
    //     $order_data['ord_orbi_id'] = 0;
    //     $order_data['ord_state'] = 1;
    //     $ord_res = DB::table('order')
    //         ->where('ord_orbi_id', $sd_data->sdob_orbi_id)
    //         ->update($order_data);
    //     if ($sdob_res && $sobd_res && $orbi_res && $ord_res && $rece_res && $rece_two) {
    //         Common::addLog($user_info, getRealIp($request), '账单对比', '驳回', '速电账单驳回：'.$sd_data->sdob_sd_bill_bumber.'成功');

    //         if(config('apisystem.SYNC_STATE') && $orbi_info->orbi_type == 3){
    //             $url = config('apisystem.sd_server_name').'/index.php/Supply/operation';
    //             $param['time'] = date('Y-m-d H:i:s');//收货时间
    //             $param['ip'] = getRealIp($request);
    //             $param['apply_note'] = $request['remark'];//拒单备注
    //             $param['token'] = md5(md5($param['time'].config('apisystem.sd_token')));//token
    //             $param['wat_num'] = $sd_data->sdob_sd_bill_bumber;//速电账单号
    //             $doPost_res = Common::doPost($param,$url,2);
    //             $doPost_res = json_decode($doPost_res);
    //             if($doPost_res->code != 200){
    //                 DB::rollBack();
    //                 return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
    //             }
    //         }
    //         DB::commit();
    //         return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'账单驳回成功']);
    //     } else {
    //         DB::rollBack();
    //         return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账单驳回失败']);
    //     }
    // }

    // 速电驳回
    public function reject(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2);
        $request = json_decode($request, true);

        $sd_data = DB::table('sd_order_bill')
            ->where('sdob_sd_bill_bumber', $request['sd_bill_bumber'])
            ->where('sdob_state', '!=', 2)
            ->first(['sdob_sd_bill_bumber', 'sdob_orbi_id', 'sdob_id']);
        if (empty($sd_data)) {
            return response()->json(['code'=>203, 'msg'=>'结算单号错误']);
        }

        $more_id = DB::table('money_record')
            ->where('more_orbi_id', $sd_data->sdob_orbi_id)
            ->value('more_id');
        if (!empty($more_id)) {
            return response()->json(['code'=>203, 'msg'=>'此账单已结款不能驳回']);
        }

        $orbi_info = DB::table('order_bill')
            ->where('orbi_id', $sd_data->sdob_orbi_id)
            ->first(['orbi_state', 'orbi_type']);
        if ($orbi_info->orbi_state != 1) {
            return response()->json(['code'=>203, 'msg'=>'此账单已结款不能驳回']);
        }

        DB::beginTransaction();
        //删除速电账单
        $sdob_res = DB::table('sd_order_bill')
            ->where('sdob_id', $sd_data->sdob_id)
            ->update(['sdob_state' => 2, 'sdob_update_time' => date('Y-m-d H:i:s')]);

        //删除该账单
        $orbi_res = DB::table('order_bill')
            ->where('orbi_id', $sd_data->sdob_orbi_id)
            ->delete();
        //删除已生成的应收账单
        $rece_res = DB::table('receivable_credit')
            ->where('recr_original_id', $sd_data->sdob_orbi_id)
            ->delete();
        //把所属账单id修改成0
        $rece_two = DB::table('receivable_credit')
            ->where('recr_belongs_id', $sd_data->sdob_orbi_id)
            ->update(['recr_belongs_id' => 0, 'recr_update_time' => date('Y-m-d H:i:s')]);

        $order_data['ord_update_time'] = date('Y-m-d H:i:s');
        $order_data['ord_orbi_id'] = 0;
        $order_data['ord_state'] = 1;
        DB::table('order')
            ->where('ord_orbi_id', $sd_data->sdob_orbi_id)
            ->update($order_data);
        if ($sdob_res && $orbi_res && $rece_res && $rece_two) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'账单撤回成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'账单撤回失败']);
        }
    }

    // 查看
    public function look(Request $request)
    {
        if (empty($request['sdob_id'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
        }
        $sd_bill = DB::table('sd_order_bill')
            ->where('sdob_id', $request['sdob_id'])
            ->first(['sdob_sd_bill_bumber', 'sdob_start_time', 'sdob_end_time', 'sdob_bill_price', 'sdob_orbi_id', 'sdob_shop_name']);

        $data['sd_order'] = DB::table('sd_order_bill_details')
            ->where('sobd_sdob_id', $request['sdob_id'])
            ->get(['sobd_order_number', 'sobd_actual_price', 'sobd_relative_price', 'sobd_ord_id', 'sobd_details_price', 'sobd_car_owner_name']);
        foreach ($data['sd_order'] as $key => $value) {
            $data['sd_order'][$key]->sobd_details_price = json_decode($value->sobd_details_price);
        }
        $data['mk_order'] = DB::table('order')
            ->where('ord_orbi_id', $sd_bill->sdob_orbi_id)
            ->get(['ord_order_number', 'ord_actual_price', 'ord_id']);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }
}
