<?php

namespace app\controller\admin;

use app\extra\basic\Base;
use app\extra\service\blue\TaskService;
use app\extra\tools\CodeExtend;
use app\extra\tools\XcJob;
use app\middleware\AuthMiddleware;
use app\model\blue\BlueCategory;
use app\model\blue\BlueExpertLevel;
use app\model\blue\BlueTask;
use app\model\system\SystemData;
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: "/api/task"),Middleware(AuthMiddleware::class)]
class Task extends Base
{

    #[Inject]
    protected TaskService $service;

    #[Inject]
    protected BlueTask $model;

    #[Route(path: "list",methods: "get")]
    public function getCategoryData(Request $request): Response
    {
        try {
            $param = $request->all();
            $list = $this->service->getList($param);
            return successTrans("success.data",pageFormat($list),200);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }
    /**
     * 编辑信息
     * @param Request $request
     * @return Response
     */
    #[Route(path: "save",methods: "post")]
    public function setListData(Request $request): Response
    {
        try {
            $param = $request->post();
            if (!isset($param['id'])) {
                $param['task_sn'] = CodeExtend::random(16);
                $job = $this->model->where("job_id",$param['job_id'])->findOrEmpty();
                if (!$job->isEmpty()) return error("该任务已添加");
            }
            $param['total_budget'] = !empty($param['total_budget']) ? $param['total_budget']*100 : 0;
            $state = $this->model->setAutoData($param);
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 批量操作
     * @param Request $request
     * @return Response
     */
    #[Route(path: "batch",methods: "post")]
    public function setGoodsBatch(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => "参数错误",
                "value.require"     => "参数错误",
                "field.require"     => "参数错误",
                "type.require"      => "参数错误"
            ],"post");
            if (!is_array($param)) return error($param);
            if ($param['type'] == "batch") {
                $state = $this->model->where("id","in",$param['id'])->save([$param['field'] => $param['value']]);
            } else {
                $state = $this->model->where("id",$param['id'])->save([$param['field'] => $param['value']]);
            }
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 删除
     * @param Request $request
     * @return Response
     */
    #[Route(path: "del",methods: "post")]
    public function delData(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "id.require"        => "参数错误",
            ],"post");
            if (!is_array($param)) return error($param);
            $data = $this->model->where("id",$param['id'])->findOrEmpty();
            if ($data->isEmpty()) return errorTrans("empty.data");
            $state = $data->delete();
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    /**
     * 获取星川任务详情
     * @param Request $request
     * @return Response
     */
    #[Route(path: "job",methods: "get")]
    public function getJobDetail(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "job_id.require"    => trans("empty.require")
            ]);
            if (!is_array($param)) return error($param);
            $data = (new XcJob)->token()->getJobDetail($param['job_id']);
            if ($data['base_resp']['status_code'] <> 0) return error("获取任务失败");
            $task  = [
                "expiration_time_end"   => date("Y-m-d H:i:s",$data['object_field_info']['object_basic_info']['expiration_time_end']),
                "title"                 => $data['object_field_info']['object_basic_info']['object_name']??'',
                "product_cover_url"     => $data['object_field_info']['object_product_info']['product_cover_url']??'',
                "product_name"          => $data['object_field_info']['object_product_info']['product_name']??'',
                "product_id"            => $data['object_field_info']['object_product_info']['external_product_id']??'',
                "auto"                  => 2,
                "job_id"                => $param['job_id'],
                "category"              => "douyin",
                "category_detail"       => $data['object_field_info']['object_product_info']['category_detail']['second_cname']??'',
                "product_selling_point" => $data['object_field_info']['object_product_info']['product_selling_point_detail']??'',
                "target_audience"       => $data['object_field_info']['object_product_info']['target_audience_desc']??'',
                "content"               => $data['object_field_info']['object_requirement_info']['author_preference']?nl2br($data['object_field_info']['object_requirement_info']['author_preference']):'',
                "total_budget"          => $data['object_field_info']['object_project_info']['total_budget_fen']?format_money($data['object_field_info']['object_project_info']['total_budget_fen']/100):'',
            ];
            return success("ok",$task);
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    #[Route(path: "param",methods: "get")]
    public function getTaskParam(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "type.default"  => "douyin"
            ],$request->all());
            if (!is_array($param)) return error($param);
            $category = (new BlueCategory)->where("type",1)->select()->toArray();
            $level = (new BlueExpertLevel)->where("status",1)->append(['start_format','end_format'])->withAttr(['start_format' => function ($data,$resp) {
                return formatMoneyKw($resp['gmv_start']);
            },'end_format' => function ($data,$resp) {
                return formatMoneyKw($resp['gmv_end']);
            }])->select()->toArray();
            $dicData = (new SystemData)->where("code",$param['type'])->value("content");
            $dic = empty($dicData)?[]:json_decode($dicData,true);
            return success("ok",compact("category","level","dic"));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}