<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Account_detailed;
use App\Models\LuckyMoney;
use App\Lib\Biz\Money\AddOrCutMoney;
use Illuminate\Http\Request as Req;
use Illuminate\Support\Facades\App;
use Ramsey\Uuid\Uuid;
use Request;
use DB;

class RefundController extends Controller {

    public function index(Req $req) {
        $request['type'] = isset($req->type) ? trim($req->type) : '-1';
        $request['lm_order_id'] = $req->lm_order_id ? $req->lm_order_id : '';
        $request['account'] = $req->account ? $req->account : '';
        $request['start_time'] = isset($req->start_time) ? trim($req->start_time) : null;
        $request['end_time'] = isset($req->end_time) ? trim($req->end_time) : null;
        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/Refund/getList');
        $dt->setLang('lucky_money');
        $dt->addColsFields('lm_order_id', array('templet' => '#lm_order_id', 'sort' => false, 'width' => 300));
        $dt->addColsFields('account', array('sort' => false));
        $dt->addColsFields('room_name', array('sort' => false));
        $dt->addColsFields('money', array('sort' => false));
        $dt->addColsFields('num', array('sort' => false, 'width' => 120));
        $dt->addColsFields('take_num', array('sort' => false, 'width' => 120));
        $dt->addColsFields('take_money', array('sort' => false));
        $dt->addColsFields('created_at', array('templet' => '#created_at', 'sort' => false, 'width' => 160));
        // $dt->addColsFields('lm_return_money', array('sort' => false));
        // $dt->addColsFields('type_name', array('sort' => false));
        // $dt->addColsFields('action_d', array('templet' => '#waterTool', 'sort' => false));
        $dt->enableCheckBox();

        return view('admin.refund/index', $dt->render($request));

    }


    function getList(Req $req) {
        $list = isset($req->limit) ? trim($req->limit) : 50;
        $request['type'] = isset($req->type) ? trim($req->type) : '-1';
        $start_time = Request::has('start_time') ? Request::get('start_time') : '';
        $end_time = Request::has('end_time') ? Request::get('end_time') : '';
        $lm_order_id = $req->lm_order_id ? $req->lm_order_id : '';
        $account = $req->account ? $req->account : '';
        $where = array();
        if ($request['type'] > '-1') {
            $where['type'] = $request['type'];
        }
        if (!empty($lm_order_id)) {
            $where[] = array('lm_order_id', $lm_order_id);
        }
        if (!empty($account)) {
            $where[] = array('account', 'like', '%' . $account . '%');
        }
        if (!empty($start_time)) {
            $where[] = array('created_at', '>=', $start_time);
        }
        if (!empty($end_time)) {
            $where[] = array('created_at', '<=', $end_time);
        }
        $langinfo = trans('lucky_money');
        $db = new \App\Models\LuckyMoney;
        $data = $db->getRefund($list, $where);

        foreach ($data['data'] as $k => $v) {
            $room_info = DB::table('chat_rooms')->where('id', $v['room_id'])->first();
            if ($room_info) {
                $data['data'][$k]['room_name'] = $room_info->room_name;
            }
        }
        return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
    }

    function delete(Req $req) {
        set_time_limit(0);
        $get_data = $req->data;
//        $star_time = $req->star_time ? $req->star_time . ' 00:00:00' : '';
//        $end_time = $req->end_time ? $req->end_time . ' 23:59:59' : '';
        if (!is_array($get_data)) {
            return responseToJson(-2001);
        }
        $err_times = 0;
        $s_times = 0;
        $skip=0;
        foreach ($get_data as $k => $v) {
            $money = $v['money'] - $v['take_money'];
            if ($money == 0){
                $skip++;
                continue;
            }
                $i = $this->handleRefund($v['account_identity'], $v['account'], $v['lm_order_id'], $money, session('adminInfo.admin_id'));
            if (!$i) $err_times++;
            else
                $s_times++;
        }
        return responseToJson( ['ok' => $s_times, 'nok' => $err_times,'skip'=>$skip]);
    }

