<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\apicom\model\Money   as MoneyModel;
use app\apicom\model\Member  as MemberModel;
use app\apicom\model\Record  as RecordModel;
use app\apicom\model\Recharge;
use app\apicom\model\Withdraw;

use app\admin\model\Money   as AdminBank;
use think\facade\Db;

class Money extends AdminBase
{
    /*
     * 获取收款银行列表
     */
    public function getRichBanks()
    {
        $name   = input('payee', '');
        $card   = input('card' , '',['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'create_time desc';
        $where  = [];
        if(!empty($name)) $where[] = ['payee' ,'=', $name];
        if(!empty($card)) $where[] = ['card' ,'=', $card];
        $res    = AdminBank::getBanks($where,$order,$offset);
        if(!$res) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$res);
    }
    /*
     * 禁用/启用
     */
    public function doDisable()
    {
        $id     = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
		$res = AdminBank::where('id', $id)->save(['status'=> $status]);
        if ($res) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
    /*
     * 删除收款银行
     */
    public function delRichBank()
    {
        $id = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $rt = AdminBank::where('id', $id)->find();
        if(empty($rt)) return ajaxmsg('查询失败',0);
		$result = AdminBank::where('id', $id)->delete();
        if ($result) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
    /*
     * 编辑用户
     */
    public function editRichBank()
    {
        $data = input();
        $data['type'] = $data['type'][0];
        // 验证数据
		$result = $this->validate($data, 'Bank.create');
		if ($result !== true) return ajaxmsg($result,0);
        $data['create_time'] = time();
		if($data['id']){
		    $res = AdminBank::where('id',$data['id'])->strict(false)->save($data);
		}else{
		    $res = AdminBank::strict(false)->insert($data);
		}
		if (!$res) return ajaxmsg('操作失败',0);
        return ajaxmsg('操作成功',200);
    }
    /*
     * 获取资金列表
     */
    public function getMoneyList()
    {
        $name   = input('name', '');
        $mobile = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'create_time desc';
        if(!empty($name))   $where[] = ['a.name' ,'=', $name];
        if(!empty($mobile)) $where[] = ['a.mobile' ,'=', $mobile];
        $where[] = ['a.is_del' ,'=', 0];
        $res     = MemberModel::view('member a','id,name,mobile')
            ->view('money b','account,freeze,operate_account,bond_account,give_fee,freeze_give_fee,status','a.id=b.mid')
            ->where($where)
            ->order($order)
            ->paginate($offset, false, ['query' => request()->param()]);
        if(!$res) return ajaxmsg('没有数据',0);
        //print_r($data_list);exit;
        foreach ($res as $k => $val){
            $res[$k]['account'] = money_convert($val['account']);//bcdiv(strval($val['account']),'100',2);
            $res[$k]['freeze']  = money_convert($val['freeze']);//bcdiv(strval($val['freeze']),'100',2);
            $res[$k]['operate_account'] = money_convert($val['operate_account']);//bcdiv(strval($val['freeze']),'100',2);
            $res[$k]['bond_account']    = money_convert($val['bond_account']);//bcdiv(strval($val['freeze']),'100',2);
            $res[$k]['give_fee']        = money_convert($val['give_fee']);//bcdiv(strval($val['freeze']),'100',2);
            $res[$k]['freeze_give_fee'] = money_convert($val['freeze_give_fee']);//bcdiv(strval($val['freeze']),'100',2);
        }
        return ajaxmsg('操作成功',200,$res);
    }
    /* 
     * 获取资金明细
     */
    public function getMoneyRecord()
    {
        $name   = input('name', '');
        $mobile = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'create_time desc';
        if(!empty($name))   $where[] = ['m.name' ,'=', $name];
        if(!empty($mobile)) $where[] = ['m.mobile' ,'=', $mobile];
        $where[] = ['m.is_del' ,'=', 0];
        $res = RecordModel::getAll($where,$order,$offset);
        if(!$res) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$res);
    }
    /*
     * 获取充值列表
     */
    public function getRecharge()
    {
        $name   = input('name', '');
        $mobile = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = ['status','create_time desc'];
        if(!empty($name))   $where[] = ['m.name' ,'=', $name];
        if(!empty($mobile)) $where[] = ['m.mobile' ,'=', $mobile];
        $where[] = ['m.is_del' ,'=', 0];
        $res = Recharge::getAll($where,$order,$offset);
        if(!$res) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$res);
    }
    /*
     * 获取提现列表
     */
    public function getWithdraw()
    {
        $name   = input('name', '');
        $mobile = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = ['status','create_time desc'];
        if(!empty($name))   $where[] = ['m.name' ,'=', $name];
        if(!empty($mobile)) $where[] = ['m.mobile' ,'=', $mobile];
        $where[] = ['m.is_del' ,'=', 0];
        $res = Withdraw::getAll($where,$order,$offset);
        if(!$res) return ajaxmsg('没有数据',0);
        return ajaxmsg('操作成功',200,$res);
    }
    /**
     * 充值审核信息保存
     * @return [type] [description]
     */
    public static function auditRecharge()
    {
        $id     = input('id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $remark = input('remark', '');
        if(!$id) return ajaxmsg('缺少ID参数',0);
        $charge = Db::name('money_recharge')->where('id', $id)->find();
        if($charge['status'] > 0) return ajaxmsg('该充值订单已处理',0);
        $up_charge['status'] = $status;
        $up_charge['id'] = $id;
        Db::startTrans();
        try{
            if($status==1){
                $account = Db::name('money')->where('mid', $charge['mid'])->find();
                $upMoney = isset($account['account']) && $account['account'] > 0 ? bcadd(strval($account['account']), strval($charge['money'])) : strval($charge['money']);
                if($account){
                    $res_m = Db::name('money')->where('mid', $charge['mid'])->update(['account' => $upMoney]);
                }else{
                    $res_m = Db::name('money')->insert(['mid'=>$charge['mid'],'account'=>$upMoney,'status'=>'1']);
                }
                // 检测是否满足首充赠送管理费活动
                $counts = Db::name('money_recharge')->where('mid', $charge['mid'])->count();
                if(sysConfig('give_open') == 1 && $counts == 1) MoneyModel::setGiveFee($charge['mid'], 'give_firstcharge', 0);
                
                $res_r = RecordModel::saveData($charge['mid'],  $charge['money'], $upMoney, 1, '充值单号：'.$charge['order_no']);
                $res_c = Db::name('money_recharge')->update($up_charge);
                $datas['status'] = '充值成功';
                if($res_m && $res_r && $res_c){ 
                    Db::commit();
                    return ajaxmsg('操作成功',200,$datas);
                }else{
                    Db::rollback();
                    return ajaxmsg('充值失败',0);
                }
            }
            if($status==2){
                $res_c = Db::name('money_recharge')->update($up_charge);
                $datas['status'] = '充值失败';
                if($res_c){ 
                    Db::commit();
                    return ajaxmsg('操作成功',200,$datas);
                }
            }
        }catch(\Exception $e){
            Db::rollback();
            return ajaxmsg('数据异常',0);
        }
    }
    /**
     * 提现审核信息保存
     * @return [type] [description]
     */
    public static function auditWithdraw()
    {
        $id     = input('id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        if(!$id) return ajaxmsg('缺少ID参数',0);
        $withdraw = Db::name('money_withdraw')->where('id', $id)->find();
        $up_withdraw['status'] = $status;
        $up_withdraw['id'] = $id;
        Db::startTrans();
        $money_info = Db::name('money')->where('mid', $withdraw['mid'])->lock(true)->find();
        try{
            switch ($status) {
                case 1:// 提现通过 减去冻结金额
                    $up_money['freeze'] = bcsub(strval($money_info['freeze']), strval($withdraw['money']));
                    $info = "提现单号：".$withdraw['order_no'];
                    $affect = $withdraw['money'];
                    $type = 3;
                    $account = $money_info['account'];
                    $datas['status'] = '提现成功';
                    break;
                case 2:// 提现失败 解冻冻结金额
                    $up_money['freeze']  = bcsub(strval($money_info['freeze']),  strval($withdraw['money']));
                    $up_money['account'] = bcadd(strval($money_info['account']), strval($withdraw['money']));
                    $info = "解冻金额".($withdraw['money'])."元,提现单号：".$withdraw['order_no'];
                    $affect = $withdraw['money'];
                    $type = 4;
                    $account = $up_money['account'];
                    $datas['status'] = '提现失败';
                    break;
                case 3:// 提现退回 补充可用金额 !!!!这里不会释放冻结金额
                    $up_money['account'] = bcadd(strval($money_info['account']), strval($withdraw['money']));
                    $info = "退回金额".($withdraw['money'])."元,提现单号：".$withdraw['order_no'];
                    $affect = $withdraw['money'];
                    $type = 6;
                    $account = $up_money['account'];
                    $datas['status'] = '提现退回';
                    break;
                default:
                    return ajaxmsg('状态有误', 0);
                    break;
            }
            $res1 = Db::name('money')->where('mid', $withdraw['mid'])->update($up_money); 
			$res2 = Db::name('money_withdraw')->update($up_withdraw);
			$res3 = RecordModel::saveData($withdraw['mid'], $affect, $account, $type, $info);
    		if($res1 && $res2 && $res3){
    			Db::commit();
    			return ajaxmsg('操作成功', 200, $datas);
    		}else{
    			Db::rollback();
    			return ajaxmsg('数据更新失败',0);
    		}
        }catch(\Exception $e){
            Db::rollback();
            return ajaxmsg('数据异常',0);
        }
    }
    /*
     赠送管理费列表
     */
    public function getGiveList() 
    {
        $map['mobile'] = input('mobile' , '',['trim', FILTER_SANITIZE_NUMBER_INT]);
		$map['name']   = input('name' , '');
        //print_r($map['mobile']);exit;
		if($map['mobile']) {
			$map['mid'] = Db::name('member')->where('mobile', $map['mobile'])->value('id');
			$map['mid'] = [ 'eq' , $map['mid'] ];
		}
		unset($map['mobile']);
		unset($map['name']);
        $order = 'money_givefee.create_time desc';
		$order = "";
		$data_list = MoneyModel::getGiveFee($map, $order);
        $map['type'] = ['in',[7,8,9,16,1,100, 24,28,21,22,32,33,23,25,27,29,17,18]];
        $map['fee_affect'] = ['<>', '0'];
        // 分页数据
        //$page = $data_list->render();
        $givefee_arr = [
            'give_charge'         => '银行充值',
            'give_firstcharge'    => '首次充值',
            'give_realname'       => '银行充值',
            'zdxf_feesub'         => '自动续期扣除',
            'give_admin'          => '管理员赠送',
            'pzxf_freeze'         => '配资冻结',
            'pzxf_freeze_fee'     => '配资扣除',
            'give_reg'            => '注册赠送',
            'give_firstborrow'    => '首次配资',
            'mfpz_yl'             => '免费配资盈利',
            'give_bankcard'       => '绑定银行卡',
            'kdpz_freeze'         => '扩大配资冻结',
            'kdpz_freeze_fee'     => '扩大配资扣除',
            'give_firstaddborrow' => '首次增加配资赠送'
        ];
        return ajaxmsg('操作成功', 200, $data_list);
	}
	/*
	 赠送管理费
	 */
	public function addGiveFee()
    {
        $mobile  = input('mobile' , '',['trim', FILTER_SANITIZE_NUMBER_INT]);
        $givefee = input('givefee' , '',['trim', FILTER_SANITIZE_NUMBER_INT]);
        $info    = input('info' , '');
        //print_r($data);
        if($mobile) {
            $uid = Db::name('member')->where('mobile' , $mobile)->value('id');
        }
        if(!$uid) return ajaxmsg('该用户不存在',0);
        if(!$givefee) return ajaxmsg('管理费不能为空',0);
            
        Db::name('money')->where("mid", $uid)->inc('give_fee',  intval($givefee) )->update();
        $loginfo = '管理员赠送管理费'. $givefee .','. $info ;
        $res = MoneyModel::giveFeeLog($uid, $givefee, 'give_admin', $loginfo);
        if($res){
            return ajaxmsg('管理费添加成功', 200);
        }else{
            return ajaxmsg('操作失败',0);
        }
    }
    /*
    赠送资金列表
    */
    public function getGiveCash()
    {
        $map['type'] = 100;
        empty($order) && $order = 'id desc';
        //print_r($map);exit;
        $data_list = RecordModel::getAll($map, $order, 20);
        
        return $data_list;
    }
}