<?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\UserService;
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\project\UserMoneyLog;
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 (isset($data['status']) && $data['status'] !== '') {
            $where['status'] = (int)$data['status'];
        }

        if (isset($data['sh_status']) && $data['sh_status'] !== '') {
            $where['sh_status'] = (int)$data['sh_status'];
        }


        $query = ProjectModel::with(['thumb'])->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);
            }
        }

        $query->order('createtime desc');
        $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->param();
        $userId = $request->userId;


        $res = (new ProjectModel())->projectDetail($data['project_id'], $userId);
        if (!$res) {
            return $this->returnMsg('项目不存在');
        }

        $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']];

        //如果当前项目已确定接单人 只查询接单人的申请记录 单独新开接口 （getProjectPut）
//        $put_user = ProjectPut::where('project_id', $request->param('project_id'))
//            ->where('status',2)
//            ->value('user_id');
//
//        if ($put_user)
//        {
//            $where['user_id'] = $put_user;
//        }


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




        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 getProjectPut(Request $request)
    {
        $filed = ['project_id'];

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

        $data = $request->param();


        $where = ['project_id' => $data['project_id'],'status'=>2];


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




        $list = $query->select();

        $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','type'];

        // 验证参数
        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }
        $filed[] = 'reason';
        $filed[] = 'code';
        $data = $request->only($filed);
        if ($data['type']==1)
        {
            $userId = $request->userId;
            $mobile = \app\model\project\User::where('id',$userId)->value('mobile');

            $checkSmsCode = UtilService::checkSmsCode($mobile, $data['code']);
            if (!$checkSmsCode) {
                return $this->returnMsg('验证码错误');
            }
        }

        $res = ProjectService::confirmCompletion($data['project_put_id'],$data['type'],$data['reason'] ?? null);
        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(), 'put_time' => 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', 'put_end_time'];

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

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

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

            if ($data['put_end_time']<time())
            {
                throw new \Exception('项目截止日期应大于当前日期');
            }


            //检查用户信用余额是否足够
            $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('项目创建失败');
            }
            $project_id = $res->id;
            // 2. 更新用户金额（扣除预算）
            $moneyResult = UserModel::where(['id' => $request->userId, 'is_del' => 0])
                ->dec('credit_money', $data['yusuan'])
                ->update();
            if (!$moneyResult) {
                throw new \Exception('企业信用金额更新失败');
            }
            //增加信用金额记录
            UserMoneyLog::addUserMoneyLog($request->userId, '-' . $data['yusuan'], $user['credit_money'], 3, '发布项目:【' . $data['title'] . '】', $project_id, 1);

            // 提交事务
            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', 'put_end_time', 'thumb'];
        $filedpost = ['project_id', 'title', 'cate_id', 'tag_ids', 'yusuan', 'zhouqi', 'description', 'put_end_time', 'thumb','content','file_id_str'];
        $vo = (new ProjectValidate())->goCheck($filed);
        if ($vo !== true) {
            return $vo;
        }

//        $data = $request->param();
        $data = $request->only($filedpost);
        $id = $data['project_id'];
        unset($data['project_id']);
        $data['put_end_time'] = strtotime($data['put_end_time']);

        $project = ProjectModel::where(['id' => $id, 'user_id' => $request->userId])->find();
        if (!$project) {
            return $this->returnMsg('项目不存在');
        }
        if ($project->sh_status == 2) {
            return $this->returnMsg('项目已审核不能编辑');
        }

        if ($data['put_end_time']<strtotime($project->createtime))
        {
            return $this->returnMsg('项目截止日期应大于当前日期');
        }

        $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);

    }

}