<?php

namespace App\Imports;

use App\Components\AsyncResponse;
use App\OwnerPriceExpress;
use App\OwnerPriceExpressProvince;
use App\Province;
use App\Services\common\BatchUpdateService;
use App\Services\LogService;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class ExpressImport implements WithMultipleSheets,ToArray
{

    use AsyncResponse;

    public function sheets(): array
    {
        return [
            0 => $this,
        ];
    }

    /** @var OwnerPriceExpress|\stdClass $express */
    protected $express;
    /** @var array $errors */
    private $errors = [];

    public function __construct(OwnerPriceExpress $express = null)
    {
        $this->express = $express;
    }

    public function array(array $array)
    {
        if (isset($array[0][0]) && $array[0][0]=='省')array_splice($array,0,1);
        $array = $this->filter($array);
        if (!$this->express)$this->success(["data"=>$array,"errors"=>$this->errors]);

        if (!$this->express->operation)$this->express = app("OwnerPriceExpressService")->copy($this->express);

        //已存在的计费
        $existDetails = [];
        foreach ($this->express->details as $detail){
            $existDetails[$detail->province_id] = $detail->id;
        }
        //导入的数据整理，存在更新
        $id = $this->express->id;
        $insert = [];
        $update = [["id","initial_weight_price","additional_weight_price","updated_at"]];
        $date = date('Y-m-d H:i:s');
        foreach ($array as $index => $item){
            if (isset($existDetails[$item[0]])){
                $update[] = [
                    "id" => $existDetails[$item[0]],
                    "initial_weight_price" => $item[1],
                    "additional_weight_price" => $item[2],
                    "updated_at" => $date,
                ];
                continue;
            }
            $insert[] = [
                "owner_price_express_id" => $id,
                "province_id" => $item[0],
                "initial_weight_price" => $item[1],
                "additional_weight_price" => $item[2],
                "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.province");
        $this->success(["data"=>$this->express->details,"errors"=>$this->errors]);
    }

    public function filter(array $array)
    {
        $result = [];
        //省份map
        $map = [];
        $provinces = Province::query()->get();
        foreach ($provinces as $province){
            $map[mb_substr($province->name,0,2)] = $province->id;
        }
        foreach ($array as &$item){
            if (count($item)<3 || (!$item[0] && !$item[1] && !$item[2]))continue;
            $province = mb_substr($item[0],0,2);
            if (!isset($map[$province])){
                $this->errors[] = "“".$province."”此省份未被记录";
                continue;
            }else $item[0] = $map[$province];
            $sign = false;
            for($i=1;$i<count($item);$i++){
                if (($item[$i] && !is_numeric($item[$i])) || ($item[$i]!==null && $item[$i]<=0)){
                    $this->errors[] = "“".$province."”非法价格";
                    $sign = true;
                    break;
                }
                if ($item[$i]===null && $i>3)break;
            }
            if ($sign)continue;
            $result[] = $item;
        }
        return $result;
    }
}
