<?php

namespace app\common\dao\shared;

use app\common\dao\BaseDao;
use app\common\enum\shared\SharedProsperityRewardRecordEnum;
use app\common\model\BaseModel;
use app\common\model\shared\SharedProsperityRewardRecord;
use app\entity\data\shared\SharedProsperityRewardRecordEntity;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SharedProsperityRewardRecordDao extends BaseDao
{
    /**
     * @return BaseModel
     */
    protected function getModel(): string
    {
        return SharedProsperityRewardRecord::class;
    }

    /**
     * @param array $idList
     * @return SharedProsperityRewardRecordEntity[]
     */
    public function getSharedProsperityRewardRecordEntityListByIdList(array $idList): array
    {
        $entityList = [];
        try {
            /** @var SharedProsperityRewardRecord $model */
            $model = $this->getModel();
            $dataRes = $model::getDB()
                ->whereIn('id', $idList)
                ->select()
                ->toArray();
            if (!empty($dataRes)) {
                $entityList = array_map(function ($data) {
                    return SharedProsperityRewardRecordEntity::newInstance($data);
                }, $dataRes);
            }
        } catch (\Exception $e) {

        }
        return $entityList;
    }

    /**
     * 批量更新
     * @param $dataList
     * @return array
     */
    public function saveAll($dataList): array
    {
        try {
            return $this->getModel()::getInstance()->allowField(array_keys(reset($dataList)))->saveAll($dataList)->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    /**
     * @param string $typeShop
     * @param array $orderSnList
     * @return SharedProsperityRewardRecordEntity[]
     */
    public function getSharedProsperityRewardRecordEntityListByOrderSnListAndPending(string $typeShop, array $orderSnList): array
    {
        $entityList = [];
        try {
            /** @var SharedProsperityRewardRecord $model */
            $model = $this->getModel();
            $dataList = $model::getDB()
                ->where('type_shop', '=', $typeShop)
                ->whereIn('order_sn', $orderSnList)
                ->where('status', '=', SharedProsperityRewardRecordEnum::STATUS['PENDING']['code'])
                ->select()
                ->toArray();

            if (!empty($dataList)) {
                $entityList = array_map(function ($data) {
                    return SharedProsperityRewardRecordEntity::newInstance($data);
                }, $dataList);
            }
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {

        }
        return $entityList;
    }

    /**
     * 获取奖励记录分页列表
     * @param int|null $userId 用户ID
     * @param int|null $type 奖励类型
     * @param int|null $status 状态：0=待确定 1=有效 -1=无效
     * @param int|null $typeShop 类型店铺：0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上 9话费
     * @param int|null $pm 0=支出 1=获得
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getRewardList(?int $userId = null, ?int $type = null, ?int $status = null, ?int $typeShop = null, ?int $pm = null, int $page = 1, int $pageSize = 10): array
    {
        $list = [];
        try {
            /** @var SharedProsperityRewardRecord $model */
            $model = $this->getModel();
            $query = $model::getDB();
            // 构建 where 条件
            if (!is_null($userId) && $userId > 0) {
                $query->where('user_id', $userId);
            }
            if (!is_null($type)) {
                $query->where('type', $type);
            }
            if (!is_null($status)) {
                $query->where('status', $status);
            }
            if (!is_null($typeShop)) {
                $query->where('type_shop', $typeShop);
            }
            if (!is_null($pm)) {
                $query->where('pm', $pm);
            }
            // 按创建时间倒序排列
            $query->order('create_time', 'desc');
            $list = $query->paginate(['page' => $page, 'list_rows' => $pageSize])
                ->toArray();
        } catch (\Exception $e) {
            // 记录日志或忽略
        }
        return $list;
    }

    /**
     * 根据条件求和奖励记录中的 number 字段
     * @param int|array|null $userIds 单个用户ID或用户ID数组，为null时忽略此条件
     * @param int|null $type
     * @param int|null $status
     * @param int|null $typeShop
     * @param int|null $pm
     * @return float
     */
    public function getRewardSum($userIds = null, ?int $type = null, ?int $status = null, ?int $typeShop = null, ?int $pm = null): float
    {
        try {
            /** @var SharedProsperityRewardRecord $model */
            $model = $this->getModel();
            $query = $model::getDB();
            if (!is_null($userIds)) {
                if (is_array($userIds)) {
                    if (empty($userIds)) {
                        return 0.0;
                    }
                    $query->whereIn('user_id', $userIds);
                } else {
                    $query->where('user_id', (int) $userIds);
                }
            }
            if (!is_null($type)) {
                $query->where('type', $type);
            }
            if (!is_null($status)) {
                $query->where('status', $status);
            }
            if (!is_null($typeShop)) {
                $query->where('type_shop', $typeShop);
            }
            if (!is_null($pm)) {
                $query->where('pm', $pm);
            }
            $sum = $query->sum('number');
            return (float) $sum;
        } catch (\Exception $e) {
            return 0.0;
        }
    }

    /**
     * @param $start
     * @param $end
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author 史晨
     * @date 2026/2/10 13:56
     * 时间范围搜索
     */
    public function getListByTime($start, $end, $type)
    {
        $model = $this->getModel();
        return $model::getDB()
            ->where('type',$type)
            ->where('take_time', '>', $start)
            ->where('take_time', '<', $end)
            ->select()
            ->toArray();
    }
}
