<?php

namespace app\api\controller\mine;

use app\api\middleware\Auth;
use app\api\service\UserService;
use app\api\validate\ProjectValidate;
use app\BaseController;
use app\model\Project as ProjectModel;
use app\model\ProjectPut;
use think\Request;

class Project extends BaseController
{
    protected $middleware = [
        Auth::class,
    ];

    // 状态映射关系
    const STATUS_MAP = [
        'apply' => [
            0 => '申请中',
            1 => '申请失败',
            2 => '申请成功'
        ],
        'complete' => [
            0 => '未上传',
            1 => '验收中',
            2 => '验收失败',
            3 => '验收成功'
        ]
    ];

    const PROGRESS_RULES = [
        'apply' => [
            0 => 10,   // 申请中
            1 => 0,     // 申请失败
            2 => 20     // 申请成功
        ],
        'complete' => array(
            0 => 0,     // 未上传
            1 => 60,    // 验收中
            2 => 80,    // 验收失败
            3 => 100    // 验收成功
        )
    ];


    public function getProjectList(Request $request)
    {

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

        $data = $request->param();

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

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

        if (!empty($data['complete_status'])) {
            $where['pp.complete_status'] = $data['complete_status'];
        }


        $query = ProjectPut::where($where)
            ->alias('pp')
            ->join('project p', 'p.id = pp.project_id')
            ->field([
                'pp.*',
                'p.title',
                'p.sn',
                'p.id as project_id'
            ])
            ->with(['project' => ['getuserdata']]);

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

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

        // 处理结果集
        // 添加调试信息
        $list->each(function($item) {
            $applyProgress = self::PROGRESS_RULES['apply'][$item->status] ?? 0;
            $completeProgress = ($item->status == 2) ? (self::PROGRESS_RULES['complete'][$item->complete_status] ?? 0) : 0;


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

            // 调试信息
//            $item->debug = [
//                'status' => $item->status,
//                'complete_status' => $item->complete_status,
//                'apply_progress' => $applyProgress,
//                'complete_progress' => $completeProgress,
//                'final_progress' => $item->progress
//            ];

            return $item;
        });

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

    }

    public function getProjectDetail(Request $request)
    {

        $vo = (new ProjectValidate())->goCheck(['project_put_id']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();


        $item = ProjectPut::where(['id'=>$data['project_put_id'],'user_id'=>$request->userId])
            ->with(['project'])
            ->find();

        $applyProgress = self::PROGRESS_RULES['apply'][$item->status] ?? 0;
        $completeProgress = ($item->status == 2) ? (self::PROGRESS_RULES['complete'][$item->complete_status] ?? 0) : 0;


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

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

    //项目提交
    public function putProject(Request $request)
    {
        $vo = (new ProjectValidate())->goCheck(['project_put_id','complete_file_id_str']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $count = ProjectPut::where(['id'=>$data['project_put_id'],'user_id'=>$request->userId,'complete_status'=>0])->count();

        if (!$count)
        {
            return $this->returnMsg('项目不存在或已有提交记录');
        }

        $update = ['complete_status'=>1,'complete_post_time'=>time(),'complete_file_id_str'=>$data['complete_file_id_str']];
        ProjectPut::where('id',$data['project_put_id'])->update($update);

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

    }

}