<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\dice\controller\play_record_test;

use app\dice\helper\AdminScopeHelper;
use plugin\saiadmin\basic\BaseController;
use app\dice\logic\play_record_test\DicePlayRecordTestLogic;
use app\dice\validate\play_record_test\DicePlayRecordTestValidate;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;
use support\think\Db;

/**
 * 玩家抽奖记录(测试数据)控制器
 */
class DicePlayRecordTestController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new DicePlayRecordTestLogic();
        $this->validate = new DicePlayRecordTestValidate;
        parent::__construct();
    }

    /**
     * 数据列表，并在结果中附带当前筛选条件下测试数据的平台总盈利 total_win_coin（付费金额 paid_amount 求和 - 玩家总收益）
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录(测试数据)列表', 'dice:play_record_test:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['reward_config_record_id', ''],
            ['lottery_config_id', ''],
            ['lottery_type', ''],
            ['direction', ''],
            ['is_win', ''],
            ['win_coin_min', ''],
            ['win_coin_max', ''],
            ['paid_amount', ''],
            ['ante', ''],
            ['reward_tier', ''],
            ['roll_number', ''],
        ]);
        $query = $this->logic->search($where);
        AdminScopeHelper::applyAdminScope($query, $this->adminInfo ?? null, $request->input('dept_id'));
        $query->with(['diceLotteryPoolConfig']);

        // 按当前筛选条件统计：平台总盈利 = 付费金额(paid_amount 求和) - 玩家总收益(win_coin 求和)
        $sumQuery = clone $query;
        $playerTotalWin = (float) $sumQuery->sum('win_coin');
        $paidAmountQuery = clone $query;
        $paidAmount = (float) $paidAmountQuery->where('lottery_type', 0)->sum('paid_amount');
        $totalWinCoin = round($paidAmount - $playerTotalWin, 2);

        $data = $this->logic->getList($query);
        $data['total_win_coin'] = $totalWinCoin;
        return $this->success($data);
    }

    /**
     * 读取数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录(测试数据)读取', 'dice:play_record_test:index:read')]
    public function read(Request $request): Response
    {
        $id = $request->input('id', '');
        $model = $this->logic->read($id);
        if ($model) {
            $data = is_array($model) ? $model : $model->toArray();
            return $this->success($data);
        } else {
            return $this->fail('not found');
        }
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录(测试数据)添加', 'dice:play_record_test:index:save')]
    public function save(Request $request): Response
    {
        $data = $request->post();
        $this->validate('save', $data);
        AdminScopeHelper::prepareBusinessSaveData($data, $this->adminInfo ?? null, $request->input('dept_id'), $data);
        $result = $this->logic->add($data);
        if ($result) {
            return $this->success('add success');
        } else {
            return $this->fail('add failed');
        }
    }

    /**
     * 删除数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录(测试数据)删除', 'dice:play_record_test:index:destroy')]
    public function destroy(Request $request): Response
    {
        $ids = $request->post('ids', '');
        if (empty($ids)) {
            return $this->fail('please select data to delete');
        }
        $result = $this->logic->destroy($ids);
        if ($result) {
            return $this->success('delete success');
        } else {
            return $this->fail('delete failed');
        }
    }
    
    /**
     * 一键删除所有测试数据：清空 dice_play_record_test 表
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录(测试数据)删除', 'dice:play_record_test:index:clearAll')]
    public function clearAll(Request $request): Response
    {
        try {
            $table = (new \app\dice\model\play_record_test\DicePlayRecordTest())->getTable();
            Db::execute('TRUNCATE TABLE `' . $table . '`');
            return $this->success('all test data cleared');
        } catch (\Throwable $e) {
            return $this->fail('clear failed: ' . $e->getMessage());
        }
    }
}
