<?php

namespace app\api\controller\manage;

use app\api\common\StatusConstants;
use app\api\middleware\Auth;
use app\api\service\ProjectService;
use app\api\service\UtilService;
use app\api\validate\ProjectValidate;
use app\BaseController;
use app\model\Project as ProjectModel;
use app\model\project\User as UserModel;
use app\model\ProjectPut;
use think\facade\Db;
use think\Log;
use think\Request;

class Project extends BaseController
{

    protected $middleware = [
        Auth::class,
    ];

    public function getProjectList(Request $request)
    {

        $data = $request->param();

        $page = $request->param('page/d', 1);
        $pageSize = $request->param('pageSize/d', 10);

        $where = ['user_id' => $request->userId];

        if (!empty($data['status']) || $data['status'] == 0) {
            $where['status'] = (int)$data['status'];
        }

        if (!empty($data['sh_status'])) {
            $where['sh_status'] = $data['sh_status'];
        }


        $query = ProjectModel::where($where);

        if (!empty($data['search_str'])) {
            $searchStr = trim($data['search_str']);
            $query->where(function ($q) use ($searchStr) {
                $q->where('title|sn', 'like', "%{$searchStr}%");
            });
        }
        if (!empty($data['start_date']) || !empty($data['end_date'])) {
            if (!empty($data['start_date'])) {
                $startTimestamp = strtotime($data['start_date']);
                $query->where('createtime', '>=', $startTimestamp);
            }

            if (!empty($data['end_date'])) {
                $endTimestamp = strtotime($data['end_date']);
                $query->where('createtime', '<=', $endTimestamp);
            }
        }


        $list = $query->paginate([
            'page' => $page,
            'list_rows' => $pageSize
        ]);
        // 处理结果集
        // 添加调试信息
        $list->each(function ($item) {
            $applyProgress = StatusConstants::PROGRESS_RULES['apply'][$item->sh_status] ?? 0;
            $completeProgress = ($item->sh_status == 2) ? (StatusConstants::PROGRESS_RULES['complete'][$item->status] ?? 0) : 0;


            $item->progress = max(1, min(100, $applyProgress + $completeProgress));


            return $item;
        });


        return $this->returnMsg('success', 1, $list);
    }

    public function getProjectDetail(Request $request)
    {
        $filed = ['project_id'];

        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->only($filed);

        $res = ProjectModel::where(['id'=>$data['project_id'],'user_id'=>$request->userId])->find();

        $applyProgress = StatusConstants::PROGRESS_RULES['apply'][$res->sh_status] ?? 0;
        $completeProgress = ($res->sh_status == 2) ? (StatusConstants::PROGRESS_RULES['complete'][$res->status] ?? 0) : 0;
        $res->progress = max(1, min(100, $applyProgress + $completeProgress));

        $res = UtilService::infoWithTags($res,\app\model\ProjectTag::class,'tag_ids');

        return $this->returnMsg('success',1,$res);

    }

    public function getProjectPutList(Request $request)
    {
        $filed = ['project_id'];

        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->param();

        $page = $request->param('page/d', 1);
        $pageSize = $request->param('pageSize/d', 10);

        $where = ['project_id'=>$data['project_id']];
        $query = ProjectPut::with(['getuserdata'])
            ->where($where);

        $order_status = ProjectModel::where('id',$request->param('project_id'))->value('status');
        if ($order_status>=2)
        {
            $query->where(['project_put.status'=>2]);
        }


        if (!empty($data['search_str'])) {
            $searchStr = trim($data['search_str']);
            $query->hasWhere('getuserdata', function ($q) use ($searchStr) {
                $q->where('username', 'like', "%{$searchStr}%");
            });
        }


        $list = $query->paginate([
            'page' => $page,
            'list_rows' => $pageSize
        ]);

        $list->each(function ($item) {
            $item->done_num = ProjectPut::where(['user_id'=>$item->user_id,'complete_status'=>3])->count();;
            return $item;
        });

        return $this->returnMsg('success',1,$list);

    }

