<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/1
 * Time: 10:03
 */

namespace App\Api\Model;

use \System\Model;

class LuckyMoneyTake extends Model {
    protected $table = 'lucky_money_take';

    /**
     * 插入领取记录到表
     * @param string $account_identity
     * @param int $room_id
     * @param string $lm_id
     * @param string $lm_oid
     * @param float $money
     * @param int $type
     * @return mixed
     */
    public function addLuckyMoneyTake(string $account_identity, int $room_id, string $lm_id, string $lm_oid, float $money, int $type = 0) {
        $data = [
            'account_identity' => $account_identity,
            'money' => $money,
            'room_id' => $room_id,
            'lm_id' => $lm_id,
            'md_order_id' => $lm_oid,
            'time' => time(),
            'hash' => md5($room_id . $lm_id . $account_identity),
            'type' => $type,
        ];
        $ret = self::insertGetId($data);
        return $ret > 0 ? $lm_oid : -7029;
    }

    /**
     * 抢红包函数
     * @param string $account_identity
     * @param int $room_id
     * @param string $lm_id
     * @param float $money
     * @return string
     */
    public function handleLuckyMoneyTake(string $account_identity, int $room_id, string $lm_id, float $money): string {
        $hash = md5($room_id . $lm_id . $account_identity);
        $data = self::where('hash', $hash)->first(['md_order_id']);
        if ($data) return $data->md_order_id;
        $obj = C()->get('AutoLottery');
        $obj->account_identity = $account_identity;
        $obj->operation_time = date('Y-m-d H:i:s', time());
        $account = lm('Account', 'api')->where('identity', $account_identity)->first();
        if (!$account) {
            return -51017;//用户不存在
        }
        $accountDetail = lm('AccountDetail', 'Api')->where('account_identity', $account_identity)->first();
        if (!$accountDetail) {
            return -51017;//用户不存在
        }
        $obj->account_name = $account->account;//用户账号
        $obj->money = number_format($money, 2,'.','');//充值金额
        $obj->money_cash = $accountDetail->cash + $money;
        $obj->order_id = OrderID();//生成订单号
        $obj->trade_type = 16;//红包打赏；
        $obj->rate = 0;//流水倍数；
        $obj->money_type = 1;
        $obj->operator = 'system_auto';//审核人
        _beginTransaction();
        $updateAccountDetail = $obj->incrAccountDetailMoney($account_identity, $money);

        if ($updateAccountDetail != 1) {
            _rollback();
//            dd(1111, $updateAccountDetail);
            return $updateAccountDetail;
            //更新余额失败
        }

        $detail = "{$obj->account_name}于{$obj->operation_time}在{$room_id}号房间领取了红包，金额为{$money}元,红包编号为【{$lm_id}】";//备注

        $opDetail = $obj->addMoneyDetailRec($detail, '领取红包', 2);
        if ($opDetail == -50014) {
            _rollback();
//            dd(222, $opDetail, $obj);
            return $opDetail;
        }

        $mr = $obj->addMoneyRechargeRec('领取红包', '领取红包', '红包打赏');
        if (intval($mr) < 0) {
            _rollback();//资金记录创建失败
            return intval($mr);
        }
        $opLmRec = self::addLuckyMoneyTake($account_identity, $room_id, $lm_id, $opDetail, $money);
        if ($opLmRec < 0) {
            _rollback();
            return $opDetail;
        }
        $lm = new LuckyMoney();
        $lmObj = $lm->where('lm_order_id', $lm_id)->first();
        if ($lmObj) {
            $num = $lmObj->num; //红包总个数
            $take_num = $lmObj->take_num; //红包已被领取个数
            if ($num > $take_num) {
                $lmObj->take_num++;
                $lmObj->take_money += $money;
                $lmObj->save();
            } else {
                _rollback();
                return -7012; //红包已领完
            }

        } else {
            _rollback();
            return -70161; //红包ID不存在
        }
        //todo:用户操作日志添加
        _commit();
        return $opLmRec;
//        return self::where('id', $opLmRec)->first()->md_order_id;

    }

    /**
     * 用户抢红包历史记录
     * @param string $account_identity
     * @param int $page
     * @param int $limit
     * @return mixed
     */
    public function getHistory(string $account_identity, int $page, int $limit) {
        $offset = $page * $limit;
        return $ret = self::where('account_identity', $account_identity)
            ->orderBy('time', 'desc')
            ->limit($offset, $limit)
            ->select($this->table . '.money', $this->table . '.time')
            ->get();
    }

    /**
     * 根据红包ID查询红包领取记录
     * @param $lm_id
     * @param $page
     * @param $limit
     * @return mixed
     */
    public function getHisByLuckyMoneyId($lm_id, $page, $limit) {
        $ret = $this
            ->leftJoin('account', "{$this->table}.account_identity", '=', 'account.identity')
            ->where($this->table . '.lm_id', $lm_id)
            ->leftJoin('account_detailed', $this->table . '.account_identity', '=', 'account_detailed.account_identity')
            ->orderBy($this->table . '.time', 'DESC')
            ->limit($page * $limit, $limit)
            ->select($this->table . '.money', $this->table . '.time', $this->table . '.room_id', 'account.account',
                'account_detailed.img_url', 'account_detailed.img_id')
            ->get()
            ->toArray();
        $myInfo = [];
        if ($ret) {
            $room_id = $ret[0]['room_id'];
            $nickNames = (new Chat_rooms())->getNickNames($room_id);
            $room_mangers_id = $nickNames['room_mangers_id'];
            unset($nickNames['room_mangers_id']);
            foreach ($ret as $k => $v) {
                if ($v['account'] === $_SESSION['uinfo']['account']) {
                    $myInfo['account'] = $v['account'];
                    $myInfo['money'] = $v['money'];
                }
                if (isset($nickNames[$v['account']])) {
                    $v['account'] = $nickNames[$v['account']];
                } else {
                    if(!in_array($_SESSION['uinfo']['account'],explode(',',$room_mangers_id))){
                        $strHeader = substr($v['account'], 0, -4);
                        $strEnd = substr($v['account'], -1);
                        $v['account'] = $strHeader . '***' . $strEnd;
                    }
                    
                }
                $ret[$k] = $v;
            }
        }

        return ['list' => $ret, 'myInfo' => (Object)$myInfo];
    }
}
