<?php

namespace app\controller\api;

use app\extra\basic\Base;
use app\extra\service\blue\BlueTaskUserService;
use app\middleware\WxMiddleware;
use app\model\blue\BlueExpertPlatform;
use app\model\blue\BlueTaskUser;
use DI\Attribute\Inject;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Middleware;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;


#[Controller(prefix: "/wx_api/task/user"),Middleware(WxMiddleware::class)]
class TaskUser extends Base
{
    protected array $noNeedLogin = [];

    #[Inject]
    protected BlueTaskUser $model;

    #[Inject]
    protected BlueTaskUserService $service;


    /**
     * 已接任务列表
     * @param Request $request
     * @return Response
     */
    #[Route(path: "list",methods: "get")]
    public function getTaskUserList(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "status.default"    => 0,
                "size.default"      => 10,
                "page.default"      => 1,
            ],$request->method());
            $list = $this->service->getHomeList(['openid' => $request->user['openid'],'status' => $param['status'],'pageSize' => $param['size'],'page' => $param['page']]);
            return success("ok",pageFormat($list));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 提交任务资料
     * @param Request $request
     * @return Response
     */
    #[Route(path: "submit",methods: "post")]
    public function updateTaskUser(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => trans("empty.require"),
                "task_sn.require"   => trans("empty.require"),
                "star_id.require"   => trans("empty.require"),
            ],$request->method());
            if (!is_array($param)) return error($param);
            $task = $this->model->where(['id' => $param['id'],'task_sn' => $param['task_sn'],'openid' => $request->user['openid'] ])->findOrEmpty();
            if ($task->isEmpty()) return errorTrans("empty.data");
            $platformUser = (new BlueExpertPlatform)->where(['openid' => $request->user['openid'],"source" => $task['source'],"status" => 1])->findOrEmpty();
            if ($platformUser->isEmpty()) return error("请先完成平台绑定");
            if (empty($platformUser['star_id'])) {
                $platformUser->star_id = $param['star_id'];
                $platformUser->save();
            }
            $task->star_id = $param['star_id'];
            $task->status = 1;
            $task->submit_at = getDateFull();
            $task->platform = json_encode($platformUser);
            $state = $task->save();
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 检查是否绑定星图ID
     * @param Request $request
     * @return Response
     */
    #[Route(path: "starId",methods: "post")]
    public function getStarId(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => trans("empty.require"),
                "task_sn.require"   => trans("empty.require"),
            ],$request->method());
            if (!is_array($param)) return error($param);
            $task = $this->model->where(['task_sn' => $param['task_sn'],'id' => $param['id']])->findOrEmpty();
            if ($task->isEmpty()) return errorTrans("empty.data");
            $platformUser = (new BlueExpertPlatform)->where(['openid' => $request->user['openid'],"source" => $task['source'],"status" => 1])->findOrEmpty();
            if ($platformUser->isEmpty()) return error("请先完成平台绑定");
            return success("ok",['star_id' => $platformUser['star_id']]);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }



    /**
     * 已接任务详情
     * @param Request $request
     * @return Response
     */
    #[Route(path: "detail",methods: "get")]
    public function getTaskUserDetail(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => trans("empty.require"),
                "task_sn.require"   => trans("empty.require"),
            ],$request->method());
            if (!is_array($param)) return error($param);
            $task = $this->model->where(['id' => $param['id'],'task_sn' => $param['task_sn'],'openid' => $request->user['openid'] ])->with(['task' => function ($query) {
                $query->field("id,title,task_sn,product_cover_url,total_budget,sign_number,need_number,category,level,sys_level,product_price")->append(['progress','total_budget_format'])->withAttr(['progress' => function ($data,$resp) {
                    if ($resp['sign_number'] == 0) return $resp['sign_number'];
                    return ceil($resp['sign_number']/$resp['need_number'] * 100);
                },'total_budget_format' => function($data,$resp) {
                    return formatMoneyKw($resp['total_budget']/100);
                }]);
            }])->findOrEmpty();
            if ($task->isEmpty()) return errorTrans("empty.data");
            return success("ok",$task->toArray());
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 任务收益记录
     * @param Request $request
     * @return Response
     */
    public function getTaskRevenue(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => trans("empty.require"),
                "task_sn.require"   => trans("empty.require"),
                "date.default"      => date("Y-m-d",strtotime("-1 day")),
            ],$request->method());
            if (!is_array($param)) return error($param);

            return success("ok");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}