<?php
namespace app\apicom\model;

use app\apicom\model\Record;
use think\helper\Hash;
use think\model;
use think\facade\Db;

class Money extends Base
{

    // 设置当前模型对应的完整数据表名称
    protected $name = 'money';


    public static function  getAll($map=[], $order='')
    {
        $data_list = self::view('money', true)
            ->view('member', 'mobile, name, id_card', 'member.id=money.mid', 'left')
            ->where($map)
            ->order($order)
            ->paginate()
            ->each( 
                function($item, $key){
                    $item->account         = money_convert($item->account);
                    $item->freeze          = money_convert($item->freeze);
                    $item->operate_account = money_convert($item->operate_account);
                    $item->bond_account    = money_convert($item->bond_account);
                }
            );
        return $data_list;

    }

    public static function getMoney($mid)
    {
        $result = self::where(['mid'=>$mid])->find();
        if(empty($result)){
            $result['account']=0;
            $result['freeze']=0;
            $result['operate_account']=0;
            $result['bond_account']=0;
            $result['total']=0;
        }else{
            $result['total'] = bcadd($result['bond_account'], bcadd($result['account'], $result['freeze']));
        }
        return $result;
    }

    /*
     * 申请时冻结资金
     * @mid 会员ID
     * @minfo 会员资金信息
     * @money 冻结金额
     * */
    public static function money_freeze($mid,$freeze,$account)
    {
        return self::where(['mid'=>$mid])->update(['freeze'=>$freeze,'account'=>$account]);
    }
    /*
     * 申请通过更新资金
     *
     */
    public static function money_up($mid,$money)
    {
        return self::where("mid",$mid)->update($money);
    }


	public static function getDayList($map, $order) 
	{
		//$map = array_merge($map, ['status' => 1]);
        $data_list = self::view('money_recharge', true)
			->field('SUM(money)/100 AS amoney')

            //->view('member', 'mobile, name, id_card', 'member.id=money_recharge.mid', 'left')
            ->where($map)
            ->order($order)
			->group('create_day')
            ->paginate()
/*                        ->each( function($item, $key){
				$key = $item->create_day;
               // $item->money = money_convert($item->money);
    			//$item->fee = money_convert($item->fee);
            })*/
			;
		return $data_list;

	}

	public static function getWithdrawList($map, $order) {

        $data_list = self::view('money_withdraw', true)
			->field('SUM(money)/100 AS amoney')

            //->view('member', 'mobile, name, id_card', 'member.id=money_recharge.mid', 'left')
            ->where($map)
            ->order($order)
			->group('create_day')
            ->paginate()
/*                        ->each( function($item, $key){
				$key = $item->create_day;
               // $item->money = money_convert($item->money);
    			//$item->fee = money_convert($item->fee);
            })*/
			;
		return $data_list;
	}
    //冻结管理费
    public static function freeze_give_fee($mid, $freeze_give_fee, $give_fee)
    {
        return self::where(['mid'=>$mid])->update(['freeze_give_fee' => $freeze_give_fee,'give_fee' => $give_fee]);
    }
	/*
	$type =
		give_reg	完成注册赠送管理费	单行文本		100
		give_renzheng	实名认证赠送管理费	单行文本		100
		give_firstborrow	首次配资赠送管理费	单行文本		100
		give_firstcharge	首次充值赠送管理费	单行文本		100
		give_bankcard	绑定银行卡赠送管理费	单行文本		100
		give_firstaddborrow	首次追加配资赠送管理费	单行文本		100
		give_firstaddmoney	首次补亏赠送管理费	单行文本		100
		give_firstdrawprofit	首次提盈赠送管理费	单行文本		100
		give_charge 银行卡充值送管理费
		//give_bankcharge
	**
	*/
	public static function setGiveFee($uid, $type, $charge = 0)
	{
		$typeArr = array(
			'give_charge'         => '银行充值送管理费',
			'give_reg'            => '完成注册赠送管理费',
			'give_realname'	      => '实名认证赠送管理费',
			'give_firstborrow'	  => '首次配资赠送管理费',
			'give_firstcharge'	  => '首次充值赠送管理费',
			'give_bankcard'	      => '绑定银行卡赠送管理费',
			'give_firstaddborrow' => '首次追加配资赠送管理费',
			'give_firstaddmoney'  => '首次追加保证金赠送管理费',
			'give_firstdrawprofit'=> '首次提盈赠送管理费',

		);
		if (sysConfig('give_open') != 1) return false;
		if (!$type) return false;
		$addfee = sysConfig($type) ;
		if ($addfee) {
			if ($type != 'give_charge') {
				Db::name('money')->where("mid",$uid)->inc('give_fee', $addfee)->update();
			} else {
				$addfee = $charge * $addfee / 100;
				Db::name('money')->where("mid",$uid)->inc('give_fee', $addfee)->update();
			}
			$loginfo = $typeArr[$type]. ' '. $addfee ;
			self::giveFeeLog($uid, $addfee, $type, $loginfo);
		}
		return true;

	}
	public static function getGiveFee($map=[], $order='',$offset=20) 
    {
		$data_list = self::view('money_givefee', true)
            ->view('member', 'mobile, name', 'member.id=money_givefee.mid', 'left')
            ->where($map)
            ->order($order)
            ->paginate($offset, false, ['query' => request()->param()])
            ->each( function($item, $key){
                //$item->remain = money_convert($item->remain);
                //$item->affect = money_convert($item->affect);
                $item->create_time = date("Y-m-d h:i:s",$item->create_time);
            });
        return $data_list;
	}
	
