<?php

namespace App\Imports;

use App\OwnerPriceExpress;
use App\OwnerPriceExpressProvince;
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 ExpressImport implements ToCollection,WithHeadingRow
{
    protected $express;
    public function __construct(OwnerPriceExpress $express = null)
    {
        $this->express = $express;
    }

    /**
    * @param Collection $collection
    * @return bool
    */
    public function collection(Collection $collection)
    {
        if (!$this->express){
            Cache::put("express",["success"=>false, "data"=>"不存在父级"],86400);
            return false;
        }
        $row = $collection->first();
        $header = [
            "省","首重价格","续重价格"
        ];
        foreach ($header as $str){
            if (!isset($row[$str])){
                Cache::put("express",["success"=>false, "data"=>"表头不存在“".$str."”"],86400);
                return false;
            }
        }

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

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

        //导入的数据整理，存在更新
        $id = $this->express->id;
        $errors = [];
        $insert = [];
        $update = [["id","initial_weight_price","additional_weight_price","updated_at"]];
        $date = date('Y-m-d H:i:s');
        foreach ($collection as $index => $item){
            if (!isset($map[$item["省"]])){
                $errors[] = "第“".($index+2)."”行未知省份";
                continue;
            }
            if (!is_numeric($item["首重价格"]) || $item["首重价格"] <= 0){
                $errors[] = "第“".($index+2)."”行非法首重价格";
                continue;
            }
            if (!is_numeric($item["续重价格"]) || $item["续重价格"] <= 0){
                $errors[] = "第“".($index+2)."”行非法续重价格";
                continue;
            }
            if (isset($existDetails[$map[$item["省"]]])){
                $update[] = [
                    "id" => $existDetails[$map[$item["省"]]],
                    "initial_weight_price" => $item["首重价格"],
                    "additional_weight_price" => $item["续重价格"],
                    "updated_at" => $date,
                ];
                continue;
            }
            $insert[] = [
                "owner_price_express_id" => $id,
                "province_id" => $map[$item["省"]],
                "initial_weight_price" => $item["首重价格"],
                "additional_weight_price" => $item["续重价格"],
                "created_at" => $date,
            ];
        }
        if (count($update) > 1){
            app(BatchUpdateService::class)->batchUpdate("owner_price_express_provinces",$update);
            LogService::log(__METHOD__,"快递计费导入修改",json_encode($update));
        }
        if (count($insert) > 0){
            OwnerPriceExpressProvince::query()->insert($insert);
            LogService::log(__METHOD__,"快递计费导入录入",json_encode($insert));
        }

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