<?php
/**
 * Created by PhpStorm.
 * User: machengjun
 * Date: 2018/3/13
 * Time: 下午5:47
 */

namespace App\Http\Controllers\Api\Business;

use App\Common\Enums\HtTab;
use App\Http\Controllers\LoginController;
use App\Repositories\Business\GuideRepository;
use App\Repositories\Business\MachineRepository;
use App\Repositories\Business\ProductionRepository;
use App\Repositories\Business\RentRepository;
use App\Repositories\Business\ReportRepository;
use App\Repositories\Business\SpotRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class ReportController extends LoginController
{
    protected $spot;
    protected $machine;
    protected $rent;
    protected $production;
    protected $guide;
    protected $report;


    public function __construct(SpotRepository $spot, MachineRepository $machine, RentRepository $rent, ProductionRepository $production, GuideRepository $guide, ReportRepository $report)
    {
        $this->spot = $spot;
        $this->machine = $machine;
        $this->rent = $rent;
        $this->production = $production;
        $this->guide = $guide;
        $this->report = $report;

    }

    function index(Request $request)
    {
        $response = [];
        if ($spot_id = $request->get('spot_id')) {
            //指定景点查询，验证权限
            $spotData = $this->spot->spotPermission($request->get('user'), $spot_id);
            $spotName = $spotData->spotname;
        } else {
            //未指定景点，系统自动选择
            $spotData = $this->spot->getToShowSpot($request->get('user'), true);
            $spot_id = $spotData->id;
            $spotName = $spotData->spotname;
        }
        //景区信息
        $response['spotName'] = $spotName;

        //机柜信息
        $machines_obj = $this->machine->getSpotMachine($spot_id);
        
        
        if ($spot_id == 14) {
            $yangzhou_info = $this->rent->getYangzhouData($spot_id)->first();
            // return $this->responseSuccess($yangzhou_info);
            $response['machines'] = $this->_formatMachineInfoTest($machines_obj);
            //当天租借个数
            $response['today_rent_number'] = $yangzhou_info->rent_today;

            //当天租借有效单
            $response['today_rent_valid_number'] = $yangzhou_info->rent_valied;

            //未归还个数
            $response['not_return_number'] = $yangzhou_info->rent_noreturned;

            //当天收益
            $response['today_income'] = $yangzhou_info->today_income;

            //订单完成数量
            //租借订单
            $response['order_finish'] = $yangzhou_info->rent_finished;

            //当月收益
            $response['this_month_income'] = $yangzhou_info->month_income;
        }else{
            $response['machines'] = $this->_formatMachineInfo($machines_obj);
            //当天租借个数
            $response['today_rent_number'] = $this->rent->getTodayRent($spot_id);

            //当天租借有效单
            $response['today_rent_valid_number'] = $this->rent->getTodayValidRent($spot_id);

            //未归还个数
            $response['not_return_number'] = $this->production->getNotReturnProduction($spot_id);

            //当天收益
            //租借收益
            $rent_today_income = $this->rent->getTodayIncome($spot_id);
            //微导览收益
            $guide_today_income = $this->guide->getTodayIncome($spot_id);

            $response['today_income'] = round(($rent_today_income + $guide_today_income) / 100, 2);

            //订单完成数量
            //租借订单
            $response['order_finish'] = $this->rent->rentFinish($spot_id);

            //当月收益
            $rent_this_month_income = $this->rent->getThisMonthIncome($spot_id);
            //微导览收益
            $guide_this_month_income = $this->guide->getThisMonthIncome($spot_id);

            $response['this_month_income'] = round(($rent_this_month_income + $guide_this_month_income) / 100, 2);
        }
        

        //订单优惠
        $response['discount_number'] = $this->rent->getDiscount($spot_id);

        
        //微导览
        $response['order_finish'] += $this->guide->guideFinish($spot_id);

        return $this->responseSuccess($response);

    }

    function chart(Request $request)
    {
        $spot_id = $this->spot->getToShowSpot($request->get('user'));
        switch ($request->get('type')) {
            case 1:
                $response['data'] = $this->_getSevenDayData($spot_id);
                break;
            case 2:
                $response['data'] = $this->_getOneMonthData($spot_id);
                break;

            case 3:
                $response['data'] = $this->_getSixMonthData($spot_id);
                break;
            default:
                $response['data'] = $this->_getSevenDayData($spot_id);
                break;
        }

        return $this->responseSuccess($response);

    }

    function rentOverRecord(Request $request)
    {

        Log::info("[rentRecord] params:" . json_encode($request->all()));

        $spot_id = $this->spot->getToShowSpot($request->get('user'));
        $data = $request->only('page', 'limit');
        $data['page'] = isset($data['page']) ? $data['page'] : 0;
        $data['limit'] = isset($data['limit']) ? $data['limit'] : HtTab::DEFAULT_LIMIT;
        $search = $request->only('day', 'month');
        if ($spot_id == 14) {
            $rent_records_obj = $this->rent->getSpotRentRecordTest($spot_id, $data['page'], $data['limit'], $search);
        }else{
            $rent_records_obj = $this->rent->getSpotRentRecord($spot_id, $data['page'], $data['limit'], $search);    
        }
        
        $response['data'] = $this->_formatRentRecord($rent_records_obj, $spot_id);
        return $this->responseSuccess($response);

    }

    function guideRecord(Request $request)
    {

        Log::info("[guideRecord] params:" . json_encode($request->all()));

        $spot_id = $this->spot->getToShowSpot($request->get('user'));
        $data = $request->only('page', 'limit');
        $data['page'] = isset($data['page']) ? $data['page'] : 0;
        $data['limit'] = isset($data['limit']) ? $data['limit'] : HtTab::DEFAULT_LIMIT;
        $search = $request->only('day', 'month');
        $guide_records_obj = $this->guide->getSpotGuideRecord($spot_id, $data['page'], $data['limit'], $search);
        $response['data'] = $this->_formatGuideRecord($guide_records_obj, $spot_id);
        return $this->responseSuccess($response);

    }

    private function _formatGuideRecord($guide_records_obj, $spot_id)
    {

        $data = [];
        if ($guide_records_obj != null) {
            foreach ($guide_records_obj as $guide_record_obj) {
                $month = substr($guide_record_obj->pay_time, '0', '7');
                $data[$month]['list'][] = [
                    'real_total' => $guide_record_obj->real_total,
                    'pay_time' => $guide_record_obj->pay_time,
                ];
            }
            foreach ($data as $k => $v) {
                $data[$k]['income'] = $this->_getSpotGuideInMonthIncome($k, $spot_id);
            }
        }
        return $data;

    }

    private function _getSpotGuideInMonthIncome($month, $spot_id)
    {
        if ($month == date('Y-m')) {
            return $this->guide->getThisMonthIncome($spot_id);
        }
        return $this->report->getSpotGuideInMonthIncomeTotal($month);
    }

    private function _formatRentRecord($rent_records_obj, $spot_id)
    {
        $data = [];
        if ($rent_records_obj != null) {
            foreach ($rent_records_obj as $rent_record_obj) {
                $month = substr($rent_record_obj->over_time, '0', '7');
                $data[$month]['list'][] = [
                    'real_total' => $rent_record_obj->real_total,
                    'over_time' => $rent_record_obj->over_time,
                ];
            }
            foreach ($data as $k => $v) {
                $data[$k]['income'] = $this->_getSpotRentInMonthIncome($k, $spot_id);
            }
        }
        return $data;

    }

    private function _getSpotRentInMonthIncome($month, $spot_id)
    {

        if ($month == date('Y-m')) {
            return $this->rent->getThisMonthIncome($spot_id);
        }
        return $this->report->getSpotRentInMonthIncomeTotal($month,$spot_id);

    }


    private function _getSevenDayData($spot_id)
    {
        $eight_date = date('Y-m-d', strtotime("-8 day"));
        $one_date = date('Y-m-d', strtotime("-1 day"));
        if ($spot_id == 14) {
            $data = $this->report->getSpotDayIncomeTest($eight_date, $one_date, $spot_id);
        }else{
            $data = $this->report->getSpotDayIncome($eight_date, $one_date, $spot_id);    
        }
        
        return $this->_formatSevenDayData($data);
    }


    private function _getOneMonthData($spot_id)
    {
        $start_date = date('Y-m-d', strtotime("-31 day"));
        $end_date = date('Y-m-d', strtotime("-1 day"));
        if ($spot_id == 14) {
            $data = $this->report->getSpotDayIncomeTest($start_date, $end_date, $spot_id);
        }else{
            $data = $this->report->getSpotDayIncome($start_date, $end_date, $spot_id);    
        }
        
        return $this->_formatOneMonthData($data);
    }

    private function _getSixMonthData($spot_id)
    {
        $start_mon = date('Ym', strtotime("-7 month"));
        $end_mon = date('Ym', strtotime("-1 month"));
        if ($spot_id == 14) {
            $data = $this->report->getSpotMonthIncomeTest($start_mon, $end_mon, $spot_id);
        }else{
            $data = $this->report->getSpotMonthIncome($start_mon, $end_mon, $spot_id);    
        }
        
        return $this->_formatSixMontData($data);
    }

    private function _formatSixMontData($data)
    {
        $real_data = [];
        if ($data != null) {
            foreach ($data as $v) {
                $real_data[$v->month] = round($v->total + $v->guide_total, 2);
            }
        }
        $new_data = [];
        $n = 0;
        for ($i = 6; $i >= 1; $i--) {
            $month_show = date("Y-m", strtotime("-{$i} month ", strtotime(date("Y-m"))));
            $month = str_replace('-', '', $month_show);
            $new_data[$n]['month'] = $month_show;
            $new_data[$n]['total'] = isset($real_data[$month]) ? $real_data[$month] : 0;
            $n++;
        }
        return $new_data;
    }

    private function _formatOneMonthData($data)
    {
        $real_data = [];
        if ($data != null) {
            foreach ($data as $v) {
                $real_data[$v->day] = round($v->total + $v->guide_total, 2);
            }
        }
        $new_data = [];
        $n = 0;

        for ($i = 30; $i >= 1; $i--) {
            $date = date("Y-m-d", strtotime("-{$i} day "));
            $new_data[$n]['day'] = $date;
            $new_data[$n]['total'] = isset($real_data[$date]) ? $real_data[$date] : 0;
            $n++;
        }
        return $new_data;
    }

    private function _formatSevenDayData($data)
    {
        $real_data = [];
        if ($data != null) {
            foreach ($data as $v) {
                $real_data[$v->day] = round($v->total + $v->guide_total, 2);
            }
        }
        $new_data = [];
        $n = 0;
        for ($i = 7; $i >= 1; $i--) {
            $date = date("Y-m-d", strtotime("-{$i} day "));
            $new_data[$n]['day'] = $date;
            $new_data[$n]['total'] = isset($real_data[$date]) ? $real_data[$date] : 0;
            $n++;
        }
        return $new_data;
    }

    private function _formatMachineInfo($machines_obj)
    {
        $data = [];
        foreach ($machines_obj as $k => $machine_obj) {
            $data[$k]['mac_no'] = $machine_obj->mac_no;
            $data[$k]['life'] = $machine_obj->life;
            $data[$k]['hatch_number'] = $machine_obj->hatch_number;
            $data[$k]['available_number'] = $machine_obj->available_number;
            $data[$k]['take_out_tool'] = $machine_obj->life == 1 ? $machine_obj->take_out_tool : 0;
        }
        return $data;
    }

    private function _formatMachineInfoTest($machines_obj)
    {
        $data = [];
        foreach ($machines_obj as $k => $machine_obj) {
            $data[$k]['mac_no'] = $machine_obj->mac_no;
            $data[$k]['life'] = $machine_obj->life;
            $data[$k]['hatch_number'] = $machine_obj->hatch_number;
            $data[$k]['available_number'] = rand(20,40);
            $data[$k]['take_out_tool'] = $machine_obj->life == 1 ? $machine_obj->take_out_tool : 0;
        }
        return $data;
    }


}
