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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DateUtils;
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.service.IFeiShuCommonService;
import org.jeecg.modules.okki.site.service.IFeiShuMsgService;
import org.jeecg.modules.okki.site.service.IFeiShuSeoTeamSheetService;
import org.jeecg.modules.okki.site.service.IOkCommonService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FeiShuSeoTeamSheetService implements IFeiShuSeoTeamSheetService {

    @Autowired
    private IFeiShuCommonService feiShuCommonService;

    @Autowired
    private IOkkiExternalLinkService okkiExternalLinkService;

    @Autowired
    private IFeiShuMsgService feiShuMsgService;

    /**
     * 获取飞书群内所有外链
     *
     * @param recordSheetDto
     */
    @Override
    public void syncSeoExternalLink(FeiShuSeoTeamRecordSheetDto recordSheetDto) {
        String siteId = recordSheetDto.getSiteId();
        Map<String, Object> linkRequestMap = feiShuCommonService.sendGetFeiShuSheetSeoExternalLinkRequest(recordSheetDto);
        log.info("linkRequestMap:{}", FastJsonUtil.toJSONString(linkRequestMap));
        JSONObject linkRequestObj = new JSONObject(linkRequestMap);

        String appToken = linkRequestObj.getString("appToken");
        String tableId = linkRequestObj.getString("tableId");

        List<Map<String, Object>> needUploadExternalList = new ArrayList<>();

        JSONArray allExternalLinkList = linkRequestObj.getJSONArray("data");
        for (int i = 0; i < allExternalLinkList.size(); i++) {
            JSONObject fields = allExternalLinkList.getJSONObject(i);
            if ("待上传".equals(fields.get("status"))) {
                JSONObject linkObj = fields.getJSONObject("livelinks");
                String link = linkObj.getString("link");
                fields.put("link", link);

                int lastSlashIndex = link.lastIndexOf('/');
                int secondLastSlashIndex = link.lastIndexOf('/', lastSlashIndex - 1);
                String title = link.substring(secondLastSlashIndex + 1, lastSlashIndex).replace("-", " ");
                String[] words = title.split(" ");
                StringBuilder upTitle = new StringBuilder();
                for (String word : words) {
                    if (!word.isEmpty()) {
                        String capitalizedWord = word.substring(0, 1).toUpperCase() + word.substring(1);
                        upTitle.append(capitalizedWord).append(" ");
                    }
                }
                fields.put("title", upTitle.toString().trim());

                needUploadExternalList.add(fields);
            }
        }
        log.info("needUploadExternalList:{}", FastJsonUtil.toJSONString(needUploadExternalList));
        if (needUploadExternalList.isEmpty()) {
            log.info("needUploadExternalList:{}", FastJsonUtil.toJSONString(needUploadExternalList));
            feiShuMsgService.sendSyncSeoExternalLinkMsg(recordSheetDto.getCustomerName(), recordSheetDto.getSeoMemberFeiShuUnionId(), recordSheetDto.getSiteId(), recordSheetDto.getExternalLink(), "未找到“待上传”的外链，请检查SEO外链表");
        }

        List<Map<String, Object>> requestErrorExternalList = new ArrayList<>();
        List<Map<String, Object>> requestSuccessExternalList = new ArrayList<>();
        for (Map<String, Object> item : needUploadExternalList) {
            JSONObject jsonObject = new JSONObject(item);
            String title = jsonObject.getString("title");
            String link = jsonObject.getString("link");
            String recordId = jsonObject.getString("recordId");
            boolean sendResult = okkiExternalLinkService.sendExternalLinkRequest(siteId, title, link);
//            boolean sendResult = true;
            if (sendResult) {
                updateSeoExternalTableField(recordSheetDto.getCustomerName(), appToken, tableId, recordId, title);
                requestSuccessExternalList.add(item);
            } else {
                requestErrorExternalList.add(item);
            }
        }

        if (!requestErrorExternalList.isEmpty()) {
            log.info("requestErrorExternalList:{}", FastJsonUtil.toJSONString(requestErrorExternalList));
            feiShuMsgService.sendSyncSeoExternalLinkMsg(recordSheetDto.getCustomerName(), recordSheetDto.getSeoMemberFeiShuUnionId(), recordSheetDto.getSiteId(), recordSheetDto.getExternalLink(), "小满接口报错，请重试");
        }

        if (!requestSuccessExternalList.isEmpty()) {
            log.info("requestSuccessExternalList:{}", FastJsonUtil.toJSONString(requestSuccessExternalList));
            feiShuMsgService.sendSyncSeoExternalLinkMsg(recordSheetDto.getCustomerName(), recordSheetDto.getSeoMemberFeiShuUnionId(), recordSheetDto.getSiteId(), recordSheetDto.getExternalLink(), "SEO外链同步成功");
        }
    }

    /**
     * 更新飞书表格-客户网站外链字段
     *
     * @param customerName
     * @param thirdAppToken
     * @param thirdTableId
     * @param recordId
     * @param title
     */
    public void updateSeoExternalTableField(String customerName, String thirdAppToken, String thirdTableId, String recordId, String title) {
        FeiShuRecordSheetDto recordSheetDto = new FeiShuRecordSheetDto();
        recordSheetDto.setThirdAppToken(thirdAppToken);
        recordSheetDto.setThirdTableId(thirdTableId);
        recordSheetDto.setRecordId(recordId);
        recordSheetDto.setOkTablePage("N");
        recordSheetDto.setCustomerName(customerName);

        Map<String, Object> updateGroupFieldMap = new HashMap<>();
        updateGroupFieldMap.put("上传日期", DateUtils.getMillis());
        updateGroupFieldMap.put("status", "已上传");
        updateGroupFieldMap.put("标题", title);
        feiShuCommonService.sendUpdateRequestFeiShuSheet(updateGroupFieldMap, recordSheetDto);
    }
}
