package com.malk.siku.controller;

import com.alibaba.fastjson.JSONObject;
import com.malk.server.common.McR;
import com.malk.siku.service.SikuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping()
public class SikuController {
    @Autowired
    private SikuService sikuService;

    @Value(value = "${mk.downloadFilePath}")
    private String fileStoragePath;

    //保存每刻往来单位
    @PostMapping("/saveTradingPartner")
    public McR saveTradingPartner(@RequestBody Map map) {
        return sikuService.saveTradingPartner(map);
    }

    /**
     * 保存云票客户
     * @param map
     * @return
     */
    @PostMapping("/saveYpClient")
    public McR saveYpClient(@RequestBody Map map){
        return sikuService.saveYpClient(map);
    }

    /**
     * 开票申请单导入和更新
     * @param map
     * @return
     */
    @PostMapping("/saveYpApplication")
    public McR saveYpApplication(@RequestBody Map map){
        return sikuService.saveYpApplication(map);
    }

    /**
     * 报销单导入（采购需求&结算）
     * @param map
     * @return
     */
    @PostMapping("/saveBxReimbursement")
    public McR saveBxReimbursement(@RequestBody Map map){
        return sikuService.saveBxReimbursement(map);
    }

    /**
     * 报销单导入2（直接采购结算单）
     * @param map
     * @return
     */
    @PostMapping("/saveBxReimbursement2")
    public McR saveBxReimbursement2(@RequestBody Map map){
        return sikuService.saveBxReimbursement2(map);
    }

    /**
     * 预付退回导入
     * @param map
     * @return
     */
    @PostMapping("/saveRepayment")
    public McR saveRepayment(@RequestBody Map map){
        return sikuService.saveRepayment(map);
    }

    /**
     * 采购单可用预算校验-停用
     * @param map
     * @return
     */
    /*@PostMapping("/checkBudgetAmt")
    public McR checkBudgetAmt(@RequestBody Map map){
        return sikuService.checkBudgetAmt(map);
    }*/

    //每刻云票收款核销回调
    @PostMapping("/VERIFICATION_AR/callback")
    public McR callback(@RequestBody Map map){
        log.info("每刻云票收款核销回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack(map);

        return McR.success();
    }

    //每刻云票应收单回调（开票成功）
    @PostMapping("/RECEIVABLE_AR/callback")
    public McR callback9(@RequestBody Map map){
        log.info("每刻云票应收单完成回调：{}",JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack9(map);

        return McR.success();
    }

    //每刻云票开票申请单回调（开票失败）
    @PostMapping("/INVOICE_APPLICATION_AR/callback")
    public McR callback2(@RequestBody Map map){
        log.info("每刻云票开票申请单回调：{}",JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack2(map);

        return McR.success();
    }

    //每刻报销报销单完成回调
    @PostMapping("/reimbursement/callback")
    public McR callback3(@RequestBody Map map){
        log.info("每刻报销报销单完成回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack3(map);

        return McR.success();
    }

    //每刻报销付款单完成回调
    @PostMapping("/pay/callback")
    public McR callback4(@RequestBody Map map){
        log.info("每刻报销付款单完成回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack4(map);

        return McR.success();
    }

    //每刻报销预付退回完成回调
    @PostMapping("/repay/callback")
    public McR callback5(@RequestBody Map map){
        log.info("每刻报销预付退回完成回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack5(map);

        return McR.success();
    }

    //每刻报销借款单完成回调（押金（"是否项目相关"为【是】） 、借款单（项目））
    @PostMapping("/loan/callback")
    public McR callback6(@RequestBody Map map){
        log.info("每刻报销借款单完成回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack6(map);

        return McR.success();
    }

    //每刻报销还款单完成回调
    @PostMapping("/repayment/callback")
    public McR callback7(@RequestBody Map map){
        log.info("每刻报销还款单完成回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack7(map);

        return McR.success();
    }

    //每刻报销费用报销单完成回调（项目报销单（个人）、项目差旅报销单、打车（企业支付）（"是否有项目"为【是】））
    @PostMapping("/reimbursement2/callback")
        public McR callback8(@RequestBody Map map){
        log.info("每刻报销费用报销单完成回调：{}", JSONObject.toJSONString(map));

        sikuService.invoiceWriteBack8(map);

        return McR.success();
    }

    //每刻预算冻结/释放
    @PostMapping("/updateBudget")
    public McR updateBudget(@RequestBody Map map){
        sikuService.updateBudget(map);

        return McR.success();
    }

    //创建/更新企业滴滴项目
    @PostMapping("/ddProject")
    public McR ddProject(@RequestBody Map map){
        return sikuService.ddProject(map);
    }

    @GetMapping("/files/{fileId}")
    public ResponseEntity<Resource> getFileResource(
            @PathVariable String fileId,
            @RequestParam(defaultValue = "download") String option) throws IOException {

        // 根据fileId获取实际文件路径，这里简化处理，实际可能需要从数据库查询
        Path filePath = Paths.get(fileStoragePath).resolve(fileId).normalize();

        // 检查文件是否存在
        if (!Files.exists(filePath)) {
            return ResponseEntity.notFound().build();
        }

        // 创建Resource对象
        Resource resource =  new UrlResource(filePath.toUri());

        // 根据选项设置响应头
        HttpHeaders headers = new HttpHeaders();
        if ("preview".equalsIgnoreCase(option)) {
            // 预览模式 - 尝试确定内容类型
            String contentType = Files.probeContentType(filePath);
            // 强制修正 PDF 的 Content-Type
            if (filePath.toString().toLowerCase().endsWith(".pdf")) {
                contentType = "application/pdf";
            } else if (contentType == null) {
                contentType = "application/octet-stream";
            }
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.add("Content-Disposition", "inline; filename=\"" + resource.getFilename() + "\"");
            headers.add("X-Content-Type-Options", "nosniff"); // 防止浏览器忽略 Content-Type
        } else {
            // 下载模式 - 默认处理
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.add("Content-Disposition", "attachment; filename=\"" + resource.getFilename() + "\"");
        }

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);
    }
}
