<?php

namespace App\Admin\Imports;

use App\Models\Coupon;
use App\Models\CouponPaCheck;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;


class SettleCouponImport implements ToModel, WithStartRow, WithChunkReading, WithBatchInserts
{

    use Importable, SkipsErrors;

    public $chunk = 5000;

    /**
     * @param  array  $row
     * @return \Illuminate\Database\Eloquent\Model|null
     * @throws \Exception
     */
    public function model(array $row)
    {
        try {
            $order_id = trim($row[0]);
            $exists   = Coupon::query()->where('pa_order_id', $order_id)->exists();
            if ($exists) {
                Coupon::query()->where('pa_order_id', $order_id)->update([
                    'is_settle' => 1
                ]);
            } else {
                $exists = CouponPaCheck::query()->where('pa_order_id', $order_id)->exists();
                if (! $exists) {
                    CouponPaCheck::create([
                        'pa_order_id' => $order_id
                    ]);
                }
            }


        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

    }

    /**
     * 从第几行开始处理数据 就是不处理标题
     *
     * @return int
     */
    public function startRow(): int
    {
        return 2;
    }

    /**
     * Notes: 批量导入1000条
     *
     * @Author: 玄尘
     * @Date  : 2020/11/23 13:40
     * @return int
     */
    public function chunkSize(): int
    {
        return $this->chunk;
    }

    /**
     * Notes: 以1000条数据基准切割数据
     *
     * @Author: 玄尘
     * @Date  : 2020/11/23 13:41
     * @return int
     */
    public function batchSize(): int
    {
        return $this->chunk;
    }


}
