/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package cn.ysk.cashier.service.impl.shopimpl;

import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.pojo.shop.TbPrintMachine;
import cn.ysk.cashier.dto.shop.PrintMachineDto;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.ListUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import cn.ysk.cashier.vo.TbPrintMachineVO;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.repository.shop.TbPrintMachineRepository;
import cn.ysk.cashier.service.shop.TbPrintMachineService;
import cn.ysk.cashier.dto.shop.TbPrintMachineDto;
import cn.ysk.cashier.dto.shop.TbPrintMachineQueryCriteria;
import cn.ysk.cashier.mapper.shop.TbPrintMachineMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author lyf
* @date 2024-02-28
**/
@Service
@RequiredArgsConstructor
public class TbPrintMachineServiceImpl implements TbPrintMachineService {

    private final TbPrintMachineRepository tbPrintMachineRepository;
    private final TbPrintMachineMapper tbPrintMachineMapper;

    @Override
    public List<TbPrintMachineVO> queryAll(TbPrintMachineQueryCriteria criteria, Pageable pageable){
        Page<TbPrintMachine> page = tbPrintMachineRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<TbPrintMachineVO> printMachineVOList = new ArrayList<>();
        for (TbPrintMachine dtoData : page.getContent()) {
            TbPrintMachineVO tbPrintMachineVO = new TbPrintMachineVO();
            if (dtoData.getConfig() != null){
                tbPrintMachineVO.setConfig(ListUtil.stringToJSONObject(dtoData.getConfig()));
            }
            BeanUtils.copyProperties(dtoData,tbPrintMachineVO);
            printMachineVOList.add(tbPrintMachineVO);
        }
        return printMachineVOList;
    }

//    @Override
//    public List<TbPrintMachineDto> queryAll(TbPrintMachineQueryCriteria criteria){
//        List<TbPrintMachineDto> dto = tbPrintMachineMapper.toDto(tbPrintMachineRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
//        List<TbPrintMachineVO> printMachineVOList = new ArrayList<>();
//        for (TbPrintMachineDto dtoData : dto) {
//            TbPrintMachineVO tbPrintMachineVO = new TbPrintMachineVO();
//            if (dtoData.getConfig() != null){
//                tbPrintMachineVO.setConfig(ListUtil.stringChangeList(dtoData.getConfig()));
//            }
//            BeanUtils.copyProperties(dtoData,tbPrintMachineVO);
//            printMachineVOList.add(tbPrintMachineVO);
//        }
//        return printMachineVOList;
//    }

    @Override
    @Transactional
    public TbPrintMachineVO findById(Integer id) {
        TbPrintMachine tbPrintMachine = tbPrintMachineRepository.findById(id).orElseGet(TbPrintMachine::new);
        if (tbPrintMachine.getId() == null){
            throw new BadRequestException("数据有误");
        }
        TbPrintMachineVO tbPrintMachineVO = new TbPrintMachineVO();
        if (tbPrintMachine.getConfig() != null){
            tbPrintMachineVO.setConfig(ListUtil.stringToJSONObject(tbPrintMachine.getConfig()));
        }
        BeanUtils.copyProperties(tbPrintMachine,tbPrintMachineVO);
        ValidationUtil.isNull(tbPrintMachine.getId(),"TbPrintMachine","id",id);
        return tbPrintMachineVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbPrintMachine create(PrintMachineDto resources) {
        TbPrintMachine tbPrintMachine = new TbPrintMachine();
        resources.setCreatedAt(Instant.now().toEpochMilli());
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        if (resources.getConfig() != null){
            tbPrintMachine.setConfig(ListUtil.toString(resources.getConfig()));
        }
        BeanUtils.copyProperties(resources,tbPrintMachine);
        tbPrintMachine.setConnectionType("network");
        return tbPrintMachineRepository.save(tbPrintMachine);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PrintMachineDto resources) {
        TbPrintMachine tbPrintMachine = tbPrintMachineRepository.findById(resources.getId()).orElseGet(TbPrintMachine::new);
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        if (resources.getConfig() != null){
            tbPrintMachine.setConfig(ListUtil.toString(resources.getConfig()));
        }
        ValidationUtil.isNull( tbPrintMachine.getId(),"TbPrintMachine","id",resources.getId());
        BeanUtils.copyProperties(resources,tbPrintMachine);
        tbPrintMachineRepository.save(tbPrintMachine);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            tbPrintMachineRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TbPrintMachineDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbPrintMachineDto tbPrintMachine : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("设备名称", tbPrintMachine.getName());
            map.put("printer", tbPrintMachine.getType());
            map.put("现在打印机支持USB 和 网络、蓝牙", tbPrintMachine.getConnectionType());
            map.put("ip地址", tbPrintMachine.getAddress());
            map.put("端口", tbPrintMachine.getPort());
            map.put("打印类型（分类）", tbPrintMachine.getSubType());
            map.put("状态 online", tbPrintMachine.getStatus());
            map.put("店铺Id", tbPrintMachine.getShopId());
            map.put("分类Id", tbPrintMachine.getCategoryIds());
            map.put("现在打印机支持USB 和 网络两种", tbPrintMachine.getContentType());
            map.put("主配置", tbPrintMachine.getConfig());
            map.put(" createdAt",  tbPrintMachine.getCreatedAt());
            map.put(" updatedAt",  tbPrintMachine.getUpdatedAt());
            map.put("分类", tbPrintMachine.getCategoryList());
            map.put("排序", tbPrintMachine.getSort());
            map.put("Android打印机需要标识设备ID ", tbPrintMachine.getVendorId());
            map.put("Android打印机需要标识设备ID ", tbPrintMachine.getProductId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}