<?php
declare (strict_types=1);

namespace app\controller;

use app\common;
use app\model\ChargeStation as ChargeStationModel;

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

class ChargeStation extends common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
 
        $sql = "SELECT charge_station_id,count(charge_station_id) pile_number FROM charge_pile GROUP BY charge_station_id HAVING count(charge_station_id)>1 ORDER BY charge_station_id";
        $message = Db::query($sql);
        foreach ($message as $m) {
            $charge_station_id = $m['charge_station_id'];
            $pile_number = $m['pile_number'];
            ChargeStationModel::where('charge_station_id', $charge_station_id)->update(['charge_pile_num' => $pile_number]);
        }
        $list = ChargeStationModel::withSearch(['charge_station_name', 'station_type', 'city', 'area', 'street', 'address', 'price'], [
            'charge_station_name' => request()->param('charge_station_name'),
            'station_type' => request()->param('station_type'),
            'city' => request()->param('city'),
            'area' => request()->param('area'),
            'street' => request()->param('street'),
            'address' => request()->param('address'),
            'price' => request()->param('price')
        ])->paginate([
            'list_rows' => 20,
            'query' => request()->param()
        ]);
//        return Db::getLastSql();
        return json($list);
    }

    public function station_all()
    {
        $sql = "SELECT charge_station_id,count(charge_station_id) pile_number FROM charge_pile GROUP BY charge_station_id HAVING count(charge_station_id)>1 ORDER BY charge_station_id";
        $message = Db::query($sql);
        foreach ($message as $m) {
            $charge_station_id = $m['charge_station_id'];
            $pile_number = $m['pile_number'];
            ChargeStationModel::where('charge_station_id', $charge_station_id)->update(['charge_pile_num' => $pile_number]);
        }
        $list = ChargeStationModel::select();
//        return Db::getLastSql();
        return json($list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->param();
        $charge_station_name = $data['charge_station_name'];
        $id = ChargeStationModel::where('charge_station_name', $charge_station_name)->value('charge_station_id');
        if (empty($id)) {
            $message = [
                'charge_station_name' => $data['charge_station_name'],
                'station_type' => $data['station_type'],
                'city' => $data['city'],
                'area' => $data['area'],
                'street' => $data['street'],
                'address' => $data['address'],
                'charge_pile_num' => $data['charge_pile_num'],
                'charge_station_phone' => $data['charge_station_phone'],
                'longitude' => $data['longitude'],
                'latitude' => $data['latitude'],
                'price' => $data['price']
            ];
            $result = ChargeStationModel::create($message);
            if ($result != false) {
                return json(['code' => 200, 'massage' => '增加成功']);
            } else {
                return json(['code' => 1, 'massage' => '增加失败']);
            }
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    public function price_update(Request $request)
    {
        $data = $request->param();
        $price = $data['price'];
        $id = $data['charge_station_id'];
        $id_message = ChargeStationModel::where('charge_station_id', $id)->find();
        $time = date('Y-m-d H:i:s');
        if (!empty($id_message)) {
            $result = ChargeStationModel::update([
                'ElectricityFee' => $price
            ], ['charge_station_id' => $id]);
            if ($result != null) {
                Db::table('charge_station')->where('charge_station_id', $id)->update(
                    ['last_update_time' => $time]
                );
                return json(['code' => 200, 'massage' => '更新成功', 'update_time' => $time]);
            }
        } else {
            return json(['code' => 1, 'massage' => '更新价格失败']);
        }
    }


    public function InnerChargeStation($station_number, $openid, $lat, $lng)
    {
        $sql = "SELECT charge_station_id,count(charge_station_id) pile_number FROM charge_pile GROUP BY charge_station_id HAVING count(charge_station_id)>1 ORDER BY charge_station_id";
        $message = Db::query($sql);
        foreach ($message as $m) {
            $charge_station_id = $m['charge_station_id'];
            $pile_number = $m['pile_number'];
            ChargeStationModel::where('charge_station_id', $charge_station_id)->update(['charge_pile_num' => $pile_number]);
        }

        $charge_station_number = $station_number;
        $station_id = Db::table('charge_station')->where('charge_station_number', $charge_station_number)->value('charge_station_id');
        $station_name = Db::table('charge_station')->where('charge_station_number', $charge_station_number)->value('charge_station_name');
        $free = 0;
        $occupy = 0;
        $fault = 0;
        $i = 1;
        $mess = Db::table('charge_pile')->where('charge_station_id', $station_id)->select();
        foreach ($mess as $m) {
            if ($m['status'] == 1) {
                $free += 1;
            } elseif ($m['status'] == 2) {
                $occupy += 1;
            } elseif ($m['status'] == 3) {
                $occupy += 1;
            } elseif ($m['status'] == 255) {
                $fault += 1;
            }
            $no = Db::table('charge_pile')->where('charge_pile_id', $m['charge_pile_id'])->value('no');
            if ($no == null) {
                Db::table('charge_pile')->where('charge_pile_id', $m['charge_pile_id'])->update(['no' => $i]);
            }
            $i += 1;
        }
        $data_station = [
            'pile_free' => $free,
            'pile_occupy' => $occupy,
            'pile_fault' => $fault
        ];
        Db::table('charge_station')->where('charge_station_id', $station_id)->update($data_station);
        $lat1 = $lat;
        $lng1 = $lng;
        $lat2 = Db::table('charge_station')->where('charge_station_id', $station_id)->value('latitude');
        $lng2 = Db::table('charge_station')->where('charge_station_id', $station_id)->value('longitude');
        $distance = $this->getDistance($lat1, $lng1, $lat2, $lng2);
        $s = 0;
        $no_mess = Db::table('charge_pile')->where('charge_station_id', $station_id)->field('no,status,ConnectorId,VoltageUpperLimits')->orderRaw('CAST(no AS SIGNED) ASC')->select()->toArray();
        $xian = 0;
        foreach ($no_mess as $m) {
            if ($m['status'] == 1) {
                $xian++;
                $no_mess[$s]['code'] = '1';
                $no_mess[$s]['status'] = '空闲中';
            } elseif ($m['status'] == 2) {
                $no_mess[$s]['code'] = '2';
                $no_mess[$s]['status'] = '占用（未充电）';
            } elseif ($m['status'] == 3) {
                $no_mess[$s]['code'] = '3';
                $no_mess[$s]['status'] = '占用（充电中）';
            } elseif ($m['status'] == 255) {
                $no_mess[$s]['code'] = '255';
                $no_mess[$s]['status'] = '故障中';
            } elseif ($m['status'] == 0) {
                $no_mess[$s]['code'] = '0';
                $no_mess[$s]['status'] = '离网中';
            }
            $s += 1;
        }
        $Type = Db::table('charge_station')->where('charge_station_id', $station_id)->value('station_type');
        if ((int)$Type == 0) {
            $Type = '快充';
        } elseif ((int)$Type == 1) {
            $Type = '慢充';
        }

        $table = 'zxc_user_collect';
        $collect = Db::table($table)->where('openid', $openid)->where('charge_station_id', $station_id)->find();
        if (empty($collect)) {
            $is_collect = 0;
            $collect_message = '收藏';
        } else {
            $is_collect = 1;
            $collect_message = '取消收藏';
        }
        $info = Db::table('charge_station')->where('charge_station_id', $station_id)->field('longitude,latitude,address,ElectricityFee,ServiceFee')->find();
        $longitude = $info['longitude'];
        $latitude = $info['latitude'];
        $address = $info['address'];
        $electrovalence = $this->returnFree($info['ElectricityFee'], $info['ServiceFee']);

        $info2 = [
            'electrovalence' => $electrovalence,
            'station_name' => $station_name,
            'distance' => $distance,
            'is_collect' => $is_collect,
            'collect_message' => $collect_message,
            'pile' => $no_mess,
            'type' => $Type,
            'xian' => $xian,
        ];
        return json(array_merge($info, $info2));
    }

    public function charge_station_withpile(Request $request)
    {
        $sql = "SELECT charge_station_id,count(charge_station_id) pile_number FROM charge_pile GROUP BY charge_station_id HAVING count(charge_station_id)>1 ORDER BY charge_station_id";
        $message = Db::query($sql);
        foreach ($message as $m) {
            $charge_station_id = $m['charge_station_id'];
            $pile_number = $m['pile_number'];
            ChargeStationModel::where('charge_station_id', $charge_station_id)->update(['charge_pile_num' => $pile_number]);
        }
        $data = $request->param();
        $charge_station_number = $data['charge_station_number'];
        $station_id = Db::table('charge_station')->where('charge_station_number', $charge_station_number)->value('charge_station_id');
        $station_name = Db::table('charge_station')->where('charge_station_number', $charge_station_number)->value('charge_station_name');
        $free = 0;
        $occupy = 0;
        $fault = 0;
        $i = 1;
        $mess = Db::table('charge_pile')->where('charge_station_id', $station_id)->select();
        foreach ($mess as $m) {
            if ($m['status'] == 1) {
                $free += 1;
            } elseif ($m['status'] == 2) {
                $occupy += 1;
            } elseif ($m['status'] == 3) {
                $occupy += 1;
            } elseif ($m['status'] == 255) {
                $fault += 1;
            }
            $no = Db::table('charge_pile')->where('charge_pile_id', $m['charge_pile_id'])->value('no');
            if ($no == null) {
                Db::table('charge_pile')->where('charge_pile_id', $m['charge_pile_id'])->update(['no' => $i]);
            }
            $i += 1;
        }
        $data_station = [
            'pile_free' => $free,
            'pile_occupy' => $occupy,
            'pile_fault' => $fault
        ];
        Db::table('charge_station')->where('charge_station_id', $station_id)->update($data_station);
        $s = 0;
        $no_mess = Db::table('charge_pile')->where('charge_station_id', $station_id)->field('no,status')->select()->toArray();
        foreach ($no_mess as $m) {
            if ($m['status'] == 1) {
                $no_mess[$s]['status'] = '空闲中';
            } elseif ($m['status'] == 2) {
                $no_mess[$s]['status'] = '联通中';
            } elseif ($m['status'] == 3) {
                $no_mess[$s]['status'] = '充电中';
            } elseif ($m['status'] == 0) {
                $no_mess[$s]['status'] = '离网中';
            } elseif ($m['status'] == 255) {
                $no_mess[$s]['status'] = '故障中';
            } else {
                $no_mess[$s]['status'] = '未知状态';
            }
            $s += 1;
        }
        $info = [
            'charge_station_number' => $charge_station_number,
            'station_name' => $station_name,
            'pile' => $no_mess
        ];
        return json($info);
    }

    public function getDateFromRange($startdate, $enddate)
    {

        $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;
    }

    public function Order_Total(Request $request)
    {
        $data = $request->param();

// 基础UNION查询
//        $unionSql = "(SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney,
//             ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status,
//             start_time, openid, ConnectorID, charge_date
//      FROM charge_order_qianlongzhiyaozhan)
//      UNION ALL
//      (SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney,
//             ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status,
//             start_time, openid, ConnectorID, charge_date
//      FROM charge_order_kechuangzhongxin)
//      UNION ALL
//      (SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney,
//             ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status,
//             start_time, openid, ConnectorID, charge_date
//      FROM charge)";

        $where = [];

        switch ($data['mouth']) {
            case '月':
                $startDate = date('Y-m-01 00:00:00', strtotime($data['value']));
                $endDate = date('Y-m-t 23:59:59', strtotime($data['value']));
                break;

            case '季度':
                $year = (int)date('Y');
                $quarter = (int)$data['value'] ?? 1;


                $startMonth = ($quarter - 1) * 3 + 1;
                $endMonth = $quarter * 3;

                $startDate = date("Y-m-01 00:00:00", mktime(0, 0, 0, $startMonth, 1, $year));
                $endDate = date("Y-m-t 23:59:59", mktime(0, 0, 0, $endMonth, 1, $year));
                break;

            case '年':
                $year = isset($data['value']) && !empty($data['value']) ? $data['value'] : date('Y');
                $startDate = "$year-01-01 00:00:00";
                $endDate = "$year-12-31 23:59:59";
                break;

            default:
                $startDate = $data['start_time'] . ' 00:00:00';
                $endDate = $data['end_time'] . ' 23:59:59';
                break;
        }

// 获取所有充电站信息（先查询所有充电站，确保没有数据的也返回）
        $allStations = Db::table('charge_station')
            ->column('charge_station_name', 'charge_station_id');

// 初始化所有充电站统计数据
        $stationStats = [];
        foreach ($allStations as $id => $name) {
            $stationStats[$id] = [
                'charge_station_id' => $id,
                'charge_station_name' => $name,
                'TotalMoney' => 0,
                'TotalPower' => 0,
                'order_num' => 0
            ];
        }

// 查询并处理订单数据
//        $finalSql = "SELECT * FROM ($unionSql) AS temp_table WHERE charge_date BETWEEN ? AND ?";
//        $allOrders = Db::query($finalSql, [$startDate, $endDate]);
        $where[] = ['charge_date', '>=', $startDate];
        $where[] = ['charge_date', '<=', $endDate];
        $allOrders = Db::table('zxc_charge_order')->where($where)->select();

// 更新有数据的充电站统计
        foreach ($allOrders as $order) {
            $stationId = $order['charge_station_id'];
            if (isset($stationStats[$stationId])) {
                $stationStats[$stationId]['TotalMoney'] += $order['TotalMoney'];
                $stationStats[$stationId]['TotalPower'] += $order['TotalPower'];
                $stationStats[$stationId]['order_num']++;
            }
        }

// 格式化返回结果
        $result = array_values(array_map(function ($item) {
            return [
                'charge_station_id' => $item['charge_station_id'],
                'charge_station_name' => $item['charge_station_name'],
                'TotalMoney' => round($item['TotalMoney'], 2),
                'TotalPower' => round($item['TotalPower'], 2),
                'order_num' => $item['order_num']
            ];
        }, $stationStats));

        return $result;

    }

    public function FaultInfo()
    {
        $hasfault = Db::table('charge_pile')->whereRaw('status = 255 OR status = 0')->order('charge_pile_id desc')->count('charge_pile_id');
        $faultInfo = Db::table('charge_pile,charge_station')
            ->whereRaw('status = 255 OR status = 0')
            ->where('charge_pile.charge_station_id = charge_station.charge_station_id')
            ->order('charge_station.charge_station_id desc')
            ->field('charge_station.charge_station_id,charge_station_name,address,charge_pile.no,charge_pile.charge_pile_number,charge_station.area,charge_station.street,charge_pile.status')
            ->select();
        return json(['code' => 200, 'message' => '请求成功', 'count' => $hasfault, 'data' => $faultInfo]);
    }

    public function Time_Data(Request $request)
    {

        // 获取请求参数
        $data = $request->param();
        $timeType = $data['time_type'] ?: '日';
        $strDay = $data['str_time'] ?? '';
        $chargeStationName = $data['area'] ?? '';


        // 设置当前日期
        $currentDate = $strDay ?: date('Y-m-d');

        // 获取充电站ID

        $stationId = Db::table('charge_station')
            ->where('charge_station_name', $chargeStationName)
            ->value('charge_station_id');


        // 基础UNION查询
//        $unionSql = "(SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney,
//                 ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status,
//                 start_time, openid, ConnectorID, charge_date
//          FROM charge_order_qianlongzhiyaozhan)
//          UNION ALL
//          (SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney,
//                 ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status,
//                 start_time, openid, ConnectorID, charge_date
//          FROM charge_order_kechuangzhongxin)
//          UNION ALL
//          (SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney,
//                 ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status,
//                 start_time, openid, ConnectorID, charge_date
//          FROM charge)";

        // 根据时间类型设置查询范围
        switch ($timeType) {
            case '日':
                $startDate = $currentDate . ' 00:00:00';
                $endDate = $currentDate . ' 23:59:59';
                $where = '';
                if ($stationId) {
                    $where .= "charge_station_id = {$stationId} AND ";
                }
                $where .= "start_time BETWEEN '{$startDate}' AND '{$endDate}'";
                $groupBy = "DATE_FORMAT(start_time, '%H:00')";
                $timeFormat = "DATE_FORMAT(start_time, '%H:00') AS time";
                break;

            case '周':
                $monday = date('Y-m-d', strtotime('monday this week', strtotime($currentDate)));
                $sunday = date('Y-m-d', strtotime('sunday this week', strtotime($currentDate)));
                $startDate = $monday . ' 00:00:00';
                $endDate = $sunday . ' 23:59:59';
                $where = '';
                if ($stationId) {
                    $where .= "charge_station_id = {$stationId} AND ";
                }
                $where .= "charge_date BETWEEN '{$startDate}' AND '{$endDate}'";
                $groupBy = "DATE(charge_date)";
                $timeFormat = "DATE(charge_date) AS time";
                break;

            case '月':
                $firstDay = date('Y-m-01', strtotime($currentDate));
                $lastDay = date('Y-m-t', strtotime($currentDate));
                $startDate = $firstDay . ' 00:00:00';
                $endDate = $lastDay . ' 23:59:59';
                $where = '';
                if ($stationId) {
                    $where .= "charge_station_id = {$stationId} AND ";
                }
                $where .= "charge_date BETWEEN '{$startDate}' AND '{$endDate}'";
                $groupBy = "WEEK(charge_date, 1)";
                $timeFormat = "CONCAT('第', WEEK(charge_date, 1) - WEEK('{$firstDay}', 1) + 1, '周') AS time";
                break;

            case '年':
                $firstDay = date('Y-01-01', strtotime($currentDate));
                $lastDay = date('Y-12-31', strtotime($currentDate));
                $startDate = $firstDay . ' 00:00:00';
                $endDate = $lastDay . ' 23:59:59';
                $where = '';
                if ($stationId) {
                    $where .= "charge_station_id = {$stationId} AND ";
                }
                $where .= "charge_date BETWEEN '{$startDate}' AND '{$endDate}'";
                $groupBy = "MONTH(charge_date)";
                $timeFormat = "CONCAT(MONTH(charge_date), '月') AS time";
                break;

            default:
                return json(['error' => '不支持的查询类型'], 400);
        }

        // 构建完整SQL查询
//        $sql = "SELECT
//                {$timeFormat},
//                SUM(TotalMoney) AS revenue,
//                SUM(TotalPower) AS degree,
//                COUNT(*) AS order_num,
//                SUM(SeviceMoney) AS service_money
//            FROM ({$unionSql}) AS combined_tables
//            WHERE {$where}
//            GROUP BY {$groupBy}
//            ORDER BY time";

        // 执行查询
//        $result = Db::query($sql);

        $result = Db::table('zxc_charge_order')->where($where)
            ->field("{$timeFormat},SUM(TotalMoney) AS revenue,SUM(TotalPower) AS degree,
                COUNT(*) AS order_num,
                SUM(SeviceMoney) AS service_money")
            ->order($groupBy)->select();

        // 计算总量
        $total = [
            'revenue' => 0,
            'degree' => 0,
            'order_num' => 0,
            'service_money' => 0
        ];

        $perData = [];
        foreach ($result as $item) {
            $perData[] = [
                'time' => $item['time'],
                'data' => [
                    'revenue' => round($item['revenue'], 2),
                    'degree' => round($item['degree'], 2),
                    'order_num' => $item['order_num'],
                    'service_money' => round($item['service_money'], 2)
                ]
            ];

            $total['revenue'] += $item['revenue'];
            $total['degree'] += $item['degree'];
            $total['order_num'] += $item['order_num'];
            $total['service_money'] += $item['service_money'];
        }

        // 格式化总量数据
        $total = [
            'revenue' => round($total['revenue'], 2),
            'degree' => round($total['degree'], 2),
            'order_num' => $total['order_num'],
            'sevice_money' => round($total['service_money'], 2)
        ];

        return json([
            'per' => $perData,
            'total' => $total
        ]);

    }


    //待整改
    public function Time_Data_Total(Request $request)
    {
        $data = $request->param();
        $time_type = $data['time_type'] ?? '周';
        $str_day = $data['str_time'] ?? date('Y-m-d', time());
        $time = strtotime($str_day);
        $date_time = date('Y-m-d', $time);

        // 基础UNION查询
        $unionSql = "(SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney, 
                 ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status, 
                 start_time, openid, ConnectorID, charge_date
          FROM charge_order_qianlongzhiyaozhan) 
          UNION ALL 
          (SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney, 
                 ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status, 
                 start_time, openid, ConnectorID, charge_date
          FROM charge_order_kechuangzhongxin)
          UNION ALL 
          (SELECT charge_station_id, order_number, order_id, TotalPower, TotalMoney, 
                 ElecMoney, SeviceMoney, end_time, EndTime, DetailMessage, status, 
                 start_time, openid, ConnectorID, charge_date
          FROM charge)";

        // 初始化结果数组
        $mess = [
            'per' => [],
            'total' => [
                'revenue' => 0,
                'degree' => 0,
                'order_num' => 0,
                'service_money' => 0
            ]
        ];

        // 根据时间类型处理数据
        switch ($time_type) {
            case '日':
                $start_time = date('Y-m-d 00:00:00', $time);
                $date_ranges = $this->getDayDate($start_time);
                $date_start = $date_ranges['start_time'];
                $date_end = $date_ranges['end_time'];

                foreach ($date_start as $i => $d_start) {
                    $interval = substr($date_start[$i], 11) . '~' . substr($date_end[$i], 11);
                    $this->processTimeRange($mess, $unionSql, $date_start[$i], $date_end[$i], $interval);
                }
                break;

            case '周':
                $end_time = date("Y-m-d 23:59:59", strtotime("$date_time Saturday"));
                $start_time = date("Y-m-d 00:00:00", strtotime("$end_time - 6 days"));
                $dates = $this->getDateFromRange($start_time, $end_time);

                foreach ($dates as $d) {
                    $this->processTimeRange($mess, $unionSql, "$d 00:00:00", "$d 23:59:59", $d);
                }
                break;

            case '月':
                $start_time = date("Y-m-d", strtotime(date('Y-m-01', $time)));
                $dates = $this->getMonthDate($start_time);
                $i = 1;

                foreach ($dates as $d) {
                    $week_label = '第' . $i . '周';
                    $this->processTimeRange($mess, $unionSql, "$d 00:00:00", date('Y-m-d 23:59:59', strtotime("$d +6 days")), $week_label);
                    $i++;
                }
                break;

            case '季':
                $season = ceil(date('m', $time) / 3);
                $start_month = $season * 3 - 2;
                $start_time = date("Y-m-d H:i:s", strtotime(date("Y-{$start_month}-01", $time)));
                $end_time = date("Y-m-d 23:59:59", strtotime("$start_time +3 month -1 day"));
                $dates = $this->getSeasonDate($start_time);
                $i = date("m", strtotime($start_time));

                foreach ($dates as $d) {
                    $month_label = $i . '月';
                    $this->processTimeRange($mess, $unionSql, "$d 00:00:00", date('Y-m-d 23:59:59', strtotime("$d +1 month -1 day")), $month_label);
                    $i++;
                }
                break;

            case '年':
                $start_time = date('Y-01-01 00:00:00', $time);
                $dates = $this->getYearDate($start_time);
                $i = 1;

                foreach ($dates as $d) {
                    $month_label = $i . '月';
                    $this->processTimeRange($mess, $unionSql, "$d-01 00:00:00", "$d-" . date('t', strtotime($d)) . " 23:59:59", $month_label);
                    $i++;
                }
                break;
        }

        // 格式化金额数据
        $mess['total']['revenue'] = round($mess['total']['revenue'], 2);
        $mess['total']['degree'] = round($mess['total']['degree'], 2);
        $mess['total']['service_money'] = round($mess['total']['service_money'], 2);

        return json($mess);
    }

    /**
     * 处理时间范围数据
     */
    private function processTimeRange(&$mess, $unionSql, $start_time, $end_time, $label)
    {

        // 查询该时间范围内的数据
        $sql = "SELECT * FROM ($unionSql) AS temp_table 
            WHERE charge_date BETWEEN ? AND ?";
        $orders = Db::query($sql, [$start_time, $end_time]);

        // 计算统计数据
        $revenue = 0;
        $degree = 0;
        $order_num = count($orders);
        $service = 0;

        foreach ($orders as $order) {
            $revenue += $order['TotalMoney'];
            $degree += $order['TotalPower'];

            // 服务费计算逻辑
            if (strtotime($start_time) < strtotime('2023-02-03 00:00:00')) {
                $service += round($order['TotalPower'] * 0.2, 2);
            } else {
                $service += $order['SeviceMoney'];
            }
        }

        // 更新结果数组
        $mess['per'][] = [
            'time' => $label,
            'data' => [
                'revenue' => round($revenue, 2),
                'degree' => round($degree, 2),
                'order_num' => $order_num,
                'service_money' => round($service, 2)
            ]
        ];

        $mess['total']['revenue'] += $revenue;
        $mess['total']['degree'] += $degree;
        $mess['total']['order_num'] += $order_num;
        $mess['total']['service_money'] += $service;
    }


    public function Recharge_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')->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) {

                $table = 'zxc_charge_order';
                $table_recharge = 'zxc_recharge';
                $result = Db::table($table)->select();
                if (empty($result)) {
                    continue;
                } else {
                    $revenue = Db::table($table_recharge)->whereDay('success_time', $d)->sum('total');
                    $order_num = Db::table($table_recharge)->whereDay('success_time', $d)->count();
                }

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

            }
            $mess['total'] = ['revenue' => round($revenue_total / 100, 2), 'order_num' => $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;
                foreach ($area as $a) {
                    $table = 'zxc_charge_order';
                    $table_recharge = 'zxc_recharge';
                    $result = Db::table($table)->select();
                    if (empty($result)) {
                        continue;
                    } else {
                        $order = Db::table($table);
                        $recharge = Db::table($table_recharge);
                        $revenue = $recharge->whereWeek('success_time', $d)->sum('total');
                        $order_num = $recharge->whereWeek('success_time', $d)->count();

                    }
                }
                $mess['per'][] = ['time' => $z, 'data' => ['revenue' => round($revenue / 100, 2), 'order_num' => $order_num]];
                $revenue_total += $revenue;
                $order_num_total += $order_num;
                $i += 1;
            }
            $mess['total'] = ['revenue' => round($revenue_total / 100, 2), 'order_num' => $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;
                foreach ($area as $a) {
                    $table = 'zxc_charge_order';
                    $table_recharge = 'zxc_recharge';
                    $result = Db::table($table)->select();
                    if (empty($result)) {
                        continue;
                    } else {
                        $recharge = Db::table($table_recharge);
                        $revenue = $recharge->whereMonth('success_time', $d)->sum('total');
                        $order_num = $recharge->whereMonth('success_time', $d)->count();

                    }
                }
                $mess['per'][] = ['time' => $z, 'data' => ['revenue' => round($revenue / 100, 2), 'order_num' => $order_num]];
                $revenue_total += $revenue;
                $order_num_total += $order_num;
                $i += 1;
            }
            $mess['total'] = ['revenue' => round($revenue_total / 100, 2), 'order_num' => $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;

                foreach ($area as $a) {
                    $table = 'zxc_charge_order';
                    $table_recharge = 'zxc_recharge';
                    $result = Db::table($table)->select();
                    if (empty($result)) {
                        continue;
                    } else {
                        $recharge = Db::table($table_recharge);
                        $revenue = $recharge->whereMonth('success_time', $d)->sum('total');
                        $order_num = $recharge->whereMonth('success_time', $d)->count();

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

    public function The_Last_Five($lat, $lng, $openid)
    {


        //更新所有站的充电桩数量统计
        $sql = "SELECT charge_station_id,count(charge_station_id) pile_number FROM charge_pile GROUP BY charge_station_id HAVING count(charge_station_id)>1 ORDER BY charge_station_id";
        $message = Db::query($sql);
        foreach ($message as $m) {
            $charge_station_id = $m['charge_station_id'];
            $pile_number = $m['pile_number'];
            ChargeStationModel::where('charge_station_id', $charge_station_id)->update(['charge_pile_num' => $pile_number]);
        }


        //获取附近充电站并按距离排序
        $lat1 = $lat;
        $lng1 = $lng;
        $list = Db::table('charge_station')->select();
        $mess = array();
        foreach ($list as $l) {
            $distance = $this->getDistance($lat1, $lng1, $l['latitude'], $l['longitude']);
            $mess[$l['charge_station_id']] = $distance;
        }
        asort($mess);

        //站点信息
        $ss = array();
        $a = 0;
        foreach ($mess as $key => $value) {

            $info = Db::table('charge_station')->where('charge_station_id', $key)->find();


            $mess = Db::table('charge_pile')->where('charge_station_id', $key)->select();
            $free = 0;
            $occupy = 0;
            $fault = 0;
            foreach ($mess as $m) {
                if ($m['status'] == 1) {
                    $free += 1;
                } elseif ($m['status'] == 2) {
                    $occupy += 1;
                } elseif ($m['status'] == 3) {
                    $occupy += 1;
                } elseif ($m['status'] == 255) {
                    $fault += 1;
                }
            }
            Db::table('charge_station')->where('charge_station_id', $key)->update([
                'pile_free' => $free,
                'pile_occupy' => $occupy,
                'pile_fault' => $fault
            ]);


            $kk['electrovalence'] = $this->returnFree($info['ElectricityFee'], $info['ServiceFee']);
            $kk['ChargeStationNumber'] = $info['charge_station_number'];
            $kk['ChargeStationName'] = $info['charge_station_name'];
            $kk['Free'] = $free;
            $kk['Occupy'] = $occupy;
            $kk['Fault'] = $fault;
            $kk['Distance'] = $value;
            $kk['is_show'] = ($a == 0 && $value * 1000 < 100) ? '当前站点' : '';
            $kk['type'] = $info['station_type'] == 0 ? '快充' : '慢充';
            $kk['longitude'] = $info['longitude'];
            $kk['latitude'] = $info['latitude'];
            $kk['address'] = $info['address'];

            $ss[] = $kk;
            $a++;
        }
        return json($ss);
    }


    public function SearchStation($message, $lat, $lng, $openid)
    {

        $table = 'zxc_user_collect';
        $lat1 = $lat;
        $lng1 = $lng;
        $list = Db::table('charge_station')->where('charge_station_number|charge_station_name', 'like', '%' . $message . '%')->select();
        $mess = array();
        foreach ($list as $l) {
            $charge_station_id = $l['charge_station_id'];
            $lat2 = $l['latitude'];
            $lng2 = $l['longitude'];
            $distance = $this->getDistance($lat1, $lng1, $lat2, $lng2);
            $mess[$charge_station_id] = $distance;
        }
        asort($mess);
        $l = 1;
        $ss = array();
        foreach ($mess as $key => $value) {
            $distance = $value;
            $sql = "SELECT charge_station_id,count(charge_station_id) pile_number FROM charge_pile GROUP BY charge_station_id HAVING count(charge_station_id)>1 ORDER BY charge_station_id";
            $message = Db::query($sql);
            foreach ($message as $m) {
                $charge_station_id = $m['charge_station_id'];
                $pile_number = $m['pile_number'];
                ChargeStationModel::where('charge_station_id', $charge_station_id)->update(['charge_pile_num' => $pile_number]);
            }
            $station_id = $key;
            $station_name = Db::table('charge_station')->where('charge_station_id', $station_id)->value('charge_station_name');
            $station_number = Db::table('charge_station')->where('charge_station_id', $station_id)->value('charge_station_number');
            $Type = Db::table('charge_station')->where('charge_station_id', $station_id)->value('station_type');
            if ((int)$Type == 0) {
                $Type = '快充';
            } elseif ((int)$Type == 1) {
                $Type = '慢充';
            }
            $free = 0;
            $occupy = 0;
            $fault = 0;
            $i = 1;
            $mess = Db::table('charge_pile')->where('charge_station_id', $station_id)->select();
            foreach ($mess as $m) {
                if ($m['status'] == 1) {
                    $free += 1;
                } elseif ($m['status'] == 2) {
                    $occupy += 1;
                } elseif ($m['status'] == 3) {
                    $occupy += 1;
                } elseif ($m['status'] == 255) {
                    $fault += 1;
                }
                $no = Db::table('charge_pile')->where('charge_pile_id', $m['charge_pile_id'])->value('no');
                if ($no == null) {
                    Db::table('charge_pile')->where('charge_pile_id', $m['charge_pile_id'])->update(['no' => $i]);
                }
                $i += 1;
            }
            $data_station = [
                'pile_free' => $free,
                'pile_occupy' => $occupy,
                'pile_fault' => $fault
            ];
            Db::table('charge_station')->where('charge_station_id', $station_id)->update($data_station);

            $collect = Db::table($table)->where('openid', $openid)->where('charge_station_id', $station_id)->find();
            if (empty($collect)) {
                $is_collect = 0;
                $collect_message = '收藏';
            } else {
                $is_collect = 1;
                $collect_message = '取消收藏';
            }
            $info = Db::table('charge_station')->where('charge_station_id', $station_id)->field('longitude,latitude,address,ElectricityFee,ServiceFee')->find();
            $longitude = $info['longitude'];
            $latitude = $info['latitude'];
            $address = $info['address'];
            $kk['ChargeStationNumber'] = $station_number;
            $kk['ChargeStationName'] = $station_name;
            $kk['Free'] = $free;
            $kk['Occupy'] = $occupy;
            $kk['Fault'] = $fault;
            $kk['Distance'] = $distance;
            $kk['is_collect'] = $is_collect;
            $kk['type'] = $Type;
            $kk['message'] = $collect_message;
            $kk['longitude'] = $longitude;
            $kk['latitude'] = $latitude;
            $kk['address'] = $address;

            $ss[] = $kk;
        }
        return json($ss);
    }

    public function GetDiscounts($openid)
    {
        $discounts = Db::table('discount')->where('id', 1)->value('message');
        return json(['code' => 200, 'message' => $discounts]);
    }


    public function getConnectorIDCharge(){
        $params = input();
        if($params['ConnectorID']){
            $info = Db::table('charge_pile')->where('ConnectorID',$params['ConnectorID'])->find();
            $info['parent'] = Db::table('charge_station')->where('charge_station_id',$info['charge_station_id'])->value('charge_station_name');
            return json($info);
        }
         return json([]);
    }
}



