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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.ysk.cashier.dto.shop.ShopPrinterDTO;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mybatis.mapper.TbPrintMachineMapper;
import cn.ysk.cashier.pojo.shop.TbPrintMachineEntity;
import cn.ysk.cashier.service.shop.ShopPrinterService;
import cn.ysk.cashier.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 店铺打印机配置ServiceImpl
 *
 * @author tankaikai
 * @since 2024-09-25 13:53
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopPrinterServiceImpl extends ServiceImpl<TbPrintMachineMapper, TbPrintMachineEntity> implements ShopPrinterService {

    private QueryWrapper<TbPrintMachineEntity> getWrapper(Map<String, Object> params) {

        MapProxy mapProxy = MapProxy.create(params);
        QueryWrapper<TbPrintMachineEntity> wrapper = new QueryWrapper<>();

        String shopId = mapProxy.getStr("shopId");
        wrapper.lambda().eq(StrUtil.isNotEmpty(shopId), TbPrintMachineEntity::getShopId, shopId);
        String name = mapProxy.getStr("name");
        wrapper.lambda().likeRight(StrUtil.isNotEmpty(name), TbPrintMachineEntity::getName, name);
        String type = mapProxy.getStr("type");
        wrapper.lambda().eq(StrUtil.isNotEmpty(type), TbPrintMachineEntity::getType, type);
        String connectionType = mapProxy.getStr("connectionType");
        wrapper.lambda().eq(StrUtil.isNotEmpty(connectionType), TbPrintMachineEntity::getConnectionType, connectionType);
        String address = mapProxy.getStr("address");
        wrapper.lambda().eq(StrUtil.isNotEmpty(address), TbPrintMachineEntity::getAddress, address);
        String port = mapProxy.getStr("port");
        wrapper.lambda().eq(StrUtil.isNotEmpty(port), TbPrintMachineEntity::getPort, port);
        String subType = mapProxy.getStr("subType");
        wrapper.lambda().eq(StrUtil.isNotEmpty(subType), TbPrintMachineEntity::getSubType, subType);
        Integer status = mapProxy.getInt("status");
        wrapper.lambda().eq(ObjectUtil.isNotNull(status), TbPrintMachineEntity::getStatus, status);
        String categoryIds = mapProxy.getStr("categoryIds");
        wrapper.lambda().eq(StrUtil.isNotEmpty(categoryIds), TbPrintMachineEntity::getCategoryIds, categoryIds);
        String contentType = mapProxy.getStr("contentType");
        wrapper.lambda().eq(StrUtil.isNotEmpty(contentType), TbPrintMachineEntity::getContentType, contentType);
        String config = mapProxy.getStr("config");
        wrapper.lambda().eq(StrUtil.isNotEmpty(config), TbPrintMachineEntity::getConfig, config);
        String categoryList = mapProxy.getStr("categoryList");
        wrapper.lambda().eq(StrUtil.isNotEmpty(categoryList), TbPrintMachineEntity::getCategoryList, categoryList);
        String vendorId = mapProxy.getStr("vendorId");
        wrapper.lambda().eq(StrUtil.isNotEmpty(vendorId), TbPrintMachineEntity::getVendorId, vendorId);
        String productId = mapProxy.getStr("productId");
        wrapper.lambda().eq(StrUtil.isNotEmpty(productId), TbPrintMachineEntity::getProductId, productId);

        wrapper.lambda().orderByAsc(TbPrintMachineEntity::getSort);
        wrapper.lambda().orderByDesc(TbPrintMachineEntity::getId);

        return wrapper;
    }

    @Override
    public Map<String, Object> page(Map<String, Object> params) {
        MapProxy mapProxy = MapProxy.create(params);
        int pageNum = mapProxy.getInt("page", 1);
        int pageSize = mapProxy.getInt("size", 10);
        Page<TbPrintMachineEntity> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), getWrapper(params));
        List<ShopPrinterDTO> list = BeanUtil.copyToList(page.getRecords(), ShopPrinterDTO.class);
        return PageUtil.toPlusPage(list, Convert.toInt(page.getTotal()));
    }

    @Override
    public List<ShopPrinterDTO> list(Map<String, Object> params) {
        List<TbPrintMachineEntity> list = baseMapper.selectList(getWrapper(params));
        return BeanUtil.copyToList(list, ShopPrinterDTO.class);
    }

    @Override
    public ShopPrinterDTO get(Integer id) {
        TbPrintMachineEntity entity = baseMapper.selectById(id);
        return BeanUtil.toBean(entity, ShopPrinterDTO.class);
    }

    @Override
    public void save(ShopPrinterDTO dto) {
        CopyOptions options = new CopyOptions();
        options.setIgnoreProperties("createdAt", "updatedAt");
        //分类打印选择部分打印时必传，JsonArray字符串数据 如：[{"id":125,"name":"意式咖啡"},{"id":127,"name":"饮品"}]
        if ("1".equals(dto.getClassifyPrint()) || "2".equals(dto.getClassifyPrint())) {
            if (StrUtil.isBlank(dto.getCategoryList())) {
                throw new BadRequestException("分类打印选择部分打印时，必须勾选需要部分打印的菜品");
            }
            if (!JSONUtil.isTypeJSONArray(dto.getCategoryList())) {
                throw new BadRequestException("传递的部分打印菜品数据不合法");
            }
            if (StrUtil.isBlank(dto.getCategoryIds())) {
                throw new BadRequestException("分类打印选择部分打印时，传递的部分打印菜品id数据不能为空");
            }
        } else {
            dto.setCategoryIds(null);
            dto.setCategoryList(null);
        }
        TbPrintMachineEntity entity = BeanUtil.toBean(dto, TbPrintMachineEntity.class, options);
        entity.setCreatedAt(System.currentTimeMillis());
        entity.setUpdatedAt(System.currentTimeMillis());
        baseMapper.insert(entity);
    }

    @Override
    public void update(ShopPrinterDTO dto) {
        TbPrintMachineEntity entity = baseMapper.selectById(dto.getId());
        CopyOptions options = new CopyOptions();
        options.setIgnoreProperties("createdAt", "updatedAt");
        //分类打印选择部分打印时必传，JsonArray字符串数据 如：[{"id":125,"name":"意式咖啡"},{"id":127,"name":"饮品"}]
        if ("1".equals(dto.getClassifyPrint()) || "2".equals(dto.getClassifyPrint())) {
            if (StrUtil.isBlank(dto.getCategoryList())) {
                throw new BadRequestException("分类打印选择部分打印时，必须勾选需要部分打印的菜品");
            }
            if (!JSONUtil.isTypeJSONArray(dto.getCategoryList())) {
                throw new BadRequestException("传递的部分打印菜品数据不合法");
            }
            if (StrUtil.isBlank(dto.getCategoryIds())) {
                throw new BadRequestException("分类打印选择部分打印时，传递的部分打印菜品id数据不能为空");
            }
        } else {
            dto.setCategoryIds(null);
            dto.setCategoryList(null);
        }
        BeanUtil.copyProperties(dto, entity, options);
        entity.setUpdatedAt(System.currentTimeMillis());
        baseMapper.updateById(entity);
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        baseMapper.update(null, new LambdaUpdateWrapper<TbPrintMachineEntity>()
                .set(TbPrintMachineEntity::getStatus, status).eq(TbPrintMachineEntity::getId, id));
    }

}
