package com.malk.aosk.event;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.delegate.DDEvent;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Primary
@Service
public class DDaskEventImpl implements DDEvent {

    @Autowired
    private DDClient_Workflow ddClientWorkflow;
    @Autowired
    private DDClient ddClient;
    @Value("${aosk.oa.path}")
    private String PATH;
    
    @Override
    public void executeEvent_Task_Finish(String processInstanceId, String processCode, boolean isAgree, String remark) {

    }

    @Override
    public void executeEvent_Task_Start(String processInstanceId, String processCode) {

    }

    @Override
    public void executeEvent_Task_Comment(String processInstanceId, String processCode) {
        if(isNotSync(processCode)){
            log.info("不需要同步：{}/{}",processCode,processInstanceId);
            return;
        }
        log.info("评论附件同步：{}/{}",processCode,processInstanceId);
        // 评论回调 1.查询审批实例 2.获取评论附件 3.保存附件
        Map form = ddClientWorkflow.getForms(ddClient.getAccessToken(),processCode);
        Map map = ddClientWorkflow.getProcessInstanceId(ddClient.getAccessToken(), processInstanceId);
        String createTime=UtilMap.getString(map,"createTime");
        String yearMonth = createTime.substring(0,7).replace("-","");
        String filePath = PATH+"/"+yearMonth+"/"+UtilMap.getString(form,"name")+"/"+UtilMap.getString(map,"businessId")+"/";
        List<Map> list = UtilMap.getList(map, "operationRecords");
        for (Map record : list) {
            if("ADD_REMARK".equals(UtilMap.getString(record,"type"))){
                if((record.containsKey("attachments")&& UtilMap.getList(record,"attachments").size()>0)){
                    saveFile(filePath, JSONArray.parseArray(UtilMap.getString(record,"attachments")),processInstanceId);
                }
                if((record.containsKey("images")&& UtilMap.getList(record,"images").size()>0)){
                    saveImg(filePath, UtilMap.getList(record,"images"));
                }
            }
        }
    }

    private void saveImg(String filePath, List<String> attachments){
        for(String attachment : attachments){
            // 1. 获取URL的路径部分（自动解码%20等字符）
            String path = URLUtil.getPath(attachment);
            // 2. 从路径中提取文件名
            String fileName = FileUtil.getName(path);
            HttpUtil.downloadFile(attachment,filePath+fileName);
        }
    }

    private void saveFile(String filePath,JSONArray fileIds,String pid){
        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,true);
            HttpUtil.downloadFile(url,filePath+fileName);
        }
    }



    @Override
    public void executeEvent_Task_Redirect(String processInstanceId, String processCode) {

    }

    @Override
    public void executeEvent_Instance_Finish(String processInstanceId, String processCode, boolean isAgree, boolean isTerminate, String staffId) {

    }

    @Override
    public void executeEvent_Instance_Start(String processInstanceId, String processCode) {
        if(isNotSync(processCode)){
            log.info("不需要同步：{}/{}",processCode,processInstanceId);
            return;
        }
        log.info("附件同步：{}/{}",processCode,processInstanceId);
        // 发起审批回调 1.查询审批实例 2.获取评论附件 3.保存附件
        Map form = ddClientWorkflow.getForms(ddClient.getAccessToken(),processCode);
        Map map = ddClientWorkflow.getProcessInstanceId(ddClient.getAccessToken(), processInstanceId);
        String createTime=UtilMap.getString(map,"createTime");
        String yearMonth = createTime.substring(0,7).replace("-","");
        String filePath = PATH+"/"+yearMonth+"/"+UtilMap.getString(form,"name")+"/"+UtilMap.getString(map,"businessId")+"/";
        List<Map> list = UtilMap.getList(map, "formComponentValues");
        for (Map formComponent : list) {
            if("DDAttachment".equals(UtilMap.getString(formComponent,"componentType"))){
                JSONArray files = JSONObject.parseArray(UtilMap.getString(formComponent,"value"));
                if(files==null||files.size()<1){
                    continue;
                }
                for(int i=0;i<files.size();i++){
                    JSONObject fileInfo=files.getJSONObject(i);
                    String fileId=fileInfo.getString("fileId");
                    String fileName=fileInfo.getString("fileName");
                    System.out.println(fileId);
                    String url=ddClientWorkflow.getFileUrl(ddClient.getAccessToken(),processInstanceId,fileId);
                    HttpUtil.downloadFile(url,filePath+fileName);
                }
            }
        }
    }
    private static String CODE_STRING="PROC-7176DBF8-30BE-406E-9ED0-CACC76A1604E," +
            "PROC-0497FB30-EC43-4B5F-8125-A5FF90C87892," +
            "PROC-8D860D88-F227-4227-9964-EA9427E62F05," +
            "PROC-6B345937-965F-4F8C-BF60-5519EA79B089," +
            "PROC-C8C908FF-3086-49F9-9D73-C0179896C829," +
            "PROC-F5220478-0F57-4BFB-B3FF-19DF1BAE8D38," +
            "PROC-6322A3F5-0B57-42FF-9D9E-2F49E7C9B008," +
            "PROC-CCE9F92B-315A-4684-AC9F-3A86D5937FAA," +
            "PROC-BD364031-F093-4C94-BA26-A7C602037160," +
            "PROC-77B1B01C-4EAD-4E39-B8DB-A99659E3852B," +
            "PROC-55B1A05D-49B4-4F98-A250-5E42B80BD21F," +
            "PROC-A513DC9A-1F1F-48ED-A08B-8C5873C612C0," +
            "PROC-ED3EE25D-136C-49EB-8A91-20010910DF7A," +
            "PROC-2AFFB3AE-E5F3-44D8-9E41-214E22D76157," +
            "PROC-C5D68072-937E-4D77-A513-82770BE405CD," +
            "PROC-C8B88B78-8919-4453-A9A7-B8038D0758AF," +
            "PROC-759DB187-0BC8-43CD-943E-F1162AF4F605," +
            "PROC-06BFB267-A685-489E-8F0B-FF540917336C," +
            "PROC-96B0A29A-E363-46E7-A6C2-02EF09D3B07D," +
            "PROC-6D74669A-2298-439A-B40A-AA31BE318A81," +
            "PROC-18590605-AF82-415B-8100-7801F11B59C0," +
            "PROC-2FD8F066-F070-4965-A3D7-7ED7F2DAD190," +
            "PROC-FB5B7A66-D870-4261-8B70-FA4CCF4A2AC7," +
            "PROC-1071CE60-6C5E-4E3C-8AC4-C656C8DB7D71," +
            "PROC-6923C3CE-C86A-4ACD-98C5-5866313BCE45," +
            "PROC-F8FBA1CE-6F1D-4BB3-86FC-532164D69572," +
            "PROC-A330F4D5-9847-4819-8387-6202918596F0";

    private static boolean isNotSync(String code){
        List<String> codeList= Arrays.asList(CODE_STRING.split(","));
        return codeList.contains(code);
    }

    public static void main(String[] args) {
        System.out.println(isNotSync("PROC-A330F4D5-9847-4819-8387-6202918596F02"));
    }
}
