<?php

namespace App\Http\Controllers\Api\AccountControl;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountControl\VerifyInitialBalanceController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

// 期初余额
class InitialBalanceController extends Controller
{
	// 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyInitialBalanceController;
        $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('account_subject')
            ->where('acsu_cid', $user_info->adm_cid)
		    ->where('acsu_shop_id', $user_info->adm_shop_id)
            ->where('subjlev', 1)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['subjcode'])) {
                    $query->where('subjcode', 'like', '%'.$search_data['subjcode'].'%');
                }
            }) //科目编码
            ->where(function($query) use($search_data) {
                if (!empty($search_data['subjname'])) {
                    $query->where('subjname', 'like', '%'.$search_data['subjname'].'%' );
                }
            }) //科目名称
           	 ->select('acsu_id', 'subjcode', 'subjname', 'balanorient', 'unit', 'endflag', 'acsu_bdin_id')
            ->orderBy('acsu_id', 'asc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
		    // 查询期末余额数据
        	$acsu_id = array_column($list_items, 'acsu_id');
        	$find_acib_data = DB::table('account_initial_balance')
            ->where('acib_cid', $user_info->adm_cid)
		    ->where('acib_shop_id', $user_info->adm_shop_id)
            ->where('currtypecode', $search_data['currtypecode'])
            ->whereIn('acib_acsu_id', $acsu_id)
            ->select('acib_id', 'acib_acsu_id', 'debtor_amount', 'debtor_original_currency', 
            	'debtor_home_currency', 'creditor_amount', 'creditor_original_currency', 'creditor_home_currency', 'initial_amount', 
            	'initial_original_currency', 'initial_home_currency', 'beginning_amount', 'beginning_original_currency', 
            	'beginning_home_currency')
            ->get()->toArray();
            $acib_data = array_column($find_acib_data, null, 'acib_acsu_id');
            // 将查询出的期末余额表数据赋值给相关科目
            foreach ($list_items as $key => $value) {
            	if (isset($acib_data[$value->acsu_id])) {
            		// 合并两个对象数据
            		$list_items[$key] = (object)array_merge((array)$value, (array)$acib_data[$value->acsu_id]);
            	}
            }
        	$list_items = $this->inquireChildren($user_info, $list_items, $search_data, 1);
        }
        $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;                //返回数据

        // 获取当前列表下的按钮
        $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 edit(Request $request)
    {
    	// 验证数据
        $verify_data = new VerifyInitialBalanceController;
        $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']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 查询科目是否是末级
        $find_data = DB::table('account_subject')
	            ->where('acsu_cid', $user_info->adm_cid)
	            ->where('acsu_shop_superior_id', $shop_id)
	            ->where('acsu_id', $request['acsu_id'])
	            ->select('subjcode', 'subjname', 'subjlev', 'endflag', 'balanorient')
	            ->first();
	    if ($find_data->endflag != 'Y') {
	        return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'不是末级科目无法编辑']);
	    }
	    if ($user_info->adm_id != 1) {
        	return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'期初余额编辑成功']);
	    }
    	$creditor_original_currency = empty($request['creditor_original_currency']) ? 0 : $request['creditor_original_currency'];
    	$debtor_original_currency = empty($request['debtor_original_currency']) ? 0 : $request['debtor_original_currency'];
    	$initial_original_currency = empty($request['initial_original_currency']) ? 0 : $request['initial_original_currency'];

    	$acib_data['debtor_original_currency'] = $debtor_original_currency;//借方原币
    	$acib_data['debtor_home_currency'] = $debtor_original_currency;//借方本币

    	$acib_data['creditor_original_currency'] = $creditor_original_currency;//贷方原币
    	$acib_data['creditor_home_currency'] = $creditor_original_currency;//贷方本币

    	$acib_data['initial_original_currency'] = $initial_original_currency;//期初原币
    	$acib_data['initial_home_currency'] = $initial_original_currency;//期初本币

    	// 科目方向是借：年初原币计算 = 贷方-借方+期初  
    	// 科目方向是贷：年初原币计算 = 借方-贷方+期初  
    	// 期初余额的上级金额，下级的贷 100 上级的借 -100，借贷不一样，金额是相反的
    	// balanorient 余额方向 1:借2:贷
    	if ($find_data->balanorient == 1) {
    		$initial_home_currency = $creditor_original_currency - $debtor_original_currency + $initial_original_currency;
    	}else{
    		$initial_home_currency = $debtor_original_currency - $creditor_original_currency + $initial_original_currency;
    	}
    	$acib_data['beginning_original_currency'] = $initial_home_currency;//年初原币
    	$acib_data['beginning_home_currency'] = $initial_home_currency;//年初本币

        DB::beginTransaction();
        // 判断是否为一级科目
	    if ($find_data->subjlev != 1) {
	    	$first_code = substr($find_data->subjcode, 0, 4);//一级编码,前四位是一级编码
	        $subjlev_rank = [4,2,2,2];//级别对应的位数
	        $subjlev = $find_data->subjlev - 1;//科目级别
	    	$rank = 0;
	    	// 上级科目编码
	        foreach ($subjlev_rank as $key => $value) {
	        	$rank += $value;
	        	if ($key < $subjlev) {
	    			$rank_code[] = substr($find_data->subjcode, 0, $rank);//要更改金额的上级科目编码
	        	}
	        }
	        // 查询出上级的科目
	    	$rank_acsu_data = DB::table('account_subject')
	            ->where('acsu_cid', $user_info->adm_cid)
	            ->where('acsu_shop_superior_id', $shop_id)
	            ->where('subjcode', 'like', $first_code.'%')
	            ->where('subjlev', '<', $find_data->subjlev)
	            ->whereIn('subjcode', $rank_code)
	            ->select('acsu_id', 'subjcode', 'subjname', 'subjlev', 'endflag', 'balanorient')
	            ->get()->toArray();
	        $acsu_id = array_column($rank_acsu_data, 'acsu_id');//科目id

	        // 查询上级科目的期初余额数据
	        $find_rank_acib = DB::table('account_initial_balance')
	            ->where('acib_cid', $user_info->adm_cid)
	            ->where('acib_shop_superior_id', $shop_id)
	            ->whereIn('acib_acsu_id', $acsu_id)
	            ->where('currtypecode', $request['currtypecode'])//币种编码
	            ->select('acib_id', 'acib_acsu_id', 'debtor_original_currency', 'debtor_home_currency', 'creditor_original_currency', 
	            	'creditor_home_currency', 'initial_original_currency', 'initial_home_currency', 'beginning_original_currency',
	            	'beginning_home_currency')
	            ->get()->toArray();
	        // 判断期初余额是否存在
	        if (empty($find_rank_acib)) {
	        	$rank_add_data = [];
	        	// 不存在就新增
	        	foreach ($rank_acsu_data as $key => $value) {
	        		$rank_add_data[$key]['acib_cid'] = $user_info->adm_cid;
		        	$rank_add_data[$key]['acib_shop_id'] = $user_info->adm_shop_id;
		        	$rank_add_data[$key]['acib_shop_superior_id'] = $shop_id;
		        	$rank_add_data[$key]['acib_acsu_id'] = $value->acsu_id;//账户科目id
		    		$rank_add_data[$key]['currtypecode'] = $request['currtypecode'];//币种编码
	        		$rank_add_data[$key]['debtor_original_currency'] = $debtor_original_currency;//借方原币
			    	$rank_add_data[$key]['debtor_home_currency'] = $debtor_original_currency;//借方本币

			    	$rank_add_data[$key]['creditor_original_currency'] = $creditor_original_currency;//贷方原币
			    	$rank_add_data[$key]['creditor_home_currency'] = $creditor_original_currency;//贷方本币

	        		// 判断上级科目的方向 跟 编辑科目的方向是否一致
	        		if ($find_data->balanorient == $value->balanorient) {
	        			// 方向一致，上级科目的期初余额加上相同的金额
				    	$rank_add_data[$key]['initial_original_currency'] = $initial_original_currency;//期初原币
				    	$rank_add_data[$key]['initial_home_currency'] = $initial_original_currency;//期初本币

				    	// 科目方向是借：年初原币计算 = 贷方-借方+期初  
				    	// 科目方向是贷：年初原币计算 = 借方-贷方+期初  
				    	// balanorient 余额方向 1:借2:贷
				    	if ($value->balanorient == 1) {
				    		$initial_home_currency = $creditor_original_currency - $debtor_original_currency + $initial_original_currency;
				    	}else{
				    		$initial_home_currency = $debtor_original_currency - $creditor_original_currency + $initial_original_currency;
				    	}
	        		}else{
	        			// 方向不一致，上级科目的期初余额减去相同的金额
	        			$rank_add_data[$key]['initial_original_currency'] = '-'.$initial_original_currency;//期初原币
				    	$rank_add_data[$key]['initial_home_currency'] = '-'.$initial_original_currency;//期初本币
				    	// balanorient 余额方向 1:借2:贷
				    	if ($value->balanorient == 1) {
				    		$initial_home_currency = $creditor_original_currency - $debtor_original_currency - $initial_original_currency;
				    	}else{
				    		$initial_home_currency = $debtor_original_currency - $creditor_original_currency - $initial_original_currency;
				    	}
	        		}
	        		$rank_add_data[$key]['beginning_original_currency'] = $initial_home_currency;//年初原币
					$rank_add_data[$key]['beginning_home_currency'] = $initial_home_currency;//年初本币
	        	}
	        	$rank_add_res = DB::table('account_initial_balance')->insert($rank_add_data);
	        	if (!$rank_add_res) {
		            DB::rollBack();
		            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'期初余额编辑失败']);
		        }
	        }else{
	        	// 存在就编辑数据
	        	$rank_acib_data = array_column($find_rank_acib, null, 'acib_acsu_id');
	        	$num = 0;
	        	foreach ($rank_acsu_data as $key => $value) {
	        		// 判断上级科目的期初余额是否存在
	        		if (isset($rank_acib_data[$value->acsu_id])) {
	        			$new_creditor_original_currency = $creditor_original_currency - $rank_acib_data[$value->acsu_id]->creditor_original_currency;
	        			$new_debtor_original_currency = $debtor_original_currency - $rank_acib_data[$value->acsu_id]->debtor_original_currency;
	        			$new_initial_original_currency = $initial_original_currency - $rank_acib_data[$value->acsu_id]->initial_original_currency;

		        		$rank_data['debtor_original_currency'] = $rank_acib_data[$value->acsu_id]->debtor_original_currency + $new_debtor_original_currency;//借方原币
				    	$rank_data['debtor_home_currency'] = $rank_acib_data[$value->acsu_id]->debtor_home_currency + $new_debtor_original_currency;//借方本币

				    	$rank_data['creditor_original_currency'] = $rank_acib_data[$value->acsu_id]->creditor_original_currency + $new_creditor_original_currency;//贷方原币
				    	$rank_data['creditor_home_currency'] = $rank_acib_data[$value->acsu_id]->creditor_home_currency + $new_creditor_original_currency;//贷方本币

		        		// 判断上级科目的方向 跟 编辑科目的方向是否一致
		        		if ($find_data->balanorient == $value->balanorient) {
		        			// 方向一致，上级科目的期初余额加上相同的金额
					    	$rank_data['initial_original_currency'] = $rank_acib_data[$value->acsu_id]->initial_original_currency + $new_initial_original_currency;//期初原币
					    	$rank_data['initial_home_currency'] = $rank_acib_data[$value->acsu_id]->initial_home_currency + $new_initial_original_currency;//期初本币

					    	// 科目方向是借：年初原币计算 = 贷方-借方+期初  
					    	// 科目方向是贷：年初原币计算 = 借方-贷方+期初  
					    	// balanorient 余额方向 1:借2:贷
					    	if ($value->balanorient == 1) {
					    		$initial_home_currency = $new_creditor_original_currency - $new_debtor_original_currency + $new_initial_original_currency;
					    	}else{
					    		$initial_home_currency = $new_debtor_original_currency - $new_creditor_original_currency + $new_initial_original_currency;
					    	}
		        		}else{
		        			// 方向不一致，上级科目的期初余额减去相同的金额
		        			$rank_data['initial_original_currency'] = $rank_acib_data[$value->acsu_id]->initial_original_currency - $new_initial_original_currency;//期初原币
					    	$rank_data['initial_home_currency'] = $rank_acib_data[$value->acsu_id]->initial_home_currency - $new_initial_original_currency;//期初本币
					    	// balanorient 余额方向 1:借2:贷
					    	if ($value->balanorient == 1) {
					    		$initial_home_currency = $new_creditor_original_currency - $new_debtor_original_currency - $new_initial_original_currency;
					    	}else{
					    		$initial_home_currency = $new_debtor_original_currency - $new_creditor_original_currency - $new_initial_original_currency;
					    	}
		        		}
		        		$rank_data['beginning_original_currency'] = $rank_acib_data[$value->acsu_id]->beginning_original_currency + $initial_home_currency;//年初原币
						$rank_data['beginning_home_currency'] = $rank_acib_data[$value->acsu_id]->beginning_home_currency + $initial_home_currency;//年初本币
						$rank_edit_res = DB::table('account_initial_balance')
									->where('acib_id', $rank_acib_data[$value->acsu_id]->acib_id)
									->update($rank_data);
						if (!$rank_edit_res) {
				            DB::rollBack();
				            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'期初余额编辑失败']);
				        }
	        		}else{
		        		$rank_add_data[$num]['acib_cid'] = $user_info->adm_cid;
			        	$rank_add_data[$num]['acib_shop_id'] = $user_info->adm_shop_id;
			        	$rank_add_data[$num]['acib_shop_superior_id'] = $shop_id;
			        	$rank_add_data[$num]['acib_acsu_id'] = $value->acsu_id;//账户科目id
			    		$rank_add_data[$num]['currtypecode'] = $request['currtypecode'];//币种编码
		        		$rank_add_data[$num]['debtor_original_currency'] = $debtor_original_currency;//借方原币
				    	$rank_add_data[$num]['debtor_home_currency'] = $debtor_original_currency;//借方本币

				    	$rank_add_data[$num]['creditor_original_currency'] = $creditor_original_currency;//贷方原币
				    	$rank_add_data[$num]['creditor_home_currency'] = $creditor_original_currency;//贷方本币

		        		// 判断上级科目的方向 跟 编辑科目的方向是否一致
		        		if ($find_data->balanorient == $value->balanorient) {
		        			// 方向一致，上级科目的期初余额加上相同的金额
					    	$rank_add_data[$num]['initial_original_currency'] = $initial_original_currency;//期初原币
					    	$rank_add_data[$num]['initial_home_currency'] = $initial_original_currency;//期初本币

					    	// 科目方向是借：年初原币计算 = 贷方-借方+期初  
					    	// 科目方向是贷：年初原币计算 = 借方-贷方+期初  
					    	// balanorient 余额方向 1:借2:贷
					    	if ($value->balanorient == 1) {
					    		$initial_home_currency = $creditor_original_currency - $debtor_original_currency + $initial_original_currency;
					    	}else{
					    		$initial_home_currency = $debtor_original_currency - $creditor_original_currency + $initial_original_currency;
					    	}
		        		}else{
		        			// 方向不一致，上级科目的期初余额减去相同的金额
		        			$rank_add_data[$num]['initial_original_currency'] = '-'.$initial_original_currency;//期初原币
					    	$rank_add_data[$num]['initial_home_currency'] = '-'.$initial_original_currency;//期初本币
					    	// balanorient 余额方向 1:借2:贷
					    	if ($value->balanorient == 1) {
					    		$initial_home_currency = $creditor_original_currency - $debtor_original_currency - $initial_original_currency;
					    	}else{
					    		$initial_home_currency = $debtor_original_currency - $creditor_original_currency - $initial_original_currency;
					    	}
		        		}
		        		$rank_add_data[$num]['beginning_original_currency'] = $initial_home_currency;//年初原币
						$rank_add_data[$num]['beginning_home_currency'] = $initial_home_currency;//年初本币
						$num++;
	        		}
	        	}
	        	if (empty($rank_add_data)) {
	        		$rank_add_res = true;
	        	}else{
	        		$rank_add_res = DB::table('account_initial_balance')->insert($rank_add_data);
	        	}
	        	if (!$rank_add_res) {
		            DB::rollBack();
		            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'期初余额编辑失败']);
		        }
	        }
	    }

    	// 查询期初余额表数据
    	$acib_id = DB::table('account_initial_balance')
	            ->where('acib_cid', $user_info->adm_cid)
	            ->where('acib_shop_superior_id', $shop_id)
	            ->where('acib_acsu_id', $request['acsu_id'])
	            ->where('currtypecode', $request['currtypecode'])
	            ->value('acib_id');
        // 判断是否有期初余额id
        if (!empty($acib_id)) {
        	// 编辑
        	$acib_data['acib_update_time'] = date('Y-m-d H:i:s');
        	$acib_res = DB::table('account_initial_balance')
	            ->where('acib_cid', $user_info->adm_cid)
	            ->where('acib_shop_superior_id', $shop_id)
	            ->where('acib_id', $acib_id)
	            ->update($acib_data);
        } else {
        	// 新增
        	$acib_data['acib_cid'] = $user_info->adm_cid;
        	$acib_data['acib_shop_id'] = $user_info->adm_shop_id;
        	$acib_data['acib_shop_superior_id'] = $shop_id;
        	$acib_data['acib_acsu_id'] = $request['acsu_id'];//账户科目id
    		$acib_data['currtypecode'] = $request['currtypecode'];//币种编码
    		$acib_res = DB::table('account_initial_balance')
    					->insert($acib_data);
        }
        if($acib_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '期初余额', '编辑',  '期初余额 '.$find_data->subjname . '编辑成功');
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'期初余额编辑成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'期初余额编辑失败']);
        }
    }

    /**
     * [inquireChildren 搜索下级数据]
     * @param  [type]  $user_info [用户信息]
     * @param  [type]  $data      [列表数据]
     * @param  integer $subjlev   [科目级数]
     * @return [type]             [description]
     */
    private function inquireChildren($user_info, $data, $search_data, $subjlev = 1)
    {
    	$subjlev = $subjlev + 1;//科目级次
    	foreach ($data as $key => $value) {
    		if ($value->endflag == 'N') {
		        $children = DB::table('account_subject as acsu')
		            ->where('acsu_cid', $user_info->adm_cid)
		            ->where('acsu_shop_id', $user_info->adm_shop_id)
		            ->where('subjcode', 'like', $value->subjcode.'%' )
		            ->where('subjlev', $subjlev)
		           	->select('acsu_id', 'subjcode', 'subjname', 'balanorient', 'unit', 'endflag', 'acsu_bdin_id')
		            ->get()->toArray();
		            // 查询期末余额数据
		            $acsu_id = array_column($children, 'acsu_id');
		        	$find_acib_data = DB::table('account_initial_balance')
		            ->where('acib_cid', $user_info->adm_cid)
		            ->where('acib_shop_id', $user_info->adm_shop_id)
		            ->where('currtypecode', $search_data['currtypecode'])
		            ->whereIn('acib_acsu_id', $acsu_id)
		            ->select('acib_id', 'acib_acsu_id', 'debtor_amount', 'debtor_original_currency', 
		            	'debtor_home_currency', 'creditor_amount', 'creditor_original_currency', 'creditor_home_currency', 'initial_amount', 
		            	'initial_original_currency', 'initial_home_currency', 'beginning_amount', 'beginning_original_currency', 
		            	'beginning_home_currency')
		            ->get()->toArray();
		            $acib_data = array_column($find_acib_data, null, 'acib_acsu_id');
		            // 将查询出的期末余额表数据赋值给相关科目
		            foreach ($children as $chil_key => $chil_value) {
		            	if (isset($acib_data[$chil_value->acsu_id])) {
		            		// 合并两个对象数据
		            		$children[$chil_key] = (object)array_merge((array)$chil_value, (array)$acib_data[$chil_value->acsu_id]);
		            	}
		            }
		        // 递归查询下一级的数据
		        $data[$key]->children = $this->inquireChildren($user_info, $children, $search_data, $subjlev);
		        unset($children);
		        unset($acsu_id);
		        unset($find_acib_data);
		        unset($acib_data);
    		}
    	}
    	return $data;
    }
}
