<?php

namespace App\Imports;

use App\Logistic;
use App\WaybillPriceModel;
use App\Events\WaybillPriceModelEvent;
use App\Unit;
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 WaybillPriceModelsImport implements ToCollection,WithHeadingRow
{
    protected $isOverride;
    public function __construct($isOverride)
    {
        if ($isOverride==1){
            $this->isOverride=true;
        }
    }


    /**
     * @param Collection $collection
     */
    public function Collection(Collection $collection)
    {
        $endIs=false;
        $cityIs=true;
        if (isset($collection->toArray()[0]['承运商'])&&isset($collection->toArray()[0]['计数单位'])&&isset($collection->toArray()[0]['省份'])
            &&isset($collection->toArray()[0]['单价'])){
                $endIs=true;
        }else Cache::put('error','请检查您第一行标题是否存在承运商，计数单位，省份，单价，市，计数区间，起步费，最低计数',86400);
        $exception=[];
        $sum=2;
        if ($endIs) {
            foreach ($collection as $row) {
                if ($row['承运商'] && $row['计数单位'] && $row['省份'] && $row['单价']!=='') {
                    if (strstr($row['省份'], '省')){$row['省份']=str_replace('省','',$row['省份']);};
                    $logistic = Logistic::query()->where('name', $row['承运商'])->first();
                    $unit = Unit::query()->where('name', $row['计数单位'])->first();
                    $province = app("RegionService")->getProvince($row['省份']);
                    $city = app("RegionService")->getCity($row['市'],$province);
                    if ($logistic && $unit && $province) {
                        $billing = WaybillPriceModel::query()->where('logistic_id', $logistic->id);
                        $billing = $billing->where('unit_id', $unit->id);
                        $billing = $billing->where('province_id', $province);
                        if ($row['市']) {
                            if ($city) $billing = $billing->where('city_id', $city);
                            else $billing->whereNull("city_id");
                        }
                        if ($row['计数区间'] && !strstr($row['计数区间'], '∞')) {
                            $str = explode('-', $row['计数区间']);
                            if (count($str) == 2) {
                                $billing = $billing->where('range_min', $str[0]);
                                $billing = $billing->where('range_max', $str[1]);
                            }
                        }
                        $billing = $billing->first();
                        if (!$billing) {
                            if ($row['市']){
                                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NULL',[$logistic->id,$province])->first();
                                if ($waybillPriceModelProvince){
                                    $cityIs=false;
                                    array_push($exception, ['第' . $sum . '行数据已存在省份模型，无需录入城市模型']);
                                }
                            }else{
                                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NOT NULL',[$logistic->id,$province])->first();
                                if ($waybillPriceModelProvince){
                                    $cityIs=false;
                                    array_push($exception, ['第' . $sum . '行数据已存在城市模型，无法录入省份模型']);
                                }
                            }
                            if ($cityIs){
                                $waybillPriceModel = ['logistic_id' => $logistic->id, 'unit_id' => $unit->id, 'province_id' => $province, 'unit_price' => $row['单价']];
                                if ($row['计数区间']) {
                                    $str = explode('-', $row['计数区间']);
                                    if (preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $str[0]) >= 0
                                        && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $str[1]) > 0
                                        && $str[0] < $str[1] && count($str) == 2
                                    ) {
                                        $waybillPriceModel = array_merge($waybillPriceModel, ['range_min' => $str[0], 'range_max' => $str[1]]);
                                    } else {
                                        array_push($exception, ['第' . $sum . '行数据计数区间数据有误，应为：最小值-最大值']);
                                    }
                                }
                                if ($row['市']) {
                                    if ($city) $waybillPriceModel = array_merge($waybillPriceModel, ['city_id' => $city]);
                                }
                                if ($row['起步费'] && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $row['起步费']) > 0) {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['base_fee' => $row['起步费']]);
                                } else {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['base_fee' => 0]);
                                    array_push($exception, ['第' . $sum . '行数据起步费为空，或为负，已默认设为0']);
                                }
                                if ($row['最低计数'] && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $row['最低计数']) > 0) {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['initial_weight' => $row['最低计数']]);
                                } else {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['initial_weight' => 0]);
                                    array_push($exception, ['第' . $sum . '行数据最低计数为空，或为负，已默认设为0']);
                                }
                                $waybillPriceModel=WaybillPriceModel::query()->create($waybillPriceModel);
                                /** @var WaybillPriceModel $waybillPriceModel */
                                event(new WaybillPriceModelEvent($waybillPriceModel));
                            }
                        } else {
                            if ($this->isOverride) {
                                $waybillPriceModel = ['logistic_id' => $logistic->id, 'unit_id' => $unit->id, 'province_id' => $province, 'unit_price' => $row['单价']];
                                if ($row['计数区间']&& !strstr($row['计数区间'], '∞')) {
                                    $str = explode('-', $row['计数区间']);
                                    if (preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $str[0]) > 0
                                        && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $str[1]) > 0
                                        && $str[0] < $str[1] && count($str) == 2
                                    ) {
                                        $waybillPriceModel = array_merge($waybillPriceModel, ['range_min' => $str[0], 'range_max' => $str[1]]);
                                    } else {
                                        array_push($exception, ['第' . $sum . '行数据计数区间数据有误，应为：最小值-最大值']);
                                    }
                                }
                                if ($row['市']) {
                                    if ($city) $waybillPriceModel = array_merge($waybillPriceModel, ['city_id' => $city]);
                                }
                                if ($row['起步费'] && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $row['起步费']) > 0) {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['base_fee' => $row['起步费']]);
                                } else {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['base_fee' => 0]);
                                    array_push($exception, ['第' . $sum . '行数据起步费为空，或为负，已默认设为0']);
                                }
                                if ($row['最低计数'] && preg_match('/^[1-9]\d*\,\d*|[1-9]\d*$/', $row['最低计数']) > 0) {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['initial_weight' => $row['最低计数']]);
                                } else {
                                    $waybillPriceModel = array_merge($waybillPriceModel, ['initial_weight' => 0]);
                                    array_push($exception, ['第' . $sum . '行数据最低计数为空，或为负，已默认设为0']);
                                }
                                $billing->fill($waybillPriceModel);
                                if ($billing->save()) {
                                    /** @var WaybillPriceModel $billing */
                                    event(new WaybillPriceModelEvent($billing));
                                    array_push($exception, ['第' . $sum . '行数据已覆盖原计费模型']);
                                }
                            } else {
                                array_push($exception, ['第' . $sum . '行数据在计费模型中已存在']);
                            }
                        }
                    } else {
                        array_push($exception, ['第' . $sum . '行数据承运商，单位，省在基础数据中未定义']);
                    }
                } else {
                    array_push($exception, ['第' . $sum . '行数据必填项为空']);
                }
                $sum++;
            }
            Cache::put('exception', $exception, 86400);
        }
    }
}
