package cn.ysk.cashier.service.impl.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.dto.freedine.UpdateFreeDineConfigDTO;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mybatis.entity.TbFreeDineConfig;
import cn.ysk.cashier.mybatis.service.TbFreeDineConfigService;
import cn.ysk.cashier.service.app.TbFreeDineService;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class TbFreeDineServiceImpl implements TbFreeDineService {
    private final TbFreeDineConfigService freeDineConfigService;

    @Override
    public TbFreeDineConfig getConfig(Integer shopId) {
        TbFreeDineConfig freeDineConfig = freeDineConfigService.getByShopId(shopId);
        if (freeDineConfig == null) {
            freeDineConfig = new TbFreeDineConfig();
            freeDineConfig.setShopId(shopId);
            freeDineConfig.setCreateTime(DateUtil.date());
            freeDineConfigService.save(freeDineConfig);
        }

        if (StrUtil.isNotBlank(freeDineConfig.getUseType())) {
            freeDineConfig.setUseTypeList(JSONObject.parseArray(freeDineConfig.getUseType()).toJavaList(String.class    ));
        }
        return freeDineConfig;
    }

    @Override
    public TbFreeDineConfig updateConfig(UpdateFreeDineConfigDTO updateFreeDineConfigDTO) {
        TbFreeDineConfig config = freeDineConfigService.getByIdAndShopId(updateFreeDineConfigDTO.getId(), updateFreeDineConfigDTO.getShopId());
        if (config == null) {
            throw new BadRequestException("霸王餐信息未配置");
        }
        BeanUtil.copyProperties(updateFreeDineConfigDTO, config);
        config.setUpdateTime(DateUtil.date());
        if (updateFreeDineConfigDTO.getUseTypeList() != null) {
            config.setUseType(JSONObject.toJSONString(updateFreeDineConfigDTO.getUseTypeList()));
        }
        freeDineConfigService.updateById(config);
        return config;
    }
}
