<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\Record;
use app\apicom\model\Money as MoneyModel;
use app\apicom\model\Recharge;
use app\apicom\model\Bank as BankModel;
use app\apicom\model\Withdraw as WithdrawModel;
use think\facade\Db;
use  think\helper\Hash;
class Money extends BaseController
{
    /**
     * 资金明细
     * @return [type] [description]
     */
    public function index(){
        $type  = input('type', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $start = input('start_date', '');
		$end   = input('end_date', '');
        $page  = input('page', 1, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        // 获取查询条件
        //$endDate   = $end   ? strtotime($end) + 86400   : strtotime(date("Y-m-d 23:59:59"));
        //$startDate = $start ? strtotime($start) : strtotime(date("Y-m-d 00:00:00"));
        
        $order  = 'id desc';
        $page   = $page ? $page : 1;
        $offset = intval($page);
        // 数据列表
        $data_list = Db::name('money_record')
            ->where('mid','=',$this->userId)
            ->order($order)
            ->page($offset,20)
            ->select()
            ->toArray();
        if(!$data_list) return ajaxmsg('没有数据',0);
        foreach ($data_list as $k => $v) {
            $data_list[$k]['happend_time'] = getTimeFormt($v['create_time'],4);
            $data_list[$k]['happend_date'] = getTimeFormt($v['create_time'],5);
            $data_list[$k]['type_name']    = MONET_TYPE_NAME[$v['type']];
            $data_list[$k]['affect']       = money_convert($v['affect']);//bcdiv(strval($v['affect']),'100',2);
            $data_list[$k]['account']      = money_convert($v['account']);//bcdiv(strval($v['account']),'100',2);
        }
        return ajaxmsg('数据列表',1,$data_list);
    }
    /*代理查询下级明细*/
    public function agent_index(){
        $id       = input('id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $type     = input('type', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $keyword  = input('keyword', '');
        if(!$id) return ajaxmsg('无效对象',0);
        // 获取查询条件
        $map = $this->getMap();

        if($keyword){
            $searchurl2='&_search_field=type&keyword='.$map['type'][1];
        }else{
            $searchurl2="";
        }
        if($type){
            $searchurl1='&_filter_time2=r.create_time&_filter_time_from='.$map['r.create_time'][1][0].'&_filter_time_to='.$map['r.create_time'][1][1].'&type='.$type;
        }else{
            $searchurl1="";
        }
        if(isset($map['r.create_time'][1])){
            $map['r.create_time'][1][0]=strtotime($map['r.create_time'][1][0]);
            $map['r.create_time'][1][1]=strtotime($map['r.create_time'][1][1]);
        }
        $map['mid'] = $this->userId;
        $order  = 'r.id desc';
        $page   = intval($this->request->param("page"));
        $page   = $page ? $page : 1;
        $offset = $page;
        // 数据列表
        $data_list = Db::name('money_record')
            ->alias('r')
            ->where($map)
            ->field('r.*')
            ->order($order)
            ->page($offset,10)
            ->select();
        if(empty($data_list))return ajaxmsg('未获取到数据',0);
        foreach ($data_list as $k => $v) {
            $data_list[$k]['happend_time'] = getTimeFormt($v['create_time'],4);
            $data_list[$k]['happend_date'] = getTimeFormt($v['create_time'],5);
            $data_list[$k]['type_name']    = getTypeNameForMoney($v['type']);
            $data_list[$k]['money']   = money_convert($v['money']);//bcdiv($v['money'],100,2);
            $data_list[$k]['affect']  = money_convert($v['affect']);//bcdiv($v['affect'],100,2);
            $data_list[$k]['account'] = money_convert($v['account']);//bcdiv($v['account'],100,2);
        }
        
        return ajaxmsg('数据列表',1,$data_list);
    }
    /*
     * 充值
     */
    public function recharge()
    {	
		//$money   = MoneyModel::getMoney($this->userId);
    	$account = Db::name("admin_bank")->where(['status'=>1])->select()->toArray();
        foreach($account as $k=>$v){
            if(!empty($v['image'])){
                $account[$k]['image'] =  sysConfig('app_url').getFilePath($v['image']);
            }
        }
		//$data['money']   = $money;
		//$data['offline'] = sysConfig('web_site_account');
		$data['account']  = $account;
        $data['mtips']    = !empty(sysConfig('web_money_tip')) ? arrayEol(sysConfig('web_money_tip')) : [];
		return ajaxmsg('用户账户信息',1,$data);
    }
    /*
     * 充值操作
     */
	public function doCharge()
	{
		$card_id   = input('cardno', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
		$money     = input('money', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
		$form_name = input('form_name', '');
		$type      = input('transfer', ''); // transfer 线下转账支付
		$receipt   = '';//转账凭证
		$type_id   = input('type_id', 0, ['trim', FILTER_SANITIZE_NUMBER_INT]);
		if($money <= 0) return ajaxmsg('充值金额必须大于0',0);
		if(!$type) return ajaxmsg('充值方式不对',0);
		$line_bank = $type == 'transfer' ? '卡号：'.$card_id.'；时间：'.date('Y-m-d',time()) : '';
		$order_no  = Recharge::saveData($money, $this->userId, $type, $line_bank,$receipt,$type_id,$form_name);
		if($order_no){
			return ajaxmsg('充值已提交，请耐心等待审核',1);
		}else{
			return ajaxmsg('操作错误',0);
		}
	}
	/*
	 * 充值记录
	 */
	public function rechargeRecord()
	{
        $page   = input('page', 1, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data   = Recharge::getRecordById($this->userId,$offset);
        
	    return ajaxmsg('操作成功',1,$data);
	}
	/*
     * 提现
     */
    public function withdraw()
    {
        $money = MoneyModel::getMoney($this->userId);
        $banks = BankModel::getBank($this->userId);
        if(!empty($banks[0]) && !$money) {
            return ajaxmsg('操作失败！',0);
        }
        $data['money'] = money_convert($money['account']);
        $data['banks'] = isset($banks[0]) ? $banks[0] : '';
        $data['mtips'] = !empty(sysConfig('web_money_tip')) ? arrayEolTip(sysConfig('web_money_tip')) : [];
        return ajaxmsg('线下提现信息',1,$data);
        
    }
    /*
     * 提现操作
     */
	/*
     * 操作提现操作
     */
    public function doWithdraw()
    {
        $data['mid']     = $this->userId;
        $data['money']   = input('money', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data['paywd']   = input('paywd', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data['bank_id'] = input('bank_id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $result = $this->validate($data, "Withdraw.create");
        if($result !== true) return ajaxmsg($result,0);
        if(round(intval($data['money'])) < sysConfig('low_withdrawal_amount')){
            return ajaxmsg('最低提现额：'.sysConfig('low_withdrawal_amount'),0);
        }
        $money_res=Db::name('money')->where(['mid'=>$this->userId])->find();
        if(empty($money_res['account'])) return ajaxmsg('查询账户资金出错！',0);
        //print_r($money_res);exit;
        if(isset($money_res['account']) && $money_res['account']<$data['money']){
            return ajaxmsg('可用余额不足！',0);
        }
        $withdraw_info=Db::name('money_withdraw')->where(['mid' => $this->userId,'status'=>0])->find();
        if(!empty($withdraw_info)){
            return ajaxmsg('您已有提现申请，请耐心等待审核。',0);
        }
        $cash = Db::name('member')->where(["id"=>$this->userId])->find();
        //print_r(strval($cash['paywd']));exit;
        if(!password_verify(strval($data['paywd']), strval($cash['paywd']))) return ajaxmsg('支付密码错误',0);
        $res = WithdrawModel::saveData($data);
        if(!$res['status']) return ajaxmsg('提现申请提交失败',0);
        return ajaxmsg('提现申请已提交，请耐心等待审核',1);
    }
	/*
	 * 提现记录
	 */
	public function withdrawRecord()
	{
	    $page   = input('page', 1, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data   = WithdrawModel::getRecordById($this->userId,$offset);
        
	    return ajaxmsg('操作成功',1,$data);
	}
}