<?php
/**
 * DBERP 进销存系统
 *
 * ==========================================================================
 * @link      http://www.dberp.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   http://www.dberp.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Store\Service;

use Doctrine\ORM\EntityManager;
use Store\Entity\Brand;
use Store\Entity\Goods;
use Store\Entity\GoodsCategory;
use Store\Entity\Unit;

class GoodsManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加商品
     * @param array $data
     * @param int $adminId
     * @return Goods
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoods(array $data, int $adminId): Goods
    {
        $goodsCategory = $this->entityManager->getRepository(GoodsCategory::class)->findOneByGoodsCategoryId($data['goodsCategoryId']);
        $unitInfo = $this->entityManager->getRepository(Unit::class)->findOneByUnitId($data['unitId']);
        $brandInfo= $this->entityManager->getRepository(Brand::class)->findOneByBrandId($data['brandId']);

        if (isset($data['goodsImage']['tmp_name']) && !empty($data['goodsImage']['tmp_name'])) $data['goodsImage'] = '/upload/goods/' . basename($data['goodsImage']['tmp_name']);
        else unset($data['goodsImage']);

        $goods = new Goods();
        $goods->valuesSet($data);

        $goods->setGoodsStock(0);
        $goods->setAdminId($adminId);
        $goods->setGoodsCategory($goodsCategory);
        $goods->setOneUnit($unitInfo);
        if($brandInfo) $goods->setBrand($brandInfo);

        $this->entityManager->persist($goods);
        $this->entityManager->flush();

        return $goods;
    }

    /**
     * 编辑商品
     * @param array $data
     * @param Goods $goods
     * @return Goods
     * @throws \Doctrine\ORM\Exception\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoods(array $data, Goods $goods): Goods
    {
        if (isset($data['goodsImage']['tmp_name']) && !empty($data['goodsImage']['tmp_name'])) $data['goodsImage'] = '/upload/goods/' . basename($data['goodsImage']['tmp_name']);
        else unset($data['goodsImage']);

        $goods->valuesSet($data);

        $this->entityManager->flush();

        return $goods;
    }

    /**
     * 更新商品的价格和库存(入库)
     * @param array $data
     * @param Goods $goods
     * @return void
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateGoodsPriceAndStock(array $data, Goods $goods)
    {
        $goods->setGoodsStock($data['goodsStock']);
        $goods->setGoodsPrice($data['goodsPrice']);

        $this->entityManager->flush();
    }

    /**
     * 更新商品的库存
     * @param $stockNum
     * @param Goods $goods
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateGoodsStock($stockNum, Goods $goods)
    {
        $goods->setGoodsStock($stockNum);
        $this->entityManager->flush();
    }

    /**
     * 更新商品的库存(出库)
     * @param array $data
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \Doctrine\Persistence\Mapping\MappingException
     */
    public function outGoodsStock(array $data): bool
    {
        if(empty($data)) return false;
        foreach ($data as $goodsId => $sendNum) {
            $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
            if( !$goodsInfo || $goodsInfo->getGoodsStock() < $sendNum) return false;

            $goodsInfo->setGoodsStock($goodsInfo->getGoodsStock() - $sendNum);
            $this->entityManager->flush();
            $this->entityManager->clear(Goods::class);
        }
        return true;
    }

    /**
     * 删除商品
     * @param Goods $goods
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoods(Goods $goods): bool
    {
        $this->entityManager->remove($goods);
        $this->entityManager->flush();

        return true;
    }


    //到出 exe 表格 第一个为数组 ，第二个为 表头/字段 ，表头和字段长度要一致 ，第四个为中文表头/字段
    public function export_excel($list, $head_columns = [], $fileName_as = '导出',$head_columns_CH=[])
    {
        require_once __DIR__.'/../../../../vendor/PHPExcel/PHPExcel.php';
        $excel = new \PHPExcel();
        $excel->getProperties();
        $worksheet = $excel->setActiveSheetIndex(0);
        //设置第一行内容
        $header_arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 'P', 'Q',
            'R', "S", 'T', "U", "V", "W",'X', "Y", "Z", "AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK",
            "AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU"];
        $head_count=count($head_columns);
        $headerI=0;
        for ($i = 0; $i < $head_count; $i++) {
            $headerI=$i;
            $excel->getActiveSheet()->getColumnDimension($header_arr[$i])->setAutoSize(true);
            $worksheet->setCellValue($header_arr[$i]."1", $head_columns[$i]);
        }
        foreach ($list as $k => $val) {
            $k = $k + 2;
            for ($i = 0; $i < $head_count; $i++) {
                if(isset($val[$head_columns[$i]])){
                    if(is_object($val[$head_columns[$i]])){
                        $childlist=collection($val[$head_columns[$i]])->toArray();
                        $arr=array();
                        $arr_header=array();
                        foreach ($childlist as $key=>$value){
                            $array=array();
                            $child_columns=array_keys($value);
                            foreach ($child_columns as $y=>$z){
                                $array[$z]=$value[$z];
                                array_push($arr_header,$z);
                                $excel->getActiveSheet()->getColumnDimension($header_arr[$headerI+$y])->setAutoSize(true);
                                $worksheet->setCellValue($header_arr[$headerI+$y]."1", $z);
                            }
                            array_push($arr,$array);
                        }
                        $header=array_unique($arr_header);
                        foreach ($header as $t=>$xval){
                            $worksheet->setCellValue($header_arr[$headerI+$t].$k, implode("   ，  ",array_column($arr,$xval)));
                        }
                    }else {
                        $worksheet->setCellValue($header_arr[$i].$k, $val[$head_columns[$i]]);
                    }
                }else{
                    $columns=explode(".",$head_columns[$i]);
                    if(isset($val[$columns[0]])){
                        $worksheet->setCellValue($header_arr[$i].$k, $val[$columns[0]][$columns[1]]);
                    }
                }
            }
        }

        //重新给表头注释中文
        if($head_columns_CH){
            $head_count_CH=count($head_columns_CH);
            for ($i = 0; $i < $head_count_CH; $i++) {
                $excel->getActiveSheet()->getColumnDimension($header_arr[$i])->setAutoSize(true);
                $worksheet->setCellValue($header_arr[$i]."1", $head_columns_CH[$i]);
            }
        }


        $excel->createSheet();
        $title = $fileName_as. date("Y-m-d");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
        return;
    }


}