<?php

namespace App\Http\Services\Backend\DataManagement;

use App\Http\Services\ConstDef\GeneralConst;
use App\Models\Web\Event;
use App\Models\Web\Item;
use App\Models\Web\Submit;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class SubmitManagementService
{
    // 相關私有 model 調用器宣告
    private $eventManagementDb;
    private $itemManagementDb;
    private $submitManagementDb;
    
    public function __construct()
    {
        date_default_timezone_set("Asia/Taipei");
        // 建構 model 調用器
        $this->eventManagementDb = new Event();
        $this->itemManagementDb = new Item();
        $this->submitManagementDb = new Submit();
    }
    
    public function getEvents()
    {
        $events = $this->eventManagementDb
            ->select([
                'id',
                \DB::raw("CONCAT(date_begin, ' ~ ', date_final, ': ', name) as name"),
            ])
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $events;
    }
    
    public function getItems($eid)
    {
        $items = $this->itemManagementDb
            ->select([
                'id',
                'name',
            ])
            ->where('eid', $eid)
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $items;
    }
    
    public function getSubmits(
        &$cnt = 0,
        $orderColumn,
        $orderDir,
        $start,
        $length,
        $searchValue,
        $submitDateStart,
        $submitDateFinal,
        $iid,
        $searchcol,
        $duplicate
    )
    {
        // 是否合併
        $d = '';
        if ($duplicate == GeneralConst::DUPLICATE_POLICY_MAX_BY_ID) {
            $d = $this->submitManagementDb
                ->select([
                    'iid',
                    'identity',
                    \DB::raw("MAX(id) as id"),
                ])
                ->groupby('iid', 'identity')->get();
            if ($d) {
                $dd = $d->toArray();
                $d = [];
                foreach ($dd as $i) $d[] = $i['id'];
            } else {
                $d = [];
            }
        }
        $submits = $this->submitManagementDb
            ->leftJoin('items', 'submits.iid', '=', 'items.id')
            ->leftJoin('events', 'items.eid', '=', 'events.id')
            ->select([
                'submits.id',
                \DB::raw("events.name as event_name"),
                \DB::raw("items.name as item_name"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.name), \"" . env('KK') . "\")) as name"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.identity), \"" . env('KK') . "\")) as identity"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_host), \"" . env('KK') . "\")) as add_host"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_contact), \"" . env('KK') . "\")) as add_contact"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.tel), \"" . env('KK') . "\")) as tel"),
                \DB::raw("CASE items.is_ide WHEN '" . GeneralConst::PHOTO_YES . "' THEN CONCAT('<a href=\"/', submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] . ", '\" target='\"_blank\"'>下載</a>') ELSE '' END as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql']),
                \DB::raw("CASE items.is_ide WHEN '" . GeneralConst::PHOTO_YES . "' THEN CONCAT('<a href=\"/', submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] . ", '\" target='\"_blank\"'>下載</a>') ELSE '' END as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql']),
                \DB::raw("CASE items.id_acc WHEN '" . GeneralConst::PHOTO_YES . "' THEN CONCAT('<a href=\"/', submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] . ", '\" target='\"_blank\"'>下載</a>') ELSE '' END as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql']),
                \DB::raw("CONCAT('<a class=\"dl\" href=\"/', submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] . ", '\" target='\"_blank\"'>下載</a>') as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql']),
                'submits.cdate',
            ]);
        // 過濾搜尋條件
        $submits = $submits->where('submits.cdate', '>=', $submitDateStart . ' 00:00:00');
        $submits = $submits->where('submits.cdate', '<=', $submitDateFinal . ' 23:59:59');
        $submits = $submits->where('submits.iid', $iid);
        if ($duplicate == GeneralConst::DUPLICATE_POLICY_MAX_BY_ID) {
            $submits = $submits->whereIn('submits.id', $d);
        }
        $submits = $submits->whereRaw("(
            FROM_BASE64(AES_DECRYPT(UNHEX(submits.name), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.identity), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_host), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_contact), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.tel), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
        )");
        // 取總筆數
        $cnt = $submits->count();
        // 排序
        $submits = $submits
            ->orderByRaw((int)$orderColumn . ' ' . $orderDir);
        // 彙整
        // 分頁
        $submits = $submits
            ->skip($start)->take($length);
        // 實際取資料
        $submits = $submits
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $submits;
    }
    
    public function getExportSubmits(
        $submitDateStart,
        $submitDateFinal,
        $iid,
        $searchcol,
        $duplicate
    )
    {
        // 是否合併
        $d = '';
        if ($duplicate == GeneralConst::DUPLICATE_POLICY_MAX_BY_ID) {
            $d = $this->submitManagementDb
                ->select([
                    'iid',
                    'identity',
                    \DB::raw("MAX(id) as id"),
                ])
                ->groupby('iid', 'identity')->get();
            if ($d) {
                $dd = $d->toArray();
                $d = [];
                foreach ($dd as $i) $d[] = $i['id'];
            } else {
                $d = [];
            }
        }
        $submits = $this->submitManagementDb
            ->leftJoin('items', 'submits.iid', '=', 'items.id')
            ->leftJoin('events', 'items.eid', '=', 'events.id')
            ->select([
                'submits.id',
                \DB::raw("events.name as event_name"),
                \DB::raw("items.name as item_name"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.name), \"" . env('KK') . "\")) as name"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.identity), \"" . env('KK') . "\")) as identity"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_host), \"" . env('KK') . "\")) as add_host"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_contact), \"" . env('KK') . "\")) as add_contact"),
                \DB::raw("FROM_BASE64(AES_DECRYPT(UNHEX(submits.tel), \"" . env('KK') . "\")) as tel"),
                \DB::raw("submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql'] . " as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_FRONT ]['sql']),
                \DB::raw("submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql'] . " as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_IDENTITY_BACK ]['sql']),
                \DB::raw("submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql'] . " as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_PASSBOOK ]['sql']),
                \DB::raw("submits." . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql'] . " as " . GeneralConst::$appendixMap[ GeneralConst::APPENDIX_DECLARE_PDF ]['sql']),
                'submits.cdate',
            ]);
        // 過濾搜尋條件
        $submits = $submits->where('submits.cdate', '>=', $submitDateStart . ' 00:00:00');
        $submits = $submits->where('submits.cdate', '<=', $submitDateFinal . ' 23:59:59');
        $submits = $submits->where('submits.iid', $iid);
        if ($duplicate == GeneralConst::DUPLICATE_POLICY_MAX_BY_ID) {
            $submits = $submits->whereIn('submits.id', $d);
        }
        $submits = $submits->whereRaw("(
            FROM_BASE64(AES_DECRYPT(UNHEX(submits.name), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.identity), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_host), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.add_contact), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
            OR FROM_BASE64(AES_DECRYPT(UNHEX(submits.tel), \"" . env('KK') . "\")) like '%" . $searchcol . "%'
        )");
        // 實際取資料
        $submits = $submits
            ->get()
            ->toArray();
        
        // 整理返回值並返回
        return $submits;
    }
    
    public function getExcel($titles = [], $datas = [], $fileName = 'simple')
    {
        $spreadsheet = new Spreadsheet();
        ini_set('memory_limit', '1024M');
        ini_set("max_execution_time", "600");
        $spreadsheet->getActiveSheet()->fromArray($titles, null, 'A1');
        $spreadsheet->getActiveSheet()->fromArray($datas, null, 'A2');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($fileName);
    }
    
}