package com.czg.service.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.JSON;
import com.czg.account.dto.msg.ShopMsgEditDTO;
import com.czg.account.entity.ShopMsgState;
import com.czg.account.entity.ShopPushOpenId;
import com.czg.account.param.ShopPushConfigParam;
import com.czg.account.service.ShopMsgStateService;
import com.czg.service.account.mapper.ShopMsgStateMapper;
import com.czg.service.account.mapper.ShopPushOpenIdMapper;
import com.czg.service.account.util.AliOssUtil;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * 店铺消息推送设置 服务层实现。
 *
 * @author zs
 * @since 2025-03-07
 */
@Service
public class ShopMsgStateServiceImpl extends ServiceImpl<ShopMsgStateMapper, ShopMsgState> implements ShopMsgStateService {
    private static final HashMap<String, String> MSG_TYPE = new HashMap<>();

    static {
        MSG_TYPE.put("0", "stockState");
        MSG_TYPE.put("1", "conState");
        MSG_TYPE.put("2", "opeState");
        MSG_TYPE.put("-1", "allState");
    }

    @Resource
    private ResourceLoader resourceLoader;
    @Resource
    private AliOssUtil aliOssUtil;
    @Resource
    private ShopPushOpenIdMapper shopPushOpenIdMapper;
    @Value("${spring.profiles.active}")
    private String active;


    @Override
    public HashMap<String, Object> getState(Long shopId) {
        List<ShopMsgState> list = queryChain().eq(ShopMsgState::getShopId, shopId).list();
        HashMap<String, Object> data = new HashMap<>();
        MSG_TYPE.forEach((k, v) -> {
            ShopMsgState have = null;
            for (ShopMsgState shopMsgState : list) {
                if (shopMsgState.getType().equals(Integer.valueOf(k))) {
                    have = shopMsgState;
                    break;
                }
            }
            if (have == null) {
                ShopMsgState msgState = new ShopMsgState();
                msgState.setShopId(shopId);
                msgState.setCreateTime(DateUtil.date().toLocalDateTime());
                msgState.setType(Integer.valueOf(k));
                msgState.setState(0);
                save(msgState);
            }
            data.put(v, have != null ? have.getState() : 0);
        });

        return data;
    }

    @Override
    public Boolean edit(Long shopId, ShopMsgEditDTO shopMsgEditDTO) {
        ShopMsgState msgState = queryChain().eq(ShopMsgState::getShopId, shopId).eq(ShopMsgState::getType, shopMsgEditDTO.getType()).one();
        if (msgState == null) {
            msgState = new ShopMsgState();
            msgState.setShopId(shopId);
            msgState.setCreateTime(DateUtil.date().toLocalDateTime());
            msgState.setType(shopMsgEditDTO.getType());
            msgState.setState(shopMsgEditDTO.getState());
            return save(msgState);
        }
        BeanUtil.copyProperties(shopMsgEditDTO, msgState);
        return updateById(msgState);
    }

    @Override
    public String getCode(Long shopId) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:/static/logo.jpg");
        InputStream inputStream = resource.getInputStream();
        String url = StrUtil.format("https://invoice.sxczgkj.cn/index/wechat/weuserk?source=ysk&active={}&shopId={}", active, shopId);
        QrCodeUtil.generate(url, new QrConfig(500, 500).
                setImg(ImageIO.read(inputStream)).setErrorCorrection(ErrorCorrectionLevel.H).setRatio(4), "png", outputStream);

        return aliOssUtil.uploadSuffix(outputStream.toByteArray(), "png");
    }

    @Override
    public void modifyConfig(ShopPushConfigParam param) {
        ShopPushOpenId entity = shopPushOpenIdMapper.selectOneById(param.getId());
        entity.setTypeInfo(CollUtil.isEmpty(param.getTypeInfo()) ? null : JSON.toJSONString(param.getTypeInfo()));
        shopPushOpenIdMapper.update(entity, false);
    }
}
