<?php

namespace App\Http\Controllers\Api\AccountControl;

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

// 银行卡管理
class AccountTitleController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAccountTitleController;
        $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_title')
            ->where('acti_adm_id',$user_info->adm_cid)
            ->where('acti_shop_superior_id',$shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_subject_code'])) {
                    $query->where('acti_subject_code', 'like', '%'.$search_data['acti_subject_code'].'%');
                }
            }) //银行卡代码
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_course_title'])) {
                    $query->where('acti_course_title', 'like', '%'.$search_data['acti_course_title'].'%' );
                }
            }) //银行卡名称
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_state'])) {
                    $query->where('acti_state', $search_data['acti_state']);
                }
            }) //状态1启用2停用
            ->select('acti_id', 'acti_subject_code', 'acti_course_title', 'acti_state', 'acti_initial_count',
                     'acti_closing_account', 'acti_lend', 'acti_loan')
            ->orderBy('acti_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();

        $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 add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAccountTitleController;
        $error_message = $verify_data->addValidator($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;

        // 判断银行卡名称是否存在
        $acti_id =  DB::table('account_title')
            ->where('acti_adm_id',$user_info->adm_cid)
            ->where('acti_shop_superior_id',$shop_id)
            ->where('acti_course_title', $request['acti_course_title'])
            ->select('acti_id')
            ->first();
        if ($acti_id) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'银行卡名称已存在']);
        }

        //新增银行卡数据
        $acti_add_data['acti_adm_id'] = $user_info->adm_cid;    //公司id
        $acti_add_data['acti_shop_id'] = $user_info->adm_shop_id;    //门店id
        $acti_add_data['acti_shop_superior_id'] = $shop_id;    //总店id
        $acti_add_data['acti_subject_code'] = $request['acti_subject_code'];    //银行卡代码
        $acti_add_data['acti_course_title'] = $request['acti_course_title'];    //银行卡名称
        $acti_add_data['acti_state'] = 1;    //状态1启用2停用

        DB::beginTransaction();

        $acti_res = DB::table('account_title')->insertGetId($acti_add_data);

        //新增银行卡查询数据
        $acse_add_data['acse_acti_id'] = $acti_res;    //银行卡id
        $acse_add_data['acti_adm_cid'] = $user_info->adm_cid;    //公司id
        $acse_add_data['acti_shop_id'] = $user_info->adm_shop_id; //门店id
        $acse_add_data['acse_year'] = date('Y');    //年份
        $acse_add_data['acse_month'] = date('m');    //年份
        $acse_add_data['acse_subject_code'] = $request['acti_subject_code'];    //银行卡代码
        $acse_add_data['acse_course_title'] = $request['acti_course_title'];    //银行卡名称

        $acti_res = DB::table('account_select')->insert($acse_add_data);
        if ($acti_res && $acti_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '银行卡管理','新增','新增银行卡：'.$request['acti_course_title'].'成功');
            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 VerifyAccountTitleController;
        $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;

        // 判断银行卡名称是否存在
        $acti_id =  DB::table('account_title')
            ->where('acti_id','<>',$request['acti_id'])
            ->where('acti_adm_id',$user_info->adm_cid)
            ->where('acti_shop_superior_id',$shop_id)
            ->where('acti_course_title', $request['acti_course_title'])
            ->select('acti_id')
            ->first();
        if ($acti_id) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'银行卡名称已存在']);
        }

        //编辑数据
        $acti_edit_data['acti_subject_code'] = $request['acti_subject_code'];    //银行卡代码
        $acti_edit_data['acti_course_title'] = $request['acti_course_title'];    //银行卡名称
        $acti_edit_data['acti_update_time'] = date('Y-m-d H:i:s');    //更新时间

        //编辑银行卡查询数据
        $acse_edit_data['acse_year'] = date('Y');    //年份
        $acse_edit_data['acse_month'] = date('M');    //年份
        $acse_edit_data['acse_subject_code'] = $request['acti_subject_code'];    //银行卡代码
        $acse_edit_data['acse_course_title'] = $request['acti_course_title'];    //银行卡名称
        $acse_edit_data['acse_update_time'] = date('Y-m-d H:i:s');    //更新时间

        DB::beginTransaction();

        $acti_res = DB::table('account_title')
            ->where('acti_id',$request['acti_id'])
            ->update($acti_edit_data);

        // 查询是否有数据
        $find_acse_acti_id = DB::table('account_select')
            ->where('acse_acti_id', $request['acti_id'])
            ->value('acse_acti_id');
        if ($find_acse_acti_id) {
            $acse_res = DB::table('account_select')
                ->where('acse_acti_id', $request['acti_id'])
                ->update($acse_edit_data);
        }else{
            $acse_res = true;
        }
        if ($acti_res && $acse_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '银行卡管理','编辑','编辑银行卡：'.$request['acti_course_title'].'成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'编辑银行卡成功']);
        }else{
            DB::rollBack();
            return response()->json(['code'=>500,'msg'=>'error','data'=>'编辑银行卡失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAccountTitleController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询银行卡名称信息
        $find_adm = DB::table('account_title')
            ->whereIn('acti_id',$request['acti_id'])
            ->select('acti_course_title')
            ->get();
        foreach ($find_adm as $key => $value) {
            $acti_course_title[] = $value->acti_course_title;
        }

        // 启用
        $update_data['acti_state'] = 1;//状态1启用2停用
        $update_data['acti_update_time'] = date('Y-m-d H:i:s');
        $adm_res = DB::table('account_title')
            ->whereIn('acti_id',$request['acti_id'])
            ->update($update_data);

        if($adm_res) {
            Common::addLog($user_info, getRealIp($request), '银行卡管理','启用','银行卡名称：（'.implode(',', $acti_course_title).'）启用成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'启用成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'启用失败']);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAccountTitleController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询银行卡名称信息
        $find_adm = DB::table('account_title')
            ->whereIn('acti_id',$request['acti_id'])
            ->select('acti_course_title')
            ->get();
        foreach ($find_adm as $key => $value) {
            $acti_course_title[] = $value->acti_course_title;
        }

        // 停用
        $update_data['acti_state'] = 2;//状态1启用2停用
        $update_data['acti_update_time'] = date('Y-m-d H:i:s');
        $adm_res = DB::table('account_title')
            ->whereIn('acti_id',$request['acti_id'])
            ->update($update_data);

        if($adm_res) {
            Common::addLog($user_info, getRealIp($request), '银行卡管理','停用','银行卡名称：（'.implode(',', $acti_course_title).'）停用成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'停用成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    // 银行卡查询列表
    public function selectIndex(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAccountTitleController;
        $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']);

        $search_data = $request->all();
        $list_data = DB::table('account_select')
            ->where('acti_adm_cid',$user_info->adm_cid)
            ->where('acti_shop_id',$user_info->adm_shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_subject_code'])) {
                    $query->where('acse_subject_code', 'like', '%'.$search_data['acti_subject_code'].'%');
                }
            }) //银行卡代码
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_course_title'])) {
                    $query->where('acse_course_title', 'like', '%'.$search_data['acti_course_title'].'%' );
                }
            }) //银行卡名称
            ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_acse_year']) && !empty($search_data['end_acse_year'])){
                    $query->whereBetween('acse_year',[$search_data['start_acse_year'],$search_data['end_acse_year']]);
                }else{
                    // 如果选择开始时间
                    if (!empty($search_data['start_acse_year'])){
                        $query->where('acse_year','>=',$search_data['start_acse_year']);
                    }else{
                        // 如果选择结束时间
                        if (!empty($search_data['end_acse_year'])) {
                            $query->where('acse_year','<=',$search_data['end_acse_year']);
                        }
                    }
                }
            }) //年份
            ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_acse_month']) && !empty($search_data['end_acse_month'])){
                    $query->whereBetween('acse_month',[$search_data['start_acse_month'],$search_data['end_acse_month']]);
                }else{
                    // 如果选择开始时间
                    if (!empty($search_data['start_acse_month'])){
                        $query->where('acse_month','>=',$search_data['start_acse_month']);
                    }else{
                        // 如果选择结束时间
                        if (!empty($search_data['end_acse_month'])) {
                            $query->where('acse_month','<=',$search_data['end_acse_month']);
                        }
                    }
                }
            }) //月份
            ->select('acse_id', 'acse_year', 'acse_month', 'acse_subject_code', 'acse_course_title',
                'acse_initial_count', 'acse_lend', 'acse_loan', 'acse_closing_account')
            ->orderBy('acse_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();

         $sum_type = 1; //隐藏
        // 判断是否有搜索条件 有搜索条件
        if(!empty($search_data['acti_subject_code']) || !empty($search_data['acti_course_title']) || !empty($search_data['start_acse_year']) | !empty($search_data['end_acse_year']) || !empty($search_data['start_acse_month']) || !empty($search_data['end_acse_month'])){
            $sum_type = 2;

            $sum_data = DB::table('account_select')
                ->where('acti_adm_cid',$user_info->adm_cid)
                ->where('acti_shop_id',$user_info->adm_shop_id)
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['acti_subject_code'])) {
                        $query->where('acse_subject_code', 'like', '%'.$search_data['acti_subject_code'].'%');
                    }
                }) //银行卡代码
                ->where(function($query) use($search_data) {
                    if (!empty($search_data['acti_course_title'])) {
                        $query->where('acse_course_title', 'like', '%'.$search_data['acti_course_title'].'%' );
                    }
                }) //银行卡名称
                ->where(function($query) use($search_data) {
                    //如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_acse_year']) && !empty($search_data['end_acse_year'])){
                        $query->whereBetween('acse_year',[$search_data['start_acse_year'],$search_data['end_acse_year']]);
                    }else{
                        // 如果选择开始时间
                        if (!empty($search_data['start_acse_year'])){
                            $query->where('acse_year','>=',$search_data['start_acse_year']);
                        }else{
                            // 如果选择结束时间
                            if (!empty($search_data['end_acse_year'])) {
                                $query->where('acse_year','<=',$search_data['end_acse_year']);
                            }
                        }
                    }
                }) //年份
                ->where(function($query) use($search_data) {
                    //如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_acse_month']) && !empty($search_data['end_acse_month'])){
                        $query->whereBetween('acse_month',[$search_data['start_acse_month'],$search_data['end_acse_month']]);
                    }else{
                        // 如果选择开始时间
                        if (!empty($search_data['start_acse_month'])){
                            $query->where('acse_month','>=',$search_data['start_acse_month']);
                        }else{
                            // 如果选择结束时间
                            if (!empty($search_data['end_acse_month'])) {
                                $query->where('acse_month','<=',$search_data['end_acse_month']);
                            }
                        }
                    }
                }) //月份
                ->first(array(
                            \DB::raw('SUM(acse_lend) as lend'), //借
                            \DB::raw('SUM(acse_loan) as loan'), //贷
                            \DB::raw('SUM(acse_initial_count) as initial_count'), //期初余额
                            \DB::raw('SUM(acse_closing_account) as closing_account'), //期末余额
                        ));
        }

        $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['sum_type'] = $sum_type;   //返回总数量
        $data_info['lend'] = empty($sum_data->lend)?0:$sum_data->lend;   //借
        $data_info['loan'] = empty($sum_data->loan)?0:$sum_data->loan;   //贷
        $data_info['initial_count'] = empty($sum_data->initial_count)?0:$sum_data->initial_count;     //期初余额
        $data_info['closing_account'] = empty($sum_data->closing_account)?0:$sum_data->closing_account; //期末余额

        // 获取当前列表下的按钮
        $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 export(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $data = DB::table('account_select')
            ->where('acti_adm_cid',$user_info->adm_cid)
            ->where('acti_shop_id',$user_info->adm_shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_subject_code'])) {
                    $query->where('acse_subject_code', 'like', '%'.$search_data['acti_subject_code'].'%');
                }
            }) //银行卡代码
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_course_title'])) {
                    $query->where('acse_course_title', 'like', '%'.$search_data['acti_course_title'].'%' );
                }
            }) //银行卡名称
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acse_year'])) {
                    $query->where('acse_year', 'like', '%'.$search_data['acse_year'].'%' );
                }
            }) //年份
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acse_month'])) {
                    $query->where('acse_month', 'like', '%'.$search_data['acse_month'].'%' );
                }
            }) //月份
            ->select('acse_year', 'acse_month', 'acse_subject_code', 'acse_course_title', 'acse_initial_count',
                'acse_lend', 'acse_loan', 'acse_closing_account')
            ->orderBy('acse_id', 'desc')
            ->get()->toArray();

        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data),true);
            foreach ($data as $key => $value) {
                $data[$key]['acse_initial_count'] = $value['acse_initial_count'] / 100;
                $data[$key]['acse_lend'] = $value['acse_lend'] / 100;
                $data[$key]['acse_loan'] = $value['acse_loan'] / 100;
                $data[$key]['acse_closing_account'] = $value['acse_closing_account'] / 100;
            }
        } else {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'暂无导出数据']);
        }

        $pathName = storage_path()."/app/public/excel";//获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName,0775,true);
            chmod($pathName,0775);
        }

        $streamFileRand = time() . rand(10000,99999).'.xls';//
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' .$streamFileRand;

        $where['action_name'] = '银行卡查询'; //
        $where['field_name'] = ['年份','月份','银行卡代码','银行卡名称','期初余额','借(汇入)','贷(汇出)','期末余额'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if(file_exists($pathName))
        {
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>'storage/excel/'.$streamFileRand]);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    // 银行卡查询列表打印
    public function print(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('account_select')
            ->where('acti_adm_cid',$user_info->adm_cid)
            ->where('acti_shop_id',$user_info->adm_shop_id)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_subject_code'])) {
                    $query->where('acse_subject_code', 'like', '%'.$search_data['acti_subject_code'].'%');
                }
            }) //银行卡代码
            ->where(function($query) use($search_data) {
                if (!empty($search_data['acti_course_title'])) {
                    $query->where('acse_course_title', 'like', '%'.$search_data['acti_course_title'].'%' );
                }
            }) //银行卡名称
            ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_acse_year']) && !empty($search_data['end_acse_year'])){
                    $query->whereBetween('acse_year',[$search_data['start_acse_year'],$search_data['end_acse_year']]);
                }else{
                    // 如果选择开始时间
                    if (!empty($search_data['start_acse_year'])){
                        $query->where('acse_year','>=',$search_data['start_acse_year']);
                    }else{
                        // 如果选择结束时间
                        if (!empty($search_data['end_acse_year'])) {
                            $query->where('acse_year','<=',$search_data['end_acse_year']);
                        }
                    }
                }
            }) //年份
            ->where(function($query) use($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_acse_month']) && !empty($search_data['end_acse_month'])){
                    $query->whereBetween('acse_month',[$search_data['start_acse_month'],$search_data['end_acse_month']]);
                }else{
                    // 如果选择开始时间
                    if (!empty($search_data['start_acse_month'])){
                        $query->where('acse_month','>=',$search_data['start_acse_month']);
                    }else{
                        // 如果选择结束时间
                        if (!empty($search_data['end_acse_month'])) {
                            $query->where('acse_month','<=',$search_data['end_acse_month']);
                        }
                    }
                }
            }) //月份
            ->select('acse_id', 'acse_year', 'acse_month', 'acse_subject_code', 'acse_course_title',
                     'acse_initial_count', 'acse_lend', 'acse_loan', 'acse_closing_account')
            ->orderBy('acse_id', 'desc')
            ->get();
        
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }
}
