<?php
/**
 * Created by PhpStorm.
 * User: scstf
 * Date: 2018/10/15
 * Time: 10:27
 */

namespace Biz\Money;


class LotteryMoneyConfirm
{
    public $order_id;
    public $account_name;
    public $account_identity;
    public $money;
    public $money_cash;
    public $lottery_requestObj;
    public $operator;
    public $operation_time;
    public $rate;
    public $trade_type;
    public $money_type;

    /**
     * 根据用户ID和申请ID自动为符合条件的请求写入流水差额记录、资金记录和资金详情记录,有错返回5100开始的错误码
     * @param int $lottery_req_id
     * @param string $rechargeDetail
     * @param string $waterDetail
     * @return int
     */
    public function autoPass($lottery_req_id, $rechargeDetail = '', $waterDetail = '',$type='')
    {

        $this->operator = 'system_auto';
        $this->trade_type = 12;
        $this->operation_time = date('Y-m-d H:i:s', time());
        $this->lottery_requestObj = lm('lottery_money_log', 'api')->where('id', $lottery_req_id)->first();
        if (!$this->lottery_requestObj)
            return -30019;//彩金申请记录不存在
        if (!$this->lottery_requestObj->money)
            return -51013;//彩金申请金额为0
        if(empty($type)){
            if ($this->lottery_requestObj->status == 1)
            return -30023;//彩金申请已发放
        }
        if ($this->lottery_requestObj->status == 2)
            return -30024;//彩金申请已驳回
        $this->account_name = $this->lottery_requestObj->account_name;
        $this->account_identity = $this->lottery_requestObj->account_identity;
        $p_order_id = $this->lottery_requestObj->order_id;
        $this->order_id = $p_order_id ? 'CJ' . $p_order_id : OrderID();//要插入的资金订单号
        $this->money = $this->lottery_requestObj->money;

        $this->rate = 1;
        _beginTransaction();
        $ret = $this->changeReqStatus($lottery_req_id, 1);//通过申请
        if (!$ret) {
            _rollback ();
            return -51011;//更新审核状态记录失败
        }
        $content = json_decode ($this->lottery_requestObj->conent);
        if ($content['fr_rate']) $this->rate = $content['fr_rate'];
        $ret = $this->addMoneyRechargeRec($rechargeDetail);
        if ($ret < 1) {
            _rollback ();
            return -51011;//添加资金记录失败
        }
        $ret = $this->addMoneyDetailRec($waterDetail);
        if ($ret < 1) {
            _rollback ();
            return -51011;//添加资金详情记录失败
        }

        $ret = $this->updateNeedMoneyRec();
        if (!$ret) {
            _rollback ();
            return -51011;//更新资金流水差额记录失败
        }
        $ret = $this->addMoneyRechargeRemark();
        if ($ret < 1) {
            _rollback ();
            return -51011;//更新资金remark记录失败
        }
        $ret = $this->updateAccountDetailMoney();
        if (!$ret) {
            _rollback ();
            return -51011;//更新用户账户详情中资金记录失败
        }
        _commit ();
        $tpl='恭喜%s,您通过%s申请的彩金%s已到账，订单号为%s,请查收!';
        //$tpl = lang ('lottery_money_log','api')->get ('pass');
        $msg=sprintf ($tpl,$this->account_name,$this->lottery_requestObj->lottery_money_name??'彩金申请',$this->money,
            $this->order_id);
        lm ('Message', 'commons')->add ($title='申领彩金提醒', $msg, $from='系统', $to=$this->account_name, $type = 1, $addStatus = 2);
        return 1;
    }

    /**
     * 自动充值
     * @param string $account_identity
     * @param float $money
     * @param string $rechargeDetail
     * @param string $waterDetail
     * @return int
     */
    public function recharge(string $account_identity, float $money, string $rechargeDetail, string $waterDetail)
    {
        $this->account_identity = $account_identity;
        $this->operation_time = date ('Y-m-d H:i:s', time ());
        //$account = lm ('AccountDetail', 'api')->where ('account_identity', $account_identity)->first ();
        $account = lm ('Account', 'api')->where ('identity', $account_identity)->first ();
        if (!$account)
            return -51017;//用户不存在
        $this->account_name = $account->account;//用户账号
        $this->money = $money;//充值金额
        $this->order_id = OrderID ();//生成订单号
        $this->trade_type = 9;//充值；
        $this->rate = 1;//流水倍数
        $this->operator = 'system_auto';//审核人

        _beginTransaction();
        $ret = $this->addMoneyRechargeRec($rechargeDetail);
        if ($ret < 1) {
            _rollback ();
            return -51011;//添加资金记录失败
        }
        $ret = $this->addMoneyDetailRec($waterDetail);
        if ($ret < 1) {
            _rollback ();
            return -51011;//添加资金详情记录失败
        }
        $ret = $this->addMoneyRechargeRemark();
        if ($ret < 1) {
            _rollback ();
            return -51011;//更新资金remark记录失败
        }
        $ret = $this->updateAccountDetailMoney();
        if (!$ret) {
            _rollback ();
            return -51011;//更新用户账户详情中资金记录失败
        }
        _commit ();
        return 1;
    }

