<?php

namespace App\Imports;

use App\City;
use App\OwnerPriceLogisticDetail;
use App\Province;
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\Imports\HeadingRowFormatter;


HeadingRowFormatter::default('none');
class OwnerPriceLogisticDetailImport implements ToCollection,WithHeadingRow
{
    protected $logistic;
    public function __construct($logistic)
    {
        $this->logistic = $logistic;
    }

    /**
    * @param Collection $collection
    * @return bool
    */
    public function collection(Collection $collection)
    {
        $row = $collection->first();
        $header = [
            "计数单位","计数区间","省份","市","单价","送货费","起始计费","起始计数","费率"
        ];
        foreach ($header as $str){
            if (!isset($row[$str])){
                Cache::put("logistic",["success"=>false, "data"=>"表头不存在“".$str."”"],86400);
                return false;
            }
        }

        //省份map
        $map = [];
        $provinces = Province::query()->get();
        foreach ($provinces as $province){
            $map[$province->name] = $province->id;
        }

        //市map
        $cityMap = [];
        $cityMappingProvince = [];
        $cities = City::query()->get();
        foreach ($cities as $city){
            $cityMap[$city->name] = $city->id;
            $cityMappingProvince[$city->id] = $city->province_id;
        }

        if (!$this->logistic)
            return $this->readonly($collection, $map, $cityMap, $cityMappingProvince);

        if (!$this->logistic->operation){
            $this->logistic = app("OwnerPriceLogisticService")->copy($this->express);
        }
        //对比单位
        $unit = $this->logistic->unit ? strtoupper($this->logistic->unit->name) : '';
        $otherUnit = $this->logistic->otherUnit ? strtoupper($this->logistic->otherUnit->name) : '';

        //对比区间
        $range = [
            $unit => explode(",",$this->logistic->unit_range),
            $otherUnit => explode(",",$this->logistic->other_unit_range),
        ];

        //已存在的计费
        $existDetails = [];
        foreach ($this->logistic->details as $detail){
            $existDetails[$detail->unit_id.'_'.$detail->range."_".$detail->province_id."_".$detail->city_id] = $detail->id;
        }

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

        //导入的数据整理，存在更新
        $id = $this->logistic->id;
        $errors = [];
        $insert = [];
        $update = [["id","unit_price","delivery_fee","initial_fee","initial_amount","rate","updated_at"]];
        $date = date('Y-m-d H:i:s');
        foreach ($collection as $index => $item){
            /* 数据校验 */
            if (!$item["省份"]){
                $errors[] = "第“".($index+2)."”行省份为空";
                continue;
            }else{
                if ((!isset($map[$item["省份"]]) && !isset($map[mb_substr($item["省份"], 0,-1)]))){
                    $errors[] = "第“".($index+2)."”行未知省份";
                    continue;
                }
                if (isset($map[mb_substr($item["省份"], 0,-1)]))$item["省份"] = mb_substr($item["省份"], 0,-1);
            }
            if (!$item["计数单位"] || (strtoupper($item["计数单位"]) != $unit && strtoupper($item["计数单位"]) != $otherUnit)){
                Cache::put("logistic",["success"=>false, "data"=>"第“".($index+2)."”行单位不符合"],86400);
                return false;
            }
            if (!$item["计数区间"] || array_search($item["计数区间"],$range[strtoupper($item["计数单位"])]) === false){
                Cache::put("logistic",["success"=>false, "data"=>"第“".($index+2)."”行区间不符合"],86400);
                return false;
            }
            if (!isset($cityMap[$item["市"]])){
                $errors[] = "第“".($index+2)."”行未知城市";
                continue;
            }
            if (!$item["单价"] || !is_numeric($item["单价"]) || $item["单价"] <= 0){
                $errors[] = "第“".($index+2)."”行非法单价";
                continue;
            }
            $numeric = ["送货费","起始计费","起始计数","费率"];
            $sign = false;
            foreach ($numeric as $column){
                if ($item[$column] && (!is_numeric($item[$column]) || $item[$column] <= 0)){
                    $errors[] = "第“".($index+2)."”行非法".$column;
                    $sign = true;
                    break;
                }
            }
            if ($sign)continue;

            /* 数据转换及存在校验 */
            if ($cityMappingProvince[$cityMap[$item["市"]]] != $map[$item["省份"]]){
                $errors[] = "第“".($index+2)."”行城市不属于该省份";
                continue;
            }
            $item["省份"] = $map[$item["省份"]];
            $item["市"] = $cityMap[$item["市"]];
            $item["计数单位"] = strtoupper($item["计数单位"]) == $unit ? $this->logistic->unit_id : $this->logistic->other_unit_id;
            $key = $item["计数单位"]."_".$item["计数区间"]."_".$item["省份"]."_".$item["市"];
            if (isset($existInsert[$key])){
                $errors[] = "第“".($index+2)."”行与第“".$existInsert[$key]."”行重复";
                continue;
            }

            if (isset($existDetails[$key])){
                $update[] = [
                    "id" => $existDetails[$key],
                    "unit_price" => $item["单价"],
                    "delivery_fee" => $item["送货费"],
                    "initial_fee" => $item["起始计费"],
                    "initial_amount" => $item["起始计数"],
                    "rate" => $item["费率"],
                    "updated_at" => $date,
                ];
                continue;
            }
            $insert[] = [
                "owner_price_logistic_id" => $id,
                "unit_id" => $item["计数单位"],
                "range" => $item["计数区间"],
                "province_id" => $item["省份"],
                "city_id" => $item["市"],
                "unit_price" => $item["单价"],
                "delivery_fee" => $item["送货费"],
                "initial_fee" => $item["起始计费"],
                "initial_amount" => $item["起始计数"],
                "rate" => $item["费率"],
                "created_at" => $date,
            ];
            $existInsert[$key] = $index+2;
        }
        if (count($update) > 1){
            app(BatchUpdateService::class)->batchUpdate("owner_price_logistic_details",$update);
            LogService::log(__METHOD__,"物流计费导入修改",json_encode($update));
        }
        if (count($insert) > 0){
            OwnerPriceLogisticDetail::query()->insert($insert);
            LogService::log(__METHOD__,"物流计费导入录入",json_encode($insert));
        }

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

    public function readonly(Collection $collection, array $map, array $cityMap, array $cityMappingProvince)
    {
        //生成列表内的重复条目
        $existInsert = [];
        //符合数据
        $data = [];
        //错误信息
        $errors = [];
        foreach ($collection as $index => $item){
            /* 数据校验 */
            if (!$item["省份"]){
                $errors[] = "第“".($index+2)."”行省份为空";
                continue;
            }else{
                if ((!isset($map[$item["省份"]]) && !isset($map[mb_substr($item["省份"], 0,-1)]))){
                    $errors[] = "第“".($index+2)."”行未知省份";
                    continue;
                }
                if (isset($map[mb_substr($item["省份"], 0,-1)]))$item["省份"] = mb_substr($item["省份"], 0,-1);
            }
            if (!isset($cityMap[$item["市"]])){
                $errors[] = "第“".($index+2)."”行未知城市";
                continue;
            }
            if (!$item["单价"] || !is_numeric($item["单价"]) || $item["单价"] <= 0){
                $errors[] = "第“".($index+2)."”行非法单价";
                continue;
            }
            $numeric = ["送货费","起始计费","起始计数","费率"];
            $sign = false;
            foreach ($numeric as $column){
                if ($item[$column] && (!is_numeric($item[$column]) || $item[$column] <= 0)){
                    $errors[] = "第“".($index+2)."”行非法".$column;
                    $sign = true;
                    break;
                }
            }
            if ($sign)continue;

            /* 数据转换及存在校验 */
            if ($cityMappingProvince[$cityMap[$item["市"]]] != $map[$item["省份"]]){
                $errors[] = "第“".($index+2)."”行城市不属于该省份";
                continue;
            }
            $item["省份"] = $map[$item["省份"]];
            $item["市"] = $cityMap[$item["市"]];
            $key = $item["计数单位"]."_".$item["计数区间"]."_".$item["省份"]."_".$item["市"];
            if (isset($existInsert[$key])){
                $errors[] = "第“".($index+2)."”行与第“".$existInsert[$key]."”行重复";
                continue;
            }

            $data[] = [
                "unit_id" => $item["计数单位"],
                "range" => $item["计数区间"],
                "province_id" => $item["省份"],
                "city_id" => $item["市"],
                "unit_price" => $item["单价"],
                "delivery_fee" => $item["送货费"],
                "initial_fee" => $item["起始计费"],
                "initial_amount" => $item["起始计数"],
                "rate" => $item["费率"],
            ];
            $existInsert[$key] = $index+2;
        }
        Cache::put("logistic",["success"=>true,"data"=>$data,"errors"=>$errors],86400);
        return true;
    }
}
