<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/25
 * Time: 14:10
 */

namespace App\Lib\Settlement;
set_time_limit(600);
ini_set('memory_limit', '256M');

use Illuminate\Support\Facades\DB;
use App\Lib\Settlement\SettlementBase;
use App\Models\SettlementMiddleDetail as SettlementMiddleDetailModel;


/**
 * 按订单结算或重结算
 */
class SettlementOrder extends SettlementBase
{

    private $orderType = 1; //订单类型  1单式  2串式;
    private $BuyDatasMainModel = [];  //订单豪华版  单式一条   串式可能多条
    private $BuyDatas = [];  //订单豪华版  单式一条   串式可能多条
    private $match_id = 0;
    private $game_code = '';
    private $SN = 0;    //结算批次号
    private $set_type = 0;
    private $change_status = 1;

    private $SettlementBaseObj = '';


    private $sqlArray = [];   //最终生成的执行sql
    private $Money_buy_Orders_Array = [];    //订单主表映射
    private $Money_buy_Orders_batch_Array = [];    //订单按批次号表映射
    private $Money_buy_Match_array = [];      //单式订单表的映射
    private $account_map_array = [];            //用户账号映射
    private $account_indentity_map_array = [];  //用户账号indenty映射
    private $settlement_middle_detail_array = [];  //已结算过的数据映射,按订单号及[单串式]
    private $money_prize_map = [];                  //中奖记录数据


    //返回数据
    public static function makeData($status = 1, $message = 'success', $data = '')
    {
        return [
            'status' => $status,
            'message' => $message,
            'data' => $data,
        ];
    }


