<?php

namespace App\Http\Controllers\Api\AccountManage;

use Illuminate\Http\Request;
use App\Http\Models\Api\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Models\Api\ReceivableBill;
use App\Http\Models\Api\AccountingSettlement;
use App\Http\Controllers\Api\Verify\AccountManage\VerifySellBillController;

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

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

        $search_data = $request->all();
        $list_data = DB::table('sell_bill')
                    ->where('sebi_cid', $user_info->adm_cid)
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_state'])) {
                            $query->where('sebi_state', $search_data['sebi_state']);
                        }
                    }) //账单状态
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_payment_time'])) {
                            $query->where('sebi_payment_time', 'like', $search_data['sebi_payment_time'].'%' );
                        }
                    }) //结款时间
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_number'])) {
                            $query->where('sebi_number', 'like', $search_data['sebi_number'].'%' );
                        }
                    }) //账单编号
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_audit_adm_id'])) {
                            $query->where('sebi_audit_adm_id', $search_data['sebi_audit_adm_id']);
                        }
                    }) //审核人id
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_payment_way'])) {
                            $query->where('sebi_payment_way', $search_data['sebi_payment_way']);
                        }
                    }) //结款方式
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_remark'])) {
                            $query->where('sebi_remark', 'like', $search_data['sebi_remark'].'%' );
                        }
                    }) //备注
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['sebi_client_id'])) {
                            $query->where('sebi_type', 2 )
                                  ->where('sebi_client_id', $search_data['sebi_client_id'] );
                        }
                    }) //客户单位
                    ->select('sebi_id', 'sebi_number', 'sebi_start_time', 'sebi_end_time', 'sebi_wor_amount',
                    	     'sebi_bill_price', 'sebi_payment_time', 'sebi_payment_way', 'sebi_handle_adm_id',
                    	     'sebi_actual_price', 'sebi_state', 'sebi_audit_time', 'sebi_audit_adm_id',
                             'sebi_create_adm_id', 'sebi_remark', 'sebi_client_id', 'sebi_type','sebi_plus_minus')
                    ->orderBy('sebi_id', 'desc')
                    ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $mem_id = [];
            $channel_id = [];
            foreach ($list_items as $key => $value) {
                $adm_id[] = $value->sebi_create_adm_id;
                $adm_id[] = $value->sebi_audit_adm_id;
                $adm_id[] = $value->sebi_handle_adm_id;

                if($value->sebi_type == 1){
                    // 会员
                    $mem_id[] = $value->sebi_client_id;
                }else{
                    // 客户单位
                    $channel_id[] = $value->sebi_client_id;
                }
            }
            $adm_id = array_unique($adm_id);
            $mem_id = array_unique($mem_id);
            $channel_id = array_unique($channel_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']);
        }else{
            $find_admin = [];
            $find_mem = [];
            $find_channel = [];
        }

        $state_count = DB::table('sell_bill')
            ->where('sebi_cid', $user_info->adm_cid)
            ->select(DB::raw('count(*) as count, sebi_state'))
            ->groupBy('sebi_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;              //客户单位信息

        // 获取当前列表下的按钮
        $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 VerifySellBillController;
        $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('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
                ->first(['sebi_id','sebi_number','sebi_start_time','sebi_end_time','sebi_create_time','sebi_create_adm_id',
                         'sebi_wor_amount','sebi_bill_price','sebi_actual_price','sebi_type','sebi_client_id']);
            if($bill) {
                if($bill->sebi_type == 2){
                    // 来往单位
                    $bill->sebi_client_name = DB::table('channel_unit')
                                ->where('chun_id',$bill->sebi_client_id)
                                ->value('chun_unit_name');
                }else{
                    // 客户名称
                    $bill->sebi_client_name = DB::table('admin')
                                ->where('adm_id',$bill->sebi_client_id)
                                ->value('adm_name');
                }

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

        }else{

           $list_data = DB::table('sell as a')
                        ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.sell_ware_id')
                        ->leftJoin('sell_client as c', 'c.secl_sell_id', '=', 'a.sell_id')
                        ->where('sell_cid', $user_info->adm_cid)
                        ->where('sell_superior_shop_id', $shop_id)
                        ->where('sell_sebi_id', $request['sebi_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['sell_number'])) {
                                $query->where('sell_number', 'like', $search_data['sell_number'].'%' );
                            }
                        }) //编号
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['secl_name'])) {
                                $query->where('secl_name', 'like', '%'.$search_data['secl_name'].'%' );
                            }
                        }) //客户名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['secl_phone'])) {
                                $query->where('secl_phone', 'like', '%'.$search_data['secl_phone'].'%' );
                            }
                        }) //客户电话
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['secl_address'])) {
                                $query->where('secl_address', 'like', $search_data['secl_address'].'%' );
                            }
                        }) //客户地址
                        ->select('sell_id', 'sell_number', 'sell_state', 'sell_count', 'sell_adm_id', 'sell_remark', 
                                 'sell_data', 'sell_create_time', 'secl_channel_unit', 'secl_name', 'secl_phone', 
                                 'secl_address', 'ware_name', 'sell_actual_price')
                        ->orderBy('sell_id', 'desc')
                        ->paginate($this->show_count);
            $list_items = $list_data->items();

            if(empty($list_items)){
                $find_admin = [];
                $find_mem = [];
                $find_channel = [];
            }else{
                $mem_id = [];
                $channel_id = [];
                foreach ($list_items as $key => $value) {
                    if ($value->sell_adm_id) {
                        $adm_id[] = $value->sell_adm_id;
                    }
                    if ($value->sell_data) {
                        $value->sell_data = json_decode($value->sell_data, true);
                    }

                    // if($value->wobi_type == 1){
                    //     // 会员
                    //     $mem_id[] = $value->wobi_client_id;
                    // }else{
                    //     // 客户单位
                    //     $channel_id[] = $value->wobi_client_id;
                    // }
                } 
                $adm_id = array_unique($adm_id);
                // $mem_id = array_unique($mem_id);
                // $channel_id = array_unique($channel_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_name','mem_phone','mem_address']);
                //
                // // 查找所对应的 客户单位信息
                // $find_channel = DB::table('channel_unit')
                //         ->whereIn('chun_id', $channel_id)
                //         ->get(['chun_unit_name','chun_name','chun_phone','chun_address']);
            }

            $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;                //返回账号姓名

            // 获取当前列表下的按钮
            $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 settleAccounts(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellBillController;
        $error_message = $verify_data->getInfoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证当前账单是否存在
        $sebi_data = DB::table('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
                ->first(['sebi_number', 'sebi_state', 'sebi_start_time', 'sebi_end_time', 
                         'sebi_create_time', 'sebi_create_adm_id', 'sebi_wor_amount', 'sebi_bill_price', 
                         'sebi_client_id', 'sebi_type', 'sebi_goods_sum', 'sebi_collection_price', 
                         'sebi_total_price', 'sebi_receive_price','sebi_img','sebi_plus_minus']);
        if(empty($sebi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }

        if($request['type'] == 1){
            // 获取到创建人姓名
            $sebi_data->sebi_create_adm_name = DB::table('admin')
                        ->where('adm_id',$sebi_data->sebi_create_adm_id)
                        ->value('adm_name');
            // 获取客户单位信息
            if($sebi_data->sebi_type == 1){
                // 会员
                $member = DB::table('member')
                        ->where('mem_id',$sebi_data->sebi_client_id)
                        ->first(['mem_name','mem_phone','mem_address']);
                $sebi_data->unit_name = '';
                $sebi_data->adm_name = $member->mem_name;
                $sebi_data->adm_phone = $member->mem_phone;
                $sebi_data->adm_address = $member->mem_address;
            }else{
                // 客户单位
                $channel = DB::table('channel_unit')
                        ->where('chun_id',$sebi_data->sebi_client_id)
                        ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
                $sebi_data->unit_name = $channel->chun_unit_name;
                $sebi_data->adm_name = $channel->chun_name;
                $sebi_data->adm_phone = $channel->chun_phone;
                $sebi_data->adm_address = $channel->chun_address;
            }

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

        // 验证数据
        $verify_data = new VerifySellBillController;
        $error_message = $verify_data->settleAccountsValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        $sebi_actual_price = $request['sebi_actual_price'] * 100; //实收金额
        $zero_price = $request->input('zero_price', 0) * 100; //抹零金额

        // 还应收金额
        $surplus_price = $sebi_data->sebi_bill_price - $sebi_data->sebi_receive_price;
        if(($sebi_actual_price + $zero_price) > $surplus_price){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'实收金额不得大于结款金额']);
        }
        if ($request['sebi_payment_type'] == 3) {
            // 预收款抵账不用上传图片
            $img = '';
        }else{
            $few = 0;
            $img = '';
             foreach ($request['sebi_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 = $sebi_data->sebi_img.','.$img;
        $img = trim($img, ',');

        $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($sebi_data->sebi_type == 1){
            // 获取零售客户姓名
            $client_name = DB::table('member')
                    ->where('mem_id',$request['orbi_client_id'])
                    ->value('mem_name');
        }else{
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$sebi_data->sebi_client_id)
                    ->value('chun_unit_name');
        }

        // 判断账单状态
        // 提交的实收金额+抹零金额 == 剩余可结款金额，账单已全部结款
        if (($sebi_actual_price + $zero_price) == $surplus_price) {
            // sebi_state 账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
            $sebi_state = 2;
        }else{
            $sebi_state = 5;
        }

        // 修改工单账单表 (加已收金额)
        $update_bill = DB::update('UPDATE `faster_sell_bill` SET `sebi_receive_price`=`sebi_receive_price`+'.$sebi_actual_price.', `sebi_zero_price`=`sebi_zero_price`+'.$zero_price.' ,`sebi_actual_price`=`sebi_actual_price`+'.$sebi_actual_price.' ,`sebi_state`= '.$sebi_state.' ,`sebi_remark`= "'.$request['sebi_remark'].'" ,`sebi_payee_id`= '.$user_info->adm_id.' ,`sebi_img`= "'.$img.'" ,`sebi_payment_time`= "'.date('Y-m-d H:i:s').'" ,`sebi_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `sebi_id`=?',[$request['sebi_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',6)
                ->where('recr_account_type',7)
                ->where('recr_belongs_id',0)
                ->where('recr_original_id',$request['sebi_id'])
                ->select('recr_id','recr_remark')
                ->first();
        // 6. 更改账单的应收账款金额
        $recr_edit_data['recr_actual_price'] = $sebi_actual_price;
        $recr_edit_data['recr_zero_price'] = $zero_price;
        $recr_edit_data['recr_yet_receipt'] = $sebi_data->sebi_receive_price + $sebi_actual_price;
        $recr_edit_data['recr_remark'] = $find_recr->recr_remark.$request->input('sebi_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',6)
                ->where('recr_account_type',7)
                ->where('recr_id',$find_recr->recr_id)
                ->update($recr_edit_data);

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

        // 预收款抵账(减预收款金额)
        if($request['sebi_payment_type'] == 3){
            // 预收款金额，实际金额减少，已收金额增加
            $prepay_price = $request['sebi_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), '销售账单','结款',$sebi_data->sebi_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 VerifySellBillController;
        $error_message = $verify_data->auditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $sebi_data = DB::table('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
                ->first(['sebi_number', 'sebi_state', 'sebi_start_time', 'sebi_end_time', 
                         'sebi_create_time', 'sebi_create_adm_id', 'sebi_wor_amount', 'sebi_bill_price', 
                         'sebi_client_id', 'sebi_type', 'sebi_goods_sum','sebi_actual_price']);
        if(empty($sebi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        if($sebi_data->sebi_state != 3){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'待审核状态下才可以审核']);
        }

        if($request['type'] == 1){
            // 获取到创建人姓名
            $sebi_data->sebi_create_adm_name = DB::table('admin')
                        ->where('adm_id',$sebi_data->sebi_create_adm_id)
                        ->value('adm_name');
            // 获取客户单位信息
            if($sebi_data->sebi_type == 1){
                // 会员
                $member = DB::table('member')
                        ->where('mem_id',$sebi_data->sebi_client_id)
                        ->first(['mem_name','mem_phone','mem_address']);
                $sebi_data->unit_name = '';
                $sebi_data->adm_name = $member->mem_name;
                $sebi_data->adm_phone = $member->mem_phone;
                $sebi_data->adm_address = $member->mem_address;
            }else{
                // 客户单位
                $channel = DB::table('channel_unit')
                        ->where('chun_id',$sebi_data->sebi_client_id)
                        ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
                $sebi_data->unit_name = $channel->chun_unit_name;
                $sebi_data->adm_name = $channel->chun_name;
                $sebi_data->adm_phone = $channel->chun_phone;
                $sebi_data->adm_address = $channel->chun_address;
            }

            $sell_data = DB::table('sell as s')
                ->leftJoin('admin as a', 's.sell_adm_id', '=', 'a.adm_id')
                ->where('sell_sebi_id',$request['sebi_id'])
                ->get(['sell_create_time', 'sell_number', 'sell_adm_id', 
                       'sell_price', 'sell_actual_price', 'adm_name as sell_adm_name']);
            $data['sebi_data'] = $sebi_data;
            $data['sell_data'] = $sell_data;
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data]);
        }

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

        DB::beginTransaction();

        $update_data['sebi_state'] = $request['sebi_state'];
        $update_data['sebi_audit_time'] = date('Y-m-d H:i:s'); //审核时间
        $update_data['sebi_audit_adm_id'] = $user_info->adm_id; //审核人
        $update_data['sebi_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
                ->update($update_data);

        // 获取客户单位名称
        if($sebi_data->sebi_type == 1){
            $client_name = '';
        }else{
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$sebi_data->sebi_client_id)
                    ->value('chun_unit_name');
        }
        //如果是同意状态
        if($request['sebi_state'] == 1){
            // 6. 生成应收账单
            $createBill = ReceivableBill::create(
                $user_info, //用户信息
                6, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $request['sebi_id'], //原始id(订单账单id)
                $sebi_data->sebi_number, //应收账款单号/原始号(订单账单编号)
                $sebi_data->sebi_type, //客户类型：1.门店零售 2.来往单位
                $sebi_data->sebi_client_id, //会员id/来往单位id
                $client_name, //来往单位名称
                $sebi_data->sebi_bill_price, //结算金额
                date('Y-m-d H:i:s'), //结款时间
                0, //会计科目id
                0, //实际金额
                0, //抹零金额
                1, //状态：1.未核销 2.已核销
                2,  //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                0,  //已收金额
                '', //截止时间
                1,//金额正负1正   2负值
                7,//显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款 9销售出库单
                1//是否合并代收：1是2否
            );
            //账单下所有的订单为不统计状态
            $statistics_type_update = DB::table('receivable_credit')
                ->where('recr_belongs_id',$request['sebi_id'])
                ->where('recr_type',6)
                ->update(['recr_statistics_type'=>2,'recr_update_time'=>date('Y-m-d H:i:s')]);
        }else{
            $createBill = true;
            $statistics_type_update = true;
        }

        if($update_state && $createBill && $statistics_type_update) {
            Common::addLog($user_info, getRealIp($request), '销售账单','审核',$sebi_data->sebi_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 VerifySellBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $sebi_data = DB::table('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
                ->first(['sebi_number', 'sebi_state', 'sebi_start_time', 'sebi_end_time', 
                         'sebi_create_time', 'sebi_create_adm_id', 'sebi_wor_amount', 'sebi_bill_price', 
                         'sebi_client_id', 'sebi_type', 'sebi_goods_sum' ,'sebi_total_price',
                         'sebi_audit_time', 'sebi_audit_adm_id', 'sebi_payment_time', 'sebi_payee_id', 
                         'sebi_payment_way', 'sebi_payment_way', 'sebi_actual_price', 'sebi_remark', 'sebi_img',
                         'sebi_collection_price','sebi_zero_price']);
        if(empty($sebi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }

        // 获取到创建人姓名
        $sebi_data->sebi_create_adm_name = DB::table('admin')
                    ->where('adm_id',$sebi_data->sebi_create_adm_id)
                    ->value('adm_name');
        // 获取到审核人姓名
        $sebi_data->sebi_audit_adm_name = DB::table('admin')
                    ->where('adm_id',$sebi_data->sebi_audit_adm_id)
                    ->value('adm_name');
        // 获取到人姓名
        $sebi_data->sebi_payee_name = DB::table('admin')
                    ->where('adm_id',$sebi_data->sebi_payee_id)
                    ->value('adm_name');

        // 获取客户单位信息
        if($sebi_data->sebi_type == 1){
            // 会员
            $member = DB::table('member')
                    ->where('mem_id',$sebi_data->sebi_client_id)
                    ->first(['mem_name','mem_phone','mem_address']);
            $sebi_data->unit_name = '';
            $sebi_data->adm_name = $member->mem_name;
            $sebi_data->adm_phone = $member->mem_phone;
            $sebi_data->adm_address = $member->mem_address;
        }else{
            // 客户单位
            $channel = DB::table('channel_unit')
                    ->where('chun_id',$sebi_data->sebi_client_id)
                    ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
            $sebi_data->unit_name = $channel->chun_unit_name;
            $sebi_data->adm_name = $channel->chun_name;
            $sebi_data->adm_phone = $channel->chun_phone;
            $sebi_data->adm_address = $channel->chun_address;
        }

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

    // 删除(做成了真删)
    public function del(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $sebi_data = DB::table('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
            ->first(['sebi_number', 'sebi_state', 'sebi_type', 'sebi_client_id', 'sebi_bill_price']);
        if(empty($sebi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        if($sebi_data->sebi_state != 4){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'已驳回的账单才可以删除']);
        }

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

        // 2.解除销售出库单与账单的绑定关系
        $update_data['sell_sebi_id'] = 0;
        $update_data['sell_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('sell')
                ->where('sell_sebi_id',$request['sebi_id'])
                ->update($update_data);

        // 应收账单表新增数据
        // if($request['sebi_type'] == 2){
        //     $analyze = Common::updateAnalyze(
        //         $user_info, //用户信息
        //         $request['sebi_client_id'], //客户单位id
        //         1, //单量
        //         $request['sebi_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), '销售账单','删除',$sebi_data->sebi_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 VerifySellBillController;
        $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']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

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


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

        // 1.修改状态
        $update_state = DB::table('sell_bill')
                ->where('sebi_id',$request['sebi_id'])
                ->update($update_data);
        //删除该账单
        $del_credit = DB::table('receivable_credit')
                ->where('recr_cid',$user_info->adm_cid)
                ->where('recr_shop_superior_id',$shop_id)
                ->where('recr_type',6) //类型 6.销售账单
                ->where('recr_belongs_id',0) //所属账单id为0
                ->where('recr_original_id',$request['sebi_id']) //与类型所对应的id
                ->delete();

        // 所属账单id改为0,统计状态为1
        $update_belongs = DB::table('receivable_credit')
                    ->where('recr_type',6) //类型 : 销售账单
                    ->where('recr_belongs_id',$request['sebi_id'])
                    ->update(['recr_belongs_id'=>0,'recr_update_time'=>date('Y-m-d H:i:s'),'recr_statistics_type'=>1]);

        if($update_belongs || $update_belongs===0){
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'编辑失败']);
        }
        if($update_state && $del_credit) {
            Common::addLog($user_info, getRealIp($request), '订单账单','反审核',$sebi_data->sebi_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 VerifySellBillController;
        $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']);

        $sebi_state = DB::table('sell_bill')
                    ->where('sebi_id',$request['sebi_id'])
                    ->value('sebi_state');
        if(($sebi_state == 2) || ($sebi_state == 5)){
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'该账单已结款']);
        }
        DB::beginTransaction();
        // 1.解除该销售账单与原来销售出库单的绑定关系
        $relieve_data['sell_sebi_id'] = 0; //账单id改为0
        $relieve_data['sell_update_time'] = date('Y-m-d H:i:s');
        $relieve_relation = DB::table('sell')
                    ->where('sell_sebi_id',$request['sebi_id'])
                    ->update($relieve_data);

        $sell_price_data = DB::table('sell')
                    ->whereIn('sell_id',$request['sell_id'])
                    ->get(['sell_actual_price','sell_price']);
        $sell_actual_price = 0;
        $sell_price = 0;
        foreach ($sell_price_data as $key => $value) {
            $sell_actual_price += $value->sell_actual_price;//实际金额
            $sell_price += $value->sell_price;//合计金额
        }


        // 2.重新绑定销售出库单与账单的关系
        $sql = 'UPDATE `faster_sell` SET ';
        $sell_sebi_id = ''; //账单id
        $update_time = ''; //调货时间
        $sell_id = "";

        foreach ($request['sell_id'] as $key => $value) {
           // 更改账单id
            $sell_sebi_id = $sell_sebi_id . ' WHEN ' .$value;
            $sell_sebi_id = $sell_sebi_id . ' THEN ' .$request['sebi_id'];
            // 更改时间
            $update_time = $update_time . ' WHEN ' .$value;
            $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';
            //要更改的销售单id
            $sell_id = $sell_id . $value.',';
        }
        $sql = $sql .' `sell_sebi_id`= CASE `sell_id` '.$sell_sebi_id.' END,';
        $sql = $sql .' `sell_update_time`= CASE `sell_id` '.$update_time.' END';
        $sql = $sql .' WHERE `sell_id` IN ('.trim($sell_id,',').')';
        $save_sell = DB::update($sql);

        // 3.修改单量 改为待审核状态
        $update_bill['sebi_wor_amount'] = count($request['sell_id']); //单量
        $update_bill['sebi_state'] = 3; //3.待审核
        $update_bill['sebi_update_time'] = date('Y-m-d H:i:s');
        $update_bill['sebi_total_price'] = $sell_price;
        $update_bill['sebi_bill_price'] = $sell_actual_price;
        $bill_data = DB::table('sell_bill')
                    ->where('sebi_id',$request['sebi_id'])
                    ->update($update_bill);
        //1.未结款
        if($sebi_state == 1){
            // print_sql();
            // $credit_data = DB::table('receivable_credit')
                // ->where('recr_belongs_id',$request['sebi_id'])
                // ->update(['recr_belongs_id'=>0,'recr_update_time'=>date('Y-m-d H:i:s')]);
            $credit_data = DB::update("update `faster_receivable_credit` set `recr_belongs_id` = 0, `recr_update_time` = '".date('Y-m-d H:i:s')."' where `recr_belongs_id` = ".$request['sebi_id']);

            if($credit_data || $credit_data===0){
            }else{
                DB::rollBack();
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'编辑失败']);
            }

            $del_data = DB::table('receivable_credit')
                ->where('recr_original_id',$request['sebi_id'])
                ->where('recr_type',6)
                ->delete();
        }else{ 
            $del_data = true;
        }
        if($relieve_relation && $save_sell && $bill_data && $del_data) {
            Common::addLog($user_info, getRealIp($request), '销售账单','编辑',$request['sebi_number'].'编辑成功');
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'编辑成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'编辑失败']);
        }
    }
}