    /**
     * 审核彩金申请状态
     * @param $lottery_req_id
     * @param $status
     * @return mixed
     */
    protected function changeReqStatus($lottery_req_id, $status)
    {
        $lml = lm ('lottery_money_log', 'api')->where ('id', $lottery_req_id)->first ();
        $operator = 'system_auto';
        $operatorId = 0;
        $arr = json_decode ($lml->flow_record, 1);
        $arr['update_time'] = date ('Y-m-d H:i:s');
        $arr['operator'] = $operator;
        $remark = '';
        $datas = array(
            'status' => $status,
            'remark' => $remark,
            'operator' => $operator,
            'operator_id' => $operatorId,
            'flow_record' => json_encode ($arr),
            'update_time' => $arr['update_time']
        );
        $res = $lml->update ($datas);
        if (!$res) {
            return 0; //没有数据
        }
        return 1;

    }

    /**
     * 添加资金记录
     * @param string $remark
     * @param string $reason
     * @param string $recharge_type
     * @return int
     */
    public function addMoneyRechargeRec(string $remark, $reason = '用于活动', $recharge_type = '活动充值')
    {
        $money = $this->money;
        $moneyRechargeObj = lm('AccountDetail', 'api')->where('account_identity', $idd = $this->account_identity)->first();
        $money_cash = $moneyRechargeObj ? $moneyRechargeObj->cash : 0;
        $money_cash += $money; //当前余额
        $this->money_cash = $money_cash;

        $cj = [
            'order_id' => $this->order_id,
            'info_identity' => UUID(),
            'account_identity' => $idd,
            'account_name' => $this->account_name,
            'money' => $money,
            'reason' => $reason,
            'money_cash' => $money_cash,
            'status' => 1,
            'apply_time' => $this->operation_time,
            'complete_time' => $this->operation_time,
            'recharge_type' => $recharge_type,
            'sysetem_user' => $this->operator,

        ];
        $detail = parseTag($remark, $cj);
        $cj['remark'] = $detail;


        try {
            return lm ('MoneyRecharge', 'api')->insertGetId ($cj);
        } catch (\Exception $e) {
            //Render ($e->getMessage (), 0);
            return -50014;
        }

    }

    /**
     * 添加资金详情记录
     * @param string $detail
     * @param string $reason
     * @param int $return_type
     * @return mixed
     */
    public function addMoneyDetailRec(string $detail,string $reason='', int $return_type = 1)
    {
        $oid = UUID();
        $details['info_identity'] = $oid;
        $details['trade_id'] = $this->order_id;
        $details['account_name'] = $this->account_name;
        $details['account_identity'] = $this->account_identity;
        $details['money'] =number_format($this->money,2,'.','');
        $details['money_time'] = date('Y-m-d H:i:s');
        $details['money_type'] = $this->money_type ?? 1;//2=扣款
        $details['money_cash'] = $this->money_cash;
        $details['trade_type'] = $this->trade_type;
        $details['sysetem_user'] = $this->operator;
        $details['reason'] = $reason;
        $details['status'] = 1;
        $detail = parseTag($detail, $details);
        $details['trade_desc'] = $detail;
        try {
            $re = lm('MoneyDetails', 'api')->insertGetId($details);
            if ($return_type === 1)
                return $re;
            return $oid;
        } catch (\Exception $e) {

//            Render($e->getMessage(), 0);

            return -50014;
        }


    }

    /**
     * 更新流水差额
     * @return mixed
     */
    public function updateNeedMoneyRec()
    {
        $withdrawRuleObj = lm ('withdraw_rule', 'api');
        return $ret = $withdrawRuleObj->updateRule ($this->account_identity, $this->money, $this->rate);
    }

    /**
     * 添加资金remark
     * @return mixed
     */
    public function addMoneyRechargeRemark()
    {
        $cjd = [
            'name' => $this->account_name,
            'order_id' => $this->order_id,
            'money' => $this->money,
            'recharge_time' => $this->operation_time,
        ];
        try {
            return lm ('MoneyRechargeRemark', 'api')->insertGetId ($cjd);
        } catch (\Exception $e) {

            return -50014;
        }
    }

    /**
     * 更新用户账户详情表中余额信息(加款操作)
     * @return mixed
     */
    public function updateAccountDetailMoney()
    {
        $type = 1;
        S('DB')->select("select update_money('" . $this->account_identity . "'," . $this->money . "," . $type . ")");
        return 1;
    }
    public function incrAccountDetailMoney(string $account_identity, float $money):int
    {
        $type = 1;
        $accountDetail = lm('AccountDetail', 'api')->where('account_identity', $account_identity)->first();
        if (!$accountDetail) {
            return -1;//用户不存在
        }
        S('DB')->select("select update_money('" . $account_identity . "'," . $money . "," . $type . ")");
        return 1;
    }

    /**
     * 用户账户详情扣款操作
     * @param $account_identity
     * @param $money
     * @return int
     */
    public function decrAccountDetailMoney(string $account_identity, float $money): int
    {
        $accountDetail = lm('AccountDetail', 'api')->where('account_identity', $account_identity)->first();
        if (!$accountDetail) {
            return -1;//用户不存在
        }
        $money_cash = $accountDetail->cash ? $accountDetail->cash : 0;
//        dd($money_cash);
        $money_cash -= $money; //更新后当前余额
        if ($money_cash < 0) {
            return -2;
        }
        $type = 0;
        S('DB')->select("select update_money('" . $account_identity . "'," . $money . "," . $type . ")");
        return 1;

    }
}