package org.jeecg.modules.okki.site.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lark.oapi.service.im.v1.model.CreateChatResp;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.okki.site.dto.FeiShuRecordSheetDto;
import org.jeecg.modules.okki.site.service.IFeiShuCommonService;
import org.jeecg.modules.okki.site.service.IFeiShuGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Chen
 */
@Slf4j
@Service
public class FeiShuGroupServiceImpl implements IFeiShuGroupService {

    @Autowired
    private IFeiShuCommonService feiShuCommonService;

    /**
     * 创建飞书群
     *
     * @param customerName
     * @param siteId
     * @param planName
     * @param groupName
     * @param recordId
     */
    @Override
    public void createFeiShuGroup(String customerName, String siteId, String planName, String groupName, String recordId) {
        List<String> targetGroups = new ArrayList<>();
        targetGroups.add(groupName);
        targetGroups.add("UI设计");
        targetGroups.add("质检组");
//        targetGroups.add("技术支持");
        targetGroups.add("项目管理");
        targetGroups.add("SNS组");
        targetGroups.add("SEM1组");
        Map<String, List<JSONObject>> teamSheetMap = feiShuCommonService.getFeiShuTeamSheet(targetGroups);
        log.info("******* createFeiShuGroup ******* 需要加入群聊的人员：teamSheetMap:{}", FastJsonUtil.toJSONString(teamSheetMap));
//
        List<String> needJoinFeiShuIds = new ArrayList<>();
        for (Map.Entry<String, List<JSONObject>> entry : teamSheetMap.entrySet()) {
            List<JSONObject> groupList = entry.getValue();
            for (JSONObject group : groupList) {
                JSONArray personnelArray = group.getJSONArray("人员");
                if (personnelArray != null) {
                    for (int i = 0; i < personnelArray.size(); i++) {
                        JSONObject person = personnelArray.getJSONObject(i);
                        String id = person.getString("id");
                        if (id != null && !id.isEmpty()) {
                            needJoinFeiShuIds.add(id);
                        }
                    }
                }
            }
        }
        log.info("needJoinFeiShuIds:{}", FastJsonUtil.toJSONString(needJoinFeiShuIds));

        // 群主
        String ownerId = "";
        for (Map.Entry<String, List<JSONObject>> entry : teamSheetMap.entrySet()) {
            if ("项目管理".equals(entry.getKey())) {
                List<JSONObject> groupList = entry.getValue();
                for (JSONObject group : groupList) {
                    JSONArray personnelArray = group.getJSONArray("人员");
                    if (personnelArray != null) {
                        for (int i = 0; i < personnelArray.size(); i++) {
                            JSONObject person = personnelArray.getJSONObject(i);
                            if ("孙跃".equals(person.getString("name"))) {
                                ownerId = person.getString("id");
                            }
                        }
                    }
                }
            }
        }
        log.info("ownerId:{}", ownerId);

        // 群名称
        String feiShuGroupName = customerName + " - " + planName + " - OK项目组";

        //群成员
        String[] needJoinFeiShuIdsArray = needJoinFeiShuIds.stream().toArray(String[]::new);

        //创建群聊
        CreateChatResp createChatResp = feiShuCommonService.sendCreateFeiShuGroupRequest(customerName, siteId, feiShuGroupName, ownerId, needJoinFeiShuIdsArray, recordId);
        if (createChatResp.success()) {
            String feiShuGroupId = createChatResp.getData().getChatId();

            // 更新表格-群组字段
            updateGroupField(feiShuGroupName, recordId, feiShuGroupId);
        }
    }

    /**
     * 更新表格-群组字段
     *
     * @param feiShuGroupName
     * @param recordId
     * @param feiShuGroupId
     */
    public void updateGroupField(String feiShuGroupName, String recordId, String feiShuGroupId) {
        FeiShuRecordSheetDto recordSheetDto = new FeiShuRecordSheetDto();
        recordSheetDto.setRecordId(recordId);
        recordSheetDto.setOkTablePage("Y");
        recordSheetDto.setOkTableName("客服团队");

        List<Map<String, Object>> groupIdList = new ArrayList<>();
        Map<String, Object> updateGroupFieldMap = new HashMap<>();
        Map<String, Object> groupIdMap = new HashMap<>();
        groupIdMap.put("id", feiShuGroupId);
        groupIdList.add(groupIdMap);
        updateGroupFieldMap.put("群名称", groupIdList);
        updateGroupFieldMap.put("群ID", feiShuGroupId);
        log.info("updateMap: {}", JSONObject.toJSONString(updateGroupFieldMap));
        feiShuCommonService.sendUpdateRequestFeiShuSheet(updateGroupFieldMap, recordSheetDto);

        // 发送群消息
        feiShuCommonService.sendGroupMsg(feiShuGroupName, feiShuGroupId);
    }

    /**
     * 创建飞书群 -- oms
     *
     * @param updateGroupFieldMap
     * @param customerName
     * @param siteId
     * @param planName
     * @param recordId
     * @param ownerId
     */
    @Override
    public void createFeiShuGroupOms(Map<String, Object> updateGroupFieldMap, String customerName, String siteId, String planName, String recordId, String ownerId) {
//        log.info("updateGroupFieldMap:{}", FastJsonUtil.toJSONString(updateGroupFieldMap));
//        log.info("customerName:{}", customerName);
//        log.info("siteId:{}", siteId);
//        log.info("planName:{}", planName);
//        log.info("recordId:{}", recordId);
//        log.info("ownerId:{}", ownerId);

        //群成员
        List<String> needJoinFeiShuIds = updateGroupFieldMap.values().stream()
                .filter(value -> value instanceof List)
                .map(value -> (List<Map<String, String>>) value)
                .flatMap(List::stream)
                .map(item -> item.get("id"))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
//        log.info("needJoinFeiShuIds: {}", FastJsonUtil.toJSONString(needJoinFeiShuIds));

        // 去除 外部人员 - 韩齐齐
        needJoinFeiShuIds.remove("ou_afa4c39a90731aa2ff483c3d165aa546");

        // 转换为数组
        String[] needJoinFeiShuIdsArray = needJoinFeiShuIds.toArray(new String[0]);

        // 群名称
        String feiShuGroupName = customerName + " - " + planName + " - OK项目组";
//        log.info("feiShuGroupName:{}", feiShuGroupName);

        //创建群聊
        CreateChatResp createChatResp = feiShuCommonService.sendCreateFeiShuGroupRequest(customerName, siteId, feiShuGroupName, ownerId, needJoinFeiShuIdsArray, recordId);
        if (createChatResp.success()) {
            String feiShuGroupId = createChatResp.getData().getChatId();

            // 更新表格-群组字段
            updateGroupField(feiShuGroupName, recordId, feiShuGroupId);
        }
    }

}