    ///$order_ids 某场比塞全部订单数组, $bettype=2 订单类型: 1单式  2串式（默认）,    $settype = 1 结算次数:1首次(默认)  2非首次或重结算
    /// $change_status 对单个订单结算时，是否改赛事状态和比赛结果状态  1要改  0不改
    public function reSettlement($order_ids, $bettype = 2, $settype = 1, $game_code = 0, $match_id = 0, $change_status = 1)
    {
        $order_ids = array_unique($order_ids);
        $this->change_status = $change_status;

        if (intval($match_id) <= 0) {
            return self::makeData(8, 'matchid不能为空或0!');
        }

        if (empty($game_code)) {
            return self::makeData(8, '赛事类型不能为空!');
        }

        if (!in_array($bettype, [1, 2])) {
            return self::makeData(6, '订单类型参数错误!');
        }
        $this->orderType = $bettype;

        if (!in_array($settype, [1, 2])) {
            return self::makeData(6, '结算参数错误');
        }
        $this->set_type = $settype;

        if (empty($order_ids)) {
            $needs_matchs = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id])->count();
            if ($needs_matchs <= 0) {
                $this->cgStatus($game_code, $match_id, $this->change_status);
                return self::makeData();
            } else {
                return self::makeData(5, '订单号不能为空');
            }
            unset($needs_matchs);
        }


        if ($bettype == 1) {
            $chekArr = $this->Match_check($order_ids, $bettype);
            if (empty($chekArr) || count($chekArr) != 1) {
                return self::makeData(10, '不同场比赛不能同时结算！' . print_r($order_ids, true));
            }
        }
        $this->match_id = $match_id;
        $this->game_code = $game_code;

        if (!$this->DataPre($order_ids, $bettype, $settype, $game_code, $match_id, $change_status)) {
            return self::makeData(-1, 'false', '没找到订单信息');
        }

        try {
            DB::beginTransaction();

            $this->UndoSettlement();
            foreach ($order_ids as $order_id) {
                $this->BuyDatasMainModel = $this->Money_buy_Orders_Array[$order_id];
                if ($this->BuyDatasMainModel->settle_status == 2 && $settype == 1) {
                    continue;
                }

                if ($bettype == 1) {
                    $this->SingOrder($order_id);
                } else {
                    $this->ChuanOrder($order_id);
                }
            }
            $this->cgStatus($game_code, $match_id, $this->change_status);

            $this->RunSql();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return self::makeData(-2, $e->getMessage() . ' Line:' . $e->getLine());
        }
        return self::makeData();

    }

    public function orderTypeGet($order_id, $bettype)
    {
        if ($bettype == 1) {
            $datas = DB::table('money_buy_simplex')->where('order_id', $order_id)->first();
            $this->orderType = 1;
        } else {
            $datas = DB::table('money_buy_str')->where('order_id', $order_id)->first();
            $this->orderType = 2;
        }

        if (!$datas) {
            throw  new  \Exception('没有主订单信息');
        }

        return $datas;
    }

    /**
     * 单式注单结算
     * @param mixed $order_id 注单ID
     */
    private function singOrder($order_id)
    {
        // 查询订单下所有的单式注单
        $simplexData = $this->BuyDatasMainModel;

        $matchData = $this->Money_buy_Match_array[$simplexData->batch_id];
        if (count($matchData) <= 0) {
            throw new  \Exception("没有数据的错误!");
        }

        foreach ($matchData as $val) {
            if (!in_array($val->result, [-1, 1, 2, 3, 4])) {
                throw  new  \Exception('match 比赛结果异常或还没有输赢结果->' . $val->id);
            }
        }

        // 计算总回款
        if (empty($this->SettlementBaseObj)) {
            $settlementBase = new \App\Lib\Settlement\SettlementBase();
        } else {
            $settlementBase = $this->SettlementBaseObj;
        }
        $returnMoney = 0;
        $oddsResult = [];
        foreach ($matchData as $k => $v) {
            if ($v->result == -1) {
                continue;
            }
            $oddsResult[0]['winOrLose'] = $v->result;
            $oddsResult[0]['odds'] = $v->odds;
            $getReturnMoney = $settlementBase->stringOdds($oddsResult);
            $returnMoney += $getReturnMoney['returnMoney'] * $v->bet_money;
        }
        $returnMoney = sprintf("%.2f", substr(sprintf("%.3f", $returnMoney), 0, -1));
        // 判断盈亏  1 赢  2 输  3 平
        $game_status = $returnMoney > $simplexData->money ? 1 : ($returnMoney == $simplexData->money ? 3 : 2);
        // 修改投注表状态及盈亏
        $this->sqlArray[] = "update money_buy_simplex set settle_status=2, game_status=$game_status,gain_money=$returnMoney  where order_id='$order_id' ";

        $this->WriteOrAddSettlement($this->game_code, $this->match_id, $this->orderType, $order_id, $this->BuyDatasMainModel->account_identity, $returnMoney);
        $this->insertData(
            $order_id,
            $returnMoney,
            $simplexData->account_identity,
            1,
            $simplexData->game_code,
            $simplexData->info_identity,
            $simplexData->money,
            $this->match_id
        );

    }

    private function ChuanOrder($order_id)
    {

        $batch_id = $this->BuyDatasMainModel->batch_id;
        $matchModels = $this->Money_buy_Match_array[$batch_id];
        if (count($matchModels) <= 0) {
            throw  new  \Exception('match 数据异常');
        }

        $newTime = date('Y-m-d H:i:s');
        if ($this->BuyDatasMainModel->status == 1) {
            $in_array = [];
            foreach ($matchModels as $val) {
                if (!in_array($val->result, [-1, 1, 2, 3, 4])) {
                    throw  new  \Exception('match 比赛结果异常或还没有输赢结果->' . $val->id);
                }

                if ($val->result == -1) {
                    $this->sqlArray[] = "update  money_buy_str set wait_match_num=0, prize_note=0, game_status=3, settle_status=2, gain_money=0,settlementtime='" . date('Y-m-d H:i:s') . "' where batch_id='$batch_id' ";
                    return true;
                }
                $in_array[] = ['odds' => $val->odds, 'winOrLose' => $val->result];
            }

            $chuanNum = intval(substr($this->BuyDatasMainModel->str_type, 0, 1));
            $lasPeilv = $this->stringComputing([$in_array, $chuanNum]);
            $money = floatPointDigit($this->BuyDatasMainModel->money * $lasPeilv);

        } else {
            $money = $this->BuyDatasMainModel->money;
        }

        $this->sqlArray[] = " update money_buy_str  set settle_status=2 , game_status=1 , settlementtime='$newTime' , gain_money=$money  where order_id = '$order_id'";

        $this->WriteOrAddSettlement($this->game_code, $this->match_id, $this->orderType, $order_id, $this->BuyDatasMainModel->account_identity, $money);
        $this->insertData($order_id, $money, $this->BuyDatasMainModel->account_identity, 2, $val->game_code, $this->BuyDatasMainModel->info_identity, $this->BuyDatasMainModel->money, $this->match_id);

        return true;
    }

    //重结算时，要先扣掉先前发的钱
    private function UndoSettlement()
    {
        if (empty($this->settlement_middle_detail_array)) {
            return true;
        }

        $nowArray = $this->settlement_middle_detail_array[$this->orderType];
        foreach ($nowArray as $order => $val) {
            $money = abs(floatval($val->money));
            $acc = $val->account_identity;
            $sql = "update account_detailed  set  cash=cash-$money where identity='$acc' ";
            $this->sqlArray[] = $sql;
            $ids[] = $order;
        }

        $ids = array_map(function($i){return "'.$i.'";},$ids);
        $ids_array = implode(",", $ids);
        $sql = "update settlement_middle_detail  set  money=0 where order_id in($ids_array) and bet_type=$this->orderType  ";
        $this->sqlArray[] = $sql;

        return true;
    }


    //数据预批量获取
    private function DataPre($order_ids, $bettype = 2, $settype = 1, $game_code = 0, $match_id = 0, $change_status = 1)
    {

        if ($bettype == 1) {
            $moneytable = 'money_buy_simplex';
            $ret = DB::table('money_buy_simplex')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('order_id', $order_ids)->get();
        } else {
            $moneytable = 'money_buy_str';
            $ret = DB::table('money_buy_str')->whereIn('order_id', $order_ids)->get();
        }
        if (empty($ret)) {
            return false;
        }

        $tmpbatchid = [];
        $userindentys = [];
        $orderarr = [];
        foreach ($ret as $val) {
            $this->Money_buy_Orders_Array[$val->order_id] = $val;
            $orderarr[] = $val->order_id;
            $this->Money_buy_Orders_batch_Array[$val->batch_id][] = $val;
            $tmpbatchid[] = $val->batch_id;
            $userindentys[] = $val->account_identity;
        }

        $tmpbatchid = array_unique($tmpbatchid);
        $userindentys = array_unique($userindentys);

        if ($bettype == 1) {
            $ret = DB::table('money_buy_match')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('batch_id', $tmpbatchid)->get();
        } else {
            $ret = DB::table('money_buy_match')->where(['game_code' => $game_code])->whereIn('batch_id', $tmpbatchid)->get();
        }
        foreach ($ret as $val) {
            $this->Money_buy_Match_array[$val->batch_id][] = $val;
        }

        $ret = DB::table('account_detailed')->whereIn('account_identity', $userindentys)->get();
        foreach ($ret as $val) {
            $this->account_indentity_map_array[$val->account_identity] = $val;
        }

        $ret = DB::table('account')->whereIn('identity', $userindentys)->get();
        foreach ($ret as $val) {
            $this->account_map_array[$val->identity] = $val;
        }

        if ($settype == 2) {
            $ret = DB::table('settlement_middle_detail')->where(['game_code' => $game_code, 'match_id' => $match_id])->whereIn('order_id', $order_ids)->get();
            if ($ret) {
                foreach ($ret as $val) {
                    $this->settlement_middle_detail_array[$val->bet_type][$val->order_id] = $val;
                }
            }

            $maparr = array_map(function ($i) {
                return "'" . $i . "'";
            }, $orderarr);
            $order_str = implode(",", $maparr);
            if ($change_status) {
                if ($bettype == 1) {
                    $this->sqlArray[] = "update $moneytable set  settle_status=1, gain_money=0, game_status=0 where  game_code='$game_code' and match_id=$match_id and  status=1 and order_id in ($order_str)  ";
                } else {
                    $this->sqlArray[] = "update $moneytable set  settle_status=1, gain_money=0  where order_id in ($order_str)  ";
                }
            }
        }

        $ret = DB::table('money_prize')->whereIn('order_id', $order_ids)->get();
        if ($ret) {
            foreach ($ret as $val) {
                $this->money_prize_map[$val->order_id] = $val;
            }
        }

        return true;
    }


    private function WriteOrAddSettlement($game_code, $match_id, $bet_type, $order_id, $account_ident, $money)
    {
        if (intval($money * 100) == 0) {
            return;
        }

        if ($this->set_type == 2 && isset($this->settlement_middle_detail_array[$bet_type][$order_id])) {
            $this->sqlArray[] = "update  settlement_middle_detail  set  money=$money  where game_code='$game_code' and bet_type=$bet_type and order_id='$order_id' ";
        } else {
            $this->sqlArray[] = "insert into settlement_middle_detail(game_code,match_id,account_identity,bet_type,order_id,money) values('$game_code','$match_id','$account_ident',$bet_type,'$order_id',$money)";
        }
        return true;
    }

    /**
     * 结算数据填入
     * @param mixed $order_id 注单ID
     * @param mixed $returnMoney 返现金额
     * @param mixed $account_identity 用户ID
     * @param mixed $type 1单式 2串式
     * @param mixed $game_name 游戏名（zq，lq）
     * @param mixed $buy_identity 游戏投注id
     * @param mixed $money 投注金额
     * @param mixed $match_id 赛场ID
     */
    private function insertData($order_id, $returnMoney, $account_identity, $type, $game_name, $buy_identity, $money, $match_id = 0)
    {
        // 查询用户当前剩余金额
        $accountInfo = $this->account_indentity_map_array[$account_identity];
        // 计算用户回账后余额
        $this->account_indentity_map_array[$account_identity]->available_cash = $available_cash = $accountInfo->available_cash + $returnMoney;
        $this->account_indentity_map_array[$account_identity]->cash = $cash = $accountInfo->cash + $returnMoney;
        // 添加流水记录
        $info_identity = UUID();
        $money_time = date('Y-m-d H:i:s', time());
        $trade_desc = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';
        $reason = $type == 1 ? '单式投注订单回款' : '串式投注订单回款';

        $accountInfobase = $this->account_map_array[$account_identity];
        $sql = "insert into money_details(info_identity,trade_id,account_name,account_identity,money,money_time,money_type,money_cash,trade_type,trade_desc,reason,sysetem_user,status)  values(";
        $sql .= "'$info_identity','$order_id','$accountInfobase->account','$accountInfobase->identity',$returnMoney,'$money_time',1,$available_cash,4,'$trade_desc','$reason','系统',1)";
        $this->sqlArray[] = $sql;

        // 修改用余额
        $this->sqlArray[] = "update account_detailed  set available_cash=$available_cash,cash=$cash where  account_identity='$account_identity' ";

        // 新增用户中奖信息
        $content = $type == 1 ? '您的单式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束，如有疑问请联系客服'
            : '您的串式投注订单' . $order_id . '于' . $money_time . '成功回款' . $returnMoney . '该次投注流程结束，如有疑问请联系客服';
        $sql = "insert into account_news(identity,account_identity,title,content,details,write_time,read_status,type) values ";
        $sql .= "('$info_identity','$account_identity','投注订单回款通知','$content','$content','$money_time',-1,1)";
        $this->sqlArray[] = $sql;


        // 新增中奖记录表
        //$old = $this->money_prize_map[$order_id];
        $table = 'money_prize';
        if (isset($this->money_prize_map[$order_id])) {
            $this->sqlArray[] = "update $table  set money=$money,prize_money=$returnMoney, get_money= $returnMoney - $money where  order_id='$order_id'";
        } else {
            $tmp_account = $this->account_map_array[$account_identity]->account ;
            $sql = "insert into  $table (info_identity,order_id,account_identity,account_name,game_name,buy_identity,money,money_time,status,prize_money,get_money) values ";
            $sql .= "('$info_identity','$order_id','$account_identity','$tmp_account','$game_name','$buy_identity',$money,'$money_time',1,$returnMoney,$returnMoney - $money)";
            $this->sqlArray[] = $sql;
        }

        return true;
    }


    //改状态
    private function cgStatus($game_code, $match_id, $change_status)
    {
        $table1 = "st_" . $game_code . "_result";
        $table2 = "st_" . $game_code . "_competition";

        if ($change_status) {
            $this->sqlArray[] = "update $table1 set  status=3  where   match_id=$match_id ";
            $this->sqlArray[] = "update $table2 set  status=3  where   match_id=$match_id ";
        }
    }

    //校验是否同一场比赛的订单处理
    private function Match_check($idsArray, $betType)
    {
        array_walk($idsArray, function (&$item, $key) {
            $item = "'" . $item . "'";
        });

        $idString = implode(",", $idsArray);

        $table = "money_buy_simplex";
        $sql = "select game_code,match_id   from  $table  where  status=1 and  order_id in ($idString)  group by  game_code,match_id ";

        $ret = DB::select($sql);

        return $ret;

    }

    private function RunSql()
    {
        $len = count($this->sqlArray);
        $step = 2000;
        $j = 1;
        $pdo = DB::getPdo();
        $tmp = [];
        for ($i = 0; $i < $len; $i++) {
            if ($j > $step || $i == ($len - 1)) {
                if (empty($tmp)) {
                    return;
                }
                $sqlstr = implode(";", $tmp);
                $ret = $pdo->exec($sqlstr);
                if (!$ret) {
                    throw new  \Exception("运行sql发生错误!");
                }
                $tmp = [];
                $j = 1;
            } else {
                $tmp[] = $this->sqlArray[$i];
                $j++;
            }
        }
        return true;
    }


}