package com.fs.xiaoshouyi.controller;

import com.fs.common.core.domain.AjaxResult;
import com.fs.xiaoshouyi.dto.*;
import com.fs.xiaoshouyi.service.XiaoShouYiMaterialService;
import com.fs.xiaoshouyi.service.XiaoShouYiOAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.RedirectView;

import java.io.File;

@Slf4j
@RestController
@RequestMapping("/xiaoShouYi")
@RequiredArgsConstructor
public class XiaoShouYiController {

    private final XiaoShouYiOAuthService oAuthService;
    private final XiaoShouYiMaterialService materialService;


    /**
     * 获取授权URL
     */
    @PreAuthorize("@ss.hasPermi('xsy:auth:url')")
    @GetMapping("/auth/url/{accountId}")
    public AjaxResult getAuthUrl(@PathVariable Long accountId) {
        return AjaxResult.success(oAuthService.buildAuthUrl(accountId));
    }

    /**
     * 授权回调
     */
    @GetMapping("/auth/callback/{accountId}")
    public RedirectView authCallback(@PathVariable Long accountId,
                                     @RequestParam("code") String code) {

        try {
            TokenResponse tokenResp = oAuthService.exchangeCodeForToken(accountId, code);

            if (tokenResp.isSuccess()) {
                return new RedirectView("/xiaoShouYi/success");
            }

            return new RedirectView("/xiaoShouYi/error?msg=" + tokenResp.getError());

        } catch (Exception e) {
            log.error("授权回调异常 accountId={}", accountId, e);
            return new RedirectView("/xiaoShouYi/error?msg=" + e.getMessage());
        }
    }



    /**
     * 生成追踪链接
     */
    @PostMapping("/generateLink")
    public AjaxResult generateLink(@RequestParam Long companyUserId,
                                   @Validated @RequestBody GenerateLinkRequest request) {

        try {
            if (request.getMaterialIds() == null || request.getMaterialIds().isEmpty()) {
                return AjaxResult.error("materialIds不能为空");
            }

            GenerateLinkResponse response = materialService.generateMaterialTrackLink(
                                                                    companyUserId,
                                                                    request.getMaterialIds());

            return response.isSuccess()
                    ? AjaxResult.success(response)
                    : AjaxResult.error(response.getMsg());

        } catch (Exception e) {
            log.error("生成追踪链接异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 发送确认
     */
    @PostMapping("/sendConfirm")
    public AjaxResult sendConfirm(@RequestParam Long companyUserId,
                                  @RequestParam Long forwardId,
                                  @RequestParam Integer forwardType) {

        try {
            SendConfirmResponse response =
                    materialService.sendConfirmAuto(companyUserId, forwardId, forwardType);

            return response.isSuccess()
                    ? AjaxResult.success(response)
                    : AjaxResult.error(response.getMsg());

        } catch (Exception e) {
            log.error("发送确认异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询素材
     */
    @PostMapping("/materials/query")
    public AjaxResult queryMaterials(@RequestParam Long companyUserId,
                                     @RequestBody QueryMaterialRequest request) {

        try {
            QueryMaterialResponse response =
                    materialService.queryMaterialsAuto(companyUserId, request);

            if (!Boolean.TRUE.equals(response.getSuccess())) {
                return AjaxResult.error(response.getMsg());
            }

            return AjaxResult.success(response.getData());

        } catch (Exception e) {
            log.error("查询素材异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传素材文件
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam Long companyUserId,
                                 @RequestParam("file") MultipartFile multipartFile,
                                 @RequestParam(defaultValue = "false") Boolean isVideo) {

        if (multipartFile == null || multipartFile.isEmpty()) {
            return AjaxResult.error("文件不能为空");
        }

        File tempFile = null;
        try {
            // 保留文件后缀
            String suffix = getSuffix(multipartFile.getOriginalFilename());
            tempFile = File.createTempFile("xsy_", suffix);

            multipartFile.transferTo(tempFile);

            UploadMaterialFileResponse response =
                    materialService.uploadMaterialFileAuto(companyUserId, tempFile, isVideo);

            if (!Boolean.TRUE.equals(response.getSuccess())) {
                return AjaxResult.error(response.getMsg());
            }

            return AjaxResult.success(response.getData());

        } catch (Exception e) {
            log.error("上传素材异常", e);
            return AjaxResult.error(e.getMessage());
        } finally {
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    /**
     * 创建素材
     */
    @PostMapping("/createMaterial")
    public AjaxResult createMaterial(@RequestParam Long companyUserId,
                                     @RequestBody CreateMaterialRequest request) {

        try {
            CreateMaterialResponse response =
                    materialService.createMaterialAuto(companyUserId, request);

            return response.getSuccess()
                    ? AjaxResult.success(response)
                    : AjaxResult.error(response.getMsg());

        } catch (Exception e) {
            log.error("创建素材异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传 + 创建素材
     */
    @PostMapping("/createMaterialWithUpload")
    public AjaxResult createMaterialWithUpload(@RequestParam Long companyUserId,
                                               @RequestParam("file") MultipartFile file,
                                               @RequestParam(defaultValue = "false") Boolean isVideo,
                                               @RequestParam String corpName,
                                               @RequestParam Integer materialType,
                                               @RequestParam String categoryName,
                                               @RequestParam String title) {

        File tempFile = null;

        try {
            if (!StringUtils.hasText(corpName) || !StringUtils.hasText(categoryName) || !StringUtils.hasText(title)) {
                return AjaxResult.error("必填参数不能为空");
            }

            String suffix = getSuffix(file.getOriginalFilename());
            tempFile = File.createTempFile("xsy_", suffix);
            file.transferTo(tempFile);

            CreateMaterialRequest req = new CreateMaterialRequest();
            req.setCorpName(corpName);
            req.setMaterialType(materialType);
            req.setCategoryName(categoryName);
            req.setTitle(title);

            CreateMaterialWithUploadResponse response =
                    materialService.createMaterialWithUploadAuto(
                            companyUserId, tempFile, isVideo, req);

            return AjaxResult.success(response);

        } catch (Exception e) {
            log.error("上传+创建素材异常", e);
            return AjaxResult.error(e.getMessage());
        } finally {
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }



    @GetMapping("/success")
    public String success() {
        return "授权成功";
    }

    @GetMapping("/error")
    public String error(String msg) {
        return "授权失败: " + msg;
    }



    private String getSuffix(String fileName) {
        if (!StringUtils.hasText(fileName)) {
            return ".tmp";
        }
        int index = fileName.lastIndexOf(".");
        return index > 0 ? fileName.substring(index) : ".tmp";
    }
}