<?php
declare (strict_types=1);

namespace app\controller;

use app\common;
use app\model\ChargeOrder as ChargeOrderModel;
use app\model\ChargeStation as ChargeStationModel;
use app\model\ServiceFee;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;
use think\helper\Str;
use think\Request;

class ChargeOrder extends common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = ChargeOrderModel::withSearch(['order_number', 'charge_station_id', 'openid', 'charge_date', 'status'], [
            'order_number' => request()->param('order_number'),
            'charge_station_id' => request()->param('charge_station_id'),
            'openid' => request()->param('openid'),
            'charge_date' => request()->param('charge_date'),
            'status' => request()->param('status'),
        ])->paginate([
            'list_rows' => 20,
            'query' => request()->param()
        ]);

        return json($list);
    }


    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function FuzzyOrder($charge_station_name = '', $message = '', $start_time = '', $end_time = '', $order = ''): \think\response\Json
    {

        $where = [];

        if ($message) {
            $where[] = ['message', 'like', '%' . $message . '%'];
        }

        if ($charge_station_name) {
            $charge_station_id = Db::table('charge_station')->where('charge_station_name', $charge_station_name)->value('charge_station_id');
            if ($charge_station_id) {
                $where[] = ['charge_station_id', '=', $charge_station_id];
            }
        }

        if ($start_time) {
            $where[] = ['start_time', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['start_time', '<=', $end_time];
        }


        $list = Db::table('zxc_charge')
            ->where($where)
            ->order('start_time desc')
            ->field('charge_station_id,order_number,order_id,TotalPower,TotalMoney,ElecMoney,SeviceMoney,end_time,EndTime,DetailMessage,status,start_time,openid')
            ->select();  // 获取全部数据


        foreach ($list as $key => &$value) {
            $value['charge_station_name'] = Db::table('charge_station')->where('charge_station_id', $value['charge_station_id'])->value('charge_station_name');
            $phone = Db::table('zxc_user')->where('openid', $value['openid'])->value('phone');
            $value['phone'] = $phone;
        }

        return json($list);
    }


    public function GennerateOrder($openid, $station_number, $no, $account)
    {

        $table = 'zxc_charge_order';
        $table_user = 'zxc_user';

        $balance = Db::table($table_user)->where('openid', $openid)->value('account');

        $exit = Db::table($table)->where('openid', $openid)->find();
        $exit2 = Db::table($table)->where('openid', $openid)->order('order_id desc')->value('end_time');

        if (($balance - $account) >= 0 && ($openid == "o-wLg5DGWU_rYwfmp1-1Wck1lKGw" || (empty($exit) || !empty($exit2)))) {
            return $this->Charge($station_number, $no, $openid, $table, $table_user, $account);
        } elseif (($balance - $account) < 0) {
            return json(['code' => 3, 'message' => '余额不足 请充值']);
        } else {
            return json(['code' => 1, 'message' => '请先完成当前订单']);
        }
    }


    protected function Charge($station_number, $no, $openid, $table, $table_user, $account): \think\response\Json
    {

        $station_id = Db::table('charge_station')->where('charge_station_number', $station_number)->value('charge_station_id');
        $ConnectorID = Db::table('charge_pile')->where(['charge_station_id' => $station_id, 'no' => $no])->value('ConnectorID');
        $EquipAuthSeq = Db::table('charge_pile')->where(['charge_station_id' => $station_id, 'no' => $no])->value('EquipAuthSeq');
        if (empty($EquipAuthSeq)) {
            $EquipAuthSeq = $this->generate_EquipmentAuth(7);
            Db::table('charge_pile')->where(['charge_station_id' => $station_id, 'no' => $no])->update(['EquipAuthSeq' => $EquipAuthSeq]);
        }

        $Hard = new HardMessage();
        $AuthMessage = $Hard->Get_query_equip_auth($EquipAuthSeq, $ConnectorID);

        if (isset($AuthMessage['FailReason']) && isset($AuthMessage['SuccStat'])) {//认证成功 请求启动充电

            if ($AuthMessage['FailReason'] == 0 && $AuthMessage['SuccStat'] == 0) {
                $StartChargeSeq = $this->generate_StartChargeSeq(7);
                ChargeOrderModel::insert(['openid' => $openid, 'StartChargeSeq' => $StartChargeSeq]);
                $ChargeModel = 2;

                $StartCharge = $Hard->Get_query_start_charge_test($StartChargeSeq, $ConnectorID, 'QRCode', $ChargeModel);


                if ($StartCharge['StartChargeSeqStat'] == 1 && $StartCharge['SuccStat'] == 0 && $StartCharge['FailReason'] == 0) {
                    $check = Db::table($table)->where('openid', $openid)->order('order_id desc')->value('end_time');
                    $check2 = Db::table($table)->where('openid', $openid)->find();
                    if ((!empty($check) || empty($check2))) {
                        $order_number = $this->generate_order(6);

                        $charge_date = date('Y-m-d', time());
                        $Equipment_number = Db::table('charge_pile')->where([
                            ['charge_station_id', '=', $station_id],
                            ['no', '=', $no]
                        ])->value('charge_pile_number');
                        $mess = [
                            'order_number' => $order_number,
                            'charge_station_id' => $station_id,
                            'openid' => $openid,
                            'charge_date' => $charge_date,
                            'Equipment_number' => $Equipment_number,
                            'StartChargeSeq' => $StartChargeSeq,
                            'status' => $StartCharge['StartChargeSeqStat'],
                            'StartChargeSeqStat' => $StartCharge['StartChargeSeqStat'],
                            'ConnectorID' => $ConnectorID,
                            'WithholdingMoney' => $account
                        ];
                        Db::table($table_user)->where('openid', $openid)->update(['account' => Db::raw('account-' . $account)]);
                        Db::table($table)->save($mess);

                        return json(['code' => 200, 'message' => '订单创建成功', 'order_number' => $order_number, 'info' => Db::table($table)->where(['order_number' => $order_number])->find()]);
                    } else {
                        return json(['code' => 1, 'message' => '请不要点击过快']);
                    }
                } elseif ($StartCharge['SuccStat'] == 1) {
                    if ($StartCharge['FailReason'] == 0) {
                        return json(['code' => 1, 'message' => '设备认证操作结果失败5']);
                    } elseif ($StartCharge['FailReason'] == 1) {
                        return json(['code' => 1, 'message' => '设备认证操作结果失败 此设备不存在']);
                    } elseif ($StartCharge['FailReason'] == 2) {
                        return json(['code' => 1, 'message' => '设备认证操作结果失败 此设备离线']);
                    } elseif ($StartCharge['FailReason'] == 90) {
                        return json(['code' => 1, 'message' => '设备认证操作结果失败 车辆未备案']);
                    } elseif ($StartCharge['FailReason'] == 91) {
                        return json(['code' => 1, 'message' => '设备认证操作结果失败 该车辆充电中']);
                    } else {
                        return json(['code' => 1, 'message' => '未知错误 设备认证成功 请求充电失败']);
                    }
                } else {
                    return json(['code' => 1, 'message' => '未知错误 设备认证成功 请求充电失败']);
                }
            } elseif ($AuthMessage['SuccStat'] == 1) {
                if ($AuthMessage['FailReason'] == 0) {
                    return json(['code' => 1, 'message' => '设备认证操作结果失败3']);
                } elseif ($AuthMessage['FailReason'] == 1) {
                    return json(['code' => 1, 'message' => '设备认证操作结果失败 此设备尚未插枪']);
                } elseif ($AuthMessage['FailReason'] == 2) {
                    return json(['code' => 1, 'message' => '设备认证操作结果失败 设备检测失败']);
                } else {
                    return json(['code' => 1, 'message' => '未知错误 设备认证失败4']);
                }
            } else {
                return json(['code' => 1, 'message' => '未知错误 设备认证失败2']);
            }
        } else {
            return json(['code' => 1, 'message' => '未知错误 设备认证失败1']);
        }
    }


    // 潜江充电模式
    public function GennerateOrder2()
    {

        $params = input();

        //启动前验证

        $check = $this->startChargeCheck($params);

        if ($check && $check['code'] == 1) {
            return json(['code' => 1, 'message' => $check['message']]);
        }


        $openid = $params['openid'];
        $account = $params['account'];
        $type = $params['type'];

        //认证成功 生成系统充电订单号
        $StartChargeSeq = $this->generate_StartChargeSeq(7);


        if ($type == 1) {// 即充即退
//
//            $time = time();
//            Db::table('zxc_charge_order')->save([
//                'type' => 1,
//                'openid' => 'obUtOvjCdTSrZTqbjTByESPo6kLE',
//                'directly_pay_no' => '1217752501201407033233368026',
//                'directly_pay_status' => 1,
//                'directly_pay_time' => $time,
//                'directly_prepaid_amount' => $account,
//                'WithholdingMoney' => $account,
//                'start_time' => date('Y-m-d H:i:s', $time),
//            ]);
//
//            Db::table('zxc_charge')->save([
//                'type' => 2,
//                'openid' => 'obUtOvjCdTSrZTqbjTByESPo6kLE',
//                'out_trade_no' => $StartChargeSeq,
//                'transaction_id' => '1217752501201407033233368026',
//                'trade_state' => 1,
//                'total' => $account,
//                'payer_total' => $account,
//                'success_time' => date('Y-m-d H:i:s', $time),
//            ]);
//
//            \app\model\User::addMoneyLog('obUtOvjCdTSrZTqbjTByESPo6kLE', $account, 2, '用户使用即充即退');


            //返回支付信息 生成充电订单
            $out_trade_no = $this->generate_order(6);
            $pay_info = (new WechatPay())->directlyConfig($out_trade_no, $params['openid'], $account);
            $pay_info['StartChargeSeq'] = $StartChargeSeq;
            return json(['code' => 2, 'message' => '获取支付参数', 'data' => $pay_info]);

//            return json(['code' => 200, 'message' => '可以充值', 'data' => ['StartChargeSeq' => $StartChargeSeq]]);
        } elseif ($type == 2) { // 个人钱包充电
            // 判断余额
            // 账户余额
            $balance = Db::table('zxc_user')->where('openid', $openid)->value('account');

            if ($balance < 20) {
                return json(['code' => 1, 'message' => '余额不足 请充值']);
            }
            return json(['code' => 200, 'message' => '可以充值', 'data' => ['StartChargeSeq' => $StartChargeSeq]]);

        } elseif ($type == 3) { // 企业充电
            // 判断余额

        } else {
            return json(['code' => 1, 'message' => '参数错误']);
        }

    }

    //潜江充电----启动充电
    public function startCharging()
    {


        $params = input();

        //是否存在订单号
        $StartChargeSeq = $params['StartChargeSeq'];
        if (!$StartChargeSeq) {
            return json(['code' => 1, 'message' => '请求失败']);
        }

        //启动前验证
        $check = $this->startChargeCheck($params, true);

        if ($check && $check['code'] == 1) {
            return json(['code' => 1, 'message' => $check['message']]);
        }


        //生成充电桩唯一标识
        $charge_pile_info = Db::table('charge_pile')->where('ConnectorID', $params['ConnectorId'])->find();
        if (empty($charge_pile_info['EquipAuthSeq'])) {
            $EquipAuthSeq = $this->generate_EquipmentAuth(7);
            Db::table('charge_pile')->where(['ConnectorID' => $params['ConnectorId']])->update(['EquipAuthSeq' => $EquipAuthSeq]);
        }

        $result = false;
        //创建系统订单
        $order_number = $this->generate_order(6);
        $charge_date = date('Y-m-d', time());
        $save_data = [
            'StartChargeSeq' => $StartChargeSeq,
            'order_number' => $order_number,
            'charge_station_id' => $charge_pile_info['charge_station_id'],
            'openid' => $params['openid'],
            'charge_date' => $charge_date,
            'Equipment_number' => $charge_pile_info['charge_pile_number'],
            'status' => $StartCharge['StartChargeSeqStat'] ?? '',
            'StartChargeSeqStat' => $StartCharge['StartChargeSeqStat'] ?? '',
            'ConnectorID' => $params['ConnectorId'],
            'WithholdingMoney' => $params['account'],
            'type' => $params['type']
        ];

        if ($params['type'] == 1) {//通过支付后回调产生订单更新订单号
            $result = Db::table('zxc_charge_order')->where('directly_pay_no', $params['out_trade_no'])->update($save_data);
        } else if ($params['type'] == 2) {
            $result = Db::table('zxc_charge_order')->save($save_data);
        }

        if ($result) {
            //请求充电
            $Hard = new HardMessage();
            $StartCharge = $Hard->Get_query_start_charge_test($StartChargeSeq, $params['ConnectorId'], 'QRCode', 2);
            if ($StartCharge['StartChargeSeqStat'] != 1) {
                Db::table('zxc_charge_order')->where(['order_number' => $order_number])->delete();

                return json(['code' => 1, 'message' => '充电启动失败' . $StartCharge['FailReason']]);
            }

            $info = Db::table('zxc_charge_order')->where(['order_number' => $order_number])->find();
            return json(['code' => 200, 'message' => '订单创建成功', 'order_number' => $order_number, 'info' => $info]);
        }

        return json(['code' => 1, 'message' => '系统出错啦~']);

    }


    //潜江充电前验证
    public function startChargeCheck($params, $status = false)
    {

        //1.订单验证
        $exit2 = Db::table('zxc_charge_order')
            ->where('openid', $params['openid'])
            ->where('end_time', '=', null)
            ->find();
        if ($exit2 && !$status) {
            return ['code' => 1, 'message' => '存在未结束订单'];
        }

        //2.设备信息验证和更新
        $charge_pile_info = Db::table('charge_pile')
            ->where('ConnectorID', $params['ConnectorId'])
            ->find();
        $EquipAuthSeq = $charge_pile_info['EquipAuthSeq'];
        if (empty($EquipAuthSeq)) {
            $EquipAuthSeq = $this->generate_EquipmentAuth(7);
            Db::table('charge_pile')
                ->where(['ConnectorID' => $params['ConnectorId']])
                ->update(['EquipAuthSeq' => $EquipAuthSeq]);
        }

        //3设备认证
        $Hard = new HardMessage();
        $AuthMessage = $Hard->Get_query_equip_auth($EquipAuthSeq, $params['ConnectorId']);
        if ($AuthMessage['SuccStat'] != 0) {
            $arr = [
                '0' => '无',
                '1' => '此设备尚未插枪',
                '2' => '设备检测失败',
            ];
            return ['code' => 1, 'message' => $arr[$AuthMessage['FailReason']] ?? '设备认证1-自定义错误信息' . $AuthMessage['FailReason']];
        }
        return ['code' => 2];
    }

    public function QRCode($address, $openid)
    {
        $exit = Db::table('user')->where('openid', $openid)->value('area');
        if (!empty($exit)) {
            $ConnectorID = substr($address, 7, 13);
            $OperatorID = substr($address, 21, 9);
            if ($OperatorID != '395815801') {
                return json(['code' => 1, 'message' => '运营商出现问题']);
            }
            $Equipment = Db::table('charge_pile')->where('ConnectorID', $ConnectorID)->find();
            $Station_id = $Equipment['charge_station_id'];
            $Station_number = Db::table('charge_station')->where('charge_station_id', $Station_id)->value('charge_station_number');
            $Station_name = Db::table('charge_station')->where('charge_station_id', $Station_id)->value('charge_station_name');
            $no = $Equipment['no'];
            $status = $Equipment['status'];
            if ($status == 3 || $status == 4) {
                return json(['code' => 1, 'message' => '该充电桩已被占用']);
            } elseif ($status == 255) {
                return json(['code' => 1, 'message' => '该充电桩故障']);
            } elseif ($status == 1 || $status == 2) {
                $kk['station_name'] = $Station_name;
                $kk['station_number'] = $Station_number;
                $kk['no'] = $no;
                return json(['code' => 200, 'message' => '成功', 'data' => $kk]);
            } elseif ($status == 0) {
                return json(['code' => 1, 'message' => '该充电桩离网']);
            }

        } else {
            return json(['code' => 1, 'message' => '没有获取到地址信息 请先登录']);
        }

    }

    public function OrderDetail($openid, $order_number)
    {

        $table = 'zxc_charge_order';

        $StartChargeSeq = Db::table($table)->where('order_number', $order_number)->value('StartChargeSeq');
        $Equipment_number = Db::table($table)->where('order_number', $order_number)->value('Equipment_number');
        $message['charge_length'] = null;
        $status = Db::table($table)->where('order_number', $order_number)->value('status');
        $end_time = Db::table($table)->where('order_number', $order_number)->value('end_time');

        if (empty($end_time) && ($status == 2)) {
            $Hard = new HardMessage();
            $Hard->Get_query_equip_charge_status($StartChargeSeq);
        }

        $message = Db::table($table)->where('order_number', $order_number)->find();
        $start_time = Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->value('start_time');
        $end_time = Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->value('end_time');

        if (isset($message['start_time']) && strtotime($message['start_time']) < strtotime('2099-02-03 00:00:00') && $message['status'] == 4) {
            $station_type = \app\model\ChargeStation::where('charge_station_id', $message['charge_station_id'])->value('station_type');
            if ($station_type == 0) {
                $message['SeviceMoney'] = round($message['TotalPower'] * 0.2, 2);
            } else {
                $message['SeviceMoney'] = round($message['TotalPower'] * 0.4, 2);
            }
            $message['ElecMoney'] = round($message['TotalMoney'] - $message['SeviceMoney'], 2);
        } else {
            $message['ElecMoney'] = Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->value('ElecMoney');
            $message['SeviceMoney'] = Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->value('SeviceMoney');
        }

        if (!empty($end_time)) {
            $charge_length = (strtotime($end_time) - strtotime($start_time)) % 86400 / 3600;
            Db::table($table)->where('order_number', $order_number)->update(['charge_length' => $charge_length]);
            $message['charge_length'] = $charge_length;
        }
        $charge_station_id = Db::table($table)->where('order_number', $order_number)->value('charge_station_id');
        $charge_station_number = Db::table('charge_station')->where('charge_station_id', $charge_station_id)->value('charge_station_number');
        $charge_station_name = Db::table('charge_station')->where('charge_station_id', $charge_station_id)->value('charge_station_name');
        $no = Db::table('charge_pile')->where('charge_pile_number', $Equipment_number)->value('no');
        if ($message['TotalPower'] == null) {
            $message['TotalPower'] = 0;
        }
        $message['TotalPower'] = number_format($message['TotalPower'], 3);
        $message['charge_station_number'] = $charge_station_number;
        $message['charge_station_name'] = $charge_station_name;
        $message['no'] = $no;
        if ($message['status'] == 1) {
            $message['message'] = '启动中';
        } elseif ($message['status'] == 2) {
            $message['message'] = '充电中';
        } elseif ($message['status'] == 3) {
            $message['message'] = '停止中';
        } elseif ($message['status'] == 4) {
            $message['message'] = '已结束';
        } elseif ($message['status'] == 5) {
            $message['message'] = '未知错误';
        }


        if (strlen((string)$message['stop_type']) != 0 && $message['stop_type'] == 0) {
            $message['stop_type'] = '正常停止';
        } elseif ($message['stop_type'] == 4) {
            $message['stop_type'] = '连接器断开';
        } elseif ($message['stop_type'] == 5) {
            $message['stop_type'] = '电池已充满';
        } elseif ($message['stop_type'] == 7) {
            $message['stop_type'] = '设备异常';
        } elseif ($message['stop_type'] == 8) {
            $message['stop_type'] = '枪头被拔下';
        } elseif ($message['stop_type'] == 10) {
            $message['stop_type'] = '设备故障';
        } elseif ($message['stop_type'] == 11) {
            $message['stop_type'] = '车辆故障';
        } elseif ($message['stop_type'] == 14) {
            $message['stop_type'] = '未知';
        } elseif ($message['stop_type'] == 15) {
            $message['stop_type'] = '系统异常';
        } elseif ($message['stop_type'] == 22) {
            $message['stop_type'] = '车辆识别失败';
        } elseif ($message['stop_type'] == 24) {
            $message['stop_type'] = '设备终止';
        } elseif ($message['stop_type'] == 25) {
            $message['stop_type'] = '互联互通终止';
        } elseif ($message['stop_type'] == 26) {
            $message['stop_type'] = '平台终止';
        } elseif ($message['stop_type'] == 27) {
            $message['stop_type'] = 'SOC限制终止';
        } elseif ($message['stop_type'] == 13) {
            $message['stop_type'] = '急停按钮被按下';
        } elseif ($message['stop_type'] == 16) {
            $message['stop_type'] = '主动防护';
        } elseif ($message['stop_type'] == 6) {
            $message['stop_type'] = 'BMS异常';
        } elseif ($message['stop_type'] == 12) {
            $message['stop_type'] = '账户余额不足';
        } elseif ($message['stop_type'] == 31) {
            $message['stop_type'] = '操作频繁，请稍后再试';
        } elseif ($message['stop_type'] == 32) {
            $message['stop_type'] = '请重新插枪启动充电';
        } elseif ($message['stop_type'] == 33) {
            $message['stop_type'] = '账户超出限额';
        } elseif (strlen((string)$message['stop_type']) == 0) {
            $message['stop_type'] = null;
        } else {
            $message['stop_type'] = '未知错误';
        }

        return json(['code' => 200, 'data' => $message]);
    }

    public function OrderDetail2($openid, $order_number)
    {

        $table = 'zxc_charge_order';


        $message = Db::table($table)->where('order_number', $order_number)->find();

        $message['charge_length'] = null;

        if (empty($message['end_time']) && ($message['status'] == 2)) {
            $Hard = new HardMessage();
            $Hard->Get_query_equip_charge_status($message['StartChargeSeq']);
            $message = Db::table($table)->where('order_number', $order_number)->find();
        }


        if (isset($message['start_time']) && strtotime($message['start_time']) < strtotime('2099-02-03 00:00:00') && $message['status'] == 4) {
            $station_type = \app\model\ChargeStation::where('charge_station_id', $message['charge_station_id'])->value('station_type');
            if ($station_type == 0) {
                $message['SeviceMoney'] = round($message['TotalPower'] * 0.2, 2);
            } else {
                $message['SeviceMoney'] = round($message['TotalPower'] * 0.4, 2);
            }
            $message['ElecMoney'] = round($message['TotalMoney'] - $message['SeviceMoney'], 2);
        }

        if (!empty($message['end_time'])) {
            $charge_length = (strtotime($message['end_time']) - strtotime($message['start_time'])) % 86400 / 3600;
            Db::table($table)->where('order_number', $order_number)->update(['charge_length' => $charge_length]);
            $message['charge_length'] = $charge_length;
        }


        $charge_station_info = Db::table('charge_station')
            ->where('charge_station_id', $message['charge_station_id'])
            ->field('charge_station_number,charge_station_name')
            ->find();

        $no = Db::table('charge_pile')->where('ConnectorID', $message['ConnectorID'])->value('no');


        if ($message['TotalPower'] == null) {
            $message['TotalPower'] = 0;
        }

        $message['TotalPower'] = number_format($message['TotalPower'], 3);
        $message['charge_station_number'] = $message['ConnectorID'];
        $message['charge_station_name'] = $charge_station_info['charge_station_name'];
        $message['no'] = $no;

        $message_arr = [
            '1' => '启动中',
            '2' => '充电中',
            '3' => '停止中',
            '4' => '已结束',
            '5' => '未知错误',
        ];

        $message['message'] = $message_arr[$message['status']] ?? '未知错误';


        if (strlen((string)$message['stop_type']) != 0 && $message['stop_type'] == 0) {
            $message['stop_type'] = '正常停止';
        } elseif ($message['stop_type'] == 4) {
            $message['stop_type'] = '连接器断开';
        } elseif ($message['stop_type'] == 5) {
            $message['stop_type'] = '电池已充满';
        } elseif ($message['stop_type'] == 7) {
            $message['stop_type'] = '设备异常';
        } elseif ($message['stop_type'] == 8) {
            $message['stop_type'] = '枪头被拔下';
        } elseif ($message['stop_type'] == 10) {
            $message['stop_type'] = '设备故障';
        } elseif ($message['stop_type'] == 11) {
            $message['stop_type'] = '车辆故障';
        } elseif ($message['stop_type'] == 14) {
            $message['stop_type'] = '未知';
        } elseif ($message['stop_type'] == 15) {
            $message['stop_type'] = '系统异常';
        } elseif ($message['stop_type'] == 22) {
            $message['stop_type'] = '车辆识别失败';
        } elseif ($message['stop_type'] == 24) {
            $message['stop_type'] = '设备终止';
        } elseif ($message['stop_type'] == 25) {
            $message['stop_type'] = '互联互通终止';
        } elseif ($message['stop_type'] == 26) {
            $message['stop_type'] = '平台终止';
        } elseif ($message['stop_type'] == 27) {
            $message['stop_type'] = 'SOC限制终止';
        } elseif ($message['stop_type'] == 13) {
            $message['stop_type'] = '急停按钮被按下';
        } elseif ($message['stop_type'] == 16) {
            $message['stop_type'] = '主动防护';
        } elseif ($message['stop_type'] == 6) {
            $message['stop_type'] = 'BMS异常';
        } elseif ($message['stop_type'] == 12) {
            $message['stop_type'] = '账户余额不足';
        } elseif ($message['stop_type'] == 31) {
            $message['stop_type'] = '操作频繁，请稍后再试';
        } elseif ($message['stop_type'] == 32) {
            $message['stop_type'] = '请重新插枪启动充电';
        } elseif ($message['stop_type'] == 33) {
            $message['stop_type'] = '账户超出限额';
        } elseif (strlen((string)$message['stop_type']) == 0) {
            $message['stop_type'] = null;
        } else {
            $message['stop_type'] = '未知错误';
        }

        return json(['code' => 200, 'data' => $message]);
    }

    public function StationFee()
    {

        $params = input();
        $station_number = $params['station_number'] ?? '';
        $openid = $params['openid'] ?? '';
        $charge_station_info = Db::table('charge_station')
            ->where('charge_station_number', $station_number)->find();

        $user_info = Db::table('zxc_user')->where('openid', $openid)->field('type,account,group_id')->find();

        // if ($user_info['type'] == 3) {
        //     $ServiceFee = ServiceFee::where('type', $user_info['type'])->where('group_id', $user_info['group_id'])->where('station_type', $charge_station_info['station_type'])->value('service_fee');
        // } else {
        //     $ServiceFee = ServiceFee::where('type', $user_info['type'])->where('station_type', $charge_station_info['station_type'])->value('service_fee');
        // }
        $ServiceFee = ServiceFee::where('id', 1)->value('service_fee');

        $time_price = $this->returnFree($charge_station_info['ElectricityFee'], $ServiceFee);


        $ElectricityFee = str_replace('电费:', '', $charge_station_info['ElectricityFee']);
        $Elect = explode(',', $ElectricityFee);
        for ($index = 0; $index < count($Elect); $index++) {
            $kk['time_interval'] = substr($Elect[$index], 0, 11);
            $kk['univalence'] = explode(':', $Elect[$index])[3];
            $ss[] = $kk;
        }


        $ServiceFee = str_replace('服务费:', '', $ServiceFee);
        $Server = explode(',', $ServiceFee);
        for ($index = 0; $index < count($Server); $index++) {
            $ll['time_interval'] = substr($Server[$index], 0, -5);
            $ll['univalence'] = substr($Server[$index], Strlen($Server[$index]) - 4);
            $mm[] = $ll;
        }

        return json(['code' => 200, 'ElectricityFee' => $ss, 'ServiceFee' => $mm, 'data' => $time_price, 'balance' => $user_info ? $user_info['account'] : '0.00']);
    }

    //改后暂未使用
    public function QueryPayStatus($openid)
    {
        $table = 'zxc_charge_order';
        $paystatus = Db::table($table)->where('openid', $openid)->order('start_time desc')->value('PayStatus');

        if ($paystatus == 1) {
            $message['paystatus'] = 1;
            $message['paymessage'] = '存在订单未支付 无法生成';
            return json(['code' => 1, 'data' => $message]);
        } elseif ($paystatus == 2 || empty($paystatus)) {
            $message['paystatus'] = 2;
            $message['paymessage'] = '订单已全部支付 可以正常生成订单';
            return json(['code' => 200, 'data' => $message]);
        } elseif ($paystatus == 0) {
            $message['paystatus'] = 0;
            $message['paymessage'] = '订单未完成 请先完成当前订单';
            return json(['code' => 1, 'data' => $message]);
        }
    }


    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read_order(Request $request)
    {
        $data = $request->param();
        $table = 'zxc_charge_order';
        $count = Db::table($table)->select()->count();
        $query = Db::table($table)->paginate(20, $count)->toArray();
        $i = 0;
        foreach ($query['data'] as $d) {
            $query['data'][$i]['order_id'] = $i + 1;
            if (strtotime($query['data'][$i]['start_time']) < strtotime('2023-02-03 00:00:00') && ($query['data'][$i]['ElecMoney'] + $query['data'][$i]['SeviceMoney']) != $query['data'][$i]['TotalMoney']) {
                $station_type = \app\model\ChargeStation::where('charge_station_id', $query['data'][$i]['charge_station_id'])->value('station_type');
                if ($station_type == 0) {
                    $query['data'][$i]['SeviceMoney'] = round(($query['data'][$i]['TotalPower'] * 0.2), 2);
                } else {
                    $query['data'][$i]['SeviceMoney'] = round(($query['data'][$i]['TotalPower'] * 0.4), 2);
                }
                $query['data'][$i]['ElecMoney'] = round($query['data'][$i]['TotalMoney'] - $query['data'][$i]['SeviceMoney'], 2);
            }
            $station_name = \app\model\ChargeStation::where('charge_station_id', $query['data'][$i]['charge_station_id'])->value('charge_station_name');
            $query['data'][$i]['charge_station_name'] = $station_name;
            $i += 1;
        }
        return json($query);
    }


    public function order_all(Request $request)
    {
        $data = $request->param();
        $table = 'zxc_charge_order';
        $charge_station_name = $data['charge_station_name'];
        $charge_station_id = Db::table('charge_station')->where('charge_station_name', $charge_station_name)->value('charge_station_id');
        $list = Db::table($table)->where('charge_station_id', $charge_station_id)->select();
        return json($list);
    }

    public function read_equipment(Request $request)
    {
        $data = $request->param();
        $where = [];
        if (isset($data['area'])) {
            $where[] = ['street', '=', $data['area']];
        }
        if (isset($data['charge_station_name'])) {
            $where[] = ['charge_station_name', '=', $data['charge_station_name']];
        }
        
        if (isset($data['status'])) {
            $where[] = ['status', '>', 3];
        }
        
        $mess = Db::table('charge_pile')->where($where)->orderRaw('charge_station_id asc,CAST(no AS SIGNED) ASC')->paginate([
            'list_rows' => 20,
            'query' => request()->param()
        ]);
        $statusMap = [
            '1' => '空闲中',
            '2' => '联通中',
            '3' => '充电中',
            '0' => '离网中',
            '255' => '故障中'
        ];
        
        $mess->each(function($item, $key) use ($statusMap) {
            $item['status_text'] = $statusMap[(int)$item['status']] ?? '未知';
            $item['charge_station_name'] = Db::table('charge_station')->where('charge_station_id', $item['charge_station_id'])->value('charge_station_name');
            return $item;
        });
        
        return json($mess);
    }

    public function read_total(Request $request)
    {
        $data = $request->param();
        $charge_station_name = $data['charge_station_name'];
        $charge_station_id = Db::table('charge_station')->where('charge_station_name', $charge_station_name)->value('charge_station_id');

        $table = 'zxc_charge_order';

        $revenue = Db::table($table)->where('charge_station_id', $charge_station_id)->sum('TotalMoney');
        $degree = Db::table($table)->where('charge_station_id', $charge_station_id)->sum('TotalPower');
        $order_num = Db::table($table)->where('charge_station_id', $charge_station_id)->count();

        $message = [
            'charge_station_id' => $charge_station_id,
            'degree' => round($degree, 2),
            'revenue' => round($revenue, 2),
            'order_num' => $order_num
        ];
        return json($message);
    }


    public function EndOrder($openid, $order_number)
    {
        $table = 'zxc_charge_order';
        $StartChargeSeq = Db::table($table)->where('order_number', $order_number)->value('StartChargeSeq');
        $ConnectorID = Db::table($table)->where('order_number', $order_number)->value('ConnectorID');
        $Hard = new HardMessage();
        $Stop = $Hard->Get_query_stop_charge($StartChargeSeq, $ConnectorID);
        $StopFailReson = Db::table($table)->where('order_number', $order_number)->value('StopFailreason');
        if (!empty($StopFailReson) && (int)$StopFailReson == 2) {
            return json(['code' => 1, 'message' => '设备离线，请耐心等待，请直接拔枪，后续信息会回传']);
        } elseif (!empty($StopFailReson) && (int)$StopFailReson == 15) {
            return json(['code' => 1, 'message' => '系统异常，请多次尝试，或直接拔枪，后续信息会回传']);
        }

        if ($Stop['StartChargeSeqStat'] == 3 && $Stop['SuccStat'] == 0 && $Stop['FailReason'] == 0) {
            return json(['code' => 200, 'message' => '正在结束充电']);
        } elseif ($Stop['SuccStat'] == 1) {
            if ($Stop['FailReason'] == 1) {
                return json(['code' => 1, 'message' => '请求停止充电失败 此设备不存在']);
            } elseif ($Stop['FailReason'] == 2) {
                return json(['code' => 1, 'message' => '请求停止充电失败 此设备离线']);
            } elseif ($Stop['FailReason'] == 3) {
                return json(['code' => 1, 'message' => '请求停止充电失败 设备已停止充电']);
            } elseif ($Stop['FailReason'] == 4) {
                return json(['code' => 1, 'message' => '请求停止充电失败 订单编号不符合规范']);
            } else {
                return json(['code' => 1, 'message' => '请求停止充电失败 系统异常']);
            }
        } elseif ($Stop['SuccStat'] == 0 && $Stop['FailReason'] == 0) {
            return json(['code' => 200, 'message' => '正在结束充电']);
        } else {
            return json(['code' => 1, 'message' => '未知原因']);
        }

    }

// 请求停止充电
    public function EndOrder2($order_number)
    {

        $charge_info = Db::table('zxc_charge_order')->where('order_number', $order_number)->find();


        $StopFailReson = $charge_info['StopFailreason'];
        if (!empty($StopFailReson) && (int)$StopFailReson == 2) {
            return json(['code' => 1, 'message' => '设备离线，请耐心等待，请直接拔枪，后续信息会回传']);
        } elseif (!empty($StopFailReson) && (int)$StopFailReson == 15) {
            return json(['code' => 1, 'message' => '系统异常，请多次尝试，或直接拔枪，后续信息会回传']);
        }


        //请求停止充电
        $Hard = new HardMessage();
        $Stop = $Hard->Get_query_stop_charge($charge_info['StartChargeSeq'], $charge_info['ConnectorID']);


        if ($Stop['StartChargeSeqStat'] == 3 && $Stop['SuccStat'] == 0 && $Stop['FailReason'] == 0) {
            return json(['code' => 200, 'message' => '正在结束充电']);
        } elseif ($Stop['SuccStat'] == 1) {

            $arr = [
                '1' => '请求停止充电失败 此设备不存在',
                '2' => '请求停止充电失败 此设备离线',
                '3' => '请求停止充电失败 设备已停止充电',
                '4' => '请求停止充电失败 订单编号不符合规范'

            ];

            return json(['code' => 1, 'message' => $arr[$Stop['FailReason']] ?? '请求停止充电失败 系统异常']);

        } elseif ($Stop['SuccStat'] == 0 && $Stop['FailReason'] == 0) {
            return json(['code' => 200, 'message' => '正在结束充电']);
        } else {
            return json(['code' => 1, 'message' => '未知原因']);
        }

    }


    public function total()
    {
        $already_revenue = ChargeOrderModel::where('status', 1)->sum('revenue');
        $total_revenue = ChargeOrderModel::sum('revenue');
        $total_degree = ChargeOrderModel::sum('charge_degree');
        $message = [
            '已收益' => $already_revenue,
            '总收益' => $total_revenue,
            '总耗电量' => $total_degree
        ];
        return json([
            'code' => 200,
            'message' => $message
        ]);
    }

    public function List_ToWechat()
    {
        $list = Db::table('charge_order,charge_pile')
            ->where('charge_order.Equipment_number=charge_pile.charge_pile_number')
            ->field('order_number,start_time,end_time,charge_length,revenue,stop_type,charge_order.Equipment_number,charge_pile.charge_pile_name,charge_pile.power')
            ->select()->toArray();

        for ($i = 0; $i < count($list); $i++) {
            $list[$i]['charge_length'] *= 60;
            if ($list[$i]['stop_type'] == 1) {
                $list[$i]['stop_type'] = '正常停止';
            } elseif ($list[$i]['stop_type'] == 2) {
                $list[$i]['stop_type'] = '强制停止';
            } elseif ($list[$i]['stop_type'] == 3) {
                $list[$i]['stop_type'] = '故障停止';
            }
        }
        return json($list);
    }

    public function StreetWithName()
    {
        $area = Db::table('area_three')->column('area');
        foreach ($area as $a) {
            $station = Db::table('charge_station')->where('street', $a)->column('charge_station_name');
            $i = 0;
            foreach ($station as $st) {
                $name = $a . $i . '号充电站';
                $station_id = Db::table('charge_station')->where(['street' => $a, 'charge_station_name' => $st])->value('charge_station_id');
                $flag = Db::table('charge_station')->where('charge_station_id', $station_id)->value('charge_station_name');
                if (empty($flag)) {
                    Db::table('charge_station')->where('charge_station_id', $station_id)->update(['charge_station_name' => $name]);
                } else {
                    $i += 1;
                }

                $i += 1;
            }
        }
        $data = [];
        foreach ($area as $a) {
            $station_data = [];
            $station = Db::table('charge_station')->where('street', $a)->column('charge_station_name');
            $i = 1;
            foreach ($station as $s) {
                array_push($station_data, ['station' => $s]);
                $i += 1;
            }
            array_push($data, ['station' => $a, 'children' => $station_data]);
        }
        return json($data);

    }

    public function OrderList($openid)
    {

        $table = 'zxc_charge_order';
        $list = Db::table($table)->where('openid', $openid)->order('order_id desc')->select()->toArray();
        $i = 0;
        foreach ($list as $l) {
            if (!empty($l['end_time']) && ($l['start_time'] != $l['end_time']) && ($l['status'] == 2 || $l['status'] == 5)) {
                Db::table($table)->where('order_number', $l['order_number'])->save(['status' => 4, 'StartChargeSeqStat' => 4, 'TotalMoney' => round($l['WithholdingMoney'] - $l['FeedbackMoney'], 2)]);
            } elseif (!empty($l['end_time']) && ($l['start_time'] == $l['end_time'])) {
                Db::table($table)->where('order_number', $l['order_number'])->save(['status' => 5, 'StartChargeSeqStat' => 5]);
            } elseif (empty($l['end_time']) && $l['status'] == 4 && empty($l['FeedbackMoney'])) {
                $this->AmendmentOrders($openid, $table, $l['StartChargeSeq'], $l['WithholdingMoney']);
            }
        }
        $list = Db::table($table)->where('openid', $openid)->order('order_id desc')->select()->toArray();
        foreach ($list as $l) {
            if ($l['status'] == 1 || $l['status'] == 2 || $l['status'] == 3) {
                $list[$i]['status'] = '正在充电中';
            } elseif ($l['status'] == 4) {
                $list[$i]['status'] = '充电完成';
            } else {
                $list[$i]['status'] = '系统异常';
            }
            $list[$i]['TotalMoney'] = sprintf("%01.2f", $list[$i]['TotalMoney']);
            $i += 1;
        }
        return json($list);
    }

    public function OrderList2($openid)
    {

        $table = 'zxc_charge_order';
        $list = Db::table($table)->where('openid', $openid)->order('order_id desc')->select()->toArray();
        $i = 0;
        foreach ($list as $l) {
            if (!empty($l['end_time']) && ($l['start_time'] != $l['end_time']) && ($l['status'] == 2 || $l['status'] == 5)) {
                Db::table('zxc_charge_order')->where('order_number', $l['order_number'])->save(['status' => 4, 'StartChargeSeqStat' => 4, 'TotalMoney' => round($l['WithholdingMoney'] - $l['FeedbackMoney'], 2)]);
            } elseif (!empty($l['end_time']) && ($l['start_time'] == $l['end_time'])) {
                Db::table('zxc_charge_order')->where('order_number', $l['order_number'])->save(['status' => 5, 'StartChargeSeqStat' => 5]);
            } elseif (empty($l['end_time']) && $l['status'] == 4 && empty($l['FeedbackMoney'])) {
                $this->AmendmentOrders($openid, 'zxc_charge_order', $l['StartChargeSeq'], $l['WithholdingMoney']);
            }

        }
        $list = Db::table($table)->where('openid', $openid)->field('order_number,start_time,end_time,TotalMoney,status,PayStatus,WithholdingMoney,FeedbackMoney,StartChargeSeqStat,StartChargeSeq')->order('order_id desc')->select()->toArray();
        foreach ($list as $l) {
            if ($l['status'] == 1 || $l['status'] == 2 || $l['status'] == 3) {
                $list[$i]['status'] = '正在充电中';
            } elseif ($l['status'] == 4) {
                $list[$i]['status'] = '充电完成';
            } else {
                $list[$i]['status'] = '系统异常';
            }
            $list[$i]['TotalMoney'] = sprintf("%01.2f", $list[$i]['TotalMoney']);
            $i += 1;
        }
        return json($list);
    }

    public function AmendmentAccount($table, $StartChargeSeq)
    {
        $hard = new HardMessage();
        $data = $hard->Get_query_equip_charge_status_test($StartChargeSeq);
        $TotalMoney = Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->value('TotalMoney');
        $TotalMoney = round($TotalMoney, 2);
        if ($data['code'] == 200 && $TotalMoney == $data['data']['TotalMoney']) {
            Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->save([
                'TotalPower' => $data['data']['TotalPower'],
                'ElecMoney' => $data['data']['ElecMoney'],
                'SeviceMoney' => $data['data']['SeviceMoney'],
            ]);
        }
    }


    protected function AmendmentOrders($openid, $table, $StartChargeSeq, $WithholdingMoney)
    {
        $hard = new HardMessage();
        $data = $hard->Get_query_equip_charge_status_test($StartChargeSeq);
        if ($data['code'] == 200) {
            $FeedbackMoney = $WithholdingMoney - $data['data']['TotalMoney'];
            $table_user = 'zxc_user';
            $check = Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->value('FeedbackMoney');
            if (empty($check)) {
                Db::table($table_user)->where('openid', $openid)->update(['account' => Db::raw('account+' . round($FeedbackMoney, 2))]);
                Db::table($table)->where('StartChargeSeq', $StartChargeSeq)->save([
                    'end_time' => $data['data']['EndTime'],
                    'charge_degree' => $data['data']['TotalPower'],
                    'stop_type' => 25,
                    'TotalPower' => $data['data']['TotalPower'],
                    'ElecMoney' => $data['data']['ElecMoney'],
                    'SeviceMoney' => $data['data']['SeviceMoney'],
                    'TotalMoney' => $data['data']['TotalMoney'],
                    'Soc' => $data['data']['Soc'],
                    'DetailMessage' => $data['data']['DetailMessage'],
                    'FeedbackMoney' => $FeedbackMoney,
                    'status' => $data['data']['StartChargeSeqStat']
                ]);
            }
        }
    }

    public function OrderNum($openid)
    {
        $table = 'zxc_charge_order';
        $count = Db::table($table)->where('openid', $openid)->field('order_number,start_time,end_time,revenue,status')->count();

        return json(['code' => 200, 'message' => '请求成功', 'count' => $count]);
    }

    public function RechargeRecord($openid)
    {
        $table = 'zxc_recharge';
        $list = Db::table($table)->where('openid', $openid)->order('id desc')->select()->toArray();
        $i = 0;
        foreach ($list as $l) {
            $list[$i]['total'] /= 100;
            $list[$i]['payer_total'] /= 100;
            if ($list[$i]['trade_state'] == 'SUCCESS') {
                $list[$i]['trade_state'] = '支付成功';
            } else {
                $list[$i]['trade_state'] = '支付失败';
            }
            $i += 1;
        }
        return json($list);
    }

    public function RechargeAll($start_time = '', $end_time = '')
    {
        if (!empty($end_time)) {
            $end_time = date("Y-m-d", strtotime("+1day", strtotime($end_time)));
        }
        $query = Db::table('zxc_recharge')->select()->toArray();
        $i = 0;
        foreach ($query as $d) {
            $query[$i]['id'] = $i + 1;
            $query[$i]['total'] = round($query[$i]['total'] / 100, 2);
            $query[$i]['payer_total'] = round($query[$i]['payer_total'] / 100, 2);
            $i += 1;
        }
        return json($query);
    }

    public function RechargeAllExport($start_time = '', $end_time = '')
    {


        $where = [];
        if ($start_time) {
            $where[] = ['success_time', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['success_time', '<=', $end_time];
        }


        $list = Db::table('zxc_recharge')->where($where)->order('id desc')->select()->toArray();
        foreach ($list as $key => &$value) {

            $value['total'] = round($value['total'] / 100, 2);
            $value['payer_total'] = round($value['payer_total'] / 100, 2);

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

        }

        return json($list);

    }

    public function OrderExport($charge_station_name = '', $start_time = '', $end_time = '')
    {


        $where = [];

        if ($charge_station_name) {
            $charge_station_id = Db::table('charge_station')->where('charge_station_name', $charge_station_name)->value('charge_station_id');
            if ($charge_station_id) {
                $where[] = ['charge_station_id', '=', $charge_station_id];
            }
        }

        if ($start_time) {
            $where[] = ['start_time', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['start_time', '<=', $end_time];
        }

        $list = Db::table('zxc_charge_order')
            ->where($where)
            ->field('charge_station_id,order_number,order_id,TotalPower,TotalMoney,ElecMoney,SeviceMoney,end_time,EndTime,DetailMessage,status,start_time,openid')
            ->order('start_time DESC')
            ->select();  // 获取全部数据


        foreach ($list as $key => &$value) {
            $value['charge_station_name'] = Db::table('charge_station')->where('charge_station_id', $value['charge_station_id'])->value('charge_station_name');

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

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function OrderQuery($message)
    {

        $table = 'zxc_charge_order';
        $query = Db::table($table)->where('openid', 'like', '%' . $message . '%')->select()->toArray();
        $i = 0;
        foreach ($query as $d) {
            if (strtotime($query[$i]['start_time']) < strtotime('2023-02-03 00:00:00') && ($query[$i]['ElecMoney'] + $query[$i]['SeviceMoney']) != $query[$i]['TotalMoney']) {
                $station_type = \app\model\ChargeStation::where('charge_station_id', $d['charge_station_id'])->value('station_type');
                if ($station_type == 0) {
                    $query[$i]['SeviceMoney'] = round(($query[$i]['TotalPower'] * 0.2), 2);
                } else {
                    $query[$i]['SeviceMoney'] = round(($query[$i]['TotalPower'] * 0.4), 2);
                }
                $query[$i]['ElecMoney'] = round($query[$i]['TotalMoney'] - $query[$i]['SeviceMoney'], 2);
            }
            $query[$i]['order_id'] = $i + 1;
            $query[$i]["charge_station_name"] = Db::table('charge_station')->where('charge_station_id', $query[$i]['charge_station_id'])->value('charge_station_name');
            $i += 1;
        }
        return json(['data' => $query]);
    }

    /**
     * @param $order
     * @param string $union
     * @return string
     */
    protected function getStr($order, string $union): string
    {
        if (!empty($order) && (int)$order == 1) {
            $union .= ' AND ' . ' (status = 1 or status = 2 or status = 3)';
        } elseif (!empty($order) && (int)$order == 2) {
            $union .= ' AND ' . ' status = 4';
        } elseif (!empty($order) && (int)$order == 3) {
            $union .= ' AND ' . ' status = 5';
        }
        return $union;
    }


    protected function getSelect1($order, $query)
    {
        if (!empty($order) && (int)$order == 1) {
            $query = $query->whereOr('status', 1)->whereOr('status', 2)->whereOr('status', 3)->select();
        } elseif (!empty($order) && (int)$order == 2) {
            $query = $query->whereOr('status', 4)->select();
        } elseif (!empty($order) && (int)$order == 3) {
            $query = $query->whereOr('status', 5)->select();
        } else {
            $query = $query->select();
        }
        return $query;
    }


    // 查询充电桩信息
    public function getChargePileNew($start_time = "", $end_time = "", $station_name = [], $selectt = "", $listQuery = "")
    {
        $station_name = array_merge(...array_map(fn($item) => json_decode($item, true), $station_name));

        $statusMap = [
            '1' => '空闲中',
            '2' => '联通中',
            '3' => '充电中',
            '0' => '离网中',
            '255' => '故障中'
        ];

        $where = [];

        if (!empty($station_name)) {
            $charge_station_ids = Db::table('charge_station')->where('charge_station_name', 'in', implode(',', $station_name))->column('charge_station_id');

            $where[] = ['charge_station_id', 'in', $charge_station_ids];

        }
        $pileList = Db::table('charge_pile')->where($where)->order('charge_station_id,ConnectorID')->select()->toArray();

// 获取所有充电站ID
        $stationIds = array_unique(array_column($pileList, 'charge_station_id'));
// 批量查询充电站名称
        $stations = Db::table('charge_station')
            ->whereIn('charge_station_id', $stationIds)
            ->column('charge_station_name', 'charge_station_id');


        $where = [];
        if (!empty($station_name)) {
            $charge_station_ids = Db::table('charge_station')->where('charge_station_name', 'in', $station_name)->column('charge_station_id');

            $ids = array_map('intval', $charge_station_ids); // 强制转为整数
            $where[] = ['charge_station_id', 'in', implode(',', $ids)];

        }


        if (!empty($selectt) && !empty($listQuery)) {

            if ($selectt == 1) {
                // 当天查询 (格式: YYYY-MM-DD 00:00:00)
                $listQuery = $listQuery . ' 00:00:00';

                $where[] = ['charge_date', '=', $listQuery];


            } elseif ($selectt == 3) {
                // 当月查询 (格式: YYYY-MM)
                $monthStart = date('Y-m-01 00:00:00', strtotime($listQuery));
                $monthEnd = date('Y-m-t 23:59:59', strtotime($listQuery));

                $where[] = ['charge_date', '>=', $monthStart];
                $where[] = ['charge_date', '<=', $monthEnd];

            } elseif ($selectt == 5) {
                // 当年查询 (格式: YYYY)
                $yearStart = date('Y-01-01 00:00:00', strtotime($listQuery));
                $yearEnd = date('Y-12-31 23:59:59', strtotime($listQuery));

                $where[] = ['charge_date', '>=', $yearStart];
                $where[] = ['charge_date', '<=', $yearEnd];
            }

        } else {
            if (!empty($start_time)) {

                $where[] = ['start_time', '>=', $start_time];
            }
            if (!empty($end_time)) {

                $where[] = ['start_time', '<=', $end_time];
            }
        }


        $allOrders = Db::table('zxc_charge_order')
            ->where($where)
            ->order('charge_station_id ASC,ConnectorID')
            ->select()->toArray();


        $ordersByConnector = [];
        foreach ($allOrders as $order) {
            $connectorId = $order['ConnectorID'];
            if (!isset($ordersByConnector[$connectorId])) {
                $ordersByConnector[$connectorId] = [];
            }
            $ordersByConnector[$connectorId][] = $order;
        }
        foreach ($pileList as &$pile) {
            // 设置状态文本
            $pile['status_text'] = $statusMap[$pile['status']] ?? '未知状态';

            // 设置充电站名称
            $pile['charge_station_name'] = $stations[$pile['charge_station_id']] ?? '未知电站';

            // 初始化统计数据
            $pile['totalPower'] = 0;    // 总电量(kWh)
            $pile['totalTime'] = 0;     // 总时长(秒)
            $pile['totalPrice'] = 0;    // 总费用(元)

            // 获取该充电桩的所有订单
            $connectorId = $pile['ConnectorID'];
            if (isset($ordersByConnector[$connectorId])) {
                foreach ($ordersByConnector[$connectorId] as $order) {
                    // 计算充电时长（秒）
                    if (!empty($order['end_time']) && !empty($order['start_time'])) {
                        $startTime = strtotime($order['start_time']);
                        $endTime = strtotime($order['end_time']);
                        if ($startTime && $endTime && $endTime > $startTime) {
                            $pile['totalTime'] += ($endTime - $startTime);
                        }
                    }

                    // 累加电量和费用
                    $pile['totalPower'] += floatval($order['TotalPower'] ?? 0);
                    $pile['totalPrice'] += floatval($order['TotalMoney'] ?? 0);
                }
            }

            // 将秒转换为小时:分钟:秒格式
            $pile['totalTimeFormatted'] = number_format(($pile['totalTime'] / 3600), 4);


            // 格式化金额和电量
            $pile['totalPrice'] = number_format($pile['totalPrice'], 2);
            $pile['totalPower'] = number_format($pile['totalPower'], 2);
        }


        return $pileList;
    }
}


