<?php

namespace App\Http\Services\Backend\DataManagement;

use App\Http\Services\ConstDef\GeneralConst;
use App\Models\Web\Receipt;
use App\Models\Web\Syslogact;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Support\Facades\DB;
use App\Models\Web\Activity;

class ReceiptManagementService
{
    // 相關私有 model 調用器宣告
    private $receiptManagementDb;
    private $activityManagementDb;
    private $syslogactManagementDb;
    
    public function __construct()
    {
        // 建構 model 調用器
        $this->receiptManagementDb = new Receipt();
        $this->activityManagementDb = new Activity();
        $this->syslogactManagementDb = new Syslogact();
    }
    
    public function getActivitys()
    {
        $activity = $this->activityManagementDb->select([
            'id',
            'activityName',
        ])
            ->get()
            ->toArray();
        
        return $activity;
    }
    
    public function getReceipts(
        &$cnt = 0,
        $orderColumn,
        $orderDir,
        $start,
        $length,
        $searchValue,
        $tranDateStart,
        $tranDateFinal,
        $tranBank,
        $tranAccount,
        $tranOrderNo,
        $lineId,
        $lineName,
        $activity,
        $rStatus,
        $canGet
    )
    {
        // 選欄位
        $rStatusStr = '';
        foreach (GeneralConst::$rStatusMap as $k => $v) {
            $rStatusStr .= ' when \'' . $k . '\' then \'' . $v['back'] . '\'';
        }
        
        $receipt = $this->receiptManagementDb
            ->leftJoin('activity', 'receipt.aid', '=', 'activity.id')
            ->select([
                'receipt.id',
                'receipt.tranDate',
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranBank), \"" . env('KK') . "\")) as tranBank"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranAccount), \"" . env('KK') . "\")) as tranAccount"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranOrderNo), \"" . env('KK') . "\")) as tranOrderNo"),
                'receipt.lineId',
                'receipt.lineName',
                'activity.activityName',
                \DB::raw("(case receipt.rStatus $rStatusStr end) as rStatus"),
                \DB::raw("
                    (CASE
                        WHEN (
                            receipt.canGet = ''                                                                       -- 檢查專用的狀態位為空
                            AND receipt.rStatus = " . GeneralConst::RSTATUS_DRAW_DONE_REDEEM . "                      -- 紀錄的狀態位為檢查中
                            AND UNIX_TIMESTAMP(NOW()) >= UNIX_TIMESTAMP(CONCAT(activity.checkTimeBegin, ' 00:00:00')) -- 活動已達驗證時間
                            AND activity.isCheckBegin = '" . GeneralConst::ACTIVE_YES . "'                            -- 活動已開放驗證
                        ) THEN
                            CONCAT(
                                '<input class=\"form-check-input\" type=\"checkbox\" name=\"chk[',
                                receipt.id,
                                ']\" value=\"',
                                receipt.id,
                                '\"',
                                '>'
                            )
                         WHEN receipt.canGet = '" . GeneralConst::CANGET_YES . "' THEN '是'
                         WHEN receipt.canGet = '" . GeneralConst::CANGET_NO . "' THEN '否'
                         ELSE ''
                    END) as canGet
                "),
                'receipt.cdate',
                'receipt.mdate',
                \DB::raw("(select name from users where id=receipt.oid) as oid"),
            ]);
        // 過濾搜尋條件
        $receipt = $receipt->where('receipt.tranDate', '>=', $tranDateStart . ' 00:00:00');
        $receipt = $receipt->where('receipt.tranDate', '<=', $tranDateFinal . ' 23:59:59');
        $receipt = $receipt->whereRaw("(
            FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranBank), \"" . env('KK') . "\")) like '%" . $tranBank . "%'
            AND FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranAccount), \"" . env('KK') . "\")) like '%" . $tranAccount . "%'
            AND FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranOrderNo), \"" . env('KK') . "\")) like '%" . $tranOrderNo . "'
        )");
        if ($lineId != '') $receipt = $receipt->where('receipt.lineId', 'like', '%' . $lineId . '%');
        if ($lineName != '') $receipt = $receipt->where('receipt.lineName', 'like', '%' . $lineName . '%');
        if ($activity != '') $receipt = $receipt->where('activity.id', '=', $activity);
        if ($rStatus != '') $receipt = $receipt->where('receipt.rStatus', '=', $rStatus);
        if ($canGet != '') $receipt = $receipt->where('receipt.canGet', '=', $canGet);
        // 取總筆數
        $cnt = $receipt->count();
        // 排序
        $receipt = $receipt
            ->orderByRaw((int)$orderColumn . ' ' . 'ASC');
        // 彙整
        // 分頁
        $receipt = $receipt
            ->skip($start)->take($length);
        // 實際取資料
        $receipt = $receipt
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $receipt;
    }
    
    public function getExports($param)
    {
        // 選欄位
        $rStatusStr = '';
        foreach (GeneralConst::$rStatusMap as $k => $v) {
            $rStatusStr .= ' when \'' . $k . '\' then \'' . $v['back'] . '\'';
        }
        $receipt = $this->receiptManagementDb
            ->leftJoin('activity', 'receipt.aid', '=', 'activity.id')
            ->select([
                'receipt.id',
                'receipt.tranDate',
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranBank), \"" . env('KK') . "\")) as tranBank"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranAccount), \"" . env('KK') . "\")) as tranAccount"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranOrderNo), \"" . env('KK') . "\")) as tranOrderNo"),
                'receipt.lineId',
                'receipt.lineName',
                'activity.activityName',
                \DB::raw("(case rStatus $rStatusStr end) as rStatus"),
                'receipt.canGet',
                'receipt.cdate',
                'receipt.mdate',
                \DB::raw("(select name from users where id=receipt.oid) as oid"),
            ]);
        // 過濾搜尋條件
        $receipt = $receipt->where('receipt.tranDate', '>=', $param["tranDateStart"] . ' 00:00:00');
        $receipt = $receipt->where('receipt.tranDate', '<=', $param["tranDateFinal"] . ' 23:59:59');
        $receipt = $receipt->whereRaw("(
            FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranBank), \"" . env('KK') . "\")) like '%" . $param["tranBank"] . "%'
            AND FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranAccount), \"" . env('KK') . "\")) like '%" . $param["tranAccount"] . "%'
            AND FROM_BASE64(AES_DECRYPT(UNHEX(receipt.tranOrderNo), \"" . env('KK') . "\")) like '" . $param["tranOrderNo"] . "%'
        )");
        if ($param["lineId"] != '') $receipt = $receipt->where('receipt.lineId', 'like', '%' . $param["lineId"] . '%');
        if ($param["lineName"] != '') $receipt = $receipt->where('receipt.lineName', 'like', '%' . $param["lineName"] . '%');
        if ($param["activity"] != '') $receipt = $receipt->where('activity.id', '=', $param["activity"]);
        if ($param["rStatus"] != '') $receipt = $receipt->where('receipt.rStatus', '=', $param["rStatus"]);
        if ($param["canGet"] != '') $receipt = $receipt->where('receipt.canGet', '=', $param["canGet"]);
        // 實際取資料
        $receipt = $receipt
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $receipt;
    }
    
    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 redeemDone($chk, $oid)
    {
        $this->receiptManagementDb
            ->whereIn('id', $chk)
            ->where('rStatus', GeneralConst::RSTATUS_DRAW_DONE_REDEEM)
            ->where('canGet', '')
            ->update([
                'rStatus' => GeneralConst::RSTATUS_DRAW_DONE_REDEEM_DONE,
                'canGet'  => GeneralConst::CANGET_YES,
                'mdate'   => date('Y-m-d H:i:s'),
                'oid'     => $oid,
            ]);
        // syslogact
        $data = [
            'redeem_done' => $chk,
        ];
        $this->syslogactManagementDb
            ->insert([
                'type'    => GeneralConst::LOG_ADMIN,
                'func'    => __FUNCTION__,
                'k'       => $oid,
                'memoIn'  => json_encode(['data' => $data], JSON_UNESCAPED_UNICODE),
                'memoOut' => json_encode([], JSON_UNESCAPED_UNICODE),
                'cdate'   => date("Y-m-d H:i:s"),
            ]);
        
        // 整理返回值並返回
        return true;
    }
    
    public function redeemFail($chk, $oid)
    {
        $this->receiptManagementDb
            ->whereIn('id', $chk)
            ->where('rStatus', GeneralConst::RSTATUS_DRAW_DONE_REDEEM)
            ->where('canGet', '')
            ->update([
                'rStatus' => GeneralConst::RSTATUS_DRAW_DONE_REDEEM_FAIL,
                'canGet'  => GeneralConst::CANGET_NO,
                'mdate'   => date('Y-m-d H:i:s'),
                'oid'     => $oid,
            ]);
        // syslogact
        $data = [
            'redeem_fail' => $chk,
        ];
        $this->syslogactManagementDb
            ->insert([
                'type'    => GeneralConst::LOG_ADMIN,
                'func'    => __FUNCTION__,
                'k'       => $oid,
                'memoIn'  => json_encode(['data' => $data], JSON_UNESCAPED_UNICODE),
                'memoOut' => json_encode([], JSON_UNESCAPED_UNICODE),
                'cdate'   => date("Y-m-d H:i:s"),
            ]);
        
        // 整理返回值並返回
        return true;
    }
    
}