<?php

namespace app\controller;


use think\facade\Db;
use think\Request;

class UserRefund
{
    public function UserReimburse($openid, $money)
    {
        $money = round($money, 2);

        $user_info = Db::table('zxc_user')->where('openid', $openid)->find();
        //判断金额 余额>=提现金额
        if ($user_info['account'] < $money) {
            return json(['code' => 1, 'message' => '余额不足']);
        }
        //正在进行余额充电的订单不可提现
        $count = Db::table('zxc_charge_order')
            ->where('openid', $openid)
            ->where('type', 2)
            ->where('end_time', null)
            ->find();
        if ($count > 0) {
            return json(['code' => 1, 'message' => '存在未结算订单']);
        }

        $table_recharge = 'zxc_recharge';
        $reOrder = $this->SelectReOrder($openid, $money, $table_recharge);

        if (empty($reOrder)) {
            return json(['code' => 1, 'message' => '提现数据为空']);
        }
        $i = 0;
        $suceess = 0;
        $fail = 0;
        foreach ($reOrder as $key => $value) {
            $transaction_id = $key;
            $OriginalOrderAmount = Db::table($table_recharge)->where('transaction_id', $transaction_id)->value('total');
            $OriginalOrderAmount /= 100;
            $refundAmount = $value / 100;
            $td = new WechatReimburse();
            $kk[] = $td->Refund($transaction_id, $openid, $refundAmount, $OriginalOrderAmount);
            if ($kk[$i]['code'] == 200) {
                $suceess += 1;
            } elseif ($kk[$i]['code'] == 1) {
                $fail += 1;
            }
            $i += 1;
        }
        return json(['code' => 200, 'total' => $i, 'success' => $suceess, 'fail' => $fail, 'message' => $kk, 'reOrder' => $reOrder]);

        exit();


        $account = Db::table($table_user)->where('openid', $openid)->value('account');
        $account = round($account, 2);
        $frozenAmount = Db::table($table_user)->where('openid', $openid)->value('FrozenAccount');
        if ($money <= $account) {
            $OrderList = new ChargeOrder();
            $OrderList->OrderList($openid);//更新一下状态
            //二次确认
            $recharge_all = Db::table($table_recharge)->where('openid', $openid)->sum('total');
            $recharge_all /= 100;
            $refund_all = Db::table($table_refund)->where('openid', $openid)
                ->where('status', 'SUCCESS')
                ->sum('refund_total');
            $refund_all /= 100;
            $check = Db::table($table_order)->where('openid', $openid)
                ->where('status', '<>', 4)
                ->where('status', '<>', 5)
                ->order('start_time desc')
                ->value('end_time');
            if (empty($check)) {
                $order_all = Db::table($table_order)->where('openid', $openid)
                    ->where('status', 4)
                    ->sum('TotalMoney');
                $inorder = Db::table($table_order)->where('openid', $openid)
                    ->where('status', '<>', 4)
                    ->where('status', '<>', 5)
                    ->order('start_time desc')
                    ->value('WithholdingMoney');
                $order_total = $order_all + $inorder;
            } else {
                $order_total = Db::table($table_order)->where('openid', $openid)
                    ->where('status', 4)
                    ->sum('TotalMoney');
            }
            $order_total = round($order_total, 2);
            $mask = round($recharge_all - $order_total - $refund_all, 2); //这里还要减已经提现的
            if (round($mask, 2) == round($account, 2)) {
                $reOrder = $this->SelectReOrder($openid, $money, $table_recharge);
                if (empty($reOrder)) {
                    return json(['code' => 1, 'message' => '提现数据为空']);
                }
                $i = 0;
                $suceess = 0;
                $fail = 0;
                foreach ($reOrder as $key => $value) {
                    $transaction_id = $key;
                    $OriginalOrderAmount = Db::table($table_recharge)->where('transaction_id', $transaction_id)->value('total');
                    $OriginalOrderAmount /= 100;
                    $refundAmount = $value / 100;
                    $td = new WechatReimburse();
                    $kk[] = $td->Refund($transaction_id, $openid, $refundAmount, $OriginalOrderAmount);
                    if ($kk[$i]['code'] == 200) {
                        $suceess += 1;
                    } elseif ($kk[$i]['code'] == 1) {
                        $fail += 1;
                    }
                    $i += 1;
                }
                return json(['code' => 200, 'total' => $i, 'success' => $suceess, 'fail' => $fail, 'message' => $kk, 'reOrder' => $reOrder]);
            } else {
                Db::table('refundexception')->save([
                    'openid' => $openid,
                    'order_total' => $order_total,
                    'recharge_total' => $recharge_all,
                    'refund_total' => $refund_all,
                    'mask' => $mask,
                    'account' => $account
                ]);
                return json(['code' => 1, 'message' => '账户异常', 'order_total' => $order_total, 'recharge_all' => $recharge_all, 'mask' => $mask]);
            }
        } else {
            return json(['code' => 1, 'message' => '提现金额不能大于余额']);
        }
    }

