package com.malk.laidi.service.impl;

import com.alibaba.fastjson.JSON;
import com.malk.laidi.service.LDClient;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.dingtalk.*;
import com.malk.service.h3yun.CYClient;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LDImplClient implements LDClient {

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @Autowired
    private CYClient cyClient;

    /**
     * 同步OA出差单到氚云
     */
    @Override
    public void syncCC(String processInstanceId) {

        Map processData = ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(), processInstanceId);
        List<Map> formComponentValues = (List<Map>) processData.get("formComponentValues");

        // OA组件name, 匹配氚云组件ID
        String schemaCode = "D148911abbb84666b4b481783235d0fcfc39d8d";
        Map<String, String> compsId_main = UtilMap.map("出差事由, 出差天数, 出差备注, 同行人", "F0000002, F0000010, F0000011, F0000015");
        Map<String, String> compsId_itinerary = UtilMap.map("交通工具, 单程往返, 出发城市, 目的城市, 开始时间, 结束时间, 时长", "F0000003, F0000004, F0000005, F0000006, F0000007, F0000008, F0000009");
        compsId_main.put("行程明细", "D148911F875802263af84ddaa01b9e6bd679eb74"); // 子表组件

        String dUserId = String.valueOf(processData.get("originatorUserId"));
        String cUserId = _getCYUserIdByDingTalkUserId(dUserId);
        Map formData = UtilMap.map("F0000013", cUserId);

        for (String name : compsId_main.keySet()) {
            String compId = compsId_main.get(name);
            // 判定是否子表 [氚云]
            if (compId.startsWith("D")) {
                List<Map> details = new ArrayList<>();
                // ppExt: 出差申请单为明细组件, 存在多条情况
                String schedule = (String) formComponentValues.stream().filter(item -> "itinerary".equals(item.get("bizAlias"))).findAny().get().get("value");
                List<Map> itineraryList = ((List<Map>) JSON.parse(schedule));
                // 循环明细数据
                for (Map itinerary : itineraryList) {
                    List<Map> rowValue = (List<Map>) itinerary.get("rowValue");
                    Map rowData = new HashedMap();
                    // 循环子表组件
                    for (String subName : compsId_itinerary.keySet()) {
                        rowData.put(compsId_itinerary.get(subName), rowValue.stream().filter(item -> subName.equals(item.get("label"))).findAny().get().get("value"));
                    }
                    details.add(rowData);
                }
                formData.put(compId, details);
                continue;
            }
            Map formComp = formComponentValues.stream().filter(item -> name.equals(item.get("name"))).findAny().get();
            Object value = formComp.get("value");
            // 同行人, 数据处理
            if ("InnerContactField".equals(formComp.get("componentType")) && formComp.containsKey("value")) {
                List<Map> empInfos = (List<Map>) JSON.parse(String.valueOf(formComp.get("extValue")));
                List<String> emplsId = new ArrayList<>();
                for (Map empInfo : empInfos) {
                    emplsId.add(_getCYUserIdByDingTalkUserId(String.valueOf(empInfo.get("emplId"))));
                }
                value = emplsId; // 成员多选
            }
            formData.put(compId, value);
        }

        Map extInfo = UtilMap.map("opUserId, bizObjectJson, isDraft", cUserId, JSON.toJSONString(formData), true);
        Map rsp = cyClient.operateData(ddClient.getAccessToken(), schemaCode, extInfo);
        cyClient.operateData(ddClient.getAccessToken(), schemaCode, UtilMap.map("bizObjectId, opUserId", rsp.get("bizObjectId"), cUserId));
    }

    /// 匹配氚云用户ID [ ppExt 临时方案为, H_User系统表, 字段DingTalkAccount「返回格式为 userId.corpId」, 通过氚云定时任务储存与钉钉对照关系 ]
    String _getCYUserIdByDingTalkUserId(String dUserId) {
        Map extInfo = UtilMap.map("matcherJson", JSON.toJSONString(UtilMap.map("Type, Name, Operator, Value", "Item", "F0000003", 2, dUserId)));
        List<Map> userList = cyClient.queryData(ddClient.getAccessToken(), "D1489118960387db0274aa18b9168cde213c3d3", extInfo);
        return String.valueOf(userList.get(0).get("F0000002"));
    }


    @Autowired
    private DDClient_Storage ddClient_storage;

    @Autowired
    private DDConf ddConf;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDService ddService;

    /**
     * 同步氚云附件到钉盘 [异步]
     */
    @Async
    @Override
    public void syncDP(String sAttachments, String sProjectName, String typeName) {

        if (UtilString.isBlankCompatNull(sAttachments) || StringUtils.isBlank(sProjectName) || StringUtils.isBlank(typeName)) {
            return;
        }
        // prd: 文件目录：钉盘空间 / 氚云项目附件 + 项目名称/ 日期（年月日）/ 附件名称
        String spaceId = "2034568562"; // 钉盘空间
        String parentId = "120089274640"; // 氚云项目附件

        // 获取用户unionId
        String unionId = String.valueOf(ddClient_contacts.getUserInfoById(ddClient.getAccessToken(), ddConf.getOperator()).get("unionid"));
        // 获取项目文件夹 [RETURN_DENTRY_IF_EXISTS: 文件夹名称冲突策略, 返回已存在文件夹, 避免查询文件夹列表]UtilMap.map("conflictStrategy", "RETURN_DENTRY_IF_EXISTS")
        Map dentry = ddClient_storage.addFolders(ddClient.getAccessToken(), unionId, spaceId, parentId, sProjectName, UtilMap.map("conflictStrategy", "RETURN_DENTRY_IF_EXISTS"));
        dentry = ddClient_storage.addFolders(ddClient.getAccessToken(), unionId, spaceId, String.valueOf(dentry.get("id")), typeName, UtilMap.map("conflictStrategy", "RETURN_DENTRY_IF_EXISTS"));

        // 获取氚云附件ID, 项目名称
        List<Map> attachments = (List<Map>) JSON.parse(sAttachments);
        for (Map attachment : attachments) {
            String urlFile = cyClient.getTemporaryUrls(ddClient.getAccessToken(), String.valueOf(attachment.get("ObjectId")));
            // 上传文件
            ddService.uploadFileFormUrlForDingDrive(ddClient.getAccessToken(), unionId, spaceId, String.valueOf(dentry.get("id")), urlFile, String.valueOf(attachment.get("FileName")));
        }

    }

    /**
     * 获取钉盘&文件夹信息, spaceId, parentId [可手动创建]
     */
    @Override
    public void test() {
        String unionId = String.valueOf(ddClient_contacts.getUserInfoById(ddClient.getAccessToken(), ddConf.getOperator()).get("unionid"));

//        ddClient_storage.getSpaces(ddClient.getAccessToken(), unionId);
//        ddClient_storage.getDentries(ddClient.getAccessToken(), unionId, "2034568562", "0", UtilMap.map("conflictStrategy", "RETURN_DENTRY_IF_EXISTS"));

//        Map dentry = ddClient_storage.addFolders(ddClient.getAccessToken(), unionId, "2034568562", "0", "\\\\xxt|///est.", UtilMap.map("conflictStrategy", "RETURN_DENTRY_IF_EXISTS"));

    }
}
