<?php

namespace App\Http\Services\Backend\EcManagement;

use App\Http\Services\ConstDef\GeneralConst;
use App\Models\EcManagement\ProductManagement;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Redis;

class ProductManagementService
{
    
    // 相關私有 model 調用器宣告
    private $productManagementDb;
    
    public function __construct()
    {
        // 建構 model 調用器
        $this->productManagementDb = new ProductManagement();
    }
    
    public function insertProduct($data)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $res = $this->productManagementDb->insert($data);
        
        // 整理返回值並返回
        return $res;
    }
    
    public function deleteProductByBatchNo($del_batch_no)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $this->productManagementDb
            ->where('batch_no', '<=', $del_batch_no . ' 23:59:59')
            ->delete();
        
        // 整理返回值並返回
        return true;
    }
    
    public function getProductDetail($brand_no, $batch_no, $g_id)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $res = $this->productManagementDb
            ->select([
                'm_status',
                'm_comment',
            ])
            ->where('brand_no', $brand_no)
            ->where('batch_no', $batch_no)
            ->where('g_id', (int)$g_id)
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $res[0] ?? [
                'm_status'  => '',
                'm_comment' => '',
            ];
    }
    
    public function updateProduct($brand_no, $batch_no, $g_id, $m_status, $m_comment)
    {
        // 取得參數
        // 調用資料庫(或者其他業務邏輯)
        $this->productManagementDb
            ->where('brand_no', $brand_no)
            ->where('batch_no', $batch_no)
            ->where('g_id', (int)$g_id)
            ->update([
                'm_status'  => $m_status,
                'm_comment' => $m_comment,
            ]);
        
        // 整理返回值並返回
        return true;
    }
    
    public function getProdocts(
        &$cnt = 0,
        $orderColumn,
        $orderDir,
        $start,
        $length,
        $searchValue,
        $brand_no,
        $batch_no,
        $g_title,
        $g_description,
        $m_comment,
        $m_status
    )
    {
        // 調用資料庫(或者其他業務邏輯)
        // 選欄位
        // 選欄位
        $mStatusStr = '';
        foreach (GeneralConst::$mStatusMap as $k => $v) {
            $mStatusStr .= ' when \'' . $k . '\' then \'' . $v['ANAME'] . '\'';
        }
        
        $products = $this->productManagementDb
            ->select([
                'serno',
                'g_id',
                \DB::raw('concat(\'<a href="\', g_link, \'" target="_blank">\', g_title, \'</a>\') as g_title'),
                \DB::raw('concat(\'<button type="button" class="btn btn-outline-success btn-sm" data-toggle="popover" title="\', g_title, \'" data-content="\', g_description, \'">\', left(g_description, 10), \' ... </button>\') as g_description'),
                \DB::raw('concat(\'<img src="\', g_image_link, \'" width="100" height="100">\') as g_image_link'),
                'g_price',
                'g_sale_price',
                \DB::raw("(case m_status $mStatusStr end) as m_status"),
                'm_comment',
            ]);
        // 過濾搜尋條件
        $products = $products
            ->where('brand_no', '=', $brand_no)
            ->where('batch_no', '=', $batch_no)
            ->where('g_title', 'LIKE', '%' . $g_title . '%')
            ->where('g_description', 'LIKE', '%' . $g_description . '%')
            ->where('m_comment', 'LIKE', '%' . $m_comment . '%')
            ->where('m_status', '=', $m_status);
        // 取總筆數
        $cnt = $products->count();
        // 排序
        $products = $products
            ->orderByRaw((int)$orderColumn . ' ' . $orderDir);
        // 分頁
        $products = $products
            ->skip($start)->take($length);
        // 實際取資料
        $result = $products
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $result;
    }
    
    public function getEndpointProdocts($brand_no, $batch_no)
    {
        $products = $this->productManagementDb
            ->select([
                'g_id',
                'g_title',
                'g_description',
                'g_link',
                'g_image_link',
                'g_condition',
                'g_availability',
                'g_price',
                'g_sale_price',
                'g_brand',
                'g_google_product_category',
                'g_product_type',
                'g_custom_label_0',
            ]);
        // 過濾搜尋條件
        $products = $products
            ->where('brand_no', '=', $brand_no)
            ->where('batch_no', '=', $batch_no)
            ->whereIn('m_status', [GeneralConst::MSTATUS_PASS, GeneralConst::MSTATUS_WARNING]);
        // 實際取資料
        $result = $products
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $result;
    }
    
    public function getExportProdocts($param)
    {
        // 調用資料庫(或者其他業務邏輯)
        // 選欄位
        $mStatusStr = '';
        foreach (GeneralConst::$mStatusMap as $k => $v) {
            $mStatusStr .= ' when \'' . $k . '\' then \'' . $v['ANAME'] . '\'';
        }
        $brand_no = $param['brand_no'] ?? '';
        $batch_no = $param['batch_no'] ?? '';
        $products = $this->productManagementDb
            ->select([
                'serno',
                'g_id',
                'g_title',
                'g_description',
                'g_link',
                'g_image_link',
                'g_price',
                'g_sale_price',
                \DB::raw("(case m_status $mStatusStr end) as m_status"),
                'm_comment',
            ]);
        // 過濾搜尋條件
        $products = $products
            ->where('brand_no', '=', $brand_no)
            ->where('batch_no', '=', $batch_no)
            ->whereIn('m_status', [GeneralConst::MSTATUS_WARNING, GeneralConst::MSTATUS_DISAPPROVED]);
        $products = $products
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $products;
    }
    
    public function downloadExcel($titles = [], $datas = [], $fileName = 'simple')
    {
        $spreadsheet = new Spreadsheet();
        ini_set('memory_limit', '1024M');
        ini_set("max_execution_time", "600");
        $spreadsheet->getActiveSheet()
            ->fromArray(
                $titles, // The data to set
                null, // Array values with this value will not be set
                'A1' // Top left coordinate of the worksheet range where we want to set these values (default is A1)
            );
        
        $spreadsheet->getActiveSheet()
            ->fromArray(
                $datas, // The data to set
                null, // Array values with this value will not be set
                'A2' // Top left coordinate of the worksheet range where we want to set these values (default is A1)
            );
        
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        
        // If you're serving to IE over SSL, then the following may be needed
        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
        
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }
    
    public function getBrands()
    {
        $brands = [];
        foreach (GeneralConst::$brandMap as $k => $v) {
            $brands[] = [
                'id'         => $k,
                'brandName'  => $v['NS'],
                'brandLabel' => $v['LB'],
            ];
        }
        
        return $brands;
    }
    
    public function getBatchs()
    {
        $ret = $this->productManagementDb
            ->select([
                'batch_no',
                \DB::raw("max(m_status) as m_status"),
            ])
            ->groupBy('batch_no')
            ->orderBy('batch_no', 'desc')
            ->get()
            ->toArray();
        // 正在抓的批次號需要去除
        if (Redis::get('TLW_0_XML')) {
            array_shift($ret);
        }
        
        return $ret;
    }
    
    public function getMStatuss()
    {
        $mstatuss = [];
        foreach (GeneralConst::$mStatusMap as $k => $v) {
            $mstatuss[] = [
                'id'          => $k,
                'mstatusName' => $v['ANAME'],
            ];
        }
        
        return $mstatuss;
    }
    
}