package com.pcloud.book.group.biz.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.pcloud.book.group.biz.GroupMaterialAccountBiz;
import com.pcloud.book.group.entity.GroupMaterialAccount;
import com.pcloud.book.group.mapper.GroupMaterialAccountMapper;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.facade.wechat.material.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * GroupMaterialAccountBiz实现
 *
 * @author guiq
 * @version 1.0
 * @since 2020年7月23日
 */
@Slf4j
@Component("groupMaterialAccountBiz")
public class GroupMaterialAccountBizImpl implements GroupMaterialAccountBiz {
    /**
     * 永久图文素材群头像
     */
    private static final String GROUP_HEAD_IMAGE = "https://file.raysgo.com/oss/uploadfe/png/5ac51d7a8ad9c6ac9d32355ecbd64898.png";

    /**
     * 永久图文素材封面
     */
    private static final String COVER_IMAGE = "https://file.raysgo.com/oss/uploadfe/png/2b5d5797fc09d240c64de18fee3261d4.png";

    @Autowired
    private GroupMaterialAccountMapper groupMaterialAccountMapper;
    @Autowired
    private MaterialService materialService;


    @Override
    public GroupMaterialAccount getActiveAccount(Integer useType) {
        // 查询未达到限制或者已达到限制但已经到新的一天的
        List<GroupMaterialAccount> activeAccount = groupMaterialAccountMapper.getActiveAccount(useType);
        return checkLimit(activeAccount);
    }

    @Override
    public GroupMaterialAccount getByAccountId(Long accountId) {
        GroupMaterialAccount account = groupMaterialAccountMapper.getByAccountId(accountId);
        if (Objects.nonNull(account)) {
            // 补充群头像 - 图文消息内的图片
            if (StrUtil.isBlank(account.getCoverMediaId()) || StrUtil.isBlank(account.getHeadMediaId())) {
                try {
                    if (StrUtil.isBlank(account.getHeadMediaId())){
                        String url = ResponseHandleUtil.parseResponse(materialService.uploadImg(account.getAccountId(), GROUP_HEAD_IMAGE), String.class);
                        account.setHeadMediaId(url);
                    }
                    if (StrUtil.isBlank(account.getCoverMediaId())){
                        String mediaId = ResponseHandleUtil.parseResponse(materialService.addImgMaterial(account.getAccountId(), COVER_IMAGE), String.class);
                        account.setCoverMediaId(mediaId);
                    }
                } catch (BizException e) {
                    // 接口调用超过限制,更新状态为达到限制
                    if (e.getMsg() != null && e.getMsg().contains("接口调用超过限制") && account.getStatus() == 1) {
                        account.setStatus(0);
                        account.setUpdateTime(new Date());
                        groupMaterialAccountMapper.update(account);
                    }
                    return null;
                }
            }
            // 更新状态为可用
            if (account.getStatus() == 0 || account.getUpdateTime()==null) {
                account.setStatus(1);
                account.setUpdateTime(new Date());
                groupMaterialAccountMapper.update(account);
            }
            return account;
        }
        return null;
    }

    @Override
    public void addAccount4Material(Long accountId, Integer useType) {
        if (Objects.nonNull(accountId) && Objects.nonNull(useType)) {
            GroupMaterialAccount account = new GroupMaterialAccount();
            account.setAccountId(accountId);
            account.setCreateTime(new Date());
            account.setStatus(1);
            account.setUseType(useType);
            groupMaterialAccountMapper.insert(account);
        }
    }

    /**
     * 筛选一个可用的公众号
     */
    private GroupMaterialAccount checkLimit(List<GroupMaterialAccount> accounts) {
        if (CollUtil.isEmpty(accounts)) {
            return null;
        }
        for (GroupMaterialAccount account : accounts) {
            if (Objects.nonNull(account)) {
                // 补充群头像 - 图文消息内的图片
                if (StrUtil.isBlank(account.getCoverMediaId()) || StrUtil.isBlank(account.getHeadMediaId())) {
                    try {
                        if (StrUtil.isBlank(account.getHeadMediaId())){
                            String url = ResponseHandleUtil.parseResponse(materialService.uploadImg(account.getAccountId(), GROUP_HEAD_IMAGE), String.class);
                            account.setHeadMediaId(url);
                        }
                        if (StrUtil.isBlank(account.getCoverMediaId())){
                            String mediaId = ResponseHandleUtil.parseResponse(materialService.addImgMaterial(account.getAccountId(), COVER_IMAGE), String.class);
                            account.setCoverMediaId(mediaId);
                        }
                    } catch (BizException e) {
                        // 接口调用超过限制,更新状态为达到限制,继续循环，获取下一个公众号
                        if (e.getMsg() != null && e.getMsg().contains("接口调用超过限制") && account.getStatus() == 1) {
                            account.setStatus(0);
                            account.setUpdateTime(new Date());
                            groupMaterialAccountMapper.update(account);
                        }
                        continue;
                    }
                }
                // 更新状态为可用
                if (account.getStatus() == 0 || account.getUpdateTime()==null) {
                    account.setStatus(1);
                    account.setUpdateTime(new Date());
                    groupMaterialAccountMapper.update(account);
                }
                return account;
            }
        }
        return null;
    }
}
