<?php
namespace app\apicom\model;

use think\Model;
use think\facade\Db;
use think\Exception;

class Recharge extends Base
{

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

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    public static function setCreateTimeAttr()
    {
        return time();
    }

    public static function setCreateIpAttr()
    {
        return getClientIp();
    }

    public static function getStatusAttr($value ,$data)
    {
        $status = ['0'=>'等待处理', '1'=>'充值成功', '2'=>'充值失败', '3'=>'签名不符'];
        return $status[$data['status']];
    }
    
    public static function getTypeAttr($value ,$data)
    {
        $type = ["transfer"=>"线下转账","alipay"=>"支付宝","wechat"=>"微信"];
        return $type[$data['type']];
    }

    public static function  getAll($map=[], $order='',$listRows=20)
    {
        $data_list = self::view('money_recharge r', true)
            ->view('member m', 'mobile, name', 'm.id=r.mid', 'left')
            ->where($map)
            ->order($order)
            ->paginate($listRows, false, ['query' => request()->param()])
            ->each( function($item, $key){
                $item->money = money_convert($item->money);
                $item->fee   = money_convert($item->fee);
            });
        return $data_list;

    }
    /**
     * 根据ID获取记录
     */
    public static function getRecordById($id,$listRows=20)
    {
        $res = self::where(['mid'=>$id])
            ->order('id desc')
            ->paginate($listRows, false, ['query' => request()->param()])
            ->each( function($item, $key){
                $item->money    = money_convert($item->money);
            });
        return $res;
    }

    /**
     * 保存充值数据到数据库
     * @param  float $money     充值金额
     * @param  int $mid       用户id
     * @param  string $type      充值类型
     * @param  string $line_bank 线下转账充值的银行信息
     * @return string            返回订单号
     */
    public static function saveData($money, $mid, $type, $line_bank='',$receipt=null,$charge_type_id=0,$transfer='')
    {
        $data['order_no']    = 'cz'.date('YmdHis').generate_rand_str(4, 3);
        $data['mid']         = $mid;
        $data['money']       = money_convert($money);
        $data['type']        = $type;
        $data['line_bank']   = $line_bank;
        $data['create_time'] = time();
        $data['create_ip']   = getClientIp();
        $data['status']      = 0;
        $data['receipt_img'] = $receipt;
        $data['form_name']   = $transfer;
        $data['charge_type_id'] = $charge_type_id;
        $result = self::create($data);
        return $result->order_no;
    }
    
}
?>