    //项目完成
    public function confirmCompletion(Request $request)
    {
        $filed = ['project_put_id'];

        // 验证参数
        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->only($filed);
        $res= ProjectService::confirmCompletion($data['project_put_id']);
        if ($res['code']==1)
        {
            return $this->returnMsg('success',1);
        }
        return $this->returnMsg($res['msg']);

    }


    //确认接单人
    public function confirmOrderUser(Request $request)
    {
        $filed = ['project_id', 'user_id'];

        // 验证参数
        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->only($filed);

        try {
            // 开启事务
            Db::startTrans();
            // 检查项目状态
            $isConfirm = ProjectModel::where([
                'id' => $data['project_id'],
                'sh_status' => 2
            ])->where('status', '!=', 1)->lock(true)->count();
            if (!$isConfirm) {
                throw new \Exception('当前项目已完成或已确认接单人');
            }

            // 更新项目状态
            $projectUpdate = ['status' => 2,'updatetime'=>time()];
            $projectResult = ProjectModel::where('id', $data['project_id'])
                ->update($projectUpdate);

            if (!$projectResult) {
                throw new \Exception('更新项目状态失败');
            }

            // 更新接单记录
            $putUpdate = [
                'put_time' => time(),
                'status' => 2
            ];
            $putResult = ProjectPut::where('project_id', $data['project_id'])
                ->where('user_id', $data['user_id'])
                ->update($putUpdate);

            if (!$putResult) {
                throw new \Exception('更新接单记录失败');
            }

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

            return $this->returnMsg('success', 1);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->returnMsg($e->getMessage());
        }
    }


    //创建项目
    public function createProject(Request $request)
    {
        $filed = ['title', 'cate_id', 'tag_ids', 'yusuan', 'zhouqi', 'description', 'content', 'file_id_str'];

        // 参数验证
        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->only($filed);
        $data['sn'] = UtilService::generateCompactOrderNo(null, 'xm');
        $data['user_id'] = $request->userId;

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


            //检查用户信用余额是否足够
            $user = UserModel::where(['id' => $request->userId, 'is_del' => 0])
                ->lock(true) // 加锁防止并发修改
                ->find();

            if (!$user) {
                throw new \Exception('用户不存在或已被删除');
            }

            if ($user->credit_money < $data['yusuan']) {
                throw new \Exception('企业信用金额不足，当前可用金额：' . $user->credit_money);
            }

            // 1. 创建项目
            $res = ProjectModel::create($data);
            if (!$res) {
                throw new \Exception('项目创建失败');
            }

            // 2. 更新用户金额（扣除预算）
            $moneyResult = UserModel::where(['id' => $request->userId, 'is_del' => 0])
                ->dec('credit_money', $data['yusuan'])
                ->update();
            if (!$moneyResult) {
                throw new \Exception('企业信用金额更新失败');
            }


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

            return $this->returnMsg('success', 1, $res);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 记录错误日志
            return $this->returnMsg($e->getMessage());
        }
    }

    //编辑项目
    public function editProject(Request $request)
    {
        $filed = ['project_id','title','cate_id','tag_ids','yusuan','zhouqi','description','content','file_id_str'];

        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->only($filed);
        $id = $data['project_id'];
        unset($data['project_id']);

        $res = ProjectModel::where(['id'=>$id,'user_id'=>$request->userId])->update($data);
        return $this->returnMsg('success',1,$res);

    }

    //删除项目
    public function delProject(Request $request)
    {
        $filed = ['project_id'];

        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

        $data = $request->only($filed);

        $res = ProjectModel::where(['id'=>$data['project_id'],'user_id'=>$request->userId])->find();
        if (!$res) {
            return $this->returnMsg('项目不存在或无权删除');
        }

        $res->delete();
        return $this->returnMsg('success',1,$res);

    }

}