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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.bitable.v1.model.*;
import com.lark.oapi.service.drive.v1.model.BaseMember;
import com.lark.oapi.service.drive.v1.model.CreatePermissionMemberReq;
import com.lark.oapi.service.drive.v1.model.CreatePermissionMemberResp;
import com.lark.oapi.service.im.v1.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.okki.externallink.service.IOkkiExternalLinkService;
import org.jeecg.modules.okki.site.dto.FeiShuRecordSheetDto;
import org.jeecg.modules.okki.site.dto.FeiShuSeoTeamRecordSheetDto;
import org.jeecg.modules.okki.site.entity.FeiShuConfigEnum;
import org.jeecg.modules.okki.site.entity.FeiShuConfigManager;
import org.jeecg.modules.okki.site.entity.OkkiSite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author Chen
 */
@Slf4j
@Service
public class IFeiShuCommonService {

    @Autowired
    private IFeiShuMsgService feiShuMsgService;

    @Autowired
    private IOkkiExternalLinkService okkiExternalLinkService;

    @Autowired
    private IOkCommonService okCommonService;

    /**
     * @param targetGroups
     */
    public Map<String, List<JSONObject>> getFeiShuTeamSheet(List<String> targetGroups) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        List<Map<String, Object>> mapList = new ArrayList<>();
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        ListAppTableRecordReq listAppTableRecordReq = ListAppTableRecordReq.newBuilder()
                .appToken(configEnum.getAppToken()).tableId(configEnum.getProjectTeamTableId()).build();

        // 发起请求
        ListAppTableRecordResp resp = null;
        try {
            resp = client.bitable().appTableRecord().list(listAppTableRecordReq);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error("******** getFeiShuTeamSheet ******* :{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        if (resp.success()) {
            ListAppTableRecordRespBody recordRespBody = resp.getData();
            AppTableRecord[] items = recordRespBody.getItems();
            for (AppTableRecord item : items) {
                mapList.add(item.getFields());
            }
        }

        log.info("mapList:{}", FastJsonUtil.toJSONString(mapList));
        // 业务数据处理
        String jsonData = FastJsonUtil.toJSONString(mapList);
        JSONArray jsonArray = JSON.parseArray(jsonData);
        Map<String, List<JSONObject>> targetGroupData = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String groupNameData = jsonObject.getString("组名");
            if ("离职".equals(jsonObject.getString("状态"))) {
                continue;
            }

            if(targetGroups.isEmpty()){
                String omsId = jsonObject.getString("OMS系统ID");
                if (!targetGroupData.containsKey(omsId)) {
                    targetGroupData.put(omsId, new ArrayList<>());
                }
                targetGroupData.get(omsId).add(jsonObject);
            }else{
                if (targetGroups.contains(groupNameData)) {
                    if (!targetGroupData.containsKey(groupNameData)) {
                        targetGroupData.put(groupNameData, new ArrayList<>());
                    }
                    targetGroupData.get(groupNameData).add(jsonObject);
                }
            }
        }

        log.info("targetGroupData:{}", FastJsonUtil.toJSONString(targetGroupData));
        return targetGroupData;
    }

    /**
     * 获取飞书团队表-英文名称
     *
     * @return
     */
    public List<String> getFeiShuEnNameByTeamSheet() {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        List<Map<String, Object>> mapList = new ArrayList<>();
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        ListAppTableRecordReq listAppTableRecordReq = ListAppTableRecordReq.newBuilder()
                .appToken(configEnum.getAppToken()).tableId(configEnum.getProjectTeamTableId()).build();

        // 发起请求
        ListAppTableRecordResp resp = null;
        try {
            resp = client.bitable().appTableRecord().list(listAppTableRecordReq);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error("******** getFeiShuTeamSheet ******* :{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        if (resp.success()) {
            ListAppTableRecordRespBody recordRespBody = resp.getData();
            AppTableRecord[] items = recordRespBody.getItems();
            for (AppTableRecord item : items) {
                mapList.add(item.getFields());
            }
        }
        log.info("mapList:{}", FastJsonUtil.toJSONString(mapList));

        List<String> enNameList = new ArrayList<>();
        String jsonData = FastJsonUtil.toJSONString(mapList);
        JSONArray jsonArray = JSON.parseArray(jsonData);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if ("离职".equals(jsonObject.getString("状态"))) {
                continue;
            }
            String enName = jsonObject.getString("英文名");
            if (StringUtils.isNotBlank(enName)) {
                enNameList.add(enName);
            }
        }

        return enNameList;
    }

    /**
     * 同步站点信息到飞书表格
     *
     * @param okkiSite
     */
    public void syncWebsiteToFeiShuSheet(OkkiSite okkiSite,Map<String, Object> updateGroupFieldMap) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        Map<String, Object> map = new HashMap<>();
        map.put("公司名称", okkiSite.getCompanyName());
        map.put("网站ID", Integer.valueOf(okkiSite.getSiteId()));
        map.put("服务套餐", okkiSite.getTcName());
        map.put("状态", "正常");
        map.put("当前状态", "模版待确认");
//        map.put("顾问对接", "小满对接");
        map.putAll(updateGroupFieldMap);
        CreateAppTableRecordReq req = CreateAppTableRecordReq.newBuilder().appToken(configEnum.getAppToken()).tableId(configEnum.getKfTableId())
                .appTableRecord(AppTableRecord.newBuilder()
                        .fields(map)
                        .build())
                .build();

        // 发起请求
        CreateAppTableRecordResp resp = null;
        try {
            resp = client.bitable().v1().appTableRecord().create(req);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

        String syncStatus = "成功";
        if (!resp.success()) {
            log.error("执行 **** syncWebsiteToFeiShuSheet **** 同步站点信息到飞书表格 失败:{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
            syncStatus = "失败";
        }

//        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
//        feiShuMsgService.sendSyncFeiShuSheetMsg(okkiSite.getCompanyName(), okkiSite.getSiteId(), okkiSite.getTcName(), syncStatus);
    }

    /**
     * 发送飞书更新请求
     *
     * @param updateMap
     * @return
     */
    public boolean sendUpdateRequestFeiShuSheet(Map<String, Object> updateMap, FeiShuRecordSheetDto recordSheetDto) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        String appToken = "";
        String tableId = "";
        if ("Y".equals(recordSheetDto.getOkTablePage())) {
            appToken = configEnum.getAppToken();
            if ("客服团队".equals(recordSheetDto.getOkTableName())) {
                tableId = configEnum.getKfTableId();
            }

            if ("SEO团队".equals(recordSheetDto.getOkTableName())) {
                tableId = configEnum.getSeoTeamTableId();
            }

        } else {
            appToken = recordSheetDto.getThirdAppToken();
            tableId = recordSheetDto.getThirdTableId();
        }

        UpdateAppTableRecordReq updateReq = UpdateAppTableRecordReq.newBuilder()
                .appTableRecord(AppTableRecord.newBuilder()
                        .fields(updateMap).build()).appToken(appToken).tableId(tableId).recordId(recordSheetDto.getRecordId())
                .build();

        // 发起请求
        UpdateAppTableRecordResp updateResp = null;
        try {
            updateResp = client.bitable().appTableRecord().update(updateReq);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        String status = "成功";
        if (!updateResp.success()) {
            log.error("执行 **** sendUpdateRequestFeiShuSheet **** 执行更新信息到飞书表格 失败:{}", String.format("code:%s,msg:%s,reqId:%s", updateResp.getCode(), updateResp.getMsg(), updateResp.getRequestId()));
            status = "失败";
        }

//        feiShuMsgService.sendUpdateFeiShuSheetMsg(recordSheetDto.getCustomerName(), recordSheetDto.getSiteId(), recordSheetDto.getGroupName(), status);
        return updateResp.success();
    }


    /**
     * 发起创建群聊请求
     *
     * @param feiShuGroupName
     * @param ownerId
     * @param needJoinFeiShuIdsArray
     */
    public CreateChatResp sendCreateFeiShuGroupRequest(String customerName, String siteId, String feiShuGroupName, String ownerId, String[] needJoinFeiShuIdsArray, String recordId) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        CreateChatReq req = CreateChatReq.newBuilder()
                .createChatReqBody(CreateChatReqBody.newBuilder()
                        .name(feiShuGroupName)
                        .description(feiShuGroupName)
                        .ownerId(ownerId)
                        .userIdList(needJoinFeiShuIdsArray)
                        .botIdList(new String[]{configEnum.getAppId()})
                        .build())
                .build();

        // 发起请求
        CreateChatResp resp = null;
        try {
            resp = client.im().chat().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        String status = "成功";
        if (!resp.success()) {
            status = "失败";
            log.error("********** sendCreateFeiShuGroupRequest-error *********:{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        // 发送飞书消息通知
//        feiShuMsgService.sendCreateFeiShuGroupMsg(customerName, siteId, feiShuGroupName, status);
        if (resp.success()) {
            // 业务数据处理
            log.info("********* sendCreateFeiShuGroupRequest **********:{}", Jsons.DEFAULT.toJson(resp.getData()));
        }

        return resp;
    }

    /**
     * 发送群消息
     *
     * @param feiShuGroupName
     */
    public void sendGroupMsg(String feiShuGroupName, String feiShuGroupId) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        Map<String, Object> map = new HashMap<>();
        map.put("text", "<at user_id=\"all\"></at> \n大家好！\uD83E\uDD16\n" +
                "我是 " + feiShuGroupName + " 的机器人助理。欢迎加入项目群！我的任务是协助大家顺利推进项目进程，解答疑问，和处理各种信息。如果有任何问题或需要帮助，请随时联系我。期待与大家的合作，共同推动项目成功！\n" +
                "谢谢大家的配合！\uD83D\uDE80！");

        // 创建请求对象
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("chat_id")
                .createMessageReqBody(CreateMessageReqBody.newBuilder()
                        .receiveId(feiShuGroupId)
                        .msgType("text")
                        .content(FastJsonUtil.toJSONString(map))
                        .build())
                .build();

        // 发起请求
        CreateMessageResp resp = null;
        try {
            resp = client.im().message().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error("******* sendGroupMsg-error ******** :{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
    }

    /**
     * 获取SEO外链文档
     *
     * @param recordSheetDto
     */
    public Map<String, Object> sendGetFeiShuSheetSeoExternalLinkRequest(FeiShuSeoTeamRecordSheetDto recordSheetDto) {
        Map<String, Object> map = new HashMap<>();
        String externalLink = recordSheetDto.getExternalLink();
        String appToken = okCommonService.extractBaseId(externalLink);
        String tableId = okCommonService.extractTableId(externalLink);
        log.info("appToken:{},tableId:{}", appToken, tableId);

        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        ListAppTableRecordReq listAppTableRecordReq = ListAppTableRecordReq.newBuilder()
                .appToken(appToken).tableId(tableId).build();

        // 发起请求
        ListAppTableRecordResp resp = null;
        try {
            resp = client.bitable().appTableRecord().list(listAppTableRecordReq);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error("******** getSeoExternalLinkByFeiShuSheet ******* :{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        List<Map<String, Object>> externalLinkList = new ArrayList<>();
        ListAppTableRecordRespBody recordRespBody = resp.getData();
        AppTableRecord[] items = recordRespBody.getItems();
        for (AppTableRecord item : items) {
            Map<String, Object> fields = item.getFields();
            fields.put("recordId", item.getRecordId());
            externalLinkList.add(fields);
        }

        map.put("appToken", appToken);
        map.put("tableId", tableId);
        map.put("data", externalLinkList);
        return map;
    }

    /**
     * 创建飞书多维表格
     *
     * @param recordSheetDto
     */
    public CreateAppResp sendCreateFeiShuBitableRequest(FeiShuSeoTeamRecordSheetDto recordSheetDto) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();

        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        CreateAppReq req = CreateAppReq.newBuilder()
                .reqApp(ReqApp.newBuilder()
                        .name(recordSheetDto.getCustomerName() + "_" + recordSheetDto.getSiteId())
                        .build())
                .build();

        // 发起请求
        CreateAppResp resp = null;
        try {
            resp = client.bitable().app().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
        return resp;
    }

    /**
     * 分配权限
     *
     * @param appToken
     */
    public void assignDrivePermission(String appToken, String seoMemberFeiShuUnionId) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();

        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        CreatePermissionMemberReq req = CreatePermissionMemberReq.newBuilder()
                .token(appToken)
                .type("bitable")
                .baseMember(BaseMember.newBuilder()
                        .memberType("openid")
//                        .memberId("ou_97114baa13236ece3966eae82d7bf3f7")
                        .memberId(seoMemberFeiShuUnionId)
                        .perm("full_access")
                        .permType("container")
                        .type("user")
                        .build())
                .build();

        // 发起请求
        CreatePermissionMemberResp resp = null;
        try {
            resp = client.drive().permissionMember().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
            return;
        }
    }

    /**
     * 获取飞书表格字段
     *
     * @param appToken
     * @param customerName
     */
    public CreateAppTableResp createBitableSeoExternalNewTable(String appToken, String customerName) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        CreateAppTableReq req = CreateAppTableReq.newBuilder()
                .appToken(appToken)
                .createAppTableReqBody(CreateAppTableReqBody.newBuilder()
                        .table(ReqTable.newBuilder()
                                .name(customerName)
                                .defaultViewName("表格")
                                .fields(new AppTableCreateHeader[]{
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("自动编号")
                                                .type(1005)
                                                .uiType("AutoNumber")
                                                .build(),

                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("livelinks")
                                                .type(15)
                                                .uiType("Url")
                                                .build(),

                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("标题")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),

                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("status")
                                                .type(3)
                                                .uiType("SingleSelect").property(AppTableFieldProperty.newBuilder().options(new AppTableFieldPropertyOption[]{
                                                        AppTableFieldPropertyOption.newBuilder().name("待上传").build(),
                                                        AppTableFieldPropertyOption.newBuilder().name("未上传").build(),
                                                        AppTableFieldPropertyOption.newBuilder().name("已上传").build(),
                                                }).build())
                                                .build(),

                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("上传日期")
                                                .type(5)
                                                .uiType("DateTime")
                                                .build(),
                                })
                                .build())
                        .build())
                .build();

        // 发起请求
        CreateAppTableResp resp = null;
        try {
            resp = client.bitable().appTable().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        return resp;
    }

    /**
     * 删除多维表格
     *
     * @param appToken
     * @param tableId
     * @return
     */
    public DeleteAppTableResp deleteBitableByTableId(String appToken, String tableId) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        DeleteAppTableReq req = DeleteAppTableReq.newBuilder()
                .appToken(appToken)
                .tableId(tableId)
                .build();

        // 发起请求
        DeleteAppTableResp resp = null;
        try {
            resp = client.bitable().appTable().delete(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        return resp;
    }

    /**
     * 创建showlist-客户基表
     *
     * @param appToken
     * @param customerName
     */
    public CreateAppTableResp createBitableShowlistNewTable(String appToken, String customerName) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        CreateAppTableReq req = CreateAppTableReq.newBuilder()
                .appToken(appToken)
                .createAppTableReqBody(CreateAppTableReqBody.newBuilder()
                        .table(ReqTable.newBuilder()
                                .name("SEO Keyword")
                                .defaultViewName("表格")
                                .fields(new AppTableCreateHeader[]{
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("ID")
                                                .type(1005)
                                                .uiType("AutoNumber")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("Keyword")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("Overview")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("Advantages")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("HT1")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("HC1")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("HT2")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("HC2")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("HT3")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("HC3")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("T")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("D")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
                                        AppTableCreateHeader.newBuilder()
                                                .fieldName("K")
                                                .type(1)
                                                .uiType("Text")
                                                .build(),
//                                        AppTableCreateHeader.newBuilder()
//                                                .fieldName("创建时间")
//                                                .type(5)
//                                                .uiType("DateTime")
//                                                .build(),
                                })
                                .build())
                        .build())
                .build();

        // 发起请求
        CreateAppTableResp resp = null;
        try {
            resp = client.bitable().appTable().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        return resp;
    }

    /**
     * 获取客服团队表数据
     *
     * @return
     */
    public Map<String, List<JSONObject>> getKfTeamSheet() {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        SearchAppTableRecordReq req = SearchAppTableRecordReq.newBuilder().appToken(configEnum.getAppToken()).tableId(configEnum.getKfTableId())
                .searchAppTableRecordReqBody(SearchAppTableRecordReqBody.newBuilder()
                        .viewId(configEnum.getKfTableSummaryViewId())
                        .fieldNames(new String[]{"公司名称", "网站ID", "服务阶段", "建站顾问", "群名称", "英文名称"})
                        .automaticFields(false)
                        .build())
                .build();

        // 发起请求
        SearchAppTableRecordResp resp = null;
        try {
            resp = client.bitable().appTableRecord().search(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        List<Map<String, Object>> mapList = new ArrayList<>();
        if (resp.success()) {
            SearchAppTableRecordRespBody recordRespBody = resp.getData();
            AppTableRecord[] items = recordRespBody.getItems();
            for (AppTableRecord item : items) {
                mapList.add(item.getFields());
            }
        }

        // 业务数据处理
        log.info(Jsons.DEFAULT.toJson(resp.getData()));
//        log.info("mapList:{}", FastJsonUtil.toJSONString(mapList));

        // 业务数据处理
        String jsonData = FastJsonUtil.toJSONString(mapList);
        JSONArray jsonArray = JSON.parseArray(jsonData);
        Map<String, List<JSONObject>> kfGroupData = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
//            log.info("jsonObject:{}", jsonObject.toJSONString());
            if (!jsonObject.isEmpty()) {
                if (jsonObject.containsKey("英文名称")) {
                    JSONObject enNameFieldsObj = jsonObject.getJSONObject("英文名称");
                    JSONArray enNameDataArray = enNameFieldsObj.getJSONArray("value");
                    String enNameKey = enNameDataArray.getJSONObject(0).getString("text");
                    if (!kfGroupData.containsKey(enNameKey)) {
                        kfGroupData.put(enNameKey, new ArrayList<>());
                    }
                    kfGroupData.get(enNameKey).add(jsonObject);
                }
            }
        }
        log.info("kfGroupData:{}", FastJsonUtil.toJSONString(kfGroupData));
        return kfGroupData;
    }

    /**
     * 发送客服提醒消息
     *
     * @param feiShuGroupId
     * @param msgText
     * @param userId
     */
    public void sendKfRemindMsg(String feiShuGroupId, String msgText, String userId, String msgType) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        Map<String, Object> map = new HashMap<>();
//        if ("remindCustomerMsg".equals(msgType)) {
//            map.put("text", msgText);
//        } else {
//            map.put("text", "<at user_id=\"" + userId + "\"></at> \n" + msgText);
//        }
        map.put("text", msgText);

        // 创建请求对象
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("chat_id")
                .createMessageReqBody(CreateMessageReqBody.newBuilder()
                        .receiveId(feiShuGroupId)
                        .msgType("text")
                        .content(FastJsonUtil.toJSONString(map))
                        .build())
                .build();

        // 发起请求
        CreateMessageResp resp = null;
        try {
            resp = client.im().message().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error("******* sendGroupMsg-error ******** :{}", String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
    }

    /**
     * 拉入机器人加入飞书群
     *
     * @param chatId
     * @param needJoinIdList
     */
    public void joinFeiShuGroupRequest(String chatId, List<String> needJoinIdList) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();

        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();
        String[] needJoinIdsArr = needJoinIdList.toArray(new String[0]);

        // 创建请求对象
        CreateChatMembersReq req = CreateChatMembersReq.newBuilder()
                .chatId(chatId)
                .memberIdType("app_id")
                .createChatMembersReqBody(CreateChatMembersReqBody.newBuilder()
                        .idList(needJoinIdsArr)
                        .build())
                .build();

        // 发起请求
        CreateChatMembersResp resp = null;
        try {
            resp = client.im().chatMembers().create(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    /**
     * 检查机器人或用户是否在群里
     *
     * @param chatId
     */
    public boolean checkBotOrUserIsExistGroup(String chatId) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        // 创建请求对象
        IsInChatChatMembersReq req = IsInChatChatMembersReq.newBuilder()
                .chatId(chatId)
                .build();

        // 发起请求
        IsInChatChatMembersResp resp = null;
        try {
            resp = client.im().chatMembers().isInChat(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

        // 业务数据处理
//        log.info(Jsons.DEFAULT.toJson(resp.getData()));

        return resp.getData().getIsInChat();
    }

    /**
     * 在客服团队表根据站点ID获取数据
     *
     * @return
     */
    public List<Map<String, Object>> getCustomerInfoKfSheetBySiteId(String siteId) {
        FeiShuConfigEnum configEnum = FeiShuConfigManager.getInstance().getConfigEnum();
        // 构建client
        Client client = Client.newBuilder(configEnum.getAppId(), configEnum.getAppSecret()).build();

        SearchAppTableRecordReq req = SearchAppTableRecordReq.newBuilder().appToken(configEnum.getAppToken()).tableId(configEnum.getKfTableId())
                .searchAppTableRecordReqBody(SearchAppTableRecordReqBody.newBuilder()
                        .viewId(configEnum.getKfTableSummaryViewId())
                        .fieldNames(new String[]{"公司名称", "网站ID"})
                        .filter(FilterInfo.newBuilder()
                                .conjunction("and")
                                .conditions(new Condition[] {
                                        Condition.newBuilder()
                                                .fieldName("网站ID")
                                                .operator("is")
                                                .value(new String[] {
                                                        siteId
                                                })
                                                .build(),
                                })
                                .build())
                        .automaticFields(false)
                        .build())
                .build();

        // 发起请求
        SearchAppTableRecordResp resp = null;
        try {
            resp = client.bitable().appTableRecord().search(req);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 处理服务端错误
        if (!resp.success()) {
            log.error(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }

//        log.info(Jsons.DEFAULT.toJson(resp.getData()));

        List<Map<String, Object>> mapList = new ArrayList<>();
        if (resp.success()) {
            SearchAppTableRecordRespBody recordRespBody = resp.getData();
            AppTableRecord[] items = recordRespBody.getItems();
            for (AppTableRecord item : items) {
                Map<String,Object> fieldsObject = item.getFields();
                fieldsObject.put("record_id",item.getRecordId());
                mapList.add(fieldsObject);
            }
        }
        // 业务数据处理
        log.info("mapList:{}", FastJsonUtil.toJSONString(mapList));

        return mapList;
    }
}
