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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.czg.account.dto.print.PrinterAddDTO;
import com.czg.account.dto.print.PrinterEditDTO;
import com.czg.account.entity.PrintMachine;
import com.czg.account.service.PrintMachineService;
import com.czg.exception.ApiNotPrintException;
import com.czg.service.account.mapper.PrintMachineMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;

/**
 * 打印机设备 服务层实现。
 *
 * @author zs
 * @since 2025-02-20
 */
@DubboService
public class PrintMachineServiceImpl extends ServiceImpl<PrintMachineMapper, PrintMachine> implements PrintMachineService{

    @Override
    public boolean add(Long shopId, PrinterAddDTO dto) {
        //分类打印选择部分打印时必传，JsonArray字符串数据 如：[{"id":125,"name":"意式咖啡"},{"id":127,"name":"饮品"}]
        if ("1".equals(dto.getClassifyPrint()) || "2".equals(dto.getClassifyPrint())) {
            if (StrUtil.isBlank(dto.getCategoryList())) {
                throw new ApiNotPrintException("分类打印选择部分打印时，必须勾选需要部分打印的菜品");
            }
            if (!JSONUtil.isTypeJSONArray(dto.getCategoryList())) {
                throw new ApiNotPrintException("传递的部分打印菜品数据不合法");
            }
            if (StrUtil.isBlank(dto.getCategoryIds())) {
                throw new ApiNotPrintException("分类打印选择部分打印时，传递的部分打印菜品id数据不能为空");
            }
        } else {
            dto.setCategoryIds(null);
            dto.setCategoryList(null);
        }
        PrintMachine entity = BeanUtil.copyProperties(dto, PrintMachine.class);
        entity.setShopId(shopId);
        return save(entity);
    }

    @Override
    public Boolean edit(Long shopId, PrinterEditDTO printerEditDTO) {
        PrintMachine printMachine = getOne(new QueryWrapper().eq(PrintMachine::getShopId, shopId).eq(PrintMachine::getId, printerEditDTO.getId()));
        if (printMachine == null) {
            throw new ApiNotPrintException("打印机不存在");
        }

        BeanUtil.copyProperties(printerEditDTO, printMachine);
        return updateById(printMachine);
    }
}
