package com.malk.aosk.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.common.McR;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.PublicUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@RestController
@RequestMapping("/oa/file/")
public class AoskDingController {

    @Autowired
    private DDClient ddClient;
    @Autowired
    private DDClient_Workflow ddClientWorkflow;

    @Value("${aosk.oa.path}")
    private String PATH;

    @PostMapping("save")
    public McR save(@RequestBody JSONObject param){
        log.info("param:{}",param);
        if(PublicUtil.isNull(param,"pid","form","oano","fileId")){
            return McR.errorNullPointer();
        }
        String pid = param.getString("pid");
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String filePath = PATH+"/"+yearMonth+"/"+param.getString("form")+"/"+param.getString("oano")+"/";
        JSONArray fileIds = JSONObject.parseArray(param.getString("fileId"));
        for(int i=0;i<fileIds.size();i++){
            JSONObject fileInfo=fileIds.getJSONObject(i);
            String fileId=fileInfo.getString("fileId");
            String fileName=fileInfo.getString("fileName");
            String url=ddClientWorkflow.getFileUrl(ddClient.getAccessToken(),pid,fileId);
            HttpUtil.downloadFile(url,filePath+fileName);
        }
        return McR.success();
    }

}
