<?php

namespace App\Imports;

use App\Command\Log;
use App\Models\Brand;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

use function Matrix\trace;

class ImportExcel implements ToCollection
{
    private $className = null;

    private $filename = null;


    public function __construct($className, $filename)
    {
        $this->className = $className;
        //文件存储后临时路径含文件名
        $this->filename = $filename;
    }

    public function sheets(): array
    {
        // 只处理第一个sheet
        return [
            0 => $this,
        ];
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $rows)
    {
        set_time_limit(0);
        // 去掉表头
        unset($rows[0]);
        unset($rows[1]);
        $data = $this->uploadImg($this->filename);
        //Log::add('导入数据', $data);
        DB::enableQueryLog();
        $i = 0;
        foreach ($data as $k => $item) {

            if ($k == 0 || $k == 1) {
                continue;
            }
            $i++;
            $result = $this->className::CreateImportData($item);
            if (!$result['goods_name']) {
                continue;
            }

            $insert[] = $result;
            $res = DB::table($this->className::getTableName())->insert($insert);
            if ($res) {
                $id = DB::getPdo()->lastInsertId();
                $this->addGoodSku($result['sku'], $id);
            }
        }

        // if (!empty($insert)) {
        //     DB::table($this->className::getTableName())->insert($insert);
        // }
    }

    public function getExt($filename)
    {
        $arr = explode('.', $filename);
        return array_pop($arr);
    }

    private function uploadImg($filepath)
    {
        $imageFilePath = public_path() . '/uploads/goods/' . date("Ymd") . "/";
        if (!file_exists($imageFilePath)) {
            mkdir("$imageFilePath", 0777, true);
            chown("root", "www");
        }
        // 实例化阅读器对象。
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
        // 将文件读取到到$spreadsheet对象中
        //$filepath: storage\app/public/import/00c95d181f32fcbfca053e861cc13923.xlsx
        $spreadsheet = $reader->load($filepath);

        // 获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
        $worksheet = $spreadsheet->getSheet(0);
        $objWorksheet = $spreadsheet->getActiveSheet(0);  //getSheet(0)
        $data = $objWorksheet->toArray();

        foreach ($objWorksheet->getDrawingCollection() as $drawing) {
            list($startColumn, $startRow) = \PhpOffice\PhpSpreadsheet\cell\Coordinate::coordinateFromString($drawing->getCoordinates());
            $imageFileName = strtolower($drawing->getIndexedFilename()); //获取文件名称
            $filename = $drawing->getPath();
            $extension = strtolower($drawing->getExtension());
            switch ($extension) {
                case 'jpg':
                case 'jpeg':
                    $source = imagecreatefromjpeg($drawing->getPath());
                    imagejpeg($source, $imageFilePath . $imageFileName);
                    break;
                case 'gif':
                    $source = imagecreatefromgif($drawing->getPath());
                    imagegif($source, $imageFilePath . $imageFileName);
                    break;
                case 'png':
                    $source = imagecreatefrompng($drawing->getPath());
                    imagepng($source, $imageFilePath . $imageFileName);
                    break;
            }
            //Log::add('文件列', $startColumn);
            $startColumn = $this->ABC2decimal($startColumn);
            if ($startColumn != 9) {
                //continue;
            }
            $data[$startRow - 1][$startColumn][] = $imageFileName ? "/goods/" . date("Ymd") . "/" . $imageFileName : '';
        }

        return $data;
    }

    public function ABC2decimal($abc)
    {
        $ten = 0;
        $len = strlen($abc);
        for ($i = 1; $i <= $len; $i++) {
            $char = substr($abc, 0 - $i, 1); //反向获取单个字符
            $int = ord($char);
            $ten += ($int - 65) * pow(26, $i - 1);
        }
        return $ten;
    }


    private function addGoodSku($skuStr, $goods_id)
    {
        $skuArr = json_decode($skuStr, true);
        $attrs = isset($skuArr['attrs']) ? $skuArr['attrs'] : [];
        $attrsKey = $attrs ? array_keys($attrs) : [];
        $data = [];
        $goods_price = 0;
        //Log::add('规格数据', $skuArr);
        if (isset($skuArr['sku'])) {
            foreach ($skuArr['sku'] as $kk => $vv) {
                $tmp = [];
                $tmp['goods_id'] = $goods_id;
                $attr_name = [];
                if ($kk == 0) {
                    $price = isset($vv['price']) ? explode("、", $vv['price']) : [];
                    $goods_price = isset($price[0]) ? $price[0] : 0;
                }
                foreach ($attrsKey as $val) {
                    array_push($attr_name, $vv[$val]);
                }
                utf8_array_asort($attr_name);
                $attr_sn = join("、", $attr_name);
                $tmp['attr_val'] = $attr_sn;
                $tmp['attr_sn'] = $attr_sn ? md5($attr_sn) : '';
                $tmp['content'] = json_encode($vv, JSON_UNESCAPED_UNICODE);
                array_push($data, $tmp);
                //规格标识
                $skuArr['sku'][$kk]['attr_sn'] = $tmp['attr_sn'];
            }
            $skuCon = json_encode($skuArr, JSON_UNESCAPED_UNICODE);
            DB::table('li_goods_sku')->insert($data);
            DB::table('li_goods')->where("id", $goods_id)->update(['goods_price' => $goods_price, 'sku' => $skuCon]);
        }
    }
}