<?php

namespace App\Http\Controllers\Api\AccountManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountManage\VerifyProcurementBillController;
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 ProcurementBillController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementBillController;
        $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('procurement_bill')
                    ->where('prbi_cid', $user_info->adm_cid)
                    ->where('prbi_superior_shop_id', $shop_id)
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_state'])) {
                            $query->where('prbi_state', $search_data['prbi_state']);
                        }
                    }) //账单状态
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_number'])) {
                            $query->where('prbi_number', 'like', $search_data['prbi_number'].'%' );
                        }
                    }) //账单编号
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_audit_adm_id'])) {
                            $query->where('prbi_audit_adm_id', $search_data['prbi_audit_adm_id']);
                        }
                    }) //审核人id
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_payment_way'])) {
                            $query->where('prbi_payment_way', $search_data['prbi_payment_way']);
                        }
                    }) //付款方式
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_payment_time'])) {
                            $query->where('prbi_payment_time', 'like', $search_data['prbi_payment_time'].'%' );
                        }
                    }) //付款时间
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_remark'])) {
                            $query->where('prbi_remark', 'like', $search_data['prbi_remark'].'%' );
                        }
                    }) //备注
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['prbi_client_id'])) {
                            $query->where('prbi_type', 2 )
                                  ->where('prbi_client_id', $search_data['prbi_client_id'] );
                        }
                    }) //客户单位
                    ->select('prbi_id', 'prbi_number', 'prbi_start_time', 'prbi_end_time', 'prbi_wor_amount',
                    	     'prbi_bill_price', 'prbi_payment_time', 'prbi_payment_way',
                    	     'prbi_actual_price', 'prbi_state', 'prbi_audit_time', 'prbi_audit_adm_id',
                             'prbi_create_adm_id', 'prbi_remark', 'prbi_client_id', 'prbi_type')
                    ->orderBy('prbi_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->prbi_create_adm_id;
                $adm_id[] = $value->prbi_audit_adm_id;

                if($value->prbi_type == 1){
                    // 会员
                    $mem_id[] = $value->prbi_client_id;
                }else{
                    // 客户单位
                    $channel_id[] = $value->prbi_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('procurement_bill')
            ->where('prbi_cid', $user_info->adm_cid)
            ->where('prbi_superior_shop_id', $shop_id)
           ->select(DB::raw('count(*) as count, prbi_state'))
           ->groupBy('prbi_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 VerifyProcurementBillController;
        $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('procurement_bill')
                ->where('prbi_id',$request['prbi_id'])
                ->first(['prbi_id','prbi_number','prbi_start_time','prbi_end_time','prbi_create_time','prbi_create_adm_id',
                         'prbi_wor_amount','prbi_bill_price','prbi_actual_price','prbi_type','prbi_client_id']);
            if($bill) {
                if($bill->prbi_type == 2){
                    // 来往单位
                    $bill->prbi_client_name = DB::table('channel_unit')
                                ->where('chun_id',$bill->prbi_client_id)
                                ->value('chun_unit_name');
                }else{
                    // 客户名称
                    $bill->prbi_client_name = DB::table('admin')
                                ->where('adm_id',$bill->prbi_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('procurement as a')
                        ->leftJoin('warehouse as b', 'b.ware_id', '=', 'a.proc_ware_id')
                        ->leftJoin('procurement_client as c', 'c.prcl_proc_id', '=', 'a.proc_id')
                        ->where('proc_cid', $user_info->adm_cid)
                        ->where('proc_superior_shop_id', $shop_id)
                        ->where('proc_prbi_id', $request['prbi_id'])
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['proc_number'])) {
                                $query->where('proc_number', 'like', $search_data['proc_number'].'%' );
                            }
                        }) //订单编号
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['prcl_name'])) {
                                $query->where('prcl_name', 'like', '%'.$search_data['prcl_name'].'%' );
                            }
                        }) //客户姓名
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['prcl_phone'])) {
                                $query->where('prcl_phone', 'like', '%'.$search_data['prcl_phone'].'%' );
                            }
                        }) //客户电话
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['prcl_address'])) {
                                $query->where('prcl_address', 'like', $search_data['prcl_address'].'%' );
                            }
                        }) //客户地址
                        ->select('proc_id', 'proc_number', 'proc_state', 'proc_actual_count as proc_count', 'proc_adm_id',  'proc_audit_id',
                                 'proc_remark', 'proc_data', 'proc_create_time', 'prcl_channel_unit', 'prcl_name', 
                                 'prcl_phone', 'prcl_address', 'ware_name', 'proc_actual_price')
                        ->orderBy('proc_id', 'desc')
                        ->paginate($this->show_count);
            $list_items = $list_data->items();
            // 查找账号id
            if(empty($list_items)){
                $adm_id = [];
            }else{
                foreach ($list_items as $key => $value) {
                    if ($value->proc_adm_id) {
                        $adm_id[] = $value->proc_adm_id;
                    }
                    if ($value->proc_audit_id) {
                        $adm_id[] = $value->proc_audit_id;
                    }
                    if ($value->proc_data) {
                        $value->proc_data = json_decode($value->proc_data, true);
                    }
                } 
            }


            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                        ->whereIn('adm_id', $adm_id)
                        ->select('adm_id', 'adm_name')
                        ->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_data->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 VerifyProcurementBillController;
        $error_message = $verify_data->getInfoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证当前账单是否存在
        $prbi_data = DB::table('procurement_bill')
                ->where('prbi_id',$request['prbi_id'])
                ->first(['prbi_number', 'prbi_state', 'prbi_start_time', 'prbi_end_time', 
                         'prbi_create_time', 'prbi_create_adm_id', 'prbi_wor_amount', 'prbi_bill_price',
                         'prbi_client_id', 'prbi_type', 'prbi_goods_sum','prbi_receive_price',
                         'prbi_total_price', 'prbi_collection_price','prbi_img']);
        if(empty($prbi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }

        if($request['type'] == 1){
            // 获取到创建人姓名
            $prbi_data->prbi_create_adm_name = DB::table('admin')
                        ->where('adm_id',$prbi_data->prbi_create_adm_id)
                        ->value('adm_name');
            // 获取客户单位信息
            if($prbi_data->prbi_type == 1){
                // 会员
                $member = DB::table('member')
                        ->where('mem_id',$prbi_data->prbi_client_id)
                        ->first(['mem_name','mem_phone','mem_address']);
                $prbi_data->unit_name = '';
                $prbi_data->adm_name = $member->mem_name;
                $prbi_data->adm_phone = $member->mem_phone;
                $prbi_data->adm_address = $member->mem_address;
            }else{
                // 客户单位
                $channel = DB::table('channel_unit')
                        ->where('chun_id',$prbi_data->prbi_client_id)
                        ->first(['chun_unit_name','chun_name','chun_phone','chun_address']);
                $prbi_data->unit_name = $channel->chun_unit_name;
                $prbi_data->adm_name = $channel->chun_name;
                $prbi_data->adm_phone = $channel->chun_phone;
                $prbi_data->adm_address = $channel->chun_address;
            }
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$prbi_data]);
        }

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

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

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

        $few = 0;
        $img = '';
         foreach ($request['prbi_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 = $prbi_data->prbi_img.','.$img;
        $img = rtrim($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;

        // 获取来往单位名称
        if($request['prbi_type'] == 1){
            $client_name = '';
        }else{
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$request['prbi_client_id'])
                    ->value('chun_unit_name');
        }

        DB::beginTransaction();

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

        // 修改采购账单表
        $update_state = DB::update('UPDATE `faster_procurement_bill` SET `prbi_receive_price`=`prbi_receive_price`+'.$prbi_actual_price.', `prbi_zero_price`=`prbi_zero_price`+'.$zero_price.' ,`prbi_actual_price`=`prbi_actual_price`+'.$prbi_actual_price.' ,`prbi_state`= '.$prbi_state.' ,`prbi_remark`= "'.$request['prbi_remark'].'"  ,`prbi_payee_id`= '.$user_info->adm_id.',`prbi_img`= "'.$img.'" ,`prbi_payment_time`= "'.date('Y-m-d H:i:s').'" ,`prbi_update_time`= "'.date('Y-m-d H:i:s').'" WHERE `prbi_id`=?',[$request['prbi_id']]);

        // 查询出账单对应的应收账款id
        $find_acpa = DB::table('accounts_payable')
                ->where('acpa_cid',$user_info->adm_cid)
                ->where('acpa_shop_superior_id',$shop_id)
                ->where('acpa_type',2)
                ->where('acpa_original_id',$request['prbi_id'])
                ->select('acpa_id','acpa_remark')
                ->first();

        // 6. 更改账单的应收账款金额
        $acpa_edit_data['acpa_actual_price'] = $prbi_actual_price;
        $acpa_edit_data['acpa_zero_price'] = $zero_price;
        $acpa_edit_data['acpa_yet_receipt'] = $prbi_data->prbi_receive_price + $prbi_actual_price;
        $acpa_edit_data['acpa_remark'] = $find_acpa->acpa_remark.$request->input('prbi_remark','');
        $acpa_edit_data['acpa_update_time'] = date('Y-m-d H:i:s');
        $createBill = DB::table('accounts_payable')
                ->where('acpa_cid',$user_info->adm_cid)
                ->where('acpa_shop_superior_id',$shop_id)
                ->where('acpa_type',2)
                ->where('acpa_id',$find_acpa->acpa_id)
                ->update($acpa_edit_data);

        // 预付款抵账(减预付款金额)
        if($request['prbi_payment_type'] == 3){
            //  实收金额
            $subtract = DB::table('accounts_payable')
                ->where('acpa_id',$request['acpa_id'])
                ->decrement('acpa_actual_price',$prbi_actual_price);

            $add_data['acde_advance_id'] = $request['acpa_id']; //预付款id
            $add_data['acde_acpa_id'] = $createBill; //账单id
            $details_data = DB::table('accounts_details')->insert($add_data);
            // $AccountSubject = true;
        }else{
            $subtract = true;
            $details_data = true;

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

        $acti_closing_account = DB::table('account_title')
                ->where('acti_id',$request['acti_id'])
                ->value('acti_closing_account');
        if($prbi_actual_price > $acti_closing_account){
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'科目余额不足']);
        }

        // 添加结款明细
        $AccountingSettlement = AccountingSettlement::add(
            $user_info,                    // [用户信息]
            4,                             // [单据类型1订单2订单账单3工单账单4采购账单5销售账单6预收款]
            $request['prbi_id'],           // [与单据类型对应的id]
            $prbi_data->prbi_number,       // [与单据类型对应的单号]
            $prbi_data->prbi_type,         // [买家类型1门店零售2来往单位]
            $prbi_data->prbi_client_id,    // [会员/客户id]
            $client_name,                  // [来往单位名称]
            $request['acti_id'],           // [会计科目id]
            2,                             // [类型1收入2支出]
            $prbi_actual_price,            // [实际金额](此次的实收金额)
            $surplus_price,                // [合计金额](此次的应收金额)
            $surplus_price-$prbi_actual_price-$zero_price,    // [欠收金额](此次结款后还应收金额)
            $zero_price,          // [抹零金额]
            $request['prbi_remark']  ? $request['prbi_remark'] : ''             // [备注]
        );

        if($update_state && $createBill && $AccountingSettlement && $subtract && $details_data) {
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '采购账单','结款',$prbi_data->prbi_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 VerifyProcurementBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证当前账单是否存在
        $prbi_data = DB::table('procurement_bill')
                ->where('prbi_id',$request['prbi_id'])
                ->first(['prbi_number', 'prbi_state', 'prbi_start_time', 'prbi_end_time', 
                         'prbi_create_time', 'prbi_create_adm_id', 'prbi_wor_amount', 'prbi_bill_price',
                         'prbi_client_id', 'prbi_type', 'prbi_goods_sum'  ,'prbi_total_price',
                         'prbi_collection_price', 'prbi_bill_price', 'prbi_audit_time', 'prbi_audit_adm_id',
                         'prbi_payment_time', 'prbi_payee_id', 'prbi_payment_way', 'prbi_actual_price', 
                         'prbi_remark', 'prbi_img', 'prbi_zero_price']);
        if(empty($prbi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        

        // 获取到创建人姓名
        $prbi_data->prbi_create_adm_name = DB::table('admin')
                    ->where('adm_id',$prbi_data->prbi_create_adm_id)
                    ->value('adm_name');
        // 获取到审核人姓名
        $prbi_data->prbi_audit_adm_name = DB::table('admin')
                    ->where('adm_id',$prbi_data->prbi_audit_adm_id)
                    ->value('adm_name');
        // 获取到收款人姓名
        $prbi_data->prbi_payee_name = DB::table('admin')
                    ->where('adm_id',$prbi_data->prbi_payee_id)
                    ->value('adm_name');

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

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

    // 审核
    public function audit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementBillController;
        $error_message = $verify_data->auditValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $prbi_data = DB::table('procurement_bill')
                ->where('prbi_id',$request['prbi_id'])
                ->first(['prbi_number', 'prbi_state', 'prbi_start_time', 'prbi_end_time', 
                         'prbi_create_time', 'prbi_create_adm_id', 'prbi_wor_amount', 'prbi_bill_price',
                         'prbi_client_id', 'prbi_type', 'prbi_goods_sum']);
        if(empty($prbi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        if($prbi_data->prbi_state != 3){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'待审核状态下才可以审核']);
        }

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

            $proc_data = DB::table('procurement as p')
                ->leftJoin('admin as a', 'p.proc_adm_id', '=', 'a.adm_id')
                ->where('proc_prbi_id',$request['prbi_id'])
                ->get(['proc_create_time', 'proc_number', 'proc_adm_id', 
                       'proc_price', 'proc_actual_price', 'adm_name as proc_adm_name']);
            $data['prbi_data'] = $prbi_data;
            $data['proc_data'] = $proc_data;
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data]);
        }

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

        DB::beginTransaction();

        $update_data['prbi_state'] = $request['prbi_state'];
        $update_data['prbi_audit_time'] = date('Y-m-d H:i:s'); //审核时间
        $update_data['prbi_audit_adm_id'] = $user_info->adm_id; //审核人
        $update_data['prbi_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('procurement_bill')
                ->where('prbi_id',$request['prbi_id'])
                ->update($update_data);

        // 获取客户单位名称
        if($prbi_data->prbi_type == 1){
            $client_name = '';
        }else{
            $client_name = DB::table('channel_unit')
                    ->where('chun_id',$prbi_data->prbi_client_id)
                    ->value('chun_unit_name');
        }
        //如果是同意状态
        if($request['prbi_state'] == 1){
            // 6. 生成应付账单
            $createBill = ReceivableBill::addAccounts(
                $user_info, //用户信息
                2, //类型：1.预付款 2.采购账单
                0, //应收账款id
                $request['prbi_id'], //原始id(订单账单id)
                $prbi_data->prbi_number, //应收账款单号/原始号(订单账单编号)
                $prbi_data->prbi_type, //客户类型：1.门店零售 2.来往单位
                $prbi_data->prbi_client_id, //会员id/来往单位id
                $client_name, //来往单位名称
                $prbi_data->prbi_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), '订单账单','审核',$prbi_data->prbi_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 VerifyProcurementBillController;
        $error_message = $verify_data->delValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 验证当前账单是否存在
        $prbi_data = DB::table('procurement_bill')
                ->where('prbi_id',$request['prbi_id'])
                ->first(['prbi_number', 'prbi_state','prbi_type', 'prbi_client_id', 'prbi_bill_price']);
        if(empty($prbi_data)){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账单不存在']);
        }
        if($prbi_data->prbi_state != 4){
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'已驳回的账单才可以删除']);
        }

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

        // 2.解除采购单与账单的绑定关系
        $update_data['proc_prbi_id'] = 0;
        $update_data['proc_update_time'] = date('Y-m-d H:i:s');
        $update_state = DB::table('procurement')
                ->where('proc_prbi_id',$request['prbi_id'])
                ->update($update_data);
        
        if($del_orbi && $update_state) {
            $user_info = Common::getUserInfo($request['api_token']);
            Common::addLog($user_info, getRealIp($request), '采购账单','删除',$prbi_data->prbi_number.'删除成功');
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'success','data'=>'删除成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'删除失败']);
        }
    }

    // 搜索预付款id 
    public function advanceMoney(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementBillController;
        $error_message = $verify_data->advanceMoneyValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        
        $user_info = Common::getUserInfo($request['api_token']);

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

        // 验证当前账单是否存在
        $data = DB::table('accounts_payable')
                ->where('acpa_cid',$user_info->adm_cid)
                ->where('acpa_shop_superior_id',$shop_id)
                ->where('acpa_client_id',$request['client_id'])
                ->where('acpa_type',1)
                ->where('acpa_actual_price','!=',0)
                ->get(['acpa_id','acpa_actual_price','acpa_original_number']);

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

    // 反审核
    public function cancelAudit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyProcurementBillController;
        $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']);

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


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

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

        // 通过的账单 删除应付账款
        if($prbi_data->prbi_state == 1){
            $del_payable = DB::table('accounts_payable')
                    ->where('acpa_type',2) //类型 2.采购账单
                    ->where('acpa_original_number',$prbi_data->prbi_number) //与类型所对应的id
                    ->delete();
            $update_belongs = DB::table('accounts_payable')
                    ->where('acpa_belongs_id',$request['prbi_id'])
                    ->update(['acpa_belongs_id'=>0,'acpa_update_time'=>date('Y-m-d H:i:s')]);
        }else{
            $del_payable = true;
            $update_belongs = true;
        } 

        if($update_state && $del_payable && $update_belongs) {
            Common::addLog($user_info, getRealIp($request), '采购账单','反审核',$prbi_data->prbi_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 VerifyProcurementBillController;
        $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['proc_prbi_id'] = 0; //账单id改为0
        $relieve_data['proc_update_time'] = date('Y-m-d H:i:s');
        $relieve_relation = DB::table('procurement')
                    ->where('proc_prbi_id',$request['prbi_id'])
                    ->update($relieve_data);

        // 2.重新绑定采购入库单与账单的关系
        $sql = 'UPDATE `faster_procurement` SET ';
        $proc_prbi_id = ''; //账单id
        $update_time = ''; //调货时间
        $proc_id = "";

        foreach ($request['proc_id'] as $key => $value) {
           // 更改账单id
            $proc_prbi_id = $proc_prbi_id . ' WHEN ' .$value;
            $proc_prbi_id = $proc_prbi_id . ' THEN ' .$request['prbi_id'];
            // 更改时间
            $update_time = $update_time . ' WHEN ' .$value;
            $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';
            //要更改的采购单id
            $proc_id = $proc_id . $value.',';
        }
        $sql = $sql .' `proc_prbi_id`= CASE `proc_id` '.$proc_prbi_id.' END,';
        $sql = $sql .' `proc_update_time`= CASE `proc_id` '.$update_time.' END';
        $sql = $sql .' WHERE `proc_id` IN ('.trim($proc_id,',').')';
        $save_procurement = DB::update($sql);

        // 3.修改单量 改为待审核状态
        $update_bill['prbi_wor_amount'] = count($request['proc_id']); //单量
        $update_bill['prbi_state'] = 3; //3.待审核
        $update_bill['prbi_update_time'] = date('Y-m-d H:i:s');
        $bill_data = DB::table('procurement_bill')
                    ->where('prbi_id',$request['prbi_id'])
                    ->update($update_bill);

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