package com.czg.service.product.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.czg.constants.SystemConstants;
import com.czg.product.entity.MkOcrCountStick;
import com.czg.product.service.MkOcrCountStickService;
import com.czg.service.RedisService;
import com.czg.service.product.mapper.MkOcrCountStickMapper;
import com.czg.service.product.util.AISmartCountUtils;
import com.czg.service.product.util.MuSmartCountUtils;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数签子的外链渠道 服务层实现。
 *
 * @author ww
 * @since 2025-12-24
 */
@Slf4j
@Service
public class MkOcrCountStickServiceImpl extends ServiceImpl<MkOcrCountStickMapper, MkOcrCountStick> implements MkOcrCountStickService {

    @Resource
    private RedisService redisService;

    @Override
    public int getCountStick(byte[] fileByte, String fileName) {
        List<MkOcrCountStick> list = list(query().eq(MkOcrCountStick::getStatus, SystemConstants.OneZero.ONE).orderBy(MkOcrCountStick::getSort, true));
        for (MkOcrCountStick mkOcrCountStick : list) {
            if ("znds".equals(mkOcrCountStick.getMark())) {
                try {
                    String tickCount = AISmartCountUtils.getTickCount(mkOcrCountStick.getToken(), fileByte, fileName);
                    if (StrUtil.isNotBlank(tickCount)) {
                        return Integer.parseInt(tickCount);
                    }
                } catch (Exception e) {
                    mkOcrCountStick.setStatus(SystemConstants.OneZero.ZERO);
                    log.error("智能点数失败", e);
                    updateById(mkOcrCountStick);
                }
            } else if ("ygmh".equals(mkOcrCountStick.getMark())) {
                try {
                    String token = getToken(mkOcrCountStick.getAccount(), mkOcrCountStick.getPwd());
                    return MuSmartCountUtils.detectBambooStick(Base64.encode(fileByte), token);
                } catch (Exception e) {
                    mkOcrCountStick.setStatus(SystemConstants.OneZero.ZERO);
                    log.error("智能点数失败", e);
                    updateById(mkOcrCountStick);
                }
            }
        }
        return 0;
    }

    // 一个木涵 获取token
    private String getToken(String username, String password) {
        Object token = redisService.get("ocr:ygmh:token");
        if (token != null) {
            return token.toString();
        }
        String muToken = MuSmartCountUtils.login(username, password);
        //时间为3个月减去60秒
        redisService.set("ocr:ygmh:token", muToken, 7775940);
        return muToken;
    }
}
