<?php

namespace app\controller\v2;

use app\extra\basic\Base;
use app\extra\service\blue\TaskService;
use app\extra\tools\XcJob;
use app\middleware\WxMiddleware;
use app\model\blue\BlueCategory;
use app\model\blue\BlueExpert;
use app\model\blue\BlueExpertPlatform;
use app\model\blue\BlueTask;
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;
use yzh52521\EasyHttp\Http;


#[Controller(prefix: "/wx_v2/task"),Middleware(WxMiddleware::class)]
class Task extends Base
{


    protected array $noNeedLogin = ["getTaskDetail","getTaskList"];


    #[Inject]
    protected TaskService $service;

    #[Inject]
    protected BlueTask $model;

    /**
     * 任务列表
     * @param Request $request
     * @return Response
     */
    #[Route(path: "portal",methods: "get")]
    public function getTaskList(Request $request): Response
    {
        try {
            $param = $request->all();
            if (empty($param['size'])) return errorTrans("empty.require");
            $param['pageSize'] = $param['size'];
            $list = $this->service->getList($param,"id,title,product_cover_url,job_id,category,category_detail,expiration_time_end,sign_number,need_number,product_price,level");
            $category = (new BlueCategory)->where("type",1)->field("name,icon,small_icon,sign")->append(['id'])->withAttr(['id' => function($data,$resp){
                return $resp['sign'];
            }])->select()->toArray();
            return successTrans("success.data",[
                "category"    => $category,
                "filter"    => $this->getTaskFilter(),
                "task"      => pageFormat($list)
            ],200);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    protected function getTaskFilter(): array
    {
        return [
            [
                "name"      => "任务状态",
                "children"  => [
                    [
                        "name"  => "不限",
                        "field" => "status",
                        "val"   => 0
                    ],
                    [
                        "name"  => "进行中",
                        "field" => "status",
                        "val"   => 1
                    ],
                    [
                        "name"  => "已终止",
                        "field" => "status",
                        "val"   => 2
                    ]
                ]
            ],
            [
                "name"      => "平台等级",
                "children"  => [
                    [
                        "name"  => "不限",
                        "field" => "level",
                        "val"   => 0
                    ],
                ]
            ],
            [
                "name"      => "平台等级",
                "children"  => [
                    [
                        "name"  => "不限",
                        "field" => "sort",
                        "val"   => 0
                    ],
                ]
            ]
        ];
    }


    /**
     * 任务详情
     * @param Request $request
     * @return Response
     */
    #[Route(path: "detail",methods: "get")]
    public function getTaskDetail(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "task_sn.require"   => trans("empty.require"),
                "id.require"        => trans("empty.require"),
            ],$request->method());
            if (!is_array($param)) return error($param);
            $data = $this->service->getTaskDetail($param);
            if (empty($data)) return errorTrans("empty.data");
            $return = $data->toArray();
            $content = json_decode($return['content'],true);
            $return['content'] = $content['content_advice_v2']??[];
            $return['need_number'] = $return['need_number']>0 ? $return['need_number'] : 999;
            $return['field_tag'] = [
                [
                    "label" => "商品售价",
                    "content" => $return['price_format']
                ],
                [
                    "label" => "投放预算",
                    "content" => $return['total_budget'] == 0 ? '不限' : $return['total_budget_format']
                ],
                [
                    "label" => "商品售价",
                    "content" => $return['price_format']
                ],
                [
                    "label" => "商品售价",
                    "content" => $return['price_format']
                ],
                [
                    "label" => "商品售价",
                    "content" => $return['price_format']
                ]
            ];
            return success("ok",$return);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 任务报名
     * @param Request $request
     * @return Response
     */
    #[Route(path: "sign",methods: "post")]
    public function taskUserReg(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "task_sn.require"   => trans("empty.require"),
                "task_id.require"   => trans("empty.require"),
            ],$request->method());
            if (!is_array($param)) return error($param);
            $task = $this->model->where(['job_id' => $param['task_sn'],'id' => $param['task_id']])->findOrEmpty();
            if ($task->isEmpty()) return errorTrans("empty.data");
            $expert = (new BlueExpert)->where(["openid" => $request->user['openid'] ])->findOrEmpty();
            if ($expert->isEmpty()) return error("请先完成平台认证",[],2);
            $platform = (new BlueExpertPlatform)->where(["openid" => $request->user['openid'],'source' => $task['category']])->findOrEmpty();
            if ($platform->isEmpty()) return error("请先绑定平台账号",[],3);
            $starId = $platform['star_id'];
            if (empty($platform['star_id'])) {
                [$starState,$starData] = (new XcJob)->getStarData($platform['unique_id']);
                if (!$starState) return error($starData,[],4);
                $platform->star_id = $starData['list'][0]['star_id']??'';
                $platform->save();
                $starId = $starData['list'][0]['star_id'];
            }
            if ($platform['jd_exist'] == 0) {
                $resp = Http::asJson()->post("https://api.jiandaoyun.com/api/v1/automation/tenant/69dc899f71c9656940c3db33/hooks/69e07cb9d9016a50bb60ae230bb32ba47135e7e946bedb7a",[
                    "uid"       => $platform['unique_id'],
                    "platform"  => $task['category']
                ])->array();
            }
            $taskUser = (new BlueTaskUser)->where(['openid' => $request->user['openid'],'job_id' => $param['task_sn'],'task_id' => $param['task_id']])->findOrEmpty();
            if (!$taskUser->isEmpty()) return error("请勿重复报名");
            $state = $taskUser->insertGetId([
                "openid"    => $request->user['openid'],
                "task_id"   => $param['task_id'],
                "job_id"    => $param['task_sn'],
                "source"    => $task['category'],
                "start_id"  => $starId, // 星图ID
                "status"    => 0 // 0待提交 1审核中 2审核通过 3已拒绝
            ]);
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data",['qrcode' => "https://work.weixin.qq.com/ca/cawcde3784d6329ab7"],5);
//            return successTrans("success.data",['task_user_id' => $state]);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 绑定星图ID
     * @param Request $request
     * @return Response
     */
    #[Route(path: "star",methods: "post")]
    public function bindStarId(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "star.require"      => trans("empty.require"),
                "source.require"    => trans("empty.require")
            ],$request->method());
            if (!is_array($param)) return error($param);
            $platform = (new BlueExpertPlatform)->where(["openid" => $request->user['openid'],'source' => $param['source']])->findOrEmpty();
            if ($platform->isEmpty()) return error("未绑定该平台账号");
            $platform->star_id = $param['star'];
            $state = $platform->save();
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}