    public function SelectReOrder($openid, $money, $table_recharge)
    {
        $oneYearAgo = strtotime('-1 year');
        $oneYearAgoDate = date('Y-m-d H:i:s', $oneYearAgo);
        $reOrder = Db::table($table_recharge)->where('openid', $openid)->where('type', 1)->where('success_time', '>=', $oneYearAgoDate)->order('total')->select();
        $money *= 100;
        $money = floor($money);
        $kk = array();
        foreach ($reOrder as $re) {
            if ($re['total'] - $re['total_used'] == 0) {
                continue;
            } else {
                $backMoney = $re['total'] - $re['total_used'];
                if ($money > $backMoney) {
                    $kk[$re['transaction_id']] = $backMoney;
                    $money = $money - $backMoney;
                } elseif ($money == $backMoney) {
                    $kk[$re['transaction_id']] = $money;
                    break;
                } else {
                    $kk[$re['transaction_id']] = $money;
                    break;
                }
            }
        }
        return $kk;
    }


    public function TKRecord($openid)
    {

        $table_refund = 'zxc_refund';

        $message = Db::table($table_refund)->where('openid', $openid)->order('create_time desc')->select()->toArray();

        $statusMap = [
            'SUCCESS' => '退款成功',
            'PROCESSING' => '退款处理中',
            'ABNORMAL' => '退款异常',
            'CLOSED' => '退款关闭',
        ];

        foreach ($message as &$record) {
            $record['refund_total'] = round($record['refund_total'] / 100, 2);
            $record['status'] = $statusMap[$record['status']] ?? $record['status'];
        }

        return json($message);
    }


    public function RefundQuery($start_time = '', $end_time = '', $message = '')
    {
        // 处理结束时间
        if (!empty($end_time)) {
            $end_time = date("Y-m-d", strtotime("+1 day", strtotime($end_time)));
        }


        // 生成表名
        $refundTable = 'zxc_refund';
        $userTable = 'zxc_user';


        // 构建查询条件
        $query = Db::table($refundTable);

        // 时间范围条件
        if (!empty($start_time) && !empty($end_time)) {
            $query->whereBetween('create_time', [$start_time, $end_time]);
        }

        // 消息条件
        if (!empty($message)) {
            if (strlen($message) == 11) {
                $openid = Db::table($userTable)->where('phone', $message)->value('openid');
                if ($openid) {
                    $query->where('openid', $openid);
                } else {
                    $query->where('out_refund_no', 'like', "%{$message}%");
                }
            } else {
                $query->where('out_refund_no', 'like', "%{$message}%");
            }
        }

        // 获取数据并合并
        $resultData = $query->order('create_time desc')->select()->toArray();

        // 处理结果数据

        foreach ($resultData as $index => &$item) {
            $item['id'] = $index + 1;
            $item['refund_total'] = round($item['refund_total'] / 100, 2);

            $table = 'zxc_user';
            $phone = Db::table($table)->where('openid', $item['openid'])->value('phone');
            $item['phone'] = $phone;
        }

        return json($resultData);
    }


    public function Refund_Total(Request $request)
    {
        $data = $request->param();
        $time_type = $data['time_type'];
        $str_day = $data['str_time'];
        $time = strtotime($str_day);
        $date_time = date('Y-m-d', $time);
        $area = Db::table('area_three')->column('area');
        if ($time_type == '周') {
            $mess = [];
            $end_time = date("Y-m-d 23:59:59", strtotime("$date_time Saturday"));//结束时间(2020-04-19 23:59:59)
            $start_time = date("Y-m-d 00:00:00", strtotime("$end_time - 6 days"));//开始时间(2020-04-13 00:00:00
            $revenue_total = 0;
            $order_num_total = 0;
            $date = $this->getDateFromRange($start_time, $end_time);
            foreach ($date as $d) {
                $revenue = 0;
                $order_num = 0;
                $table_refund = 'zxc_refund';

                $result = Db::table($table_refund)->select();
                if (empty($result)) {
                    continue;
                } else {
                    $recharge = Db::table($table_refund);
                    $revenue = $recharge->whereDay('create_time', $d)->sum('refund_total');
                    $order_num = $recharge->whereDay('create_time', $d)->count();
                }

                $mess['per'][] = ['time' => $d, 'data' => ['EnterAccount' => round($revenue / 100, 2), 'AccountNum' => $order_num]];
                $revenue_total += $revenue;
                $order_num_total += $order_num;

            }
            $mess['total'] = ['EnterAccount' => round($revenue_total / 100, 2), 'AccountNum' => $order_num_total];
            return json($mess);
        } elseif ($time_type == '月') {
            $mess = [];
            $start_time = date("Y-m-d", strtotime(date('Y-m-01', $time)));//开始时间(2020-04-01 00:00:00)
            $date = $this->getMonthDate($start_time);
            $i = 1;
            $revenue_total = 0;
            $order_num_total = 0;
            foreach ($date as $d) {
                $z = '第' . $i . '周';
                $d = date('Y-m-d', strtotime($d));
                $revenue = 0;
                $order_num = 0;
                $table_refund = 'zxc_refund';

                $result = Db::table($table_refund)->select();
                if (empty($result)) {
                    continue;
                } else {
                    $recharge = Db::table($table_refund);
                    $revenue = $recharge->whereWeek('create_time', $d)->sum('refund_total');
                    $order_num = $recharge->whereWeek('create_time', $d)->count();

                }

                $mess['per'][] = ['time' => $z, 'data' => ['EnterAccount' => round($revenue / 100, 2), 'AccountNum' => $order_num]];
                $revenue_total += $revenue;
                $order_num_total += $order_num;
                $i += 1;
            }
            $mess['total'] = ['EnterAccount' => round($revenue_total / 100, 2), 'AccountNum' => $order_num_total];
            return json($mess);
        } elseif ($time_type == '季') {
            $season = intval(ceil(date('m', $time) / 3));
            if ($season == 4) {
                $start_time = date("Y-m-d H:i:s", strtotime(date('Y-' . ($season * 3 - 2) . '-01', $time)));//开始时间(2020-04-01 00:00:00)
                $end_time = date("Y-m-d 23:59:59", strtotime(date('Y-m-d', strtotime("$start_time +3 month -1 day"))));//开始时间(2020-04-01 00:00:00)
            } else {
                $start_time = date("Y-m-d H:i:s", strtotime(date('Y-0' . ($season * 3 - 2) . '-01', $time)));//开始时间(2020-04-01 00:00:00)
                $end_time = date("Y-m-d 23:59:59", strtotime(date('Y-m-d', strtotime("$start_time +3 month -1 day"))));//开始时间(2020-04-01 00:00:00)
            }
            $i = date("m", strtotime(date('Y-' . ($season * 3 - 2) . '-01', $time)));
            if ((int)substr($i, 0, 1) == 0) {
                $i = substr($i, -1);
            }
            $date = $this->getSeasonDate($start_time);
            $mess = [];
            $revenue_total = 0;
            $order_num_total = 0;
            foreach ($date as $d) {
                $z = $i . '月';
                $d = date('Y-m-d', strtotime($d));
                $revenue = 0;
                $order_num = 0;

                $table_refund = 'zxc_refund';

                $result = Db::table($table_refund)->select();
                if (empty($result)) {
                    continue;
                } else {
                    $recharge = Db::table($table_refund);
                    $revenue = $recharge->whereMonth('create_time', $d)->sum('refund_total');
                    $order_num = $recharge->whereMonth('create_time', $d)->count();

                }
                $mess['per'][] = ['time' => $z, 'data' => ['EnterAccount' => round($revenue / 100, 2), 'AccountNum' => $order_num]];
                $revenue_total += $revenue;
                $order_num_total += $order_num;
                $i += 1;
            }
            $mess['total'] = ['EnterAccount' => round($revenue_total / 100, 2), 'AccountNum' => $order_num_total];
            return json($mess);
        } elseif ($time_type == '年') {
            $start_time = date('Y-01-01 00:00:00', $time);//开始时间
            $date = $this->getYearDate($start_time);
            $mess = [];
            $revenue_total = 0;
            $order_num_total = 0;
            $i = 1;
            foreach ($date as $d) {
                $z = $i . '月';
                $d = date('Y-m', strtotime($d));
                $revenue = 0;
                $order_num = 0;

                $table_refund = 'zxc_refund';

                $result = Db::table($table_refund)->select();
                if (empty($result)) {
                    continue;
                } else {
                    $recharge = Db::table($table_refund);
                    $revenue = $recharge->whereMonth('create_time', $d)->sum('refund_total');
                    $order_num = $recharge->whereMonth('create_time', $d)->count();

                }

                $mess['per'][] = ['time' => $z, 'data' => ['EnterAccount' => round($revenue / 100, 2), 'AccountNum' => $order_num]];
                $revenue_total += $revenue;
                $order_num_total += $order_num;
                $i += 1;
            }
            $mess['total'] = ['EnterAccount' => round($revenue_total / 100, 2), 'AccountNum' => $order_num_total];
            return json($mess);
        }
    }

    private function getDateFromRange($startdate, $enddate): array
    {

        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {

            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
        }

        return $date;
    }

    private function getMonthDate($date)
    {
        $date_t = array();
        $date_t[] = $date;
        for ($i = 0; $i < 4; $i++) {
            $this_date = strtotime($date);
            $next_date = date("Y-m-d", strtotime('next monday', $this_date));
            $date_t[] = $next_date;
            $date = $next_date;
        }
        return $date_t;

    }

    private function getSeasonDate($date)
    {
        $date_t = array();
        $date_t[] = $date;
        for ($i = 0; $i < 2; $i++) {
            $this_date = strtotime($date);
            $next_date = date("Y-m-d", strtotime('next month', $this_date));
            $date_t[] = $next_date;
            $date = $next_date;
        }
        return $date_t;

    }

    private function getYearDate($date)
    {
        $date_t = array();
        $date_t[] = $date;
        for ($i = 0; $i < 11; $i++) {
            $this_date = strtotime($date);
            $next_date = date("Y-m-d", strtotime('next month', $this_date));
            $date_t[] = $next_date;
            $date = $next_date;
        }
        return $date_t;

    }

    private function getDayDate($date)
    {
        $date_t = array();
        $date_t[] = $date;
        $this_date = strtotime($date);
        $end_date = date("Y-m-d H:i:s", strtotime('+4 hour -1 second', $this_date));
        $date_end[] = $end_date;
        for ($i = 0; $i < 5; $i++) {
            $this_date = strtotime($date);
            $next_date = date("Y-m-d H:i:s", strtotime('+4 hour', $this_date));
            $this_date_end = strtotime($end_date);
            $next_date_end = date("Y-m-d H:i:s", strtotime('+4 hour', $this_date_end));
            $date_end[] = $next_date_end;
            $date_t[] = $next_date;
            $date = $next_date;
            $next_date_end = date("Y-m-d H:59:59", strtotime($next_date_end));
            $end_date = $next_date_end;
        }
        $kk['start_time'] = $date_t;
        $kk['end_time'] = $date_end;
        return $kk;

    }
}