<?php

namespace App\Http\Controllers\Api\AccountManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountManage\VerifyWorkBillController;
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\AccountSubject;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkBillController;
        $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->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('work_bill')
                ->where('wobi_cid', $user_info->adm_cid)
                ->where('wobi_superior_shop_id', $shop_id)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['wobi_state'])) {
                        $query->where('wobi_state', $search_data['wobi_state']);
                    }
                }) //账单状态
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['wobi_number'])) {
                        $query->where('wobi_number', 'like', $search_data['wobi_number'].'%' );
                    }
                }) //账单编号
                // ->where(function($query) use($search_data) {
                //     if (!empty($search_data['wobi_audit_adm_id'])) {
                //         $query->where('wobi_audit_adm_id', $search_data['wobi_audit_adm_id']);
                //     }
                // }) //审核人id
                // ->where(function($query) use($search_data) {
                //     if (!empty($search_data['wobi_payment_way'])) {
                //         $query->where('wobi_payment_way', $search_data['wobi_payment_way']);
                //     }
                // }) //付款方式
                // ->where(function($query) use($search_data) {
                //     if (!empty($search_data['wobi_payment_time'])) {
                //         $query->where('wobi_payment_time', 'like', $search_data['wobi_payment_time'].'%' );
                //     }
                // }) //付款时间
                // ->where(function($query) use($search_data) {
                //     if (!empty($search_data['wobi_payer'])) {
                //         $query->where('wobi_payer', 'like', $search_data['wobi_payer'].'%' );
                //     }
                // }) //付款人
                // ->where(function($query) use($search_data) {
                //     if (!empty($search_data['wobi_remark'])) {
                //         $query->where('wobi_remark', 'like', $search_data['wobi_remark'].'%' );
                //     }
                // }) //备注
                // ->where(function($query) use($search_data) {
                //     if (!empty($search_data['wobi_client_id'])) {
                //         $query->where('wobi_type', 2 )
                //               ->where('wobi_client_id', $search_data['wobi_client_id'] );
                //     }
                // }) //客户单位
                ->select('wobi_id', 'wobi_number', 'wobi_start_time', 'wobi_end_time', 'wobi_number',
                	     'wobi_bill_price', 'wobi_payment_time', 'wobi_payment_way',
                	     'wobi_actual_price', 'wobi_state', 'wobi_audit_time', 'wobi_audit_adm_id',
                         'wobi_create_adm_id', 'wobi_remark','wobi_wor_amount', 'wobi_client_id', 'wobi_type')
                ->orderBy('wobi_id', 'desc')
                ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $mem_id = [];
            $channel_id = [];
            $league_id = [];
            foreach ($list_items as $key => $value) {
                $adm_id[] = $value->wobi_create_adm_id;
                $adm_id[] = $value->wobi_audit_adm_id;

                if ($value->wobi_type == 1){
                    // 会员
                    $mem_id[] = $value->wobi_client_id;
                } elseif ($value->wobi_type == 2){
                    // 客户单位
                    $channel_id[] = $value->wobi_client_id;
                } else {
                    // 加盟店
                    $league_id[] = $value->wobi_client_id;
                }
            }
            $adm_id = array_unique($adm_id);
            $mem_id = array_unique($mem_id);
            $channel_id = array_unique($channel_id);
            $league_id = array_unique($league_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_address']);

            // 查找所对应的 客户单位信息
            $find_channel = DB::table('channel_unit')
                    ->whereIn('chun_id', $channel_id)
                    ->get(['chun_id','chun_unit_name','chun_name','chun_phone','chun_address']);

            // 查找所对应的 门店信息
            $find_shop = DB::table('shop')
                    ->whereIn('shop_id', $league_id)
                    ->get(['shop_id','shop_store_name','shop_name','shop_phone','shop_address']);
        }else{
            $find_admin = [];
            $find_mem = [];
            $find_channel = [];
            $find_shop = [];
        }
        $state_count = DB::table('work_bill')
            ->where('wobi_cid', $user_info->adm_cid)
            ->where('wobi_superior_shop_id', $shop_id)
            ->select(DB::raw('count(*) as count, wobi_state'))
            ->groupBy('wobi_state')
            ->get();

        $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['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_shop'] = $find_shop;                    //加盟店信息

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        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'=>'暂无数据']);
        }
    }

    // 详情
    public function billNumber(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkBillController;
        $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']);

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

        $search_data = $request->all();
        if($request['type'] == 1){
            // 账单信息
            $bill = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->first(['wobi_id','wobi_number','wobi_start_time','wobi_end_time','wobi_create_time','wobi_create_adm_id',
                         'wobi_wor_amount','wobi_bill_price','wobi_actual_price','wobi_type','wobi_client_id']);
            if($bill) {
                if($bill->wobi_type == 2){
                    // 来往单位
                    $bill->wobi_client_name = DB::table('channel_unit')
                                ->where('chun_id',$bill->wobi_client_id)
                                ->value('chun_unit_name');
                }elseif($bill->wobi_type == 1){
                    // 客户名称
                    $bill->wobi_client_name = DB::table('admin')
                                ->where('adm_id',$bill->wobi_client_id)
                                ->value('adm_name');
                }else{
                    // 加盟店名称
                    $bill->wobi_client_name = DB::table('shop')
                                ->where('shop_id',$bill->wobi_client_id)
                                ->value('shop_store_name');
                }

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

        }else{

            $list_data = DB::table('work_order as a')
                        ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
                        ->where('wor_cid', $user_info->adm_cid)
                        ->where('wor_superior_shop_id', $shop_id)
                        ->where('wor_wobi_id', $request['wobi_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['wor_order_number'])) {
                                $query->where('wor_order_number', 'like', $search_data['wor_order_number'].'%' );
                            }
                        }) //工单编号
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['wocl_name'])) {
                                $query->where('wocl_name', 'like', '%'.$search_data['wocl_name'].'%' );
                            }
                        }) //客户姓名
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['wocl_phone'])) {
                                $query->where('wocl_phone', 'like', '%'.$search_data['wocl_phone'].'%' );
                            }
                        }) //客户电话
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['wocl_address'])) {
                                $query->where('wocl_address', 'like', $search_data['wocl_address'].'%' );
                            }
                        }) //地址
                        ->select('wor_id', 'wor_create_id', 'wor_number', 'wor_order_number', 'wor_service_sepr_id',
                                 'wor_service_adm_id', 'wor_service_type', 'wor_service_state', 'wor_state', 
                                 'wor_pass', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_create_time', 
                                 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_address','wor_shop_id','wor_service_shop_id','wor_ware_id', 'wor_collection_price', 'wocl_longitude', 
                         'wocl_latitude','wor_orla_id')
                        ->orderBy('wor_id', 'desc')
                        ->paginate($this->show_count);
            $list_items = $list_data->items();

            if(empty($list_items)){
                $wor_id = [];
                $adm_id = [];
                $service_sepr_id = [];
                $find_admin = [];
                $work_goods = [];
                $service_project = [];
                $find_shop = [];
                $work_log = [];
                $recycle_price = 0;
                $order_label = [];
                $shop_ids = [];
                $wor_orla_id= [];
            }else{
                // 查找工单商品
                foreach ($list_items as $key => $value) {
                    $wor_id[] = $value->wor_id;
                    $adm_id[] = $value->wor_create_id;
                    $adm_id[] = $value->wor_service_adm_id;
                    $service_sepr_id[] = $value->wor_service_sepr_id;
                    $shop_ids[] = $value->wor_shop_id;
                    $shop_ids[] = $value->wor_service_shop_id;
                    $wor_orla_id[] = $value->wor_orla_id; //订单标签id
                }
            }
            

            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                        ->whereIn('adm_id', $adm_id)
                        ->get(['adm_id', 'adm_name']);

            // 查找工单商品
            $work_goods = DB::table('work_good')
                        ->whereIn('wogo_wor_id',$wor_id)
                        ->get(['wogo_wor_id','wogo_goo_id','wogo_goo_name','wogo_goo_goods_encode',
                               'wogo_goo_price','wogo_goo_amount','wogo_is_recycle',
                               'wogo_actual_recycle_number','wogo_remark','wogo_collection_price','wogo_state']);

            // 查找账号id对应的账号姓名
            $find_shop = DB::table('shop')
                        ->whereIn('shop_id', $shop_ids)
                        ->get(['shop_id', 'shop_store_name']);
            // 查找所有订单回收金额
            $recycle_price = DB::table('junk_recycle')
                        ->whereIn('jur_wor_id',$wor_id)
                        ->where('jur_price', '!=', 0)
                        ->get(['jur_wor_id','jur_price']);
            // 查找操作记录
            $work_log = DB::table('order_log')
                        ->whereIn('orlo_wor_id',$wor_id)
                        ->get(['orlo_wor_id','orlo_time','orlo_create_adm_name','orlo_content']);
            // // 查找订单标签
            // $order_label = DB::table('order_label')
            //         ->whereIn('orla_id',$wor_orla_id)
            //         ->get(['orla_id','orla_name']);

            // 服务项目
            $service_project = DB::table('service_project')
                        ->whereIn('sepr_id', $service_sepr_id)
                        ->get(['sepr_id', 'sepr_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_items;                       //返回数据
            $data_info['find_admin'] = $find_admin;                //返回账号姓名
            $data_info['work_goods'] = $work_goods;                //订单商品数据
            $data_info['service_project'] = $service_project;      //服务项目
            $data_info['find_shop'] = $find_shop;                    //返回门店名称
            $data_info['work_log'] = $work_log;                      //操作记录
            $data_info['recycle_price'] = $recycle_price;            //订单回收金额


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

    // 结款
    public function settleAccounts(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkBillController;
        $error_message = $verify_data->getInfoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $wobi_data = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->first(['wobi_number', 'wobi_state', 'wobi_start_time', 'wobi_end_time', 
                         'wobi_create_time', 'wobi_create_adm_id', 'wobi_wor_amount', 'wobi_bill_price', 
                         'wobi_client_id', 'wobi_type', 'wobi_goods_sum','wobi_total_price', 
                         'wobi_collection_price','wobi_receive_price','wobi_img']);
        if(empty($wobi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }

        if($request['type'] == 1){
            // 获取到创建人姓名
            $wobi_data->wobi_create_adm_name = DB::table('admin')
                        ->where('adm_id',$wobi_data->wobi_create_adm_id)
                        ->value('adm_name');
            
            // 获取客户单位信息
            if($wobi_data->wobi_type == 1){
                // 会员
                $member = DB::table('member')
                        ->where('mem_id',$wobi_data->wobi_client_id)
                        ->first(['mem_name','mem_phone','mem_address']);
                $wobi_data->unit_name = '';
                $wobi_data->adm_name = $member->mem_name;
                $wobi_data->adm_phone = $member->mem_phone;
                $wobi_data->adm_address = $member->mem_address;
            }else if($wobi_data->wobi_type == 2) {
                // 客户单位
                $channel = DB::table('channel_unit')
                        ->where('chun_id',$wobi_data->wobi_client_id)
                        ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
                $wobi_data->unit_name = $channel->chun_unit_name;
                $wobi_data->adm_name = $channel->chun_name;
                $wobi_data->adm_phone = $channel->chun_phone;
                $wobi_data->adm_address = $channel->chun_address;
            } else {
                // 加盟店
                $shops = DB::table('shop')
                        ->where('shop_id',$wobi_data->wobi_client_id)
                        ->first(['shop_store_name','shop_name','shop_phone','shop_address']);
                $wobi_data->unit_name = $shops->shop_store_name;
                $wobi_data->adm_name = $shops->shop_name;
                $wobi_data->adm_phone = $shops->shop_phone;
                $wobi_data->adm_address = $shops->shop_address;
            }
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$wobi_data]);
        }

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

        $wobi_actual_price = $request['wobi_actual_price'] * 100; //实收金额
        $zero_price = $request['zero_price'] ? $request['zero_price']*100 : 0; //抹零金额

        // 还应收金额
        $surplus_price = $wobi_data->wobi_bill_price-$wobi_data->wobi_receive_price;
        if($wobi_actual_price > $surplus_price){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'实收金额不得大于还应收金额']);
        }

        $few = 0;
        $img = '';
         foreach ($request['wobi_img'] as $key => $value) {        
            // 调用全局函数 上传图片
            $img .= uploadBase64Img($value).',';
            $few++;
        }
        if($few == 0){
            return response()->json(['code'=> 500, 'msg'=>'最少上传一张图片', 'data'=>'{}']);
        }
        if($few > 6){
            return response()->json(['code'=> 500, 'msg'=>'最多上传六张图片', 'data'=>'{}']);
        }
        $img = $wobi_data->wobi_img.','.$img;
        $img = trim($img, ',');

        $user_info = Common::getUserInfo($request['api_token']);

        // 获取来往单位名称
        if($request['wobi_type'] == 1){
            $client_name = '';
        } else if($request['wobi_type'] == 2) {
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$request['wobi_client_id'])
                    ->value('chun_unit_name');
        } else if ($request['wobi_type'] == 3) {
            $client_name = DB::table('shop')
                ->where('shop_id',$request['wobi_client_id'])
                ->value('shop_store_name');
        }

        // 查询出应收账款id
        $recr_number_id = DB::table('receivable_credit')
                ->where('recr_type',4)
                ->where('recr_original_id',$request['wobi_id'])
                ->value('recr_number_id');

        // 查询出是否应该为已核销
        if($request['wobi_payment_type'] == 1){ //抹零
            // 抹零金额+实收金额不得大于结算金额 等于结算金额改为已核销
            if($wobi_actual_price + $zero_price < $surplus_price){
                $check = 1; //未核销
            }else{
                $check = 2; //已核销
            }
        }else{ //分期结款 或者 预收款抵账
            if($wobi_actual_price < $surplus_price){
                $check = 1; //未核销
            }else{
                $check = 2; //已核销
            }
        }

        DB::beginTransaction();

        if($check == 2){
            // 已核销 将所有应收账款与本账单有关的都改为已核销
            
            // $update_state['recr_state'] = 2;
            // $update_state['recr_update_time'] = date('Y-m-d H:i:s');
            // $rece_data = DB::table('receivable_credit')
            //         ->where('recr_number_id',$recr_number_id)
            //         ->update($update_state);

            // 查询出是否有包含本账单已经完结的预收款 改为已核销
            // $recr_id = DB::table('receivable_credit')
            //         ->where('recr_type',2)
            //         ->where('recr_actual_price',0)
            //         ->get(['recr_id']);
            // $recr_id = json_decode(json_encode($recr_id),true);
            // $recr_id = array_column($recr_id,'recr_id');
            // if(!empty($recr_id)){
            //     $state_data['recr_state'] = 2;
            //     $state_data['recr_update_time'] = date('Y-m-d H:i:s');
            //     $recr_state = DB::table('receivable_credit')
            //             ->whereIn('recr_id',$recr_id)
            //             ->update($state_data);
            // }else{
            //     $recr_state = true;
            // }

            $wobi_state = 2; //2.已结款
        }else{
            // 未核销
            
            // $rece_data = true;
            // $recr_state = true;
            $wobi_state = 5; //5.部分结款
        }

        // 修改工单账单表
        $update_bill = DB::update('UPDATE `faster_work_bill` SET `wobi_receive_price`=`wobi_receive_price`+'.$wobi_actual_price.' ,`wobi_zero_price`=`wobi_zero_price`+'.$zero_price.',`wobi_actual_price`=`wobi_actual_price`+'.$wobi_actual_price.' ,`wobi_remark`= "'.$request['wobi_remark'].'" ,`wobi_payment_way`= '.$request['wobi_payment_way'].' ,`wobi_payee_id`= '.$user_info->adm_id.' ,`wobi_state`= '.$wobi_state.' ,`wobi_img`= "'.$img.'" ,`wobi_payment_time`= "'.date('Y-m-d H:i:s').'" ,`wobi_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `wobi_id`=?',[$request['wobi_id']] );
        
        // 6. 生成应收账单(记录)
        $createBill = ReceivableBill::add(
            $user_info, //用户信息
            4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
            $recr_number_id, //应收账款id
            $request['wobi_id'], //原始id(账单id)
            $wobi_data->wobi_number, //应收账款单号/原始号(账单编号)
            $wobi_data->wobi_type, //客户类型：1.门店零售 2.来往单位
            $wobi_data->wobi_client_id, //会员id/来往单位id
            $client_name, //来往单位名称
            $wobi_data->wobi_bill_price, //结算金额
            date('Y-m-d H:i:s'), //结款时间
            $request['acti_id'], //会计科目id
            $wobi_actual_price, //实际金额
            $zero_price, //抹零金额
            $check,  //状态：1.未核销 2.已核销
            1,  //应收账单id是否是自己 1.不是 2.是
            $request['wobi_remark'] ? $request['wobi_remark'] : '',  //备注
            $wobi_data->wobi_receive_price + $wobi_actual_price,  //已收金额
            '' //截止时间
        );

        // 预收款抵账(减预收款金额)
        if($request['wobi_payment_type'] == 3){
            //  实收金额
            $subtract = DB::table('receivable_credit')
                ->where('recr_id',$request['recr_id'])
                ->decrement('recr_actual_price',$wobi_actual_price);

            $add_data['rede_advance_id'] = $request['recr_id']; //预付款id
            $add_data['rede_recr_id'] = $createBill; //账单id
            $details_data = DB::table('receivable_details')->insert($add_data);
            // $AccountSubject = true;
        }else{
            $subtract = true;
            $details_data = true;

            // // 编辑科目管理表
            // $AccountSubject = AccountSubject::Subject(
            //     $user_info,                    // [用户信息]
            //     1,                             // [类型：1借2贷]
            //     $wobi_actual_price,            // [金额]
            //     $request['acti_id']            // [科目id]
            // );
        }

        // $acti_closing_account = DB::table('account_title')
        //         ->where('acti_id',$request['acti_id'])
        //         ->value('acti_closing_account');
        // if($wobi_actual_price > $acti_closing_account){
        //     DB::rollBack();
        //     return response()->json(["code"=>500,'msg'=>'error','data'=>'科目余额不足']);
        // }
        
        // 添加结款明细
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,                    // [用户信息]
            3,                             // [单据类型1订单2订单账单3工单账单4采购账单5销售账单6预收款]
            $request['wobi_id'],           // [与单据类型对应的id]
            $wobi_data->wobi_number,       // [与单据类型对应的单号]
            $wobi_data->wobi_type,         // [买家类型1门店零售2来往单位]
            $wobi_data->wobi_client_id,    // [会员/客户id]
            $client_name,                  // [来往单位名称]
            $request['acti_id'],           // [会计科目id]
            1,                             // [类型1收入2支出]
            $wobi_actual_price,            // [实际金额](此次的实收金额)
            $surplus_price,                // [合计金额](此次的应收金额)
            $surplus_price-$wobi_actual_price-$zero_price,    // [欠收金额](此次结款后还应收金额)
            $zero_price,          // [抹零金额]
            $request['wobi_remark']  ? $request['wobi_remark'] : ''             // [备注]
        );

        // 应收账单表新增数据
        // if($wobi_data->wobi_type == 2){
        //     $analyze = Common::updateAnalyze(
        //         $user_info, //用户信息
        //         $wobi_data->wobi_client_id, //客户单位id
        //         1, //单量
        //         $wobi_data->wobi_bill_price, //应收账款结算金额
        //         2  //类型1.编辑+ 2.编辑-
        //     );
        // }else{
        //     $analyze = true;
        // }
            
        if(/*$rece_data && $recr_state && */$update_bill && $createBill && $AccountingSettlement && $subtract && $details_data) {
            Common::addLog($user_info, getRealIp($request), '工单账单','结款',$wobi_data->wobi_number.'结款成功');
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'结款成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'结款失败']);
        }
    }

    // 查看
    public function lookInfo(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $wobi_data = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->first(['wobi_number', 'wobi_state', 'wobi_start_time', 'wobi_end_time', 
                         'wobi_create_time', 'wobi_create_adm_id', 'wobi_wor_amount', 'wobi_bill_price', 
                         'wobi_client_id', 'wobi_type', 'wobi_goods_sum', 'wobi_payment_way', 
                         'wobi_total_price', 'wobi_audit_time', 'wobi_audit_adm_id', 'wobi_payment_time', 
                         'wobi_payee_id', 'wobi_actual_price', 'wobi_remark', 'wobi_img']);
        if(empty($wobi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }

        // 获取到创建人姓名
        $wobi_data->wobi_create_adm_name = DB::table('admin')
                    ->where('adm_id',$wobi_data->wobi_create_adm_id)
                    ->value('adm_name');
        // 获取到审核人姓名
        $wobi_data->wobi_audit_adm_name = DB::table('admin')
                    ->where('adm_id',$wobi_data->wobi_audit_adm_id)
                    ->value('adm_name');
        // 获取到结款人姓名
        $wobi_data->wobi_payee_name = DB::table('admin')
                    ->where('adm_id',$wobi_data->wobi_payee_id)
                    ->value('adm_name');

        // 获取客户单位信息
        if($wobi_data->wobi_type == 1){
            // 会员
            $member = DB::table('member')
                    ->where('mem_id',$wobi_data->wobi_client_id)
                    ->first(['mem_name','mem_phone','mem_address']);
            $wobi_data->unit_name = '';
            $wobi_data->adm_name = $member->mem_name;
            $wobi_data->adm_phone = $member->mem_phone;
            $wobi_data->adm_address = $member->mem_address;
        } else if($wobi_data->wobi_type == 2) {
            // 客户单位
            $channel = DB::table('channel_unit')
                    ->where('chun_id',$wobi_data->wobi_client_id)
                    ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
            $wobi_data->unit_name = $channel->chun_unit_name;
            $wobi_data->adm_name = $channel->chun_name;
            $wobi_data->adm_phone = $channel->chun_phone;
            $wobi_data->adm_address = $channel->chun_address;
        } else if ($wobi_data->wobi_type == 3) {
            // 加盟店
            $shop = DB::table('shop')
                    ->where('shop_id',$wobi_data->wobi_client_id)
                    ->first(['shop_store_name','shop_name','shop_phone','shop_address']);
            $wobi_data->unit_name = $shop->shop_store_name;
            $wobi_data->adm_name = $shop->shop_name;
            $wobi_data->adm_phone = $shop->shop_phone;
            $wobi_data->adm_address = $shop->shop_address;
        }

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

    // 审核
    public function audit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkBillController;
        $error_message = $verify_data->auditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $wobi_data = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->first(['wobi_number', 'wobi_state', 'wobi_start_time', 'wobi_end_time', 
                         'wobi_create_time', 'wobi_create_adm_id', 'wobi_wor_amount', 'wobi_bill_price', 
                         'wobi_client_id', 'wobi_type', 'wobi_goods_sum']);
        if(empty($wobi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        if($wobi_data->wobi_state != 3){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'待审核状态下才可以审核']);
        }

        if($request['type'] == 1){
            // 获取到创建人姓名
            $wobi_data->wobi_create_adm_name = DB::table('admin')
                        ->where('adm_id',$wobi_data->wobi_create_adm_id)
                        ->value('adm_name');
            
            // 获取客户单位信息
            if($wobi_data->wobi_type == 1){
                // 会员
                $member = DB::table('member')
                        ->where('mem_id',$wobi_data->wobi_client_id)
                        ->first(['mem_name','mem_phone','mem_address']);
                $wobi_data->unit_name = '';
                $wobi_data->adm_name = $member->mem_name;
                $wobi_data->adm_phone = $member->mem_phone;
                $wobi_data->adm_address = $member->mem_address;
            } elseif ($wobi_data->wobi_type == 2){
                // 客户单位
                $channel = DB::table('channel_unit')
                        ->where('chun_id',$wobi_data->wobi_client_id)
                        ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
                $wobi_data->unit_name = $channel->chun_unit_name;
                $wobi_data->adm_name = $channel->chun_name;
                $wobi_data->adm_phone = $channel->chun_phone;
                $wobi_data->adm_address = $channel->chun_address;
            }else{
                // 加盟店
                $shop = DB::table('shop')
                        ->where('shop_id',$wobi_data->wobi_client_id)
                        ->first(['shop_store_name','shop_name','shop_phone','shop_address']);
                $wobi_data->unit_name = $shop->shop_store_name;
                $wobi_data->adm_name = $shop->shop_name;
                $wobi_data->adm_phone = $shop->shop_phone;
                $wobi_data->adm_address = $shop->shop_address;
            }

            $work_order = DB::table('work_order as w')
                ->leftJoin('order as o', 'w.wor_order_id', '=', 'o.ord_id')
                ->leftJoin('admin as a', 'w.wor_create_id', '=', 'a.adm_id')
                ->where('wor_wobi_id',$request['wobi_id'])
                ->get(['wor_achieve_time', 'wor_number', 'wor_create_id', 
                       'wor_actual_price', 'ord_state', 'adm_name as wor_create_name']);
            $data['wobi_data'] = $wobi_data;
            $data['work_order'] = $work_order;
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data]);
        }
        $user_info = Common::getUserInfo($request['api_token']);

        DB::beginTransaction();

        $update_data['wobi_state'] = $request['wobi_state'];
        $update_data['wobi_audit_time'] = date('Y-m-d H:i:s'); //审核时间
        $update_data['wobi_audit_adm_id'] = $user_info->adm_id; //审核人
        $update_data['wobi_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->update($update_data);

        // 获取客户单位名称/加盟店名称
        if($wobi_data->wobi_type == 1){
            // 会员
            $client_name = '';
        } elseif ($wobi_data->wobi_type == 2){
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$wobi_data->wobi_client_id)
                    ->value('chun_unit_name');
        } else {
            $client_name = DB::table('shop')
                    ->where('shop_id',$wobi_data->wobi_client_id)
                    ->value('shop_store_name');
        }
        //如果是同意状态
        if($request['wobi_state'] == 1){
            // 6. 生成应收账单
            $createBill = ReceivableBill::add(
                $user_info, //用户信息
                4, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $request['wobi_id'], //原始id(订单账单id)
                $wobi_data->wobi_number, //应收账款单号/原始号(订单账单编号)
                $wobi_data->wobi_type, //客户类型：1.门店零售 2.来往单位
                $wobi_data->wobi_client_id, //会员id/来往单位id
                $client_name, //来往单位名称/门店名称
                $wobi_data->wobi_bill_price, //结算金额
                date('Y-m-d H:i:s'), //结款时间
                0, //会计科目id
                0, //实际金额
                0, //抹零金额
                1, //状态：1.未核销 2.已核销
                2,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                0, //已收金额
                '' //截止时间
            );
        }else{
            $createBill = true;
        }

        if($update_state && $createBill) {
            Common::addLog($user_info, getRealIp($request), '工单账单','审核',$wobi_data->wobi_number.'审核成功');
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'审核成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'审核失败']);
        }
    }

    // 删除(做成了真删)
    public function del(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $wobi_data = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->first(['wobi_number', 'wobi_state', 'wobi_type', 'wobi_client_id', 'wobi_bill_price']);
        if(empty($wobi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        if($wobi_data->wobi_state != 4){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'已驳回的账单才可以删除']);
        }

        DB::beginTransaction();
        // 1.删除账单表
        $del_orbi = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->delete();

        // 2.解除工单与账单的绑定关系
        $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['wobi_id'])
                ->update($update_data);


        // 3.应收账单表新增数据
        // if($request['wobi_type'] == 2){
        //     $analyze = Common::updateAnalyze(
        //         $user_info, //用户信息
        //         $request['wobi_client_id'], //客户单位id
        //         1, //单量
        //         $request['wobi_bill_price'] * 100, //应收账款结算金额
        //         2  //类型1.编辑+ 2.编辑-
        //     );
        // }else{
        //     $analyze = true;
        // }

        if($del_orbi && $update_state) {
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '工单账单','删除',$wobi_data->wobi_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 VerifyWorkBillController;
        $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']);

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


        $update_data['wobi_state'] = 3; // 账单状态1.未结款 2.已结款 3.待审核 4.已驳回 5.部分结款
        $update_data['wobi_update_time'] = date('Y-m-d H:i:s');
        
        DB::beginTransaction();

        // 1.修改状态
        $update_state = DB::table('work_bill')
                ->where('wobi_id',$request['wobi_id'])
                ->update($update_data);

        // 通过的账单 删除应收账款
        if($wobi_data->wobi_state == 5){
            $del_credit = DB::table('receivable_credit')
                    ->where('recr_type',4) //类型 4.工单账单
                    ->where('recr_original_id',$request['wobi_id']) //与类型所对应的id
                    ->delete();
        }else{
            $del_credit = true;
        }

        if($update_state && $del_credit) {
            Common::addLog($user_info, getRealIp($request), '工单账单','反审核',$wobi_data->wobi_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 VerifyWorkBillController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $user_info = Common::getUserInfo($request['api_token']);

        // 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['wobi_id'])
                    ->update($relieve_data);

        // 2.重新绑定工单与账单的关系
        $sql = 'UPDATE `faster_work_order` SET ';
        $wor_wobi_id = ''; //账单id
        $update_time = ''; //调货时间
        $wor_id = "";

        foreach ($request['wor_id'] as $key => $value) {
           // 更改账单id
            $wor_wobi_id = $wor_wobi_id . ' WHEN ' .$value;
            $wor_wobi_id = $wor_wobi_id . ' THEN ' .$request['wobi_id'];
            // 更改时间
            $update_time = $update_time . ' WHEN ' .$value;
            $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';
            //要更改的工单id
            $wor_id = $wor_id . $value.',';
        }
        $sql = $sql .' `wor_wobi_id`= CASE `wor_id` '.$wor_wobi_id.' END,';
        $sql = $sql .' `wor_update_time`= CASE `wor_id` '.$update_time.' END';
        $sql = $sql .' WHERE `wor_id` IN ('.trim($wor_id,',').')';
        $save_work = DB::update($sql);

        // 3.修改单量 改为待审核状态
        $update_bill['wobi_wor_amount'] = count($request['wor_id']); //单量
        $update_bill['wobi_state'] = 3; //3.待审核
        $update_bill['wobi_update_time'] = date('Y-m-d H:i:s');
        $bill_data = DB::table('work_bill')
                    ->where('wobi_id',$request['wobi_id'])
                    ->update($update_bill);

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