package com.czg.service.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.czg.account.service.ShopInfoService;
import com.czg.market.dto.MkDrainageConfigDTO;
import com.czg.market.entity.MkDrainageConfig;
import com.czg.market.service.MkDrainageConfigService;
import com.czg.market.vo.MkDrainageConfigVO;
import com.czg.service.market.mapper.MkDrainageConfigMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 私域引流表 服务层实现。
 *
 * @author zs
 * @since 2025-10-14
 */
@Service
public class MkDrainageConfigServiceImpl extends ServiceImpl<MkDrainageConfigMapper, MkDrainageConfig> implements MkDrainageConfigService{
    @Resource
    private ShopInfoService shopInfoService;
    @Override
    public MkDrainageConfigVO detail(Long shopId) {
        Long mainShopId = shopInfoService.getMainIdByShopId(shopId);
        MkDrainageConfig config = getOne(new QueryWrapper().eq(MkDrainageConfig::getShopId, shopId));
        if (config == null) {
            config = new MkDrainageConfig();
            config.setMainShopId(mainShopId);
            config.setShopId(shopId);
            save(config);
            config = getOne(new QueryWrapper().eq(MkDrainageConfig::getShopId, shopId));
        }
        MkDrainageConfigVO info = BeanUtil.copyProperties(config, MkDrainageConfigVO.class, "useType");
        if (StrUtil.isNotBlank(config.getOrderType())) {
            info.setOrderType(JSONArray.parseArray(config.getOrderType()).toList(String.class));
        }

        return info;
    }

    @Override
    public Boolean edit(Long shopId, MkDrainageConfigDTO config) {
        MkDrainageConfig info = getOne(new QueryWrapper().eq(MkDrainageConfig::getShopId, shopId));
        BeanUtil.copyProperties(config, info);
        if (config.getOrderType() != null) {
            info.setOrderType(JSONArray.toJSONString(config.getOrderType()));
        }
        return updateById(info);
    }


}
