<?php
namespace Api\Model;

use Think\Model;

header("Content-Type:text/html;CharSet=UTF-8");
class FundApplyModel extends Model
{
    /**
     * 提交提现申请
     * @param  string $openid 用户标识
     * @param  float  $money  申请金额
     * @return mix
     */
    public function saveData($openid, $money)
    {
        $userLimit = M("users")->where("`openid`='{$openid}'")->getField("fund_enable");    // 用户可提现金额
        if ($money > $userLimit) {
            return array("status" => -1, "msg" => "超过可提现金额");
        } elseif ($money < 1) {
            return array("status" => -1, "msg" => "提现金额至少1元");
        } else {
            // 创建申请记录
            $data['partner_trade_no'] = $this->makeSn($openid);
            $data['openid'] = $openid;
            $data['money'] = $money;
            $data['create_time'] = $_SERVER['REQUEST_TIME'];
            $insert_id = $this->add($data);
            if ($insert_id) {
                M("users")->where("`openid`='{$openid}'")->lock()->setDec("fund_enable", $money);
                return array("status" => 1, "msg" => "申请成功");
            } else {
                file_put_contents("./Logs/Applies/saveDataFail.log", date("Y-m-d H:i:s ") . $this->getlastsql() . "\r\n", FILE_APPEND);
                return array("status" => -1, "msg" => "系统繁忙");
            }
        }
    }

    /**
     * 生成提现单号
     * @param  string $openid 用户标识
     * @return string         [description]
     */
    public function makeSn($openid)
    {
        if ($openid) {
            $userId = M("users")->where("`openid`='$openid'")->getField("uid");
        }
        if ($userId) {
            return "WX" . $userId . date("YmdHis");
        } else {
            return "WX" . date("YmdHis") . rand(0, 999);
        }
    }
}