<?php

namespace App\Modules\Activity\Manage;


use App\Helpers\CmsHtmlHelper;
use App\Http\Controllers\Support\BaseController;
use App\Modules\Activity\JoinMode;
use App\Modules\PrizePool\AmountType;
use App\Modules\PrizePool\Services\PrizePoolService;
use App\Services\DefaultService;
use Edwin404\Base\Support\InputPackage;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\RequestHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Member\Support\MemberLoginCheck;
use Edwin404\Report\ReportService;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Str;

abstract class HomeController extends BaseController
{
    abstract protected function setupActivity();

    public function index()
    {
        $this->setupActivity();
        $activities = ModelHelper::find('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', [
            'memberUserId' => $this->memberUserId()], ['id', 'desc']
        );
        return $this->_view('module.activity.index', [
            'activities' => $activities,
        ]);
    }

    public function activityEdit(DefaultService $defaultService,
                                 PrizePoolService $prizePoolService,
                                 $id = 0)
    {
        $this->setupActivity();
        if ($id) {
            $activity = ModelHelper::load('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', ['id' => $id, 'memberUserId' => $this->memberUserId()]);
            if (empty($activity)) {
                return Response::send(-1, '记录不存在');
            }
            $prizes = $prizePoolService->listPrizes(MODULE_ACTIVITY_NAME, $activity['id']);
        } else {
            $activity = null;
            $prizes = [];
        }

        if (RequestHelper::isPost()) {

            $input = InputPackage::buildFromInputJson('data');

            $activityInput = $input->getAsInput('activity');

            $update = [];
            $update['title'] = $activityInput->getTrimString('title');
            $update['enable'] = $activityInput->getBoolean('enable');
            $update['startTime'] = $activityInput->getDatetime('startTime');
            $update['endTime'] = $activityInput->getDatetime('endTime');
            $update['description'] = $activityInput->getTrimString('description');
            $update['joinMode'] = $activityInput->getType('joinMode', JoinMode::class);
            $update['joinDailyLimit'] = $activityInput->getInteger('joinDailyLimit');
            $update['background'] = $activityInput->getImagePath('background');
            $update['prizeUsersEnable'] = $activityInput->getBoolean('prizeUsersEnable');
            $update['textColor'] = $activityInput->getColorHex('textColor');
            $update['backgroundMusic'] = $activityInput->getFilePath('backgroundMusic');

            $update['shareEnable'] = $activityInput->getBoolean('shareEnable');
            $update['shareImage'] = $activityInput->getImagePath('shareImage');
            $update['shareTitle'] = $activityInput->getTrimString('shareTitle');
            $update['shareDesc'] = $activityInput->getTrimString('shareDesc');

            $prizesUpdate = [];
            foreach ($input->getArray('prizes') as $prize) {
                $prizeInput = InputPackage::build($prize);
                $prizeUpdate = [];
                $prizeUpdate['prizeId'] = $prizeInput->getInteger('prizeId');
                $prizeUpdate['rate'] = $prizeInput->getDecimal('rate');
                $prizeUpdate['amountType'] = $prizeInput->getType('amountType', AmountType::class);
                $prizeUpdate['amount'] = $prizeInput->getInteger('amount');
                $prizesUpdate[] = $prizeUpdate;
            }

            // 判断 开始
            if (empty($update['title'])) {
                return Response::send(-1, '名称为空');
            }
            if (empty($update['startTime'])) {
                return Response::send(-1, '开始时间为空');
            }
            if (empty($update['endTime'])) {
                return Response::send(-1, '结束时间为空');
            }
            if (empty($update['description'])) {
                return Response::send(-1, '描述为空');
            }
            if (empty($update['joinMode'])) {
                return Response::send(-1, '参与限制为空');
            }
            switch ($update['joinMode']) {
                case JoinMode::LIMIT_DAILY:
                    if ($update['joinDailyLimit'] <= 0) {
                        return Response::send(-1, '每日限制不能为空');
                    }
                    break;
            }

            if (empty($update['background'])) {
                return Response::send(-1, '背景图为空');
            }

            if (!empty($update['shareEnable'])) {
                if (empty($update['shareImage'])) {
                    return Response::send(-1, '分享图片为空');
                }
                if (empty($update['shareTitle'])) {
                    return Response::send(-1, '分享标题为空');
                }
                if (empty($update['shareDesc'])) {
                    return Response::send(-1, '分享描述为空');
                }
            }

            if (empty($prizesUpdate)) {
                return Response::send(-1, '奖品为空');
            }
            $totalPrizeRate = 0;
            foreach ($prizesUpdate as $prizeUpdateIndex => $prizeUpdate) {
                $prize = ModelHelper::load('module_prize_pool', ['id' => $prizeUpdate['prizeId'], 'memberUserId' => $this->memberUserId()]);
                if (empty($prize)) {
                    return Response::send(-1, '奖品不存在');
                }
                if (!$prize['enable']) {
                    return Response::send(-1, '奖品' . ($prizeUpdateIndex + 1) . '已被禁用');
                }
                if ($prizeUpdate['rate'] < 0 || $prizeUpdate['rate'] > 100) {
                    return Response::send(-1, '概率范围为0.00-100.00');
                }
                $totalPrizeRate = bcadd($totalPrizeRate, $prizeUpdate['rate'], 2);
                switch ($prizeUpdate['amountType']) {
                    case AmountType::NO_LIMITED:
                        break;
                    case AmountType::FIXED:
                        if ($prizeUpdate['amount'] < 0) {
                            return Response::send(-1, '奖品' . ($prizeUpdateIndex + 1) . '数量不能小于0');
                        }
                        break;
                }
            }
            if ($totalPrizeRate > 100) {
                return Response::send(-1, '概率总和不能大于100%');
            }
            if (count($prizesUpdate) == MODULE_ACTIVITY_MAX_PRIZE && $totalPrizeRate < 100) {
                return Response::send(-1, '您设置了所有奖品数量，但是中奖概率总和不等于100%');
            }
            // 判断结束

            ModelHelper::transactionBegin();
            if (empty($activity)) {
                $update['memberUserId'] = $this->memberUserId();
                $update['alias'] = strtolower(Str::random(8));
                $update['template'] = 'default';
                $activity = ModelHelper::add('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', $update);
            } else {
                ModelHelper::update('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', ['id' => $activity['id']], $update);
            }
            $prizePoolService->savePrizes(MODULE_ACTIVITY_NAME, $activity['id'], $prizesUpdate);
            ModelHelper::transactionCommit();

            return Response::send(0, '保存成功', null, '/module/manage/' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity/' . $activity['id']);
        }
        return $this->_view('module.activity.activityEdit', [
            'activity' => $activity,
            'prizes' => $prizes,
            'defaultBackgrounds' => $defaultService->images(MODULE_ACTIVITY_NAME . 'Background'),
        ]);
    }

    public function activityDelete($id = 0)
    {
        $this->setupActivity();
        $activity = ModelHelper::load('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', ['id' => $id, 'memberUserId' => $this->memberUserId()]);
        if (empty($activity)) {
            return Response::send(-1, '记录不存在');
        }
        ModelHelper::delete('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', ['id' => $activity['id']]);
        ModelHelper::delete('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_drawn', ['activityId' => $activity['id']]);
        return Response::send(0, '删除成功', null, '/module/manage/' . MODULE_ACTIVITY_NAME_UNDERSCORE);
    }

    public function activity(ReportService $reportService,
                             $id = 0)
    {
        $this->setupActivity();
        $activity = ModelHelper::load('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', ['id' => $id, 'memberUserId' => $this->memberUserId()]);
        if (empty($activity)) {
            return Response::send(-1, '记录不存在');
        }

        $drawLatestReport = $reportService->countDaily(
            'module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_drawn',
            ['activityId' => $activity['id']],
            date('Y-m-d', strtotime('-6 day')),
            date('Y-m-d')
        );

        return $this->_view('module.activity.activity', [
            'activity' => $activity,
            'drawLatestReport' => $drawLatestReport,
        ]);
    }

    public function drawn($id = 0)
    {
        $this->setupActivity();

        $activity = ModelHelper::load('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_activity', ['id' => $id, 'memberUserId' => $this->memberUserId()]);
        if (empty($activity)) {
            return Response::send(-1, '记录不存在');
        }

        if (RequestHelper::isPost()) {

            $page = Input::get('page');
            $pageSize = 10;
            $option = [];
            $option['where']['activityId'] = $activity['id'];
            $option['order'] = ['id', 'desc'];

            $head = [];

            $head[] = ['field' => 'created_at', 'title' => '时间',];
            $head[] = ['field' => 'user', 'title' => '用户',];

            $list = [];
            $paginateData = ModelHelper::modelPaginate('module_' . MODULE_ACTIVITY_NAME_UNDERSCORE . '_drawn', $page, $pageSize, $option);
            foreach ($paginateData['records'] as &$record) {
                $item = [];
                $item['_id'] = $record['id'];
                $item['user'] = CmsHtmlHelper::user($record['userId']);
                $item['created_at'] = $record['created_at'];
                $list[] = $item;
            }

            $data = [];
            $data['head'] = $head;
            $data['list'] = $list;
            $data['total'] = $paginateData['total'];
            $data['pageSize'] = $pageSize;
            $data['page'] = $page;

            return Response::generate(0, null, $data);
        }

        return $this->_view('module.activity.drawn', [
            'activity' => $activity,
        ]);
    }
}