<?php

namespace app\api\service;

use app\BaseController;
use app\model\Project;
use app\model\project\User as UserModel;
use app\model\project\UserMoneyLog;
use app\model\ProjectPut;
use think\facade\Db;
use think\facade\Log;


class ProjectService
{
    public static function confirmCompletion($id,$type=1)
    {
        // 定义查询条件
        $where = ['id' => $id, 'status' => 2, 'complete_status' => 1];

        try {
            // 开启事务
            Db::startTrans();

            // 1. 查询并验证接单数据
            $putData = ProjectPut::where($where)->lock(true)->find();
            if (!$putData) {
                throw new \Exception('未找到符合条件的接单记录');
            }

            //验收失败
            if ($type==2)
            {
                $putUpdate = ['complete_status' => 2, 'complete_time' => time()];

                $putResult = ProjectPut::where($where)->update($putUpdate);
                if (!$putResult) {
                    throw new \Exception('更新接单状态失败');
                }
                // 提交事务
                Db::commit();

                return ['code'=>1,'msg'=>'success'];

            }

            // 2. 更新接单状态为已完成
            $putUpdate = ['complete_status' => 3, 'complete_time' => time()];
            $putResult = ProjectPut::where($where)->update($putUpdate);
            if (!$putResult) {
                throw new \Exception('更新接单状态失败');
            }

            // 3. 查询项目信息
            $projectData = Project::where('id', $putData['project_id'])->lock(true)->find();
            if (!$projectData) {
                throw new \Exception('项目不存在');
            }
//            if ($projectData['put_end_time']<time())
//            {
//                throw new \Exception('项目已过截止日期');
//            }

            // 4. 更新项目状态为已完成
            $projectUpdate = ['status' => 4, 'updatetime' => time(),'complete_time'=>time()];
            $projectResult = Project::where('id', $putData['project_id'])->update($projectUpdate);
            if (!$projectResult) {
                throw new \Exception('更新项目状态失败');
            }

            // 5. 查询用户信息
            $user = UserModel::where('id', $putData['user_id'])->lock(true)->find();
            if (!$user) {
                throw new \Exception('用户不存在');
            }

            // 6. 给用户增加金额
            $moneyResult = UserModel::where(['id' => $user['id'], 'is_del' => 0])
                ->inc('money', $projectData['yusuan'])
                ->update();
            if (!$moneyResult) {
                throw new \Exception('用户金额更新失败');
            }

            // 7. 恢复企业高校信用额度
//            $moneyResult = UserModel::where(['id' => $projectData['user_id'], 'is_del' => 0])
//                ->inc('credit_money', $projectData['yusuan'])
//                ->update();
//
//            if (!$moneyResult) {
//                throw new \Exception('企业信用金额更新失败');
//            }

            // 8. 记录资金流水
            $logResult = UserMoneyLog::addUserMoneyLog(
                $user['id'],
                $projectData['yusuan'],
                $user['money'],
                0,
                '项目完成奖励',
                $projectData['id']
            );
            if (!$logResult) {
                throw new \Exception('资金流水记录失败');
            }

            // 提交事务
            Db::commit();

            return ['code'=>1,'msg'=>'success'];



        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 记录错误日志
            return ['code'=>0,'msg'=>$e->getMessage()];

        }
    }

    //订单招募超时
    public static function handleProjectAfterTimeout()
    {
        // 初始化返回数据和日志
        $result = [
            'status' => true,
            'code' => 200,
            'message' => '操作成功',
            'data' => [
                'processed_count' => 0,
                'success_count' => 0
            ]
        ];

        try {
            // 获取当前时间戳
            $currentTime = time();

            // 记录开始日志
            Log::channel('project_task')->info('开始执行项目招募超时处理，当前时间：'.date('Y-m-d H:i:s', $currentTime));

            // 查询符合条件的项目
            $projects = Project::where('status', 1)
                ->where('put_end_time', '<', $currentTime)
                ->select();

            $totalCount = $projects->count();
            $result['data']['processed_count'] = $totalCount;

            // 记录查询到的项目数量
            Log::channel('project_task')->info("共找到{$totalCount}个需要处理的超时项目");

            // 如果没有符合条件的项目，直接返回
            if ($totalCount === 0) {
                $result['message'] = '没有需要处理的超时项目';
                Log::channel('project_task')->info('没有需要处理的超时项目，任务结束');
                return $result;
            }

            $successCount = 0;

            // 遍历并更新项目状态
            foreach ($projects as $project) {
                try {
                    $project->status = 6; // 项目招募已结束
                    $project->updatetime = $currentTime;

                    if ($project->save()) {
                        $successCount++;

                        // 记录单个项目处理成功日志
                        Log::channel('project_task')->info("项目ID:{$project->id} 处理成功，状态已更新为招募结束");

                        // 这里可以添加其他逻辑，比如发送通知等
                        // $this->sendNotification($project);
                    } else {
                        // 记录单个项目处理失败日志
                        Log::channel('project_task')->info("项目ID:{$project->id} 处理失败，保存时出错");
                    }
                } catch (\Exception $e) {
                    // 记录单个项目处理异常日志
                    Log::channel('project_task')->info("项目ID:{$project->id} 处理异常：".$e->getMessage());
                }
            }

            $result['data']['success_count'] = $successCount;

            // 如果有部分失败的情况
            if ($successCount < $totalCount) {
                $failCount = $totalCount - $successCount;
                $result['message'] = "处理完成，成功{$successCount}个，失败{$failCount}个";
                Log::channel('project_task')->info("处理完成，成功{$successCount}个，失败{$failCount}个");
            } else {
                $result['message'] = "所有{$successCount}个项目处理成功";
                Log::channel('project_task')->info("所有{$successCount}个项目处理成功");
            }

        } catch (\Exception $e) {
            // 记录全局异常
            Log::channel('project_task')->info("项目招募超时处理出现全局异常：".$e->getMessage());

            $result = [
                'status' => false,
                'code' => 500,
                'message' => '处理过程中出现异常：'.$e->getMessage(),
                'data' => $result['data']
            ];
        }

        trace('项目招募超时处理任务结束', 'project');
        return $result;
    }


    /**
     * 获取项目完成率
     * @param $limit
     * @param $timeRange 时间范围: 'all'-全部, 'month'-本月, 'week'-本周, 'day'-今天, 'three_month'-近三月
     * @return mixed
     */
    public static function getUserProjectCompletionRanking($limit = 10, $timeRange = 'all')
    {
        // 查询接单总数和完成数量
        $query = Db::name('project_put')
            ->field('user_id,
                COUNT(*) as total_puts,
                SUM(CASE WHEN complete_status = 3 THEN 1 ELSE 0 END) as completed_projects,
                ROUND((SUM(CASE WHEN complete_status = 3 THEN 1 ELSE 0 END) / COUNT(*)) * 100, 2) as completion_rate')
            ->where('status', 2) // 只统计接单成功的记录
            ->group('user_id')
            ->having('total_puts > 0') // 确保分母不为零
            ->order('completion_rate', 'DESC')
            ->limit($limit);

        // 按时间范围筛选
        switch ($timeRange) {
            case 'month':
                $query->whereTime('put_time', 'month');
                break;
            case 'week':
                $query->whereTime('put_time', 'week');
                break;
            case 'day':
                $query->whereTime('put_time', 'today');
                break;
            case 'three_month':
                $threeMonthAgo = strtotime('-3 months');
                $query->where('put_time', '>=', $threeMonthAgo);
                break;
        }

        $ranking = $query->select()->toArray();

        // 获取用户信息
        if (!empty($ranking)) {
            $userIds = array_column($ranking, 'user_id');
            $users = Db::name('user')
                ->whereIn('id', $userIds)
                ->where('is_del', 0)
                ->column('username,realname,headico', 'id');

            foreach ($ranking as &$item) {
                $item['user_info'] = $users[$item['user_id']] ?? [];
                // 确保完成率有值，如果没有则为0
                $item['completion_rate'] = intval($item['completion_rate']) ?? 0;
            }
        }

        return $ranking;
    }
}