<?php

namespace app\admin\model;

use app\BaseModel;
use think\helper\Str;
use think\facade\Lang;

class FundsRecord extends BaseModel
{
    
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * transaction_type 订单类型
     * - recharge       充值
     * - withdraw       提现
     * - order          投注
     */
    public $transaction_type_list = [
        'recharge'      => '充值',
        'withdraw'      => '提现',
        'order'         => '投注',
        'frozen_money'  => '资金冻结',
        'return_order'  => '退款',
    ];
    
    public static function addData($data)
    {
        $data['transaction_id'] = Str::random(32);
        return static::create($data);
    }

    public static function getList($params, $user_code = '') {
        $query = FundsRecord::alias('funds_record')
                    ->join(env('database.DATABASE').'.bot_users user', 'funds_record.user_id = user.user_id', 'left');
                    // ->join('user', 'funds_record.user_id=user.user_id','left');
        if ($user_code != '') {
            $query = $query->where('user.user_code', $user_code);
        } 
        if (!empty($params['user_id'])) {
            $query->where('funds_record.user_id', $params['user_id']);
        }
        if (!empty($params['transaction_type'])) {
            $query->where('funds_record.transaction_type', $params['transaction_type']);
        }
        if (!empty($params['transaction_id'])) {
            $query->where('funds_record.transaction_id', $params['transaction_id']);     
        }
        if (!empty($params['start_time']) ) {
            $start_time = strtotime($params['start_time'] . " 00:00:00");
            $query->where('funds_record.create_time', '>=', $start_time);
        }
        if (!empty($params['end_time'])) {
            $end_time = strtotime($params['end_time'] . " 23:59:59");   
            $query->where('funds_record.create_time', '<=', $end_time);
        }
        $params['page'] = $params['page'] ?? 1;
        $params['limit'] = $params['limit'] ?? 15;
        $count = $query->count();
        $list = $query->field(['funds_record.*'])
                    ->limit($params['limit'])
                    ->page($params['page'])
                    ->order('funds_record.id', 'desc')
                    ->select();
        return [
            'transaction_type' => (new FundsRecord)->getTransactionTypeList(),
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getTransactionTypeList()
    {
        $list = $this->transaction_type_list;
        foreach ($list as $key => &$value) {
            $value = Lang::get("messages.{$value}");
        }
        return $list;
    }
}