<?php

namespace App\Imports;

use App\CarType;
use App\OwnerPriceDirectLogistic;
use App\OwnerPriceDirectLogisticCar;
use App\Services\common\BatchUpdateService;
use App\Services\LogService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');
class OwnerPriceDirectLogisticDetailImport implements ToCollection,WithHeadingRow,WithMultipleSheets
{
    public function sheets(): array
    {
        return [
            0 => $this,
        ];
    }
    protected $model;

    public function __construct($model)
    {
        $this->model = $model;
    }

    /**
    * @param Collection $collection
    * @return bool
    */
    public function collection(Collection $collection)
    {
        $row = $collection->first();
        $additional = "续费";

        foreach ($row as $key => $str){
            if (mb_strpos($key,$additional) !== false){
                $row["续费"] = $str;
                $additional = $key;
                break;
            }
        }

        $header = [
            "车型","起步费","续费"
        ];
        foreach ($header as $str){
            if (!isset($row[$str])){
                Cache::put("directLogistic",["success"=>false, "data"=>"表头不存在“".$str."”"],86400);
                return false;
            }
        }

        //车型map
        $map = [];
        $carTypes = CarType::query()->get();
        foreach ($carTypes as $carType){
            $map[$carType->name] = $carType->id;
        }

        //只读情况下
        if (!$this->model){
            return $this->readonly($collection, $map, $additional);
        }

        //拷贝数据时切换对象
        if (!$this->model->operation){
            $this->model = app("OwnerPriceDirectLogisticService")->copy($this->model);
        }

        //已存在的计费
        $existDetails = [];
        foreach ($this->model->details as $detail){
            $existDetails[$detail->car_type_id] = $detail->id;
        }

        //生成列表内的重复条目
        $existInsert = [];

        //导入的数据整理，存在更新
        $id = $this->model->id;
        $errors = [];
        $insert = [];
        $update = [["id","base_fee","additional_fee"]];
        $date = date('Y-m-d H:i:s');
        foreach ($collection as $index => $item){
            /* 数据校验 */
            if (!$item["车型"]){
                $errors[] = "第“".($index+2)."”行车型为空";
                continue;
            }else{
                if (!isset($map[$item["车型"]])){
                    $errors[] = "第“".($index+2)."”行未知车型";
                    continue;
                }
                $item["车型"] = $map[$item["车型"]];
            }
            if (!$item["起步费"] || !is_numeric($item["起步费"]) || $item["起步费"] <= 0){
                $errors[] = "第“".($index+2)."”行非法起步费";
                continue;
            }
            if (!$item[$additional] || !is_numeric($item[$additional]) || $item[$additional] <= 0){
                $errors[] = "第“".($index+2)."”行非法续费";
                continue;
            }

            if (isset($existInsert[$item["车型"]])){
                $errors[] = "第“".($index+2)."”行与第“".$existInsert[$item["车型"]]."”行重复";
                continue;
            }

            if (isset($existDetails[$item["车型"]])){
                $update[] = [
                    "id" => $existDetails[$item["车型"]],
                    "base_fee" => $item["起步费"],
                    "additional_fee" => $item[$additional],
                    "updated_at" => $date,
                ];
                continue;
            }
            $insert[] = [
                "owner_price_direct_logistic_id" => $id,
                "car_type_id" => $item["车型"],
                "base_fee" => $item["起步费"],
                "additional_fee" => $item[$additional],
                "created_at" => $date,
            ];
            $existInsert[$item["车型"]] = $index+2;
        }
        if (count($update) > 1){
            app(BatchUpdateService::class)->batchUpdate("owner_price_direct_logistic_cars",$update);
            LogService::log(__METHOD__,"直发车计费导入修改",json_encode($update));
        }
        if (count($insert) > 0){
            OwnerPriceDirectLogisticCar::query()->insert($insert);
            LogService::log(__METHOD__,"直发车计费导入录入",json_encode($insert));
        }

        $this->model->load(["details"=>function($query){$query->with("carType");}]);
        Cache::put("directLogistic",["success"=>true,"data"=>$this->model->details,"errors"=>$errors],86400);
        return true;
    }

    private function readonly(Collection $collection, array $map, $additional)
    {
        $errors = [];
        $data = [];
        $existInsert = [];
        foreach ($collection as $index => $item){
            /* 数据校验 */
            if (!$item["车型"]){
                $errors[] = "第“".($index+2)."”行车型为空";
                continue;
            }else{
                if (!isset($map[$item["车型"]])){
                    $errors[] = "第“".($index+2)."”行未知车型";
                    continue;
                }
                $item["车型"] = $map[$item["车型"]];
            }
            if (!$item["起步费"] || !is_numeric($item["起步费"]) || $item["起步费"] <= 0){
                $errors[] = "第“".($index+2)."”行非法起步费";
                continue;
            }
            if (!$item[$additional] || !is_numeric($item[$additional]) || $item[$additional] <= 0){
                $errors[] = "第“".($index+2)."”行非法续费";
                continue;
            }

            if (isset($existInsert[$item["车型"]])){
                $errors[] = "第“".($index+2)."”行与第“".$existInsert[$item["车型"]]."”行重复";
                continue;
            }
            $data[] = [
                "car_type_id" => $item["车型"],
                "base_fee" => $item["起步费"],
                "additional_fee" => $item[$additional],
            ];
            $existInsert[$item["车型"]] = $index+2;
        }
        Cache::put("directLogistic",["success"=>true,"data"=>$data,"errors"=>$errors],86400);
        return true;
    }
}
