<?php
namespace model\pdflib;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;

trait insertObject {

    public function insertModelHeaderAll($headerTag, $sheet, $col, $row, $item)
    {
        $make = $item['make'];
        $models = $item['models'];
        $hasMoreRemark = false;
        if ($headerTag > 1) {
            foreach ($models as $model) {
                $hasMoreRemark = $this->hasMoreRemark($make, $model);
            }
        }
        $fontBold = $this->staticDir . '/arial/ArialCEBoldItalic.ttf';
        $font = $this->staticDir . '/arial/ARIALI.TTF';
        $fontUni = $this->staticDir . '/arial/arialuni.ttf';
        if (!file_exists($fontBold)) {
            dd($fontBold . ' 不存在');
        }
        if (!file_exists($font)) {
            dd($font . ' 不存在');
        }
        if (!file_exists($fontUni)) {
            dd($fontUni . ' 不存在');
        }
        include(realpath(__DIR__ . '/../header/' . $headerTag . '.php'));
    }

    public function insertModelHeaderText($sheet, $row, $item)
    {
        $modelsText = $item['make'];
        foreach ($item['models'] as $i => $value) {
            $modelsText .= "\n" . $this->remarkSeq[$i] . ' ' . $value;
        }
        $style = $sheet->getStyle(MODELS_REMARK_COL . $row);
        $style->getFont()->setSize(9);
        $style->getAlignment()->setWrapText(true); //自动换行
        $style->getAlignment()->setShrinkToFit(true);
        $sheet->setCellValue(MODELS_REMARK_COL . $row, trim($modelsText));
    }

    //前桥图
    public function insertFrontAxle($sheet, $col, $row)
    {
        //
        $colChar = $this->int2Excel($col);
        $cell =  $colChar . $row;
        $pngFile = $this->staticDir . '/front.png';
        //$width = 79;
        $width = 70;
        $height = 67;

        //修正一下行数(有一些异常前面多了一行)
        $style = $sheet->getStyle('A' . ($row-1));
        $fill = $style->getFill();
        $bgColor = $fill->getStartColor()->getRGB();
        if ($bgColor != 'FFFFFF') {
            $row = $row - 1;
            $this->rowNum = $row;
        }

        //插入
        $this->setBgColor($sheet, $row, 'F4F4F4');
        $this->insertImage($sheet, $pngFile, $width, $height, $col, $row, 10);
        $this->setRowHeight($sheet, $row, $height * PT_SALC);

        $isBreak = $this->addRowNum($sheet, 'FrontAxle');
    }

    //后桥图
    public function insertRearAxle($sheet, $col, $row, $type = '')
    {
        $pngFile = $this->staticDir . '/rear.png';
        $width = 70;
        $height = 67;
        $this->insertImage($sheet, $pngFile, $width, $height, $col, $row, 10);
        $this->setRowHeight($sheet, $row, $height * PT_SALC);
        $this->setBgColor($sheet, $row, 'F4F4F4');

        $isBreak = $this->addRowNum($sheet, 'RearAxle');
    }

    //间隔
    public function insertJgAxle($sheet, $col, $row)
    {
        $startRow = $row;
        $isBreak = false;
        //间隔行 添加3行
        for ($i = $startRow; $i < ($startRow + 3); $i++) {
            $isBreak = $this->addRowNum($sheet, 'JgAxle');
            if ($isBreak) {
                break;
            } else {
                $this->setBgColor($sheet, $i);
            }
        }

        if ($isBreak) {
            // 有分页
            $row = $this->rowNum;
        } else {
            $row = $startRow + 3;
        }
        //
        $colChar = $this->int2Excel($col);
        $pngFile = $this->staticDir . '/jg.png';
        $width = 820 * SCALING_FACTOR;
        $height = 30;
        $this->insertImage($sheet, $pngFile, $width, $height, $col, $row);
        $this->setRowHeight($sheet, $row, $height * PT_SALC);
        $isBreak = $this->addRowNum($sheet, 'JgAxle');

        //间隔行
        $this->setBgColor($sheet, $row + 1, 'FFFFFF');
        $isBreak = $this->addRowNum($sheet, 'JgAxle');
    }

    //GSP No 文本
    public function insertTextGspNo($sheet, $col, $row, $gspNo)
    {
        $cell = $this->int2Excel($col) . $row;
        $sheet->setCellValue($cell, $gspNo);
        $sheet->getStyle($cell)->applyFromArray([
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'FF004DA7'],
                'endColor' => ['argb' => 'FF004DA7']
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                'vertical' => Alignment::VERTICAL_CENTER,
                'shrinkToFit' => true
            ],
            'font' => [
                'name' => 'Arial',
                'bold' => true,
                'color' => ['rgb' => Color::COLOR_WHITE]
            ],
        ]);
        //固定行高
        $this->setRowHeight($sheet, $row, 15);

        // 插入检查号码文本
        $cellCheckGspNo = MODELS_REMARK_COL . $row;
        $checkGspNoValue = $sheet->getCell($cellCheckGspNo)->getValue() ?: '';
        $arr = [];
        if ($checkGspNoValue) {
            $arr = explode('/', $checkGspNoValue);
        }
        $arr[] = $gspNo;
        $arr = array_unique($arr);
        $sheet->setCellValue($cellCheckGspNo, implode('/', $arr));
        $sheet->getStyle($cellCheckGspNo)->applyFromArray([
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_LEFT,
                'shrinkToFit' => true
            ],
        ]);
    }

    //OE 文本
    public function insertTextOE($sheet, $col, $row, $oe)
    {
        if (empty($oe)) $oe = ' ';
        $font = 'Arial';
        $colChar = $this->int2Excel($col);
        $cell = $colChar . $row;
        $style = $sheet->getStyle($cell);
        $style->getFill()->setFillType(Fill::FILL_SOLID);
        $style->getFill()->getStartColor()->setRGB(Color::COLOR_WHITE);
        $style->getAlignment()->setShrinkToFit(true);
        $style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $style->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
        $style->getFont()->setName($font);
        //$sheet->setCellValue($cell, $oe);
        $sheet->setCellValueExplicit($cell, $oe, DataType::TYPE_STRING);
        //固定行高
        $this->setRowHeight($sheet, $row, 15);
    }

    //品名 文本
    public function insertTextName($sheet, $col, $row, $name)
    {
        $font = 'Arial';
        $colChar = $this->int2Excel($col);
        $cell = $colChar . $row . ':' . $this->int2Excel($col + 1) . $row;
        $sheet->mergeCells($cell);
        $cell = $colChar . $row;
        $style = $sheet->getStyle($cell);
        $style->getFill()->setFillType(Fill::FILL_SOLID);
        $style->getFill()->getStartColor()->setRGB('F6AC2D');
        $style->getAlignment()->setShrinkToFit(true);
        $style->getFont()->getColor()->setRGB('000000');
        $style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $style->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
        $style->getFont()->setName($font);
        //$sheet->setCellValue($cell, $name);
        $sheet->setCellValueExplicit($cell, $name, DataType::TYPE_STRING);
        //固定行高
        $this->setRowHeight($sheet, $row, 15);
    }

    //区别 备注
    public function insertTextRemark($sheet, $col, $row, $remark, $hAlgin = 'center')
    {
        $font = 'Arial';
        //$font = 'Consolas';
        $fontSize = ($font == 'Arial') ? 9 : 8;
        $maxLineCharQty = ($font == 'Arial') ? 25 : 25;
        $maxPixelWidth = 150;
        $cell = '';
        if (strlen($remark) > 80) {
            if ($col == 1 ||  $col == 7) {
                $colChar = $this->int2Excel($col);
                $cell = $colChar . $row . ':' . $this->int2Excel($col + 2) . $row;
                $maxLineCharQty = ($font == 'Arial') ? 34 : 40;
                $maxPixelWidth = 225;
            } elseif ($col == 3 || $col == 9) {
                $colChar = $this->int2Excel($col - 1);
                $cell = $colChar . $row . ':' . $this->int2Excel($col + 1) . $row;
                $maxLineCharQty = ($font == 'Arial') ? 34 : 40;
                $maxPixelWidth = 225;
            } elseif ($col == 5) {
                $colChar = $this->int2Excel($col - 1);
                $cell = $colChar . $row . ':' . $this->int2Excel($col + 2) . $row;
                $maxLineCharQty = ($font == 'Arial') ? 44 : 53;
                $maxPixelWidth = 300;
            }
        }
        if (!$cell) {
            $colChar = $this->int2Excel($col);
            $cell = $colChar . $row . ':' . $this->int2Excel($col + 1) . $row;
        }
        $sheet->mergeCells($cell);
        $cell = $colChar . $row;
        $style = $sheet->getStyle($cell);
        $style->getFill()->setFillType(Fill::FILL_SOLID);
        $style->getFill()->getStartColor()->setRGB('D0CECE');
        $style->getFont()->getColor()->setRGB('000000');
        if ($hAlgin == 'center') {
            $style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        }
        $style->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
        $style->getFont()->setName($font);
        $remark = trim($remark);
        $arr = explode("\n", $remark);
        $fontPath = $this->staticDir . '/arial/ARIALI.TTF';
        $fontUni = $this->staticDir . '/arial/arialuni.ttf';
        $newRemark = $this->smart_chunk_split_visual($remark, $fontUni, $fontSize, $maxPixelWidth);

        //计算行高
        $style->getAlignment()->setWrapText(true); //自动换行
        $lineHeight = 15; // 可调：一行的高度，Arial 默认大约是 13~15
        $lineCount = substr_count($newRemark, "\n") + 1;
        $rowHeight = $lineHeight * $lineCount;
        $this->setRowHeight($sheet, $row, $rowHeight);
        $style->getFont()->setSize($fontSize);
        $sheet->setCellValue($cell, $newRemark);
    }

    /**
     *  文本智能换行
     *
     * @param [type] $text
     * @param [type] $fontPath
     * @param [type] $fontSize
     * @param [type] $maxPixelWidth
     * @return void
     */
    function smart_chunk_split_visual($text, $fontPath, $fontSize, $maxPixelWidth)
    {
        $text = trim($text);
        $lines = [];

        while (mb_strlen($text) > 0) {
            $textLen = mb_strlen($text);
            $fullLineTest = $text;
            $bbox = imagettfbbox($fontSize, 0, $fontPath, $fullLineTest);
            $fullWidth = $bbox[2] - $bbox[0];

            // 如果整段不超宽，整段作为一行
            if ($fullWidth <= $maxPixelWidth) {
                $lines[] = $text;
                break;
            }

            // 否则，我们按像素宽度裁剪，并尝试找断点
            $line = '';
            $lastValidSplitPos = -1;

            for ($i = 1; $i <= $textLen; $i++) {
                $part = mb_substr($text, 0, $i);
                $bbox = imagettfbbox($fontSize, 0, $fontPath, $part);
                $width = $bbox[2] - $bbox[0];

                if ($width > $maxPixelWidth) {
                    break;
                }

                $line = $part;

                $char = mb_substr($text, $i - 1, 1);
                $prevChar = $i >= 2 ? mb_substr($text, $i - 2, 1) : '';

                // 非字母数字，且不是小数点
                if (
                    !preg_match('/[\p{L}\p{N}]/u', $char) &&
                    !($char === '.' && preg_match('/\d/', $prevChar) && preg_match('/\d/', mb_substr($text, $i, 1)))
                ) {
                    $lastValidSplitPos = $i;
                }
            }

            if ($lastValidSplitPos !== -1) {
                $line = mb_substr($text, 0, $lastValidSplitPos);
                $text = mb_substr($text, $lastValidSplitPos);
            } else {
                // 强制断开（没有合法断点）
                $text = mb_substr($text, mb_strlen($line));
            }

            $lines[] = $line;
        }

        return implode("\n", $lines);
    }


    public function inserText($fontSize, $angle, $font, $text, $savePath)
    {

        $bbox = imagettfbbox($fontSize, $angle, $font, $text);
        $textHeight = abs($bbox[7] - $bbox[1]); // 文字高度
        $textWidth = abs($bbox[2] - $bbox[0]);  // 文字宽度
        $textWidth += 10;

        $imgWidth = $textWidth;
        $imgHeight = $textHeight + 10;

        $img = imagecreatetruecolor($imgWidth, $imgHeight);
        imagesavealpha($img, true);
        $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
        imagefill($img, 0, 0, $transparent);

        $white = imagecolorallocate($img, 255, 255, 255);

        $x = ($imgWidth - $textWidth) / 2;
        $y = ($imgHeight + $textHeight) / 2;

        imagettftext($img, $fontSize, $angle, $x, $y, $white, $font, $text);
        imagepng($img, $savePath);
        imagedestroy($img);
        return [
            'width' => $imgWidth,
            'height' => $imgHeight,
        ];
    }
    public function imageTextSize($fontSize, $angle, $font, $text)
    {
        $bbox = imagettfbbox($fontSize, $angle, $font, $text);
        $left = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
        $right = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
        $top = min($bbox[1], $bbox[3], $bbox[5], $bbox[7]);
        $bottom = max($bbox[1], $bbox[3], $bbox[5], $bbox[7]);
        $textWidth = $right - $left;
        $textHeight = $bottom - $top;
        return [
            'top' => $top,
            'bottom' => $bottom,
            'left' => $left,
            'right' => $right,
            'width' => $textWidth,
            'height' => $textHeight,
        ];
    }

    public function insertTextFitWidthByImage($targetWidth, $angle, $font, $text, $image, $x, $y, $areaHeight, $maxFontSize = 40, $minFontSize = 12)
    {
        if (!$targetWidth || !$text) {
            return [];
        }
        $fontSize = $maxFontSize;
        // 找出最合适的字体大小
        while ($fontSize >= $minFontSize) {
            $bbox = imagettfbbox($fontSize, $angle, $font, $text);
            $left = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
            $right = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
            $textWidth = $right - $left;

            if ($textWidth <= $targetWidth - 10) { // 预留边距
                break;
            }
            $fontSize--;
        }
        // 重新获取最终尺寸
        $bbox = imagettfbbox($fontSize, $angle, $font, $text);
        $left = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
        $right = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
        $top = min($bbox[1], $bbox[3], $bbox[5], $bbox[7]);
        $bottom = max($bbox[1], $bbox[3], $bbox[5], $bbox[7]);
        $textWidth = $right - $left;
        $textHeight = $bottom - $top;

        $imgWidth = $textWidth;
        $imgHeight = $textHeight;

        $img = imagecreatetruecolor($imgWidth, $imgHeight);
        imagesavealpha($img, true);
        $transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
        imagefill($img, 0, 0, $transparent);

        $white = imagecolorallocate($image, 255, 255, 255);
        $y = $y + $textHeight + ($areaHeight - $textHeight) / 2;

        imagettftext($image, $fontSize, $angle, $x, $y, $white, $font, $text);

        return [
            'fontSize' => $fontSize,
            'width' => $imgWidth,
            'height' => $imgHeight,
        ];
    }
    public function insertTextFitWidth($targetWidth, $angle, $font, $text, $savePath, $maxFontSize = 20, $minFontSize = 10)
    {
        $fontSize = $maxFontSize;
        // 找出最合适的字体大小
        while ($fontSize >= $minFontSize) {
            $bbox = imagettfbbox($fontSize, $angle, $font, $text);
            //$textWidth = abs($bbox[2] - $bbox[0]);
            $left = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
            $right = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
            $textWidth = $right - $left;

            if ($textWidth <= $targetWidth - 10) { // 预留边距
                break;
            }
            $fontSize--;
        }
        // 重新获取最终尺寸
        $bbox = imagettfbbox($fontSize, $angle, $font, $text);
        //$textWidth = abs($bbox[2] - $bbox[0]);
        //$textHeight = abs($bbox[7] - $bbox[1]);
        $left = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
        $right = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
        $top = min($bbox[1], $bbox[3], $bbox[5], $bbox[7]);
        $bottom = max($bbox[1], $bbox[3], $bbox[5], $bbox[7]);
        $textWidth = $right - $left;
        $textHeight = $bottom - $top;

        $imgWidth = $targetWidth;
        $imgHeight = $textHeight + 10;

        $img = imagecreatetruecolor($imgWidth, $imgHeight);
        imagesavealpha($img, true);
        $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
        imagefill($img, 0, 0, $transparent);

        $white = imagecolorallocate($img, 255, 255, 255);

        //$x = ($imgWidth - $textWidth) / 2;
        $x = 0;
        $y = ($imgHeight + $textHeight) / 2;

        imagettftext($img, $fontSize, $angle, $x, $y, $white, $font, $text);
        imagepng($img, $savePath);
        imagedestroy($img);

        return [
            'fontSize' => $fontSize,
            'width' => $imgWidth,
            'height' => $imgHeight,
        ];
    }

    /**
     * 根据文件后缀加载图片资源
     * @param string $filename 图片文件路径
     * @return resource|false GD image resource or false if unsupported
     */
    public function loadImageResource($filename)
    {
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                $img = imagecreatefromjpeg($filename);
                return $img;
            case 'png':
                $img = imagecreatefrompng($filename);
                imagealphablending($img, false); // 关闭混合模式
                imagesavealpha($img, true);      // 保存完整 alpha 通道
                return $img;
            case 'gif':
                $img = imagecreatefromgif($filename);
                imagealphablending($img, false); // 关闭混合模式
                imagesavealpha($img, true);      // 保存完整 alpha 通道
                return $img;
            case 'bmp':
                return imagecreatefrombmp($filename); // PHP 7.2+ 才有
            case 'webp':
                $img = imagecreatefromwebp($filename);
                imagealphablending($img, false); // 关闭混合模式
                imagesavealpha($img, true);      // 保存完整 alpha 通道
                return $img;
            default:
                return false; // 不支持的格式
        }
    }
    public function insertImage($sheet, $jpgFilename, $width, $height, $col, $row, $offsetX = 0, $offsetY = 0)
    {
        $colChar = $this->int2Excel($col);
        $cell =  $colChar . $row;
        //$drawing = new Drawing();
        //$drawing->setPath($jpgFilename);
        $drawing = new MemoryDrawing();
        $gdImage = $this->loadImageResource($jpgFilename);
        $ext = strtolower(pathinfo($jpgFilename, PATHINFO_EXTENSION));
        if (in_array($ext, ['png', 'gif', 'webp'])) {
            $drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_PNG);
            $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG);
        } else {
            $drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG);
            $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG);
        }
        $drawing->setImageResource($gdImage);

        //
        $drawing->setCoordinates($cell);
        $drawing->setOffsetX($offsetX);
        $drawing->setOffsetY($offsetY);
        $drawing->setWidth($width);
        //$drawing->setHeight($height); // 不建议同时设置
        $drawing->setResizeProportional(true); // 保持比例

        
        $drawing->setWorksheet($sheet);
        // 保存引用，避免被 GC 清掉
        $this->drawings[] = $drawing;
        $this->gdImages[] = $gdImage;
    }

    public function insertAny($sheet, $row, $item, $style, $rightItem = null)
    {
        $imgRow = $row;
        $towColWidth = 165;
        $gspNo = trim($item['ssc_outnum']);
        $gspNoRight = $rightItem ? trim($rightItem['ssc_outnum']) : '';
        $oe = trim($item['ssc_oe']);
        //$name = trim($item['ss_name']);
        $name = trim($item['pos_name']);

        $remark = trim($item['ss_remark']);
        $imgFile = $item['imgFile'];

        $offsetY = 0;
        $offsetX = 0;
        $flipOffsetX = 0;
        $col = $style['image']['col'];
        $colIndex = ($col === false) ? $style['image']['flipCol'] : $col;
        $flipColIndex = $style['image']['flipCol'] ?: $col;
        $textColIndex = ($colIndex < $flipColIndex) ? $colIndex : $flipColIndex;
        //$style['image']['height'] = 80;
        $excelImageHeightBase = 51; //80;
        $excelImageHeight = $excelImageHeightBase;
        $bili = $excelImageHeight / 1.2;

        //$uid = md5($item['ssc_make'] . '-' . $item['ssc_model'] . '-' . $item['ss_year_range'] . '-' . $item['ss_remark']);
        $uid = $item['ssc_id'];
        $keyword = $gspNo . '-' . $gspNoRight;
        if (isset($this->drawOutnums[$uid]) && in_array($item['ss_name'],[
            'Track Control Arm',
            'Control Arm'
        ])) {
            if (in_array($keyword, $this->drawOutnums[$uid])) {
                //查左侧的有没有画左型号
                $leftGspNo = '';
                if ($item['pos2'] == 'R') {
                    $leftGspNo = $sheet->getCell($this->int2Excel(1) . ($row + 1))->getValue();
                    if ($leftGspNo == '') {
                        $leftGspNo = $sheet->getCell($this->int2Excel(3) . ($row + 1))->getValue();
                    }
                }
                if ($leftGspNo != '' && $item['pos2'] == 'R') {
                    ;//当是右型号时，如果左侧有画型号，就不合并(忽略)
                } else {
                    if ($item['pos2'] == 'L/R') {
                        $count = 0;
                        foreach ($this->drawOutnums[$uid] as $v) {
                            if ($keyword == $v) {
                                $count++;
                            }
                        }
                        if ($count >= 2) {
                            //左右通用允许出现两次
                            return;
                        }
                    } else {
                        return;
                    }
                }
            }
        }
        $this->drawOutnums[$uid][] = $keyword;
        //不能去重

        switch ($item['ss_name']) {
            case 'Ball Joint':
            case 'Control Arm Bush':
            case 'Control Arm Bush Kit':
            case 'Control Arm Bushing':
            case 'Control Arm Bushing Kit':
            case 'Stabiliser Bushing':
            case 'Stabiliser Bushing Kit':
                //1.2
                $excelImageHeight = $excelImageHeightBase;
                break;
            case 'Tie Rod Axle Joint':
            case 'Steering Rack Bellow Kit':
            case 'Steering Boot':
            case 'Tie Rod End':
            case 'Rod Assembly':
            case 'Idler Arm':
            case 'Pitman Arm':
                //1.98
                $excelImageHeight = 1.98 * $bili;
                break;
            case 'Track Control Arm':
            case 'Control Arm':
            case 'Rod/Strut,stabiliser':
                //2.2
                $excelImageHeight = 2.2 * $bili;
                break;
            case 'Suspension Repair Kit':
                //2.35
                $excelImageHeight = 2.35 * $bili;
                break;
        }

        if (!$item['noimgFile']) {
            $info = getimagesize($imgFile, $info);
            $salc = $info[0] / $info[1];
            $height = $excelImageHeight - 5;
            $width = $height * $salc;
            //宽度过大
            if ($width > 200) {
                $height = $height * (200 / $width);
                $width = 200;
            }
            if (!isset($style['image']['flip']) && !$style['image']['flip']) {
                if ($width < $towColWidth) {
                    $offsetX = ($towColWidth - $width) / 2; // 中间对齐
                } else {
                    if ($colIndex == 1) {
                        $offsetX = 0 + 5; //居左
                    } else if ($colIndex == 9) {
                        $offsetX = ($width - $towColWidth) * -1 - 5; //居右
                    } else {
                        $offsetX = ($width - $towColWidth) / 2 * -1; //居右
                    }
                }
            } else if ($style['image']['flip']) {
                if ($col !== false) {
                    // 放两张图
                    $flipColIndex = $col;
                    if (($width * 2) < $towColWidth) {
                        $offsetX = ($towColWidth / 2 - $width) / 2 + 1;
                        $flipOffsetX = ($towColWidth / 2 - $width) / 2 - 1;
                        $flipColIndex = $flipColIndex + 1;
                    } else {
                        if ($colIndex == 1) {
                            $offsetX = 0 + 5; //居左
                            $flipOffsetX = $offsetX + $width + 5;
                        } else if ($colIndex == 9) {
                            $flipOffsetX = ($towColWidth - $width) * -1 - 5; //居右
                            $offsetX = $flipOffsetX - $flipOffsetX - 5;
                        } else {
                            $a = ($width * 2  - $towColWidth) / 2;
                            $offsetX = $a * -1 - 4;
                            $flipOffsetX = $offsetX + $width + 8;
                        }
                    }
                } else {
                    //只放一张图
                    if ($width < $towColWidth) {
                        $flipOffsetX = ($towColWidth - $width) / 2; // 中间对齐
                    } else {
                        if ($flipColIndex == 1) {
                            $flipOffsetX = 0 + 5; //居左
                        } else if ($flipColIndex == 9) {
                            $flipOffsetX = ($width - $towColWidth) * -1 - 5; //居右
                        } else {
                            $flipOffsetX = ($width - $towColWidth) / 2 * -1;
                        }
                    }
                }
            }

            $lineHeight = $height;
            $offsetY = 20;
        } else {
            $lineHeight = 80;
        }
        if ($style['image']['top']) {
            $getRowHeight = $sheet->getRowDimension($imgRow)->getRowHeight();
            if (isset($this->isSetHeightRows[$imgRow]) && $this->isSetHeightRows[$imgRow] >0) {
                $rowHeight = $this->isSetHeightRows[$imgRow];
            } elseif ($getRowHeight > 20) {
                $rowHeight = $getRowHeight;
            } else {
                $rowHeight = $lineHeight * PT_SALC + 22;
            }
            if ($rowHeight > $height) {
                $offsetY = $rowHeight - $height * PT_SALC;
            }
            if ($height < $excelImageHeightBase + 10) {
                //if ($offsetY < 10) $offsetY = 10;
            } else {
                //if ($offsetY < 20) $offsetY = 20;
            }
            if($gspNo == '533477') {
                //dump($gspNo, $offsetY, $rowHeight, $height, $getRowHeight, $this->isSetHeightRows[$imgRow]);
            }
            if(substr($gspNo,0,1) !== 'X') {
                // 等于 X 为虚拟编码 , 不写入任何内容
                $this->insertTextGspNo($sheet, $textColIndex, $row + 1, $gspNo);
                $this->insertTextOE($sheet, $textColIndex + 1, $row + 1, $oe);
                $this->insertTextName($sheet, $textColIndex, $row + 2, $name);
                $moreRemark = $this->findMoreRemark($item['ssc_make'], $item['model'], $gspNo);
                if ($moreRemark) {
                    $this->insertTextRemark($sheet, $textColIndex, $row + 3, $moreRemark, 'left');
                } else {
                    $this->insertTextRemark($sheet, $textColIndex, $row + 3, $remark, 'center');
                }
            }
            if (!$item['noimgFile']) {
                //$mode  h 水平翻转从左到右, h2 水平翻转从右到左, v 垂直翻转
                $flipModel = 'h';
                if (in_array($item['ss_name'], ['Tie Rod Axle Joint'])) {
                    $flipModel = 'h2'; //水平翻转从右到左
                }

                $style['image']['flipRight'] = false;
                if (in_array($item['ss_name'], ['Tie Rod Axle Joint'])) {
                    $style['image']['flipRight'] = true; 
                }
                if (isset($style['image']['flipRight']) && $style['image']['flipRight']) {
                    if ($col !== false) {
                        //镜像
                        $tmpFilename = $this->tmpDir . '/flip_' . md5($imgFile) . '.png';
                        $this->image->flipImage($imgFile, $tmpFilename, $flipModel);
                        $this->insertImage($sheet, $tmpFilename, $width, $height, $col, $row, $offsetX, $offsetY);
                    }
                    //右图(翻转)
                    if ($style['image']['flip']) {
                        $this->insertImage($sheet, $imgFile, $width, $height, $flipColIndex, $row, $flipOffsetX, $offsetY);
                    }
                } else {
                    if ($col !== false) {
                        $this->insertImage($sheet, $imgFile, $width, $height, $col, $row, $offsetX, $offsetY);
                    }
                    //右图(翻转)
                    if ($style['image']['flip']) {
                        //镜像
                        $tmpFilename = $this->tmpDir . '/flip_' . md5($imgFile) . '.png';
                        $this->image->flipImage($imgFile, $tmpFilename, $flipModel);
                        $this->insertImage($sheet, $tmpFilename, $width, $height, $flipColIndex, $row, $flipOffsetX, $offsetY);
                        if ($gspNo == '516213') {
                            //dd($item, $style, $width, $height, $col, $row, $offsetX, $offsetY);
                        }
                    }
                    if($gspNo == '516213'){
                        //dump($item, $style, $width, $height, $col, $row, $offsetX, $offsetY);
                    }
                }
            }

        } else {
        }
        $this->setRowHeight($sheet, $imgRow, $lineHeight * PT_SALC + 22);
        $addRowCout = $remark ? 4 : 3;
        for ($i = $row; $i <= ($row + $addRowCout); $i++) {
            $this->setBgColor($sheet, $i);
        }
        return $addRowCout;
    }    
}