    function delete2(Req $req) {
        $get_data = $req->data;
        $star_time = $req->star_time ? $req->star_time . ' 00:00:00' : '';
        $end_time = $req->end_time ? $req->end_time . ' 23:59:59' : '';

        // $room_id=$req->room_id?trim($req->room_id):'';
        /**时间条件***/
        $timearea = array();
        if (!empty($star_time)) {
            $star_time = date('Y-m-d H:i:s', strtotime($star_time));
            $timearea[] = array('created_at', '>=', $star_time);
        }
        if (!empty($end_time)) {
            $end_time = date('Y-m-d H:i:s', strtotime($end_time));
            $timearea[] = array('created_at', '<=', $end_time);
        }
        /**数据检验***/
        if (!is_array($get_data)) {
            return responseToJson(-2001);
        }
        $account_id_array = array();
        foreach ($get_data as $v) {
            if ($v['take_money'] < 0) {
                return responseToJson(-5030021122);
            }
            //获取用户id数组
            $account_id_array[] = $v['account_identity'];
        }

        $lm_order_id = array();
        foreach ($get_data as $v) {
            if ($v['take_money'] < 0) {
                return responseToJson(-5030021122);
            }
            //获取用户id数组
            $lm_order_id[] = $v['lm_order_id'];
        }
        //插入回水记录
        $data_min_array = array(); //详情数据数组
        $refund_money_array = array(); //详情数据数组
        //获取用户信息
        $account_detailed = new \App\Models\Account_detailed;

        //获取用户当前余额
        $account_cash_array = $account_detailed->getCashArray($account_id_array);

        $lucky_money = new \App\Models\LuckyMoney;
        $refund_money = $lucky_money->getRefundArr($lm_order_id);
        $refu_money = $lucky_money->getRefundA($lm_order_id);

        //组装数据
        foreach ($get_data as $k => $v) {
            $order_id = OrderID();
            $money = $v['money'] - $v['take_money'];
            $data_min_array[$k]['account_name'] = $v['account'];
            $data_min_array[$k]['account_identity'] = $v['account_identity'];
            $data_min_array[$k]['trade_id'] = $order_id;
            $data_min_array[$k]['money'] = $money;
            $data_min_array[$k]['sysetem_user'] = session('adminInfo.admin_name');
            $data_min_array[$k]['info_identity'] = UUID();
            $data_min_array[$k]['money_time'] = date('Y-m-d H:i:s');
            $data_min_array[$k]['money_type'] = 1;
            $data_min_array[$k]['money_cash'] = $account_cash_array[$v['account_identity']] + $money;
            $data_min_array[$k]['trade_type'] = 16;
            $data_min_array[$k]['trade_desc'] = sprintf(trans('trade.admin_refund_money'), session('adminInfo.admin_name'), $v['account'], $money, $order_id);

            $refund_money_array[$k]['lm_return_order_id'] = OrderID();
            $refund_money_array[$k]['lm_return_money'] = $money;
        }
        //插入详情记录
        $db_money_de = new \App\Models\Money_details;
        $res_detail = $db_money_de->returnData($data_min_array);
        if ($res_detail < 0) {
            DB::rollback();
            return responseToJson($res_detail);
        }
        //退还红包
        foreach ($get_data as $k => $v) {
            $money = $v['money'] - $v['take_money'];
            $order_id = OrderID();
            $re_money = $lucky_money->refundData($v['lm_order_id'], $money);
            if ($re_money < 0) {
                break;
            }
        }

        //更新用户余额
        foreach ($get_data as $k => $v) {
            $money = $v['money'] - $v['take_money'];
            $res_money = $account_detailed->addMoney($v['account_identity'], $money);
            if ($res_money < 0) {
                break;
            }
        }
        if ($res_money < 0) {
            DB::rollback();
            return responseToJson($res_money);
        }
        //组装
        $account_str = array();
        $length = count($get_data);
        $limit = 0;
        if ($length > 20) {
            $limit = ceil($length / 20);
        }
        $i = 0;
        foreach ($get_data as $k => $v) {
            if ($k < 20 * ($i + 1)) {
                if (!isset($account_str[$i])) {
                    $account_str[$i] = '';
                }
                $account_str[$i] .= $v['account'] . ',';
            } else {
                $i++;
            }
        }
        $log = array();
        foreach ($account_str as $k => $v) {
            $log[] = array(
                session('adminInfo.admin_name'),
                $v
            );
        }
        foreach ($log as $v) {
            $res = OperationLog(session('adminInfo.admin_id'), 'refund_money', $v);
            if ($res < 0) {
                break;
            }
        }
        if ($res < 0) {
            DB::rollback();
            return responseToJson($res);
        }
        DB::commit();
        return responseToJson(1);
    }

    /**
     * 退红包函数
     * @param $account_id
     * @param $account_name
     * @param $lm_id
     * @param $money
     * @param $admin
     * @return bool
     */

    protected function handleRefund($account_id, $account_name, $lm_id, $money, $admin): bool {
        $ad = new Account_detailed();
        $adObj = $ad->where('account_identity', $account_id)->first();
        DB::beginTransaction();
        $rlm_id = UUID();
        $aoc = new AddOrCutMoney();
        $trade_id = OrderID();
        $date = date('Y-m-d H:i:s');
        $trad_desc = sprintf("管理员%s于{$date}退还了%s发起的红包余额%s元(红包ID:%s),退还单号为%s", $admin, $account_name, $money, $lm_id, $rlm_id);
        $reason = '红包退还';
        $ret = $aoc->addMoneyDetailRec($adObj, $account_name, $trade_id, $money, 1, 16, $admin, $trad_desc, $reason);
        if (is_int($ret)) {
            DB::rollBack();
            return false;
        }
        $ret = DB::table('lucky_money')->where('lm_order_id', $lm_id)->update([
            'lm_return_order_id' => $rlm_id,
            'lm_return_money' => $money,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);//更新红包退还数据

        if ($ret !== 1) {
            DB::rollBack();
            return false;
        }
        $detail = $trad_desc;
        $ret = $aoc->addMoneyRechargeRec($adObj, $account_name, $trade_id, $money, '红包退还', $admin, $reason, $detail, 0, 1);//添加充值详情
        if (is_int($ret)) {
            DB::rollBack();
            return false;
        }
        $ret = $aoc->incAccountDetailMoney($adObj, $money);//更新用户余额
        if ($ret !== 1) {
            DB::rollBack();
            return false;
        }
        $res = OperationLog($admin = session('adminInfo.admin_id'), 'refund_money', [$admin, $account_name, $money]);
        if ($res < 0) {
            DB::rollBack();
            return false;
        }
        $ret=DB::table('chat_redbag')->where('redid',$lm_id)->delete();
        if(!is_int($ret)){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

}