<?php

namespace App\Repositories\Customers;

use App\Exceptions\Api\ApiException;
use App\Modules\Enums\ErrorCode;
use App\Modules\Models\Machine\Machine;
use App\Modules\Repositories\Machine\BaseMachineRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Class EloquentHistoryRepository.
 */
class MachineRepository extends BaseMachineRepository
{


    function setLifeByMacide($mac_ide, $status)
    {
        Machine::where('he_cloud_device_id', $mac_ide)->update(['life' => (int)$status]);
    }

    function setIccidByMacide($mac_ide, $iccid)
    {
        Machine::where('he_cloud_device_id', $mac_ide)->update(['iccid' => $iccid]);
    }

    function setVersionByMacide($mac_ide, $version)
    {
        Machine::where('he_cloud_device_id', $mac_ide)->update(['version' => $version]);
    }

    function getByMacide($mac_ide)
    {
        $where = [
            ['he_cloud_device_id', '=', $mac_ide]
        ];
        $machine = Machine::where($where)->first();
        if ($machine == null) {
            throw new ApiException(ErrorCode::MACHINE_NOT_EXIST, trans('api.error.machine_not_exist'));
        }
        return $machine;
    }

    function get($id, $t = false)
    {
        if ($t) {
            $where = [
                ['mac_no', '=', $id]
            ];
        } else {
            $where = [
                ['id', '=', $id]
            ];
        }

        $machine = Machine::where($where)->first();
        if ($machine == null) {
            throw new ApiException(ErrorCode::MACHINE_NOT_EXIST, trans('api.error.machine_not_exist'));
        }
        return $machine;
    }

    public function rentInfo($mac_no, $country_id = 1)
    {
//        Log::info('rentInfo: ' . $country_id);
        $machine = Machine::where('mac_no', $mac_no)->first();
        if ($machine == null) {
            throw new ApiException(ErrorCode::MACHINE_NOT_EXIST, trans('api.error.machine_not_exist'));
        }
        $available_number = $this->availablePowerNumber($machine, $country_id);

        $re = array_column($available_number, 'num');
        $total = array_sum($re);

        $response = [
            'mac_no' => $machine->mac_no,
            'life' => $machine->life,
            'one_day_price' => $machine->one_day_price,
            'free_time' => $machine->free_time,
            'deposit' => $machine->deposit,
            'available_number' => $total,
            'available_type_number' => $available_number,
            'region_type' => $machine->region_type
        ];
        return $response;

    }

    public function nearby($lat, $lng)
    {
        $select = DB::raw("id,spot_id,address,mac_no,hatch_number, one_day_price,y(position) as lng, x(position) as lat ,(st_distance (position,point($lat,$lng) ) *111195) AS distance");
        $distance = DB::raw("st_distance (position,point($lat,$lng) ) *111195");
        $machines = Machine::select($select)->where($distance, '<', 5000)->with('spot')->withCount('availableNumber as available_number')->orderBy('distance', 'asc')->get()->toArray();
        return $machines;
    }

    /**
     * @param $machine
     * @param int $has_power
     * @return mixed
     */
    public function availablePowerNumber($machine, $country_id = 1, $has_power = 75)
    {
//        Log::info('availablePowerNumber: '.$country_id);
        $where = [
            ['has_power', '>', $has_power],
            ['status', '=', 2],
        ];

        $resq = $machine
            ->power()
            ->where($where)
            ->groupBy('power.power_type')
            ->select('power.power_type', DB::raw('COUNT(power.power_type) as num'))
            ->get()
            ->toArray();

        $data = [
                ['code' => ['E2'], 'title' => '普通讲解'],
                ['code' => ['A'],  'title' => '女声讲解'],
                ['code' => ['E'],  'title' => '男声讲解'],
                ['code' => ['I'],  'title' => 'Female voice explanation'],
                ['code' => ['M'],  'title' => 'Male voice explanation'],
        ];

        $res = array_column($resq, null, 'power_type');

        $datas = [];

        if ((count($resq) == 1 && $resq[0]['power_type'] != 'E2') || count($resq) > 1) {

            foreach ($data as $k => $da) {
                $datas[$k]['power_type'] = '#';//初始化为  #
                $datas[$k]['num'] = 0;
                $datas[$k]['title'] = $da['title'];
                foreach ($res as $key => $re) {
                    if (in_array($key, $da['code'])) {
                        $datas[$k]['power_type'] = $key;
                        $datas[$k]['num'] = $re['num'];
                        break;
                    }
                }
            }
        } else {
            $num = isset($res["E2"]) ? $res["E2"]['num'] : 0;
            $datas[0]['power_type'] = 'E2';
            $datas[0]['title'] = "";
            $datas[0]['num'] = $num;
        }

        return $datas;
    }


}
