<?php

namespace model\homepro;

use \model;
use model\homepro\projectItem;


class projectRecommend extends model
{
    private $userId;
    public function __construct() {
        parent::__construct();
        $this->userId = $_SESSION['cnuser']['u_id'] ?? null;
    }
    /**
     * @param  array $params 参数
     * @method 获取项目推荐列表
     * @author hongzhang 
     * @copyright 2025-08-12
     */
    public function getList($params)
    {
        $page = $params['page'] ?: 1;
        $pagesize = $_COOKIE['pagesize'] ?: 10;

        $sidx = 'oe_id';
        $sord = 'desc';
        $orderby = $params['orderby'];

        $projectItem = new projectItem();
        $where = [];
        $join = '';

        $table = 'project_recommend(prr)';
        $join = [
            // 关联零件库信息
            '[>]oe_item(oi)' => ['prr.prr_oe_id' => 'oe_id'],
            // 关联品类信息
            '[>]pro_cate(pc)' => ['oi.oe_cate_id' => 'id'],
            // 关联用户确认状态
            '[>]project_recommend_userchk(pru)' => ['prr.prr_id' => 'pru_prr_id', 'pru.pru_u_id' => '@' .'pru_u_id='.$this->userId],
        ];
        $fields = ['oi.oe_id(oe_id)', 'oi.oe_oe(oe_oe)', 'oi.oe_' . cateName() . '(oe_name)', 'pc.' . cateName() . '(cate_name)', 'oi.oe_pos1', 'oi.oe_pos2', 'oi.oe_pos3', 'oi.oe_pos4', 'oi.oe_pos5', 'prr_update_time', 'prr_id','pru_u_id'];
        //是否是发动机相关的搜索
        $engineSearch = false;
        foreach ($params as $field => $val) {
            if (empty($val)) continue;
            switch ($field) {
                case 'mk_id':
                    $where['RAW #mk_id'] = raw("EXISTS (SELECT 1 FROM oe_model_link oml JOIN m_model mm ON oml.oml_mm_id = mm.mm_id WHERE oml.oml_oe_id = oi.oe_id AND mm.mm_mk_id = {$val})");
                    break;
                case 'ms_id':
                    $owhere = '';
                    $where['RAW #ms_id'] = raw("EXISTS (SELECT 1 FROM oe_model_link  oml JOIN m_model mm ON oml.oml_mm_id =mm.mm_id WHERE mm_ms_id = {$val} AND oi.oe_id = oml.oml_oe_id" . $owhere . ")");
                    break;
                case 'cate':
                    $ids = explode(',', $val);
                    $where['oi.oe_cate_id'] = $ids;
                    //判断搜索的分类中是否存在发动机相关属性
                    $engineSearch = $this->db->get('pro_cate', 'id', ['id' => $ids, 'is_engine' => 1]);
                    $engineSearch = $engineSearch ? true : false;
                    break;
                case 'proname':
                    $where['RAW #proname'] = raw(" (oi.oe_" . cateName() . " LIKE '%" . $val . "%')");
                    break;
                case 'engine':
                    $engineSearch = $val;
                    $owhere = '';
                    $projectItem = new projectItem();
                    $mkArr = $projectItem->getMakeList(1);
                    if ($mkArr) {
                        $mk_id = array_column($mkArr, 'mk_id');
                        $owhere = sprintf(" AND mm_mk_id IN (%s)", implode(',', $mk_id));
                    }
                    $owhere1 = '';
                    $brandArr = $projectItem->getCnMakeList(1);
                    if ($brandArr) {
                        $owhere1 = sprintf(" AND brand_id IN (%s)", implode(',', array_unique(array_column($brandArr, 'brand_id'))));
                    }
                    $orArr = [
                        "oi.oe_engine LIKE '%{$val}%'",
                        "EXISTS (
                            SELECT 1 FROM oe_model_link oml 
                            JOIN m_model mm ON oml.oml_mm_id = mm.mm_id 
                            WHERE oml.oml_oe_id = oi.oe_id 
                            AND mm.mm_engine LIKE '%{$val}%'
                            {$owhere}
                            UNION 
                            SELECT 1 FROM oe_model_cn_link omcl 
                            JOIN m_cn_model mcm ON omcl.oml_mod3_id = mcm.mod3_id 
                            WHERE omcl.oml_oe_id = oi.oe_id 
                            AND mcm.mod3_engine LIKE '%{$val}%'
                            {$owhere1}
                        )"
                    ];

                    $where['RAW #engine'] = raw('(' . implode(' OR ', $orArr) . ')');
                    break;
                case 'userchk':
                    if($val == 'Y'){
                        $where['pru_u_id'] = $this->userId;
                    }else{
                        $where['pru_u_id'] = NULL;
                    }
                    break;
            }
        }

        // 只展示推荐的项
        $where['prr_status'] = 1;

        $where = $this->listWhere($where, $page, $pagesize, $sidx, $sord, $orderby);
        if ($page > 0 && $pagesize > 0 && !$params['export']) {
            $pages = $this->paging($table, $join, '*', $where, $page, $pagesize);
            $where["LIMIT"] = [$pages['limit'], $pagesize];
        }
        $arr = $this->db->select($table, $join, $fields, $where);
        if (!empty($arr)) {
            $oeIds = array_column($arr, 'oe_id');

            //查零件参数
            $fields = ['ppv_oe_id', 'ptpa_id', 'ptpa_type', 'ptpa_unit', 'ptpa_decimal', 'ppv_val_int', 'ppv_val_double', 'ppv_val_string', 'ptpa_col_order'];
            $fields = langSqlFields($fields, 'pa.', 'ptpa_', true);
            $fields = langSqlFields($fields, 'pps.', 'ppv_val_', true);
            $fields = langSqlFields($fields, 'ppsu.', 'ptpa_unit_', true);
            $sqltpl = sprintf("SELECT " . implode(',', $fields) . "  FROM `oe_param_val` ov
            JOIN part_param pa ON ptpa_id = ppv_ptpa_id
            LEFT JOIN part_param_sche pps ON ((pps.pps_ptpa_id = ptpa_id AND ppv_val_string = pps.cn_name) or (pps.pps_ptpa_id = ptpa_pid and pps_id = ppv_val_int))
            LEFT JOIN part_param_sche ppsu ON ppsu.pps_ptpa_id = 0 and ptpa_unit = ppsu.cn_name
            WHERE ppv_oe_id IN (%s) ORDER BY ptpa_pid DESC,ptpa_id ASC", implode(',', array_unique($oeIds)));
            $rows = $this->db->query($sqltpl)->fetchAll();
            foreach ($rows as $row) {
                if ($row['ppv_val_int']) {
                    $row['ppv_val'] = $row['ppv_val_' . LG_NAME] . ($row['ptpa_unit_' . LG_NAME] ?: $row['ptpa_unit']);
                    $paramArr['oe_' . $row['ppv_oe_id']][] = ['name' => $row['ptpa_' . LG_NAME], 'value' => $row['ppv_val']];
                    continue;
                }
                if ($row['ptpa_type'] == 'string') {
                    $row['ppv_val'] = $row['ppv_val_' . LG_NAME];
                } elseif ($row['ptpa_type'] == 'double') {
                    $row['ppv_val'] = floatval(number_format($row['ppv_val_double'], $row['ptpa_decimal'], ".", ""));
                }
                $paramArr['oe_' . $row['ppv_oe_id']][] = ['name' => $row['ptpa_' . LG_NAME], 'value' => $row['ppv_val'] . ($row['ptpa_unit_' . LG_NAME] ?: $row['ptpa_unit'])];
            }


            //主图
            $picRes = $this->db->select('oe_pic', ['[><]files' => ['pic_fileid' => 'fileid']], '*', ['pic_oe_id' => $oeIds, 'pic_type' => 'img', 'pic_ismain' => 1]);
            $picArr = [];
            foreach ($picRes as $pic) {
                if ($pic['pic_type'] == 'img' && $pic['filetype'] == 'image') {
                    $picArr[$pic['pic_oe_id']]['bigImg'] = $pic['filepath'] . '/' . $pic['filebasename'] . 'big.' . $pic['fileextname'];
                    $picArr[$pic['pic_oe_id']]['smallImg'] = $pic['filepath'] . '/' . $pic['filebasename'] . 'small.' . $pic['fileextname'];
                    if ($params['isExport']) {
                        $picArr[$pic['pic_oe_id']]['type'] = 'image';
                        $picArr[$pic['pic_oe_id']]['filename'] = \mvc::$cfg['dir']['files'] . '/' . $picArr[$pic['pic_oe_id']]['smallImg'];

                        list($width, $height, $type, $attr) = getimagesize($picArr[$pic['pic_oe_id']]['filename']);
                        $picArr[$pic['pic_oe_id']]['widthScale'] = 1;
                        $picArr[$pic['pic_oe_id']]['heightScale'] = 1;
                        $picArr[$pic['pic_oe_id']]['rowHeight'] = $height;
                    }
                }
            }
            //存在商品库
            $pcs = [];
            $sql = sprintf("SELECT oe_id, p_id, p_innum,pb_" . cateName() . " AS pb_name FROM oe_numidx
				JOIN oe_item ON oe_id = on_oe_id
				JOIN pro_numidx ON on_pf_id=pn_pf_id AND on_formart=pn_formart 
				JOIN pro ON p_id=pn_p_id
                JOIN pro_brand on p_pb_id=pb_id
				WHERE oe_cate_id = p_cate AND p_pb_id = 1 AND oe_id IN (%s) group by oe_id, p_id order by p_innum", implode(',', $oeIds));
            $rows = $this->db->query($sql)->fetchAll();
            if (!empty($rows)) {
                foreach ($rows as $rv) {
                    $pcs[$rv['oe_id']][] = $rv;
                }

                $pidArr = array_column($rows, 'p_id');
                //查商品参数
                $fields = ['ppv_p_id', 'ptpa_id', 'ptpa_type', 'ptpa_unit', 'ptpa_decimal', 'ppv_val_int', 'ppv_val_double', 'ppv_val_string', 'ptpa_col_order'];
                $fields = langSqlFields($fields, 'pa.', 'ptpa_', true);
                $fields = langSqlFields($fields, 'pps.', 'ppv_val_', true);
                $fields = langSqlFields($fields, 'ppsu.', 'ptpa_unit_', true);
                $sqltpl = sprintf("SELECT " . implode(',', $fields) . "  FROM `pro_param_val` pv
				JOIN part_param pa ON ptpa_id = ppv_ptpa_id
				LEFT JOIN part_param_sche pps ON ((pps.pps_ptpa_id = ptpa_id AND ppv_val_string = pps.cn_name) or (pps.pps_ptpa_id = ptpa_pid and pps_id = ppv_val_int))
				LEFT JOIN part_param_sche ppsu ON ppsu.pps_ptpa_id = 0 and ptpa_unit = ppsu.cn_name
				WHERE ppv_p_id IN (%s) ORDER BY ptpa_pid DESC,ptpa_id ASC", implode(',', $pidArr));
                $rows = $this->db->query($sqltpl)->fetchAll();

                foreach ($rows as $row) {

                    if ($row['ppv_val_int']) {
                        $row['ppv_val'] = $row['ppv_val_' . LG_NAME] . ($row['ptpa_unit_' . LG_NAME] ?: $row['ptpa_unit']);
                        $paramArr['p_' . $row['ppv_p_id']][] = ['name' => $row['ptpa_' . LG_NAME], 'value' => $row['ppv_val']];
                        continue;
                    }
                    if ($row['ptpa_type'] == 'string') {
                        $row['ppv_val'] = $row['ppv_val_' . LG_NAME];
                    } elseif ($row['ptpa_type'] == 'double') {
                        $row['ppv_val'] = floatval(number_format($row['ppv_val_double'], $row['ptpa_decimal'], ".", ""));
                    }
                    $paramArr['p_' . $row['ppv_p_id']][] = ['name' => $row['ptpa_' . LG_NAME], 'value' => $row['ppv_val'] . ($row['ptpa_unit_' . LG_NAME] ?: $row['ptpa_unit'])];
                }
            }
            $allPos = (new \model\pro\pro())->allPos;
            foreach ($arr as &$v) {
                //获取FGIO的物料编码
                $v['pcs'] = $pcs[$v['oe_id']] ? array_values($pcs[$v['oe_id']]) : [];
                if (!empty($v['pcs'])) {
                    $v['p_comnum'] = $v['pcs'][0]['p_innum'];
                    $v['p_url'] = \mvc::$cfg['SELF_URI'] . 'index/item?id=' . $v['oe_id'] . '&type=pro&pr_id=1';
                }

                $v['pic'] = $picArr[$v['oe_id']] ?? [];

                if ($v['prr_update_time']) {
                    $v['prr_update_time'] = date('Y-m-d', strtotime($v['prr_update_time']));
                }

                // pr_id暂定为1
                $projectItem = new projectItem();
                // 国际车型
                $v['model'] = $projectItem->getPrjItemModel($v['oe_id'], 1, $engineSearch);
                // 中国车型
                $v['cnmodel'] = $projectItem->getPrjItemCnModel($v['oe_id'], 1, $engineSearch);
                // 获取国际和国内车系不重复的集合
                $modelData = is_array($v['model']) ? $v['model'] : [];
                $cnmodelData = is_array($v['cnmodel']) ? $v['cnmodel'] : [];
                $maxCount = max(count($modelData), count($cnmodelData));

                if ($maxCount > 0) {
                    $modelValues = array_values($modelData);
                    $cnmodelValues = array_values($cnmodelData);

                    for ($i = 0; $i < $maxCount; $i++) {
                        $modelSeries = isset($modelValues[$i]['uniSeries']) && is_array($modelValues[$i]['uniSeries']) ? $modelValues[$i]['uniSeries'] : [];
                        $cnmodelSeries = isset($cnmodelValues[$i]['uniSeries']) && is_array($cnmodelValues[$i]['uniSeries']) ? $cnmodelValues[$i]['uniSeries'] : [];
                        $unionSeriesTemp = array_merge($modelSeries, $cnmodelSeries);

                        $v['union_model_series'][$i]['unionSeries'] = implode(',', $unionSeriesTemp);
                        $v['union_model_series'][$i]['modelKey'] = !empty($modelData) ? key($modelData) : '';
                        $v['union_model_series'][$i]['cnmodelKey'] = !empty($cnmodelData) ? key($cnmodelData) : '';
                    }
                }
                $v['item_url'] = \mvc::$cfg['SELF_URI'] . 'index/item?id=' . $v['oe_id'] . '&type=oe&pr_id=1&isRecommend=Y';

                //取有值的位置参数
                $paramArr2 = [];
                foreach ($allPos as $pos => $vv) {
                    if ($v['cat_' . $pos] && $val['oe_' . $pos]) {
                        $pos = array_intersect(explode('/', $v['oe_' . $pos]), explode(',', $v['cat_' . $pos]));
                        if ($pos) $paramArr2[] = ['name' => $vv['name'], 'value' => implode('/', $pos)];
                    }
                }
                $v['param'] = [];
                //合并参数
                $v['param'] = array_merge(
                    $paramArr['p_' . $v['p_id']] ?? $paramArr['oe_' . $v['oe_id']] ?? [],
                    $paramArr2
                );
            }
            unset($v);
        }
        if ($params['export']) $this->export($arr);
        $data = [
            'page' => $page,
            'pageSize' => $pages['pagesize'],
            'records' => $pages['records'],
            'rows' => $arr ?: [],
        ];
        return $data;
    }

    /**
     * @method 根据现有数据获取存在的车系列表
     * @author hongzhang
     * @copyright 2025-08-13
     */
    public function getSeriesList($mkid)
    {
        $whereCondition = '';
        if ($mkid) {
            $whereCondition = " AND ms.ms_mk_id = {$mkid}";
        }

        $this->db->Begin();
        $sql = "SELECT DISTINCT ms.ms_id, ms.ms_name 
                FROM m_series ms 
                JOIN m_model mm ON ms.ms_id = mm.mm_ms_id 
                JOIN oe_model_link oml ON mm.mm_id = oml.oml_mm_id 
                WHERE EXISTS (
                    SELECT 1 FROM project_recommend pr 
                    JOIN oe_item oi ON pr.prr_oe_id = oi.oe_id 
                    WHERE pr.prr_status = 1 AND oml.oml_oe_id = oi.oe_id
                ){$whereCondition} 
                ORDER BY ms.ms_name";
        $seriesList = $this->db->query($sql)->fetchAll();
        return $seriesList;
    }

    /**
     * @method 获取项目推荐项目的小类集合
     * @author hongzhang
     * @copyright 2025-08-14
     */

    public function getProjectRecommendCate()
    {
        $cateIds = $this->db->select('project_recommend', ['[>]oe_item' => ['prr_oe_id' => 'oe_id']], 'oe_cate_id', ['prr_status' => 1]);
        return $cateIds;
    }

    /**
     * @method 项目推荐导出
     * @author hongzhang
     * @copyright 2025-08-14
     */
    public function export($dataArr)
    {
        function processBatchData($data, $fields, &$drawImgRanges, &$wrapTextRanges, &$brow)
        {
            foreach ($data as $v) {
                $row = [];
                $col = 0;
                $bcol = 'A';
                // 写入主数据
                foreach ($fields as $fk => $fv) {

                    if ($fk == 'smallImg') {
                        $val = $v['pic']['smallImg'] ?: '';
                    } elseif ($fk == 'desc') {
                        $val = [$v['oe_name'], $v['cate_name']];
                    } elseif ($fk == 'model') {
                        $val = [];
                        foreach ($v['model'] as $mk => $mv) {
                            foreach ($mv as $ms => $mmA) {
                                if ($ms != 'uniSeries') {
                                    $val[] = $mk . ' ' . $ms;
                                }
                            }
                        }
                    } elseif ($fk == 'cnmodel') {
                        $val = [];
                        foreach ($v['cnmodel'] as $bn => $bv) {
                            foreach ($bv as $m2name => $mmA) {
                                if ($m2name != 'uniSeries') {
                                    $val[] = $bn . ' ' . $m2name;
                                }
                            }
                        }
                    } else {
                        $val = isset($v['captions'][$fk]) ? $v['captions'][$fk] : (isset($v[$fk]) && !empty($v[$fk])  ? $v[$fk] : '');
                        if ($val === 0) $val = '';
                    }

                    $val = is_array($val) ? implode("\n", $val) : $val;
                    $row[$col] = $val;

                    // 如果值中包含 \n，记录单元格范围
                    if (stripos($val, "\n") !== false) {
                        $wrapTextRanges[] = $bcol . $brow;
                    }

                    if (($fk == 'smallImg' || $fv['type'] == 'Image') && $val) {
                        $imgPath = tempnam(sys_get_temp_dir(), 'excel_img_' . md5($val));
                        $filePath = \mvc::$cfg['urls']['outfiles'] . '/' . str_replace('small', '', $val);

                        // 检查文件是否存在且可访问
                        $headers = @get_headers($filePath);
                        if ($headers && strpos($headers[0], '200') !== false) {

                            $contents = file_get_contents($filePath);
                            if ($imgPath && file_exists($imgPath) && $contents) {
                                file_put_contents($imgPath, $contents);
                                $drawImgRanges[$bcol . $brow] = $imgPath;
                            }
                            $row[$col] = '';
                        }
                    }
                    $bcol++;
                    $col++;
                }

                $brow++; // 更新行号
                yield $row; // 使用 yield 返回当前行
            }
        }
        // 创建一个新的 Spreadsheet 对象
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();


        $fieldsArr = [
            [
                'oe_oe' => ['title' => 'OE',  'bold' => true, 'color' => 'ff7cded7'],
                'p_comnum' => ['title' => '商品编码', 'bold' => true, 'color' => 'ff7cded7'],
                'smallImg' => ['title' => '图片',  'bold' => true, 'color' => 'ff7cded7'],
                'desc' => ['title' => '描述', 'bold' => true, 'color' => 'ff7cded7'],
                'model' => ['title' => '国际车型', 'bold' => true, 'color' => 'ff7cded7'],
                'cnmodel' => ['title' => '中国车型', 'bold' => true, 'color' => 'ff7cded7'],
                'prr_update_time' => ['title' => '推荐时间', 'bold' => true, 'color' => 'ff7cded7'],
            ]
        ];

        // 设置标题
        $row = 1;
        $defaultColumnWidth = 15;
        $this->formatFields($fieldsArr, $defaultColumnWidth, $sheet, $row);

        $batchSize = 1000; // 每次处理 1000 条数据
        $totalRows = count($dataArr);

        for ($i = 0; $i < $totalRows; $i += $batchSize) {
            $batchData = array_slice($dataArr, $i, $batchSize); // 获取当前批次数据
            $data = [];
            $wrapTextRanges = [];
            $startRow = $row; // 记录当前批次的起始行号
            $drawImgRanges = [];

            // 使用生成器逐行处理数据
            foreach (processBatchData($batchData, $fieldsArr[0], $drawImgRanges, $wrapTextRanges, $row) as $item) {
                $data[] = $item;
            }

            // 批量写入数据到表格
            if (!empty($data)) {
                $sheet->fromArray($data, null, 'A' . $startRow);
            }

            // 批量设置换行样式
            if (!empty($wrapTextRanges)) {
                foreach ($wrapTextRanges as $cell) {
                    $sheet->getStyle($cell)->getAlignment()->setWrapText(true);
                }
            }

            //批量插入图片
            if (!empty($drawImgRanges)) {
                foreach ($drawImgRanges as $cell => $img) {
                    // 插入图片
                    $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    $drawing->setPath($img); // 图片路径
                    $drawing->setHeight(50); // 设置图片高度
                    $drawing->setCoordinates($cell); // 设置图片插入的单元格
                    $drawing->setWorksheet($sheet);

                    // 设置图片所在行的高度
                    $rowIndex = preg_replace('/[^0-9]/', '', $cell); // 提取行号
                    $sheet->getRowDimension($rowIndex)->setRowHeight(40); // 设置行高为 80，可根据需求调整
                }
            }
        }

        // 输出文件
        ob_clean();
        if (empty($filename)) {
            $filename = sprintf('project_recommend_%d.xlsx', time());
        }
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');

        // 释放内存
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }

    /**
     * @method 项目推荐项目用户确认
     * @author hongzhang
     * @copyright 2025-08-21
     */
    public function setRecommendItemChk($chkIds)
    {
        $arrIds = explode(',', $chkIds);
        $this->db->Begin();
        $existIds = $this->db->select('project_recommend_userchk', 'pru_prr_id', ['pru_u_id' => $this->userId]);
        $updateIds = array_diff($arrIds, $existIds);
        if (count($updateIds)) {
            foreach ($updateIds as $id) {
                $addTemp[] = [
                    'pru_u_id' => $this->userId,
                    'pru_prr_id' => $id,
                    'pru_create_time' => date('Y-m-d H:i:s'),
                ];
            }
            $this->db->insert('project_recommend_userchk', $addTemp);
        }
        $this->db->End();
        return true;
    }
    /**
     * @param  Array $fieldsArr 表头数组
     * @param  int $defaultColumnWidth 默认列宽
     * @param object $sheet phpspreadsheet对象
     * @param  int $row 行
     * @method 设置表格头、尾
     * @author zhengweihua 
     * @copyright 2025-07-07
     */
    public function formatFields($fieldsArr, $defaultColumnWidth, &$sheet, &$row)
    {
        foreach ($fieldsArr as $key => $fields) {
            $col = 'A';
            foreach ($fields as $vv) {
                if (!$vv) {
                    $col++;
                    continue;
                }
                // 设置列宽（如果未单独指定宽度，则使用默认宽度）
                if (is_array($vv) && !empty($vv['width'])) {
                    $sheet->getColumnDimension($col)->setWidth($vv['width']);
                } else {
                    $sheet->getColumnDimension($col)->setWidth($defaultColumnWidth);
                }
                if (is_array($vv)) {
                    if ($vv['isMerge']) {
                        $sheet->mergeCells(sprintf("%s:%s", $vv['scell'], $vv['ecell'])); // 合并单元格
                    }

                    $sheet->setCellValue($vv['scell'] ?? $col . $row, $vv['title']);

                    $cell = $vv['isMerge'] ? sprintf("%s:%s", $vv['scell'], $vv['ecell']) : $col . $row;
                    $style = $sheet->getStyle($cell);

                    if ($vv['color']) {
                        $style->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB($vv['color']);
                    }
                    // 设置字体颜色和加粗
                    if (!empty($vv['fontColor']) || !empty($vv['bold'])) {
                        $font = $style->getFont();
                        if (!empty($vv['fontColor'])) {
                            $font->getColor()->setARGB($vv['fontColor']); // 设置字体颜色
                        }
                        if (!empty($vv['bold'])) {
                            $font->setBold(true); // 设置加粗
                        }
                    }
                    // 设置字体大小
                    if (!empty($vv['fontSize'])) {
                        $style->getFont()->setSize($vv['fontSize']); // 设置字体大小
                    }
                    //设置行高
                    if ($vv['height']) {
                        $sheet->getRowDimension($row)->setRowHeight($vv['height']); // 设置行高为 80，可根据需求调整
                    }
                } else {
                    $sheet->setCellValue($col . $row, $vv);
                    $style = $sheet->getStyle($col . $row);
                }

                $styleArray = [
                    'borders' => [
                        'allBorders' => [
                            'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                            'color' => ['argb' => 'FF000000'], // 黑色边框
                        ],
                    ],
                ];
                $style->applyFromArray($styleArray);
                if ($vv['align']) {
                    $style->getAlignment()->setHorizontal($vv['align']);
                    $style->getAlignment()->setVertical($vv['align']);
                }
                $col++;
            }
            $row++;
        }
    }
}
