package com.backendsys.controller.Ai;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.aspect.HttpRequestAspect;
import com.backendsys.entity.Ai.Aiivh.AiPersonDTO;
import com.backendsys.entity.Ai.Aiivh.AiPersonTimbreCustomDTO;
import com.backendsys.entity.Ai.Aiivh.AiivhAnchorDTO;
import com.backendsys.entity.PageDTO;
import com.backendsys.entity.Tencent.TencentCustomserviceConfirmDTO;
import com.backendsys.entity.Tencent.TencentCustomserviceConfirmPlayloadDTO;
import com.backendsys.entity.Tencent.TencentCustomserviceDTO;
import com.backendsys.entity.Tencent.VirtualmanLaunchDTO;
import com.backendsys.service.Ai.Aiivh.AiivhMakeVirtualmanTaskService;

import com.backendsys.service.SDKService.SDKTencent.SDKTencentAiService;
import com.backendsys.service.SDKService.SDKTencent.SDKTencentAiTimbreService;
import com.backendsys.service.SDKService.SDKTencent.SDKTencentAiVirtualmanService;
import com.backendsys.utils.response.Result;
import com.backendsys.utils.response.ResultEnum;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;

/**
 * [创建形象] 和 [创建音色] 是同个接口
 * [创建视频] 和 [创建音频] 是不同的接口
 */
@Validated
@RestController
public class AiivhMakeVirtualmanTaskController {

    @Autowired
    private HttpRequestAspect httpRequestAspect;

    @Autowired
    private AiivhMakeVirtualmanTaskService aiivhMakeVirtualmanTaskService;

    @Autowired
    private SDKTencentAiService sdkTencentAiService;
    @Autowired
    private SDKTencentAiVirtualmanService sdkTencentAiVirtualmanService;
    @Autowired
    private SDKTencentAiTimbreService sdkTencentAiTimbreService;

    /**
     * 我的定制形象(主播/音色)任务列表
     */
    @PreAuthorize("@sr.hasPermission('33')")
    @GetMapping("/api/ai/ivh/getMyAiivhMakeVirtualmanTask")
    public Result getMyAiivhMakeVirtualmanTask(@Validated PageDTO pageDTO, @Validated AiPersonDTO aiPersonDTO) {
        // [查询] 自身 UserId
        Long user_id = httpRequestAspect.getUserId();
        aiPersonDTO.setUser_id(user_id);
        //
        return Result.success(aiivhMakeVirtualmanTaskService.queryAiivhMakeVirtualmanTaskList(pageDTO.getPage_num(), pageDTO.getPage_size(), aiPersonDTO));
    }

    /**
     * 获得全部定制形象任务列表
     */
    @PreAuthorize("@sr.hasPermission('33.1')")
    @GetMapping("/api/ai/ivh/getAiivhMakeVirtualmanTask")
    public Result getAiivhMakeVirtualmanTask(@Validated PageDTO pageDTO, @Validated AiPersonDTO aiPersonDTO) {
        return Result.success(aiivhMakeVirtualmanTaskService.queryAiivhMakeVirtualmanTaskList(pageDTO.getPage_num(), pageDTO.getPage_size(), aiPersonDTO));
    }


    /**
     * [方法] 查询任务并更新进度
     */
    private Map<String, Object> checkAndUpdateProgress(AiPersonDTO aiPersonDTO) {

        // -- 查询定制任务详情 ------------------------------------------
        Map<String, Object> response = aiivhMakeVirtualmanTaskService.queryAiivhMakeVirtualmanTaskDetail(aiPersonDTO);
        if (response == null) { return null; }

        // -- 查询并更新进度 (进度状态 的字段) -------------------------
        sdkTencentAiVirtualmanService.getProgressOfVirtualmanTask(aiPersonDTO.getTask_id());

        // 格式化 result (JSON字符串 转为 JSON)
        String respResult = (String) response.get("result");
        if (!respResult.isEmpty()) {
            JSONObject result = JSONUtil.parseObj(respResult);
            response.put("result", result);
        } else {
            response.put("result", Collections.emptyMap());
        }

        // 判断定制任务是否完成
        String stage_status = (String) response.get("stage_status");
        if (stage_status.equals("CONFIRM")) {
            // -- 查询远程接口 ------------------------------------------

            String make_type = (String) response.get("make_type");
            if(make_type.equals("IMAGE_GENERAL")) {
                // [形象] 查询远程接口获得的列表，通过遍历列表获得详情 (virtualman_key)，并更新到表
                Map<String, Object> virtualmanObject = sdkTencentAiVirtualmanService.getVirtualmanObject((String) response.get("anchor_name"));
                //
                AiivhAnchorDTO aiivhAnchorDTO = new AiivhAnchorDTO();
                aiivhAnchorDTO.setAnchor_name((String) virtualmanObject.get("anchor_name"));
                aiivhAnchorDTO.setStage_status("CONFIRM");
                aiivhAnchorDTO.setVirtualman_key((String) virtualmanObject.get("virtualman_key"));
                aiivhAnchorDTO.setAnchor_code((String) virtualmanObject.get("anchor_code"));
                aiivhAnchorDTO.setHeader_image((String) virtualmanObject.get("header_image"));
                aiivhAnchorDTO.setResolution((String) virtualmanObject.get("resolution"));
                aiivhAnchorDTO.setPose_name((String) virtualmanObject.get("pose_name"));
                aiivhAnchorDTO.setPose_image((String) virtualmanObject.get("pose_image"));
                aiivhAnchorDTO.setClothes_name((String) virtualmanObject.get("clothes_name"));
                aiivhAnchorDTO.setClothes_image((String) virtualmanObject.get("clothes_image"));
                aiivhAnchorDTO.setExpire_date((String) virtualmanObject.get("expire_date"));
                //
                aiivhMakeVirtualmanTaskService.updateAiPersoneVirtualmanCustom(aiivhAnchorDTO);
            }
            if(make_type.equals("VOICE")) {
                // [音色] 查询远程接口获得的列表，通过遍历列表获得详情 (timbre_key)，并更新到表
                Map<String, Object> timbreObject = sdkTencentAiTimbreService.getTimbreObject((String) response.get("anchor_name"));
                //
                AiPersonTimbreCustomDTO aiPersonTimbreCustomDTO = new AiPersonTimbreCustomDTO();
                aiPersonTimbreCustomDTO.setTimbre_name((String) timbreObject.get("timbre_name"));
                aiPersonTimbreCustomDTO.setTimbre_name_view((String) timbreObject.get("timbre_name"));
                aiPersonTimbreCustomDTO.setStage_status("CONFIRM");
                aiPersonTimbreCustomDTO.setTimbre_key((String) timbreObject.get("timbre_key"));
                aiPersonTimbreCustomDTO.setTimbre_sample((String) timbreObject.get("timbre_sample"));
                aiPersonTimbreCustomDTO.setTimbre_desc((String) timbreObject.get("timbre_desc"));
                aiPersonTimbreCustomDTO.setTimbre_gender((Integer) timbreObject.get("timbre_gender"));
                aiPersonTimbreCustomDTO.setExpire_date((String) timbreObject.get("expire_date"));
                //
                aiivhMakeVirtualmanTaskService.updateAiPersoneTimbreCustom(aiPersonTimbreCustomDTO);
            }
        }
        return response;
    }

    /**
     * 我的定制形象(主播/音色)任务详情 (同时查询并更新任务进度)
     */
    @PreAuthorize("@sr.hasPermission('33')")
    @GetMapping("/api/ai/ivh/getMyAiivhMakeVirtualmanTaskDetail")
    public Result getMyAiivhMakeVirtualmanTaskDetail(@Validated AiPersonDTO aiPersonDTO) {
        // [查询] 自身 UserId
        Long user_id = httpRequestAspect.getUserId();
        aiPersonDTO.setUser_id(user_id);
        Map<String, Object> response = checkAndUpdateProgress(aiPersonDTO);
        return Result.success(response);
    }

    /**
     * 全部定制形象详情 (同时查询并更新任务进度)
     */
    @PreAuthorize("@sr.hasPermission('33.1')")
    @GetMapping("/api/ai/ivh/getAiivhMakeVirtualmanTaskDetail")
    public Result getAiivhMakeVirtualmanTaskDetail(@Validated AiPersonDTO aiPersonDTO) {
        Map<String, Object> response = checkAndUpdateProgress(aiPersonDTO);
        return Result.success(response);
    }


    /**
     * [腾讯-数智人] 效果确认接口
     * https://cloud.tencent.com/document/product/1240/102665
     */
    @PreAuthorize("@sr.hasPermission('33')")
    @PostMapping("/api/ai/ivh/confirmVirtualmanTask")
    public Result confirmVirtualmanTask(@Validated @RequestBody TencentCustomserviceConfirmDTO tencentCustomserviceConfirmDTO) throws IllegalAccessException, UnsupportedEncodingException {

        // 参数校验：
        // - 驳回原因，当 Operate:REJECT 时必填
        TencentCustomserviceConfirmPlayloadDTO payload = (TencentCustomserviceConfirmPlayloadDTO) tencentCustomserviceConfirmDTO.getPayload();
        String operate = payload.getOperate();
        String reason = payload.getReason();
        if (operate.equals("REJECT") && (reason == null || reason == "")) {
            return Result.error(ResultEnum.PARAMETER_EXCEPTION.getCode(), "驳回原因不能为空", "Field: reason");
        }

        Map<String, Object> resp = sdkTencentAiVirtualmanService.confirmVirtualmanTask(tencentCustomserviceConfirmDTO);
        return Result.success(sdkTencentAiService.checkResp(resp));
    }

    /**
     * [腾讯-数智人] 查询形象定制进度
     * https://cloud.tencent.com/document/product/1240/96070
     * @param task_id
     */
    @PreAuthorize("@sr.hasPermission('33')")
    @GetMapping("/api/ai/ivh/getProgressOfVirtualmanTask")
    public Result getProgressOfVirtualmanTask(@NotEmpty(message = "task_id 不能为空")  String task_id) throws UnsupportedEncodingException {
        Map<String, Object> resp = sdkTencentAiVirtualmanService.getProgressOfVirtualmanTask(task_id);
        return Result.success(sdkTencentAiService.checkResp(resp));
    }
    /**
     * [腾讯-数智人] 查询形象定制队列
     */
    @PreAuthorize("@sr.hasPermission('33')")
    @GetMapping("/api/ai/ivh/getQueueOfVirtualmanTask")
    public Result getQueueOfVirtualmanTask(@NotEmpty(message = "task_id 不能为空")  String task_id) throws UnsupportedEncodingException {
        return Result.success(sdkTencentAiVirtualmanService.getQueueOfVirtualmanTask(task_id));
    }


    /**
     * 腾讯-数智人-定制接口 (直接发起任务)
     * https://cloud.tencent.com/document/product/1240/96069
     * @param tencentCustomserviceDTO
     * @return
     */
    @PreAuthorize("@sr.hasPermission('33')")
    @PostMapping("/api/ai/ivh/makeVirtualman")
    public Result makeVirtualTask(@Validated @RequestBody TencentCustomserviceDTO tencentCustomserviceDTO) throws IllegalAccessException, UnsupportedEncodingException {
        Map<String, Object> resp = sdkTencentAiVirtualmanService.makeVirtualTask(tencentCustomserviceDTO);
        return Result.success(sdkTencentAiService.checkResp(resp));
    }

    /**
     * 腾讯-数智人-定制接口 (未发起任务)
     */
//    public Result makeVirtualTask(@Validated @RequestBody TencentCustomserviceDTO tencentCustomserviceDTO) throws IllegalAccessException, UnsupportedEncodingException {
//        return Result.success(sdkTencentAiVirtualmanService.makeVirtualTaskQueue(tencentCustomserviceDTO));
//    }

    /**
     * 发起任务 (填写 腾讯订单、备注，同时发起任务)
     */
    @PreAuthorize("@sr.hasPermission('33.1')")
    @PostMapping("/api/ai/ivh/launchVirtualmanTask")
    public Result launchVirtualmanTask(@Validated @RequestBody VirtualmanLaunchDTO virtualmanLaunchDTO) {
        return Result.success(sdkTencentAiVirtualmanService.launchVirtualTaskQueue(virtualmanLaunchDTO));
    }

}
