package com.tzld.piaoquan.api.job.contentplatform;

import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.component.AigcApiService;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformGzhAccountMapper;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformGzhAccount;
import com.tzld.piaoquan.api.model.po.contentplatform.ContentPlatformGzhAccountExample;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class ContentPlatformGzhAccountJob {

    @Autowired
    private ContentPlatformGzhAccountMapper gzhAccountMapper;
    @Autowired
    private AigcApiService aigcApiService;

    @XxlJob("syncGzhAccountInfoJob")
    public ReturnT<String> syncGzhAccountInfoJob(String param) {
        List<ContentPlatformGzhAccount> accountList;
        if (StringUtils.hasText(param)) {
            ContentPlatformGzhAccount account = gzhAccountMapper.selectByPrimaryKey(Long.valueOf(param));
            accountList = new ArrayList<>();
            accountList.add(account);
        } else {
            accountList = getNeedSyncAccountInfo();
        }
        if (accountList.isEmpty()) {
            return ReturnT.SUCCESS;
        }
        for (ContentPlatformGzhAccount account : accountList) {
            log.info("同步公众号数据统计:{}", account.getGhId());
            JSONObject accountInfo = aigcApiService.getAccountDetail(account.getExternalId());
            if (Objects.isNull(accountInfo)) {
                continue;
            }
            String newName = accountInfo.getString("name");
            if (account.getName().equals(newName) || !StringUtils.hasText(newName)) {
                continue;
            }
            account.setName(accountInfo.getString("name"));
            gzhAccountMapper.updateByPrimaryKeySelective(account);
        }

        return ReturnT.SUCCESS;
    }

    private List<ContentPlatformGzhAccount> getNeedSyncAccountInfo() {
        ContentPlatformGzhAccountExample example = new ContentPlatformGzhAccountExample();
        example.createCriteria().andExternalIdIsNotNull().andStatusEqualTo(1);
        return gzhAccountMapper.selectByExample(example);
    }
}
