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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lark.oapi.service.bitable.v1.model.App;
import com.lark.oapi.service.bitable.v1.model.CreateAppResp;
import com.lark.oapi.service.bitable.v1.model.CreateAppTableResp;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.okki.account.entity.OkkiAccount;
import org.jeecg.modules.okki.account.service.IOkkiAccountService;
import org.jeecg.modules.okki.site.dto.FeiShuRecordSheetDto;
import org.jeecg.modules.okki.site.dto.FeiShuSeoTeamRecordSheetDto;
import org.jeecg.modules.okki.site.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author Chen
 */
@Slf4j
@Service
public class FeiShuSheetServiceImpl implements IFeiShuSheetService {

    @Autowired
    private IFeiShuCommonService feiShuCommonService;

    @Autowired
    private IFeiShuGroupService feiShuGroupService;

    @Autowired
    private IOkkiAccountService okkiAccountService;

    @Autowired
    private IOkCommonService okCommonService;

    @Autowired
    private IFeiShuMsgService feiShuMsgService;

    /**
     * 更新飞书表格
     *
     * @param recordSheetDto
     */
    @Override
    public boolean updateFeiShuTableSheetField(FeiShuRecordSheetDto recordSheetDto) {
        List<String> targetGroups = new ArrayList<>();
        targetGroups.add(recordSheetDto.getGroupName());
        targetGroups.add("UI设计");
        targetGroups.add("质检组");
//        targetGroups.add("技术支持");
        targetGroups.add("项目管理");
        Map<String, List<JSONObject>> teamSheetMap = feiShuCommonService.getFeiShuTeamSheet(targetGroups);
        log.info("teamSheetMap:{}", FastJsonUtil.toJSONString(teamSheetMap));

        List<JSONObject> jzGroups = teamSheetMap.get(recordSheetDto.getGroupName());
        log.info("jzGroups: {}", FastJsonUtil.toJSONString(jzGroups));

        Map<String, List<String>> roleToIds = new HashMap<>();
//        roleToIds.put("项目顾问", new ArrayList<>());
        roleToIds.put("建站专员", new ArrayList<>());
        roleToIds.put("资料专员", new ArrayList<>());

        for (JSONObject jsonObject : jzGroups) {
            String role = jsonObject.getString("角色");
            JSONArray personnelArray = jsonObject.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()) {
                        roleToIds.get(role).add(id);
                    }
                }
            }
        }

        Map<String, List<Map<String, Object>>> formattedRoleToIds = okCommonService.convertMapList(roleToIds);
        log.info("formattedRoleToIds: {}", FastJsonUtil.toJSONString(formattedRoleToIds));

        Map<String, Object> updateMap = new HashMap<>();
//        updateMap.put("建站顾问", formattedRoleToIds.get("项目顾问"));
        updateMap.put("组建站专员", formattedRoleToIds.get("建站专员"));
        updateMap.put("组资料员", formattedRoleToIds.get("资料专员"));
        log.info("updateMap: {}", JSONObject.toJSONString(updateMap));

        recordSheetDto.setOkTablePage("Y");
        recordSheetDto.setOkTableName("客服团队");
        boolean result = feiShuCommonService.sendUpdateRequestFeiShuSheet(updateMap, recordSheetDto);
        if (result) {
            List<String> omsAccountIds = new ArrayList<>();
            for (Map.Entry<String, List<JSONObject>> entry : teamSheetMap.entrySet()) {
                List<JSONObject> groupList = entry.getValue();
                for (JSONObject group : groupList) {
                    String omsId = group.getString("OMS系统ID");
                    omsAccountIds.add(omsId);
                }
            }
            log.info("omsAccountIds:{}", FastJsonUtil.toJSONString(omsAccountIds));

            for (int i = 0; i < omsAccountIds.size(); i++) {
                String omsId = omsAccountIds.get(i);
                log.info("~~~~~~~~~~~~~~~~~~");
                log.info("开始执行 第{}个 omsId:{} 的用户，绑定新站点", i + 1, omsId);
                OkkiAccount account = new OkkiAccount();
                account.setId(omsId);

                OkkiAccount okkiAccountInfo = okkiAccountService.getById(omsId);
                String siteIds = okkiAccountInfo.getSiteIds();
                StringBuilder sb = new StringBuilder(siteIds);
                sb.append(",").append(recordSheetDto.getSiteId());
                account.setSiteIds(sb.toString());

//                okkiAccountService.bindSites(account);
                // todo 接口升级
//                okkiAccountService.bindSitesV2(account);
                log.info("结束：第{}个 omsId:{} 的用户，绑定新站点", i + 1, omsId);
                log.info("```````````````````");
            }

            // 创建飞书群
            feiShuGroupService.createFeiShuGroup(recordSheetDto.getCustomerName(), recordSheetDto.getSiteId(), recordSheetDto.getPlanName(), recordSheetDto.getGroupName(), recordSheetDto.getRecordId());
        }
        return result;
    }

    /**
     * 创建飞书多维表格
     *
     * @param recordSheetDto
     */
    @Override
    public boolean createFeiShuSeoExternalBitable(FeiShuSeoTeamRecordSheetDto recordSheetDto) {
        CreateAppResp createAppResp = feiShuCommonService.sendCreateFeiShuBitableRequest(recordSheetDto);
        if (createAppResp == null) {
            return false;
        }
        App app = createAppResp.getData().getApp();
        String tableLink = app.getUrl();
        String tableId = app.getDefaultTableId();
        String appToken = app.getAppToken();
        feiShuCommonService.assignDrivePermission(appToken, recordSheetDto.getSeoMemberFeiShuUnionId());

        CreateAppTableResp createAppTableResp = feiShuCommonService.createBitableSeoExternalNewTable(appToken, recordSheetDto.getCustomerName());
        String newTableId = createAppTableResp.getData().getTableId();

        feiShuCommonService.deleteBitableByTableId(appToken, tableId);

        String fullTableLink = tableLink + "?table=" + newTableId;
        log.info("fullTableLink:{}", fullTableLink);
        updateSeoExternalTableLink(recordSheetDto.getCustomerName(), recordSheetDto.getRecordId(), fullTableLink);
        return true;
    }

    /**
     * 更多SEO团队-外链上传表字段
     *
     * @param customerName
     * @param recordId
     * @param tableLink
     */
    public void updateSeoExternalTableLink(String customerName, String recordId, String tableLink) {
        FeiShuRecordSheetDto recordSheetDto = new FeiShuRecordSheetDto();
        recordSheetDto.setRecordId(recordId);
        recordSheetDto.setOkTablePage("Y");
        recordSheetDto.setOkTableName("SEO团队");
        recordSheetDto.setCustomerName(customerName);

        Map<String, Object> updateGroupFieldMap = new HashMap<>();
        Map<String, Object> externalLinkMap = new HashMap<>();
        externalLinkMap.put("text", recordSheetDto.getCustomerName() + "-外链汇总表");
        externalLinkMap.put("link", tableLink);
        updateGroupFieldMap.put("外链上传表", externalLinkMap);
        log.info("updateGroupFieldMap:{}", updateGroupFieldMap);
        feiShuCommonService.sendUpdateRequestFeiShuSheet(updateGroupFieldMap, recordSheetDto);
    }

    /**
     * 创建seo客户-showlist表
     *
     * @param recordSheetDto
     */
    @Override
    public boolean createFeiShuSeoShowlistBitable(FeiShuSeoTeamRecordSheetDto recordSheetDto) {
        CreateAppResp createAppResp = feiShuCommonService.sendCreateFeiShuBitableRequest(recordSheetDto);
        if (createAppResp == null) {
            return false;
        }
        App app = createAppResp.getData().getApp();
        String tableLink = app.getUrl();
        String tableId = app.getDefaultTableId();
        String appToken = app.getAppToken();
        feiShuCommonService.assignDrivePermission(appToken, recordSheetDto.getSeoMemberFeiShuUnionId());

        CreateAppTableResp createAppTableResp = feiShuCommonService.createBitableShowlistNewTable(appToken, recordSheetDto.getCustomerName());
        String newTableId = createAppTableResp.getData().getTableId();

        feiShuCommonService.deleteBitableByTableId(appToken, tableId);

        String fullTableLink = tableLink + "?table=" + newTableId;
        log.info("fullTableLink:{}", fullTableLink);
        updateSeoTeamShowlistTableLink(recordSheetDto.getCustomerName(), recordSheetDto.getRecordId(), fullTableLink, recordSheetDto.getSiteId());

        feiShuMsgService.sendCreateSeoShowlistTableLinkMsg(recordSheetDto.getCustomerName(), recordSheetDto.getSeoMemberFeiShuUnionId(), recordSheetDto.getSiteId(), fullTableLink, "Showlist基表创建完成");
        return true;
    }

    /**
     * 更多SEO团队-外链上传表字段
     *
     * @param customerName
     * @param recordId
     * @param tableLink
     */
    public void updateSeoTeamShowlistTableLink(String customerName, String recordId, String tableLink, String siteId) {
        FeiShuRecordSheetDto recordSheetDto = new FeiShuRecordSheetDto();
        recordSheetDto.setRecordId(recordId);
        recordSheetDto.setOkTablePage("Y");
        recordSheetDto.setOkTableName("SEO团队");
        recordSheetDto.setCustomerName(customerName);

        Map<String, Object> updateGroupFieldMap = new HashMap<>();
        Map<String, Object> seoKeywordsDocMap = new HashMap<>();
        seoKeywordsDocMap.put("text", recordSheetDto.getCustomerName() + "_" + siteId);
        seoKeywordsDocMap.put("link", tableLink);
        updateGroupFieldMap.put("SEO Keyword Doc", seoKeywordsDocMap);
        log.info("updateGroupFieldMap:{}", updateGroupFieldMap);
        feiShuCommonService.sendUpdateRequestFeiShuSheet(updateGroupFieldMap, recordSheetDto);
    }
}
