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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.dto.shop.ShopPrintLogDTO;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mybatis.mapper.TbPrintMachineLogMapper;
import cn.ysk.cashier.mybatis.mapper.TbPrintMachineMapper;
import cn.ysk.cashier.pojo.shop.TbPrintMachineEntity;
import cn.ysk.cashier.pojo.shop.TbPrintMachineLogEntity;
import cn.ysk.cashier.service.shop.ShopPrintLogService;
import cn.ysk.cashier.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 店铺小票打印记录ServiceImpl
 *
 * @author tankaikai
 * @since 2024-10-8 17:10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopPrintLogServiceImpl extends ServiceImpl<TbPrintMachineLogMapper, TbPrintMachineLogEntity> implements ShopPrintLogService {

    private final TbPrintMachineMapper tbPrintMachineMapper;

    private QueryWrapper<TbPrintMachineLogEntity> getWrapper(Map<String, Object> params) {
        TbPrintMachineLogEntity entity = BeanUtil.toBean(params, TbPrintMachineLogEntity.class);

        QueryWrapper<TbPrintMachineLogEntity> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(entity.getId() != null, TbPrintMachineLogEntity::getId, entity.getId());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getShopId()), TbPrintMachineLogEntity::getShopId, entity.getShopId());
        wrapper.lambda().likeRight(StrUtil.isNotEmpty(entity.getName()), TbPrintMachineLogEntity::getName, entity.getName());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getConnectionType()), TbPrintMachineLogEntity::getConnectionType, entity.getConnectionType());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getContentType()), TbPrintMachineLogEntity::getContentType, entity.getContentType());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getSubType()), TbPrintMachineLogEntity::getSubType, entity.getSubType());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getAddress()), TbPrintMachineLogEntity::getAddress, entity.getAddress());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getPort()), TbPrintMachineLogEntity::getPort, entity.getPort());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getReceiptSize()), TbPrintMachineLogEntity::getReceiptSize, entity.getReceiptSize());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getClassifyPrint()), TbPrintMachineLogEntity::getClassifyPrint, entity.getClassifyPrint());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getTablePrint()), TbPrintMachineLogEntity::getTablePrint, entity.getTablePrint());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getPrintQty()), TbPrintMachineLogEntity::getPrintQty, entity.getPrintQty());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getPrintMethod()), TbPrintMachineLogEntity::getPrintMethod, entity.getPrintMethod());
        wrapper.lambda().like(StrUtil.isNotEmpty(entity.getPrintType()), TbPrintMachineLogEntity::getPrintType, entity.getPrintType());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getPrintReceipt()), TbPrintMachineLogEntity::getPrintReceipt, entity.getPrintReceipt());
        wrapper.lambda().eq(entity.getFailFlag() != null, TbPrintMachineLogEntity::getFailFlag, entity.getFailFlag());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getRespCode()), TbPrintMachineLogEntity::getRespCode, entity.getRespCode());
        wrapper.lambda().like(StrUtil.isNotEmpty(entity.getRespMsg()), TbPrintMachineLogEntity::getRespMsg, entity.getRespMsg());
        wrapper.lambda().eq(entity.getCreateUserId() != null, TbPrintMachineLogEntity::getCreateUserId, entity.getCreateUserId());
        wrapper.lambda().like(StrUtil.isNotEmpty(entity.getCreateUserName()), TbPrintMachineLogEntity::getCreateUserName, entity.getCreateUserName());
        wrapper.lambda().eq(StrUtil.isNotEmpty(entity.getBizType()), TbPrintMachineLogEntity::getBizType, entity.getBizType());
        wrapper.lambda().orderByDesc(TbPrintMachineLogEntity::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<TbPrintMachineLogEntity> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), getWrapper(params));
        List<ShopPrintLogDTO> list = new ArrayList<>();
        Optional.ofNullable(page).map(Page::getRecords)
                .ifPresent(itemList -> {
                    for (TbPrintMachineLogEntity item : itemList) {
                        list.add(convertToDTO(item));
                    }
                });
        return PageUtil.toPlusPage(list, Convert.toInt(page.getTotal()));
    }

    @Override
    @Async
    public void saveByConfigId(Integer configId, String printContent, boolean success, Date printTime, Long userId, String userName) {
        Optional.ofNullable(configId).filter(Objects::nonNull).orElseThrow(() -> new BadRequestException("店铺打印机配置ID不能为空"));
        TbPrintMachineEntity configEntity = tbPrintMachineMapper.selectById(configId);
        Optional.ofNullable(configEntity).filter(Objects::nonNull).orElseThrow(() -> new BadRequestException("未找到对应的打印机配置数据"));
        TbPrintMachineLogEntity entity = BeanUtil.copyProperties(configEntity, TbPrintMachineLogEntity.class);
        entity.setPrintContent(printContent);
        entity.setCreateTime(printTime);
        entity.setFailFlag(success ? 0 : 1);
        entity.setCreateUserId(userId);
        entity.setCreateUserName(userName);
        super.save(entity);
    }

    @Override
    @Async
    public void save(ShopPrintLogDTO dto) {
        TbPrintMachineLogEntity entity = BeanUtil.copyProperties(dto, TbPrintMachineLogEntity.class);
        super.save(entity);
    }

    private ShopPrintLogDTO convertToDTO(TbPrintMachineLogEntity entity) {
        ShopPrintLogDTO dto = BeanUtil.copyProperties(entity, ShopPrintLogDTO.class);
        /**
        Dict connectionType = Dict.of("local", "本地打印机", "USB", "USB打印机", "network", "网络打印机");
        Dict contentType = Dict.of("local", "本地", "printer", "USB", "yxyPrinter", "云想印", "fePrinter", "飞鹅");
        Dict subType = Dict.of("label", "标签", "kitchen", "出品", "cash", "小票");
        Dict classifyPrint = Dict.of("0", "打印所有", "1", "部分分类", "2", "部分商品");
        Dict tablePrint = Dict.of("0", "打印所有", "1", "打印部分桌台");
        Dict printQty = Dict.of("c1m1^2", "顾客+商家[2张]", "m1^1", "商家[1张]", "c1^1", "顾客[1张]", "c2m1^3", "顾客2+商家1[3张]");
        Dict printMethod = Dict.of("1", "普通", "2", "单个菜");
        Dict printType = Dict.of("1", "确认退款单", "2", "交班单", "3", "排队取号");
        Dict printReceipt = Dict.of("0", "全部打印", "1", "仅厨房", "2", "仅前台");
         */
        Dict failFlag = Dict.of("0", "成功", "1", "失败");
        //dto.setConnectionType(connectionType.getStr(dto.getConnectionType()));
        //dto.setContentType(contentType.getStr(dto.getContentType()));
        //dto.setSubType(subType.getStr(dto.getSubType()));
        //dto.setClassifyPrint(classifyPrint.getStr(dto.getClassifyPrint()));
        //dto.setTablePrint(tablePrint.getStr(dto.getTablePrint()));
        //dto.setPrintQty(printQty.getStr(dto.getPrintQty()));
        //dto.setPrintMethod(printMethod.getStr(dto.getPrintMethod()));
        //dto.setPrintType(printType.getStr(dto.getPrintType()));
        //dto.setPrintReceipt(printReceipt.getStr(dto.getPrintReceipt()));
        dto.setPrintResult(failFlag.getStr(dto.getFailFlag() + ""));
        dto.setFailReason(dto.getRespMsg());
        return dto;
    }


}