	public static function giveFeeLog($uid, $affect, $type, $loginfo = '', $remainfee = 0 ) 
	{

        if (!$remainfee) {
            $remainfee = Db::name('money')->where("mid", $uid)->value('give_fee');
        }
		//$remainfee = Db::name('money')->where("mid={$uid}")->value('give_fee');
		$givelog = array(
			'mid'         => $uid,
			'affect'      => $affect,
			'remain'      => $remainfee,
			'type'        => $type,
			'info'        => $loginfo,
			'create_time' => time()
		);
		$ret = Db::name('money_givefee')->insert($givelog);
        if ($type == 'give_admin' && $ret) {
            $allmoney = Db::name('money')->where("mid", $uid)->value('account');
            Record::saveData($uid, 0, $allmoney, 18, $loginfo, $affect);
            return true;
        }
        return false;
	}
	
	public static function getOffsetFee($uid, $manager_fee)
	{
		$give_fee = Db::name('money')->where(['mid' => $uid])->value('give_fee');
		$give_one_offset = sysConfig('give_one_offset') ?: 0;
        if ($give_fee < 0 ){
            $ret = [
          		'give_fee' => $give_fee, //原有免费管理费费额度
          		'give_one_offset' => ($give_one_offset < 1) ? $manager_fee * $give_one_offset : $give_one_offset, //单次可抵扣额度
          		'can_offset' =>  0 , //当前抵扣量
          		'remain_fee' => $manager_fee, //抵扣后剩下需支付管理费
          	];
          	return $ret;
        }
		//抵扣后剩余应扣管理费
		$remain_fee = 0;
        if ($give_one_offset < 1) {
            $give_one_offset = $manager_fee * $give_one_offset;
            //如果单次抵扣量大于，账户剩余管理费
            if ($give_one_offset > $give_fee) {
                $can_offset = $give_fee;
                $remain_fee = $manager_fee - $give_fee;
            } else {
                $can_offset = $give_one_offset;
                $remain_fee = $manager_fee - $give_one_offset;
            }
        
        } else {
            //转换成分
            //$give_one_offset =   $give_one_offset * 100;
      		//所需管理费小于单次扣除上限
      		if ($manager_fee <= $give_one_offset) {
      			//可抵扣总量足够，抵扣额等于需抵扣金额
      			if ($give_fee >= $manager_fee) {
      				$can_offset = $manager_fee;
      				//剩余管理费为0
      				$remain_fee = 0;
      			}
      			//如果可抵扣总量不够，抵扣额等于，可抵扣总量
      			if ($give_fee < $manager_fee) {
      				$can_offset = $give_fee;
      				$remain_fee = $manager_fee - $give_fee;
      			}
      		}
      		//所需管理费大于单次扣除上限
      		if ($manager_fee > $give_one_offset) {
      			//可抵扣总大于单次抵扣额
      			if ($give_fee >= $give_one_offset) {
      				$can_offset = $give_one_offset;
      				//剩余管理费为 所需管理费减去单次抵扣额0
      				$remain_fee = $manager_fee - $give_one_offset;
      			}
      			//可抵扣总量小于单次上次
      			if ($give_fee < $give_one_offset) {
      				$can_offset = $give_fee;
      				//剩余管理费为 总管理费减去全部可抵扣费用
      				$remain_fee = $manager_fee - $give_fee;
      			}
      		}
        }

		$ret = [
			'give_fee' => $give_fee,
			'give_one_offset' => $give_one_offset,
			'can_offset' =>  $can_offset ,
			'remain_fee' => $remain_fee,
		];
		return $ret;
	}
}
