<?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)
    {
        // 定义查询条件
        $where = ['id' => $id, 'status' => 2, 'complete_status' => 1];

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

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

            // 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('项目不存在');
            }

            // 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' => $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'],
                1,
                '项目完成奖励',
                $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()];

        }
    }
}