<?php
declare (strict_types=1);

namespace app\controller;


use app\controller\Bus\PlugCharge;
use app\model\EnterpriseUser;
use app\model\ServiceFee;
use DateInterval;
use DateTime;

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

class Test
{
    static $OperatorID = 'MA5UTE3F1'; //运营商标识
    static $OperatorSecret = '1234567890abcdef';//运营商密钥
    static $Seq = '0001';

    public function tttt()
    {
        $data = ["vin" => "LA9LC30F0NCLA6198", "connectorID" => "5001110048204", "StartSc" => 44];
        if (isset($data['vin']) && isset($data['connectorID'])) {
//                $this->PlugGennerateOrder($data['ConnectorID'], $data['Vin']);
            $AppointmentTime = Db::table('appointment_time')->where('id', 1)->value('AppointmentTime');
            $currentDate = new DateTime();
            $combinedDateTime = new DateTime($currentDate->format('Y-m-d') . ' ' . $AppointmentTime);
            $AppointmentTime = $combinedDateTime->format('Y-m-d H:i:s');
            $nowTime = $currentDate->format('Y-m-d H:i:s');
            $nowDay = $currentDate->format('Y-m-d');
            $check = Db::table('appointment')->whereDay('action_time', $nowDay)->where('Vin', $data['vin'])->find();
            if (empty($check)) {
                Db::table('appointment')->save(['action_time' => $nowTime, 'ConnectorID' => $data['connectorID'], 'Vin' => $data['vin'], 'plug_time' => $AppointmentTime]);
            } else {
                $checkVin = Db::table('appointment')->where('Vin', $data['vin'])->value('ConnectorID');
                if ($checkVin != $data['connectorID']) {
                    Db::table('appointment')->where('Vin', $data['vin'])->save(['action_time' => $nowTime, 'ConnectorID' => $data['connectorID']]);
                }
            }
            $kk['SuccStat'] = 0;
            $kk['FailReason'] = 0;
        }
        $data = json_encode($data);
        $h = new PlugCharge();
        $st = $h->signToken();
        $data = $h->Encrypt($data);
        return json($st);

    }

    public function GetPriceTest($station_id, $openid, $table)
    {
        $station_type = \app\model\ChargeStation::where('charge_station_id', $station_id)->value('station_type');
        $ElectricityFee = Db::table('charge_station')->where('charge_station_id', $station_id)->value('ElectricityFee');
        $type = Db::table($table)->where('openid', $openid)->value('type');
        if ($type != 3) {
            $ServiceFee = ServiceFee::where('type', $type)->where('station_type', $station_type)->value('service_fee');
        } else {
            $group_id = EnterpriseUser::where('openid', $openid)->value('group_id');
            $ServiceFee = ServiceFee::where('type', $type)->where('station_type', $station_type)->where('group_id', $group_id)->value('service_fee');
        }
//        $ServiceFee= Db::table('charge_station')->where('charge_station_id',$station_id)->value('ServiceFee');
        $ElectricityFee = str_replace('电费:', '', $ElectricityFee);
        $Elect = explode(',', $ElectricityFee);

        for ($index = 0; $index < count($Elect); $index++) {
            $kk['time_interval'] = substr($Elect[$index], 0, 11);
            $tt = explode('~', $kk['time_interval']);
            $start = $tt[0] . ':00';
            $end = $tt[1] . ':00';

            $kk['univalence'] = explode(':', $Elect[$index])[3];
            $kk['start'] = $start;
            $kk['end'] = $end;
            $ss[] = $kk;
        }
        $ServiceFee = str_replace('服务费:', '', $ServiceFee);
        $Server = explode(',', $ServiceFee);
        $wk_day = date('w');
        $now_time = time();
        $start_time = '2023-03-18 00:00:00';
        $start_time = strtotime($start_time);
        $wkday_ar = array('日', '一', '二', '三', '四', '五', '六');
        for ($index = 0; $index < count($Server); $index++) {
            $ll['time_interval'] = substr($Server[$index], 0, -5);
            // if ($wkday_ar[$wk_day] == '三' && $now_time > $start_time && $type == 1) {
            //     $ll['univalence'] = number_format((float)(substr($Server[$index], Strlen($Server[$index]) - 4) - 0.20), 2);
            // } else {
            $ll['univalence'] = substr($Server[$index], Strlen($Server[$index]) - 4);
            // }
            $mm[] = $ll;
        }
        if ($station_type == 1) {
            return json(['EPrice' => number_format((float)($ss[0]['univalence']), 6), 'SPrice' => number_format((float)($mm[0]['univalence']), 2)]);
        } elseif ($station_type == 0) {
            return json(['message' => $ss, 'SPrice' => number_format((float)($mm[0]['univalence']), 2)]);

        }
    }

    public function tsesg1()
    {
        $currentDate = new DateTime();
        $todayDate = $currentDate->format('Y-m-d H:i:s');
        $nowDay = $currentDate->format('Y-m-d');
        $PlugOrder = Db::table('appointment')->select();
        foreach ($PlugOrder as $order) {
            $status = Db::table('charge_pile')->where('ConnectorID', $order['ConnectorID'])->value('status');
            echo $status;
        }

    }

    public function index()
    {
        $map1 = [
            ['status', '=', 255],
            ['is_pushed', '=', 1],
        ];

        $map2 = [
            ['status', '=', 0],
            ['is_pushed', '=', 1],
        ];
        $hasfault = Db::table('charge_pile')->whereOr([$map1, $map2])->order('charge_pile_id desc')->select();

        $case1 = [
            ['charge_pile.status', '=', 255],
            ['is_pushed', '=', 1],
        ];
        $case2 = [
            ['charge_pile.status', '=', 0],
            ['is_pushed', '=', 1],
        ];
        $faultInfo = Db::table('charge_pile,charge_station')
            ->whereOr([$case1, $case2])
            ->where('charge_pile.charge_station_id = charge_station.charge_station_id')
            ->order('charge_pile_id desc')
            ->field('charge_station.charge_station_id,charge_station_name,charge_pile.charge_pile_number,charge_station.area,charge_station.street,charge_pile.status,charge_pile.no')
            ->find();
        return json($faultInfo);

    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $faultInfo = Db::table('charge_pile,charge_station')
            ->where('charge_pile.status', 3)
            ->where('charge_pile.is_pushed', 1)
            ->where('charge_pile.charge_station_id = charge_station.charge_station_id')
            ->order('charge_pile_id desc')
            ->field('charge_station.charge_station_id,charge_station_name,charge_pile.charge_pile_number,charge_station.area,charge_station.street,charge_pile.status,charge_pile.is_pushed')
            ->find();
        return json($faultInfo);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save()
    {
        $openid_array = Db::table('zxc_user')->column('openid');
        foreach ($openid_array as $openid) {
            $table_user = 'zxc_user';
            $table_order = 'zxc_charge_order';
            $table_recharge = 'zxc_recharge';
            $account = Db::table($table_user)->where('openid', $openid)->value('account');
            $recharge_all = Db::table($table_recharge)->where('openid', $openid)->sum('total');
            $recharge_all /= 100;
            $check = Db::table($table_order)->where('openid', $openid)->where('status', 2)->order('start_time desc')->value('end_time');
            if (empty($check)) {
                $order_all = Db::table($table_order)->where('openid', $openid)->where('status', 4)->sum('TotalMoney');
                $inorder = Db::table($table_order)->where('openid', $openid)->where('status', '<>', 4)->where('status', '<>', 5)->order('start_time desc')->value('WithholdingMoney');
                $order_total = $order_all + $inorder;
            } else {
                $order_total = Db::table($table_order)->where('openid', $openid)->where('status', 4)->sum('TotalMoney');
            }
            $order_total = round($order_total, 2);
            $mask = round($recharge_all - $order_total, 2); //这里还要减已经提现的
            if (round($mask, 2) == round($account, 2)) {
                continue;
            } else {
                $ss['order_total'] = $order_total;
                $ss['openid'] = $openid;
                $ss['recharge_all'] = $recharge_all;
                $ss['mask'] = $mask;
                $ss['account'] = $account;
            }
            $ll[] = $ss;
        }
        return json($ll);
    }


    public function FindOneUser($openid)
    {

        $table_user = 'zxc_user';
        $table_order = 'zxc_charge_order';
        $table_recharge = 'zxc_recharge';
        $table_refund = 'zxc_refund';
        $account = Db::table($table_user)->where('openid', $openid)->value('account');
        $recharge_all = Db::table($table_recharge)->where('openid', $openid)->sum('total');
        $recharge_all /= 100;
        $check = Db::table($table_order)->where('openid', $openid)->where('status', 2)->order('start_time desc')->value('end_time');
        if (empty($check)) {
            $order_all = Db::table($table_order)->where('openid', $openid)->where('status', 4)->sum('TotalMoney');
            $inorder = Db::table($table_order)->where('openid', $openid)->where('status', '<>', 4)->where('status', '<>', 5)->order('start_time desc')->value('WithholdingMoney');
            $order_total = $order_all + $inorder;
        } else {
            $order_total = Db::table($table_order)->where('openid', $openid)->where('status', 4)->sum('TotalMoney');
        }
        $refund_total = Db::table($table_refund)->where('openid', $openid)->sum('refund_total');
        $refund_total /= 100;
        $order_total = round($order_total, 2);
        $mask = round($recharge_all - $order_total - $refund_total, 2); //这里还要减已经提现的
        if (round($mask, 2) == round($account, 2)) {
            $ss['status'] = 'ok';
        } else {
            $ss['order_total'] = $order_total;
            $ss['openid'] = $openid;
            $ss['recharge_all'] = $recharge_all;
            $ss['mask'] = $mask;
            $ss['account'] = $account;
            $ss['refund_total'] = $refund_total;
        }
        return json($ss);
    }

    public function FindAllExUser($area, $time = '2023-05-11')
    {

        $table_user = 'zxc_user';
        $table_order = 'zxc_charge_order';
        $table_recharge = 'zxc_recharge';
        $table_refund = 'zxc_refund';
        $openid = Db::table($table_user)->column('openid');
        $kk = array();
        foreach ($openid as $o) {
            $checkdate = Db::table($table_order)->where('start_time', '<', $time)->find();
            if (empty($checkdate)) {
                continue;
            } else {

                $account = Db::table($table_user)->where('openid', $o)->value('account');
                $recharge_all = Db::table($table_recharge)->where('openid', $o)->sum('total');
                $recharge_all /= 100;
                $check = Db::table($table_order)->where('openid', $o)->where('status', 2)->order('start_time desc')->value('end_time');
                if (empty($check)) {
                    $order_all = Db::table($table_order)->where('openid', $o)->where('status', 4)->sum('TotalMoney');
                    $inorder = Db::table($table_order)->where('openid', $o)->where('status', '<>', 4)->where('status', '<>', 5)->order('start_time desc')->value('WithholdingMoney');
                    $order_total = $order_all + $inorder;
                } else {
                    $order_total = Db::table($table_order)->where('openid', $o)->where('status', 4)->sum('TotalMoney');
                }
                $order_total = round($order_total, 2);
                $refund_total = Db::table($table_refund)->where('openid', $o)->sum('refund_total');
                $refund_total /= 100;
                $refund_total = round($refund_total, 2);
                $mask = round($recharge_all - $order_total - $refund_total, 2); //这里还要减已经提现的
                if (round($mask, 2) == round($account, 2)) {
                    $ss['status'] = 'ok';
                } else {
                    $ss['order_total'] = $order_total;
                    $ss['openid'] = $o;
                    $ss['recharge_all'] = $recharge_all;
                    $ss['refund_total'] = $refund_total;
                    $ss['mask'] = $mask;
                    $ss['account'] = $account;
                    $kk[] = $ss;
                }

            }
        }
        return json($kk);
    }


    public function correction($openid)
    {
        $OrderList = new ChargeOrder();
        $OrderList->OrderList($openid);

        $table_order = 'zxc_charge_order';
        $order = Db::table($table_order)->where('openid', $openid)->select()->toArray();
        $i = 0;
        foreach ($order as $oo) {
            if (($oo['TotalMoney'] + $oo['FeedbackMoney']) != $oo['WithholdingMoney'] && $oo['status'] == 4) {
                Db::table($table_order)->where('order_number', $oo['order_number'])->save(['TotalMoney' => round($oo['WithholdingMoney'] - $oo['FeedbackMoney'], 2)]);
                $ss['order_number'] = $oo['order_number'];
                $ss['TotalMoney'] = $oo['TotalMoney'];
                $ss['WithholdingMoney'] = $oo['WithholdingMoney'];
                $ss['FeedbackMoney'] = $oo['FeedbackMoney'];
                $new_TotalMoney = Db::table($table_order)->where('order_number', $oo['order_number'])->value('TotalMoney');
                $ss['NewMoney'] = $new_TotalMoney;
                $i += 1;
            } else {
                continue;
            }

            $ll[] = $ss;
        }
        $ll['update_num'] = $i;
        return json($ll);
    }

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

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($order_number = 'DZZS1673603040121831')
    {
        $message = Db::table('charge_order_longgangjiedao')->where('order_number', $order_number)->find();
        echo strtotime($message['start_time']);
        echo strtotime("2023-03-03 15:09:47");
    }

    /**
     * 保存更新的资源
     *
     * @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)
    {
        //
    }
}

function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000;
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance / 1000, 2);
}

function Encrypt($data)
{
    $aes = new Aes();
    return $aes->encrypt($data);
}

function HmacMD5($data)
{
    $md5 = new HMACMD5();
    return $md5->HMAC($data);
}