<?php

namespace App\Http\Controllers;

use App\Owner;
use App\Services\OwnerAreaReportService;
use App\Services\OwnerBillReportService;
use App\Services\OwnerReportService;
use App\Services\OwnerService;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return Response
     */
    public function projectReport(Request $request)
    {
        if(!Gate::allows('客户管理-项目-报表')){ return view('customer.index');  }
        $withs = ["ownerBillReport","owner"=>function($query){
            /** @var Builder $query */
            $query->select("id","name","deleted_at","created_at","customer_id","user_owner_group_id")
                ->with(["customer","userOwnerGroup"]);
        }];
        $ownerGroups = app('UserOwnerGroupService')->getSelection();
        $customers = app('CustomerService')->getSelection();
        $owners = app('OwnerService')->getSelection();
        $reports = app("OwnerReportService")->paginate($request->input(),$withs);
        $params = $request->input();
        return response()->view('customer.project.report',compact("reports","ownerGroups","customers","owners","params"));
    }

    public function projectReportExport(Request $request)
    {
        if(!Gate::allows('客户管理-项目-报表')){ return redirect('denied');  }
        /** @var OwnerReportService $service */
        $service = app('OwnerReportService');
        $withs = ["ownerBillReport","owner"=>function($query){
            /** @var Builder $query */
            $query->select("id","name","deleted_at","created_at","customer_id","user_owner_group_id")
                ->with(["customer","userOwnerGroup"]);
        }];
        if ($request->checkAllSign ?? false){
            $params = $request->input();
            unset($params['checkAllSign']);
            $reports = $service->get($params,$withs);
        }else $reports = $service->get(["id"=>$request->data ?? ''],$withs);
        $column = ["项目小组","客户","子项目","状态","创建日期","在库时长","结算月","日均单量","结算月上月盘点面积","结算月盘点面积","初始账单金额","确认账单金额","确认日期"];
        $list = [];
        foreach ($reports as $report){
            $list[] = [
                $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
                $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
                $report->owner ? $report->owner->name : '',
                $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
                $report->owner ? (string)$report->owner->created_at : '',
                $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days)." 天"  : '') : '',
                $report->counting_month,
                $report->daily_average_order_amount,
                $report->last_month_counting_area,
                $report->current_month_counting_area,
                $report->ownerBillReport ? $report->ownerBillReport->initial_fee : '',
                $report->ownerBillReport ? $report->ownerBillReport->confirm_fee : '',
                $report->ownerBillReport ? (string)$report->ownerBillReport->updated_at : '',
            ];
        }
        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
        if ($post->status() == 500){
            throw new Exception($post->header("Msg"));
        }
        return response($post,200, [
            "Content-type"=>"application/octet-stream",
            "Content-Disposition"=>"attachment; filename=客户项目报表-".date('ymdHis').'.xlsx',
        ]);
    }

    public function projectIndex()
    {
        if(!Gate::allows('客户管理-项目-查询')){ return redirect('denied');  }
        /** @var OwnerService $service */
        $service = app('OwnerService');
        $owners = $service->paginate(['customer_id'=>true],['customer',"userOwnerGroup","ownerStoragePriceModels","ownerAreaReport"=>function($query){
            $month = date('Y-m');
            /** @var Builder $query */
            $query->where("counting_month","like",$month."%");
        }]);
        return response()->view('customer.project.index',compact("owners"));
    }

    public function projectIndexExport(Request $request)
    {
        if(!Gate::allows('客户管理-项目-查询')){ return redirect('denied');  }
        /** @var OwnerService $service */
        $service = app('OwnerService');
        $withs = ['customer',"userOwnerGroup","ownerStoragePriceModels","ownerAreaReport"=>function($query){
            $month = date('Y-m');
            /** @var Builder $query */
            $query->where("counting_month","like",$month."%");
        }];
        $params = $request->input();
        $params['customer_id']=true;
        if ($request->checkAllSign ?? false) unset($params['checkAllSign']);
        else $params = ["id"=>$request->data ?? ''];
        $owners = $service->get($params,$withs);
        $column = ["客户","税率","项目","货主代码","合同号","创建日期","销售名称","公司全称","联系人","联系电话","项目小组","用仓类型","当月结算面积","月单量预警","是否激活","项目描述"];
        $list = [];
        foreach ($owners as $owner){
            $list[] = [
                $owner->customer ? $owner->customer->name : '',
                $owner->tax_rate,
                $owner->name,
                $owner->code,
                $owner->contract_number,
                $owner->created_at,
                $owner->salesman,
                $owner->customer ? $owner->customer->company_name : '',
                $owner->linkman,
                $owner->phone_number,
                $owner->userOwnerGroup ? $owner->userOwnerGroup->name : '',
                implode(",",array_unique(array_column(($owner->ownerStoragePriceModels)->toArray(),"using_type"))),
                $owner->ownerAreaReport ? $owner->ownerAreaReport->accounting_area : '',
                $owner->waring_line_on,
                $owner->deleted_at ? '否' : '是',
                $owner->description
            ];
        }
        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
        if ($post->status() == 500){
            throw new Exception($post->header("Msg"));
        }
        return response($post,200, [
            "Content-type"=>"application/octet-stream",
            "Content-Disposition"=>"attachment; filename=客户报表-".date('ymdHis').'.xlsx',
        ]);
        $customers = $service->get(Auth::user(),['customer_id'=>true],['customer']);
        return response()->view('customer.project.index');
    }

    public function projectCreate()
    {
        if(!Gate::allows('客户管理-项目-录入')){ return redirect('denied');  }
        return response()->view('customer.project.create');
    }

    public function projectArea()
    {
        if(!Gate::allows('客户管理-项目-面积')){ return redirect('denied');  }
        return response()->view('customer.project.area');
    }

    public function financeInstantBill()
    {
        if(!Gate::allows('客户管理-财务-即时账单')){ return redirect('denied');  }
        return response()->view('customer.finance.instantBill');
    }

    public function financeBillConfirmation()
    {
        if(!Gate::allows('客户管理-财务-账单确认')){ return redirect('denied');  }
        return response()->view('customer.finance.billConfirmation');
    }
}
