package com.prolog.rdc.tms.service.print.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.ibatis.plugin.PluginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.dao.mapper.PrinterConfigurationMapper;
import com.prolog.rdc.tms.model.dto.print.PrinterBatchConfigInfoDTO;
import com.prolog.rdc.tms.model.dto.print.PrinterBatchConfigurationDTO;
import com.prolog.rdc.tms.model.dto.print.PrinterBatchTemplateDTO;
import com.prolog.rdc.tms.model.dto.print.PrinterConfigInfoDTO;
import com.prolog.rdc.tms.model.dto.print.PrinterConfigurationDTO;
import com.prolog.rdc.tms.model.dto.print.PrinterTemplateDTO;
import com.prolog.rdc.tms.model.entity.line.PrinterConfiguration;
import com.prolog.rdc.tms.model.entity.line.PrinterRoute;
import com.prolog.rdc.tms.model.entity.line.PrinterTemplate;
import com.prolog.rdc.tms.model.vo.print.DeleteSysPrinterVO;
import com.prolog.rdc.tms.model.vo.print.PrinterBatchConfigInfoVO;
import com.prolog.rdc.tms.model.vo.print.PrinterConfigInfoVO;
import com.prolog.rdc.tms.model.vo.print.PrinterConfigurationVO;
import com.prolog.rdc.tms.model.vo.print.QuerySysPrinterConfigurationVO;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.print.PrinterConfigurationService;
import com.prolog.rdc.tms.service.print.PrinterRouteService;
import com.prolog.rdc.tms.service.print.PrinterTemplateService;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;

/**
 * 
 *
 * 打印机配置实现层
 *
 * @className :PrinterConfigurationServiceImpl
 * @author :fanzw
 * @creationTime :2022/11/21
 * @description :
 *
 * @modifier :fanzw
 * @modifyTime :2022/11/21
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Service
public class PrinterConfigurationServiceImpl implements PrinterConfigurationService {

	private final Logger logger = LoggerFactory.getLogger(PrinterConfigurationServiceImpl.class);

	@Autowired
	private PrinterConfigurationMapper service;

	@Autowired
	private PrinterRouteService printerRouteService;

	@Autowired
	private PrinterTemplateService printerTemplateService;

	@Autowired
	private SysRefdatadService sysRefdatadService;

	/**
	 * @Decription 新增打印机配置
	 * @param vo 新增入参
	 */
	@Override
	public void save(PrinterConfigurationVO vo) {
		logger.info("打印机配置新增入参：" + JSONObject.toJSONString(vo));
		// 1.重复校验,通过编码和名称查询是否有打印机信息
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		List<PrinterConfiguration> modelList = service.findByCodeAndName(vo.getPrinterCode(), vo.getPrinterName(), null, user.getEnterpriseId());
		if (CollUtil.isNotEmpty(modelList) && modelList.size() > 0) {
			throw new PluginException("打印机编码已存在，不要重复添加");
		}
		PrinterConfiguration model = new PrinterConfiguration();
		DateTime currentDate = DateUtil.date();
		BeanUtils.copyProperties(vo, model);
		model.setCreatedBy(user.getNickname());
		model.setCreatedDate(currentDate);
		model.setLastModifiedBy(user.getNickname());
		model.setLastModifiedDate(currentDate);
		model.setEnterpriseId(user.getEnterpriseId());
		model.setEnterpriseName(user.getEnterpriseName());
		service.save(model);
	}

	/**
	 * 修改打印机
	 * 
	 * @param vo 修改参数
	 */
	@Override
	public void update(PrinterConfigurationVO vo) {
		Assert.notNull(vo.getId(), "打印机ID不能为空");
		// 1.重复校验,通过编码和名称查询是否有打印机信息
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		List<PrinterConfiguration> modelList = service.findByCodeAndName(vo.getPrinterCode(), vo.getPrinterName(), vo.getId(), user.getEnterpriseId());
		if (CollUtil.isNotEmpty(modelList) && modelList.size() > 0) {
			throw new PluginException("打印机编码已存在，不要重复添加");
		}
		PrinterConfiguration model = service.findByNativeId(vo.getId(), user.getEnterpriseId());
		Assert.notNull(model, "打印机信息为空");
		BeanUtils.copyProperties(vo, model);
		// 更新操作
		model.setLastModifiedBy(user.getNickname());
		model.setLastModifiedDate(DateUtil.date());
		service.update(model);
	}

	/**
	 * 打印机列表查询
	 * 
	 * @param vo 查询条件
	 * @return page
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<PrinterConfigurationDTO> findList(QuerySysPrinterConfigurationVO vo) throws Exception {
		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		List<PrinterConfiguration> list = service.findList(vo, user.getEnterpriseId());

		List<Map<String, Object>> list1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.SYS_PRINTER_STATUS, null, null, null);
		List<Map<String, Object>> list2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.SYS_PRINTER_TYPE, null, null, null);

		List<PrinterConfigurationDTO> dtoList = Lists.newArrayList();
		for (PrinterConfiguration model : list) {
			PrinterConfigurationDTO dto = new PrinterConfigurationDTO();
			BeanUtils.copyProperties(model, dto);

			dto.setPrinterStatusName(PublicMethods.change(list1, model.getPrinterStatus()));
			dto.setPrinterTypeName(PublicMethods.change(list2, model.getPrinterType()));

			dtoList.add(dto);
		}

		// 分页设置
		Page<PrinterConfigurationDTO> page = PageUtils.getPage(dtoList);
		if (list instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<PrinterConfiguration> p0 = (com.github.pagehelper.Page<PrinterConfiguration>) list;
			page.setPageCount(p0.getPages());
			page.setPageNum(p0.getPageNum());
			page.setPageSize(p0.getPageSize());
			page.setTotalCount(p0.getTotal());
			page.setStartRow(p0.getStartRow());
			page.setEndRow(p0.getEndRow());
		}
		return page;
	}

	// 删除
	@Override
	public void delete(DeleteSysPrinterVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();

		logger.info("删除入参:" + JSONObject.toJSONString(vo));

		service.delete(vo.getIds(), DateUtil.date(), user.getNickname());
	}

	// 获取详情
	@Override
	public PrinterConfigurationDTO detail(Long id) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		PrinterConfiguration model = service.findByNativeId(id, user.getEnterpriseId());
		Assert.notNull(model, "查询配置详情为空");
		PrinterConfigurationDTO dto = new PrinterConfigurationDTO();
		BeanUtils.copyProperties(model, dto);

		List<Map<String, Object>> list1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.SYS_PRINTER_STATUS, null, null, null);
		List<Map<String, Object>> list2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.SYS_PRINTER_TYPE, null, null, null);

		dto.setPrinterStatusName(PublicMethods.change(list1, model.getPrinterStatus()));
		dto.setPrinterTypeName(PublicMethods.change(list2, model.getPrinterType()));

		return dto;
	}

	@Override
	public List<PrinterConfigurationDTO> dropDownList(String printerName) throws Exception {
		List<PrinterConfiguration> list = service.dropDownList(printerName);

		List<Map<String, Object>> list1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.SYS_PRINTER_STATUS, null, null, null);
		List<Map<String, Object>> list2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.SYS_PRINTER_TYPE, null, null, null);

		List<PrinterConfigurationDTO> dtoList = Lists.newArrayList();
		if (ObjectUtil.isNull(list)) {
			return dtoList;
		}
		for (PrinterConfiguration model : list) {
			PrinterConfigurationDTO dto = new PrinterConfigurationDTO();
			BeanUtils.copyProperties(model, dto);

			dto.setPrinterStatusName(PublicMethods.change(list1, model.getPrinterStatus()));
			dto.setPrinterTypeName(PublicMethods.change(list2, model.getPrinterType()));

			dtoList.add(dto);
		}
		return dtoList;
	}

	@Override
	public PrinterConfigInfoDTO queryPrinterInfo(PrinterConfigInfoVO printerConfigInfoVO) {
		if (ObjectUtil.isEmpty(printerConfigInfoVO.getEmployeeId()) && ObjectUtil.isEmpty(printerConfigInfoVO.getTemplateCode())) {
			throw new PluginException("员工ID/模版编码不能同时为空");
		}
		PrinterConfigInfoDTO printerConfigInfoDTO = new PrinterConfigInfoDTO();
		if (ObjectUtil.isNotEmpty(printerConfigInfoVO.getEmployeeId())) {
			this.queryByEmployeeId(printerConfigInfoVO.getEmployeeId(), printerConfigInfoVO.getWarehouseId(), printerConfigInfoDTO);
		}
		if (ObjectUtil.isNotEmpty(printerConfigInfoVO.getTemplateCode())) {
			this.queryByTemplateCode(printerConfigInfoVO.getTemplateCode(), printerConfigInfoVO.getWarehouseId(), printerConfigInfoDTO, printerConfigInfoVO.getConsignorId());

		}
		return printerConfigInfoDTO;
	}

	private void queryByTemplateCode(String templateCode, Long warehouseId, PrinterConfigInfoDTO printerConfigInfoDTO, String consignorId) {
		List<PrinterTemplate> templates = printerTemplateService.findListByCode(templateCode, warehouseId, consignorId);
		if (ObjectUtil.isNotEmpty(templates)) {
			List<PrinterTemplateDTO> list = Lists.newArrayList();
			for (PrinterTemplate template : templates) {
				PrinterTemplateDTO templateDTO = new PrinterTemplateDTO();
				BeanUtils.copyProperties(template, templateDTO);
				list.add(templateDTO);
			}
			printerConfigInfoDTO.setTemplateList(list);
			printerConfigInfoDTO.setTemplateCode(templateCode);
		}
	}

	private void queryByEmployeeId(String employeeId, Long warehouseId, PrinterConfigInfoDTO printerConfigInfoDTO) {
		// 提供员工ID 获取到路由信息，对于的打印机信息
		List<PrinterRoute> printerRoutes = printerRouteService.findByEmployeeId(employeeId, warehouseId);
		if (ObjectUtil.isNotEmpty(printerRoutes)) {
			List<Long> printId = printerRoutes.stream().map(PrinterRoute::getPrinterId).collect(Collectors.toList());
			// 通过打印机ID 获取打印机信息
			List<PrinterConfiguration> printerConfigurations = service.findConfigurationByIds(printId);
			if (ObjectUtil.isNotEmpty(printerConfigurations)) {
				List<PrinterConfigurationDTO> configurationDTOS = Lists.newArrayList();
				for (PrinterConfiguration printerConfiguration : printerConfigurations) {
					PrinterConfigurationDTO dto = new PrinterConfigurationDTO();
					BeanUtils.copyProperties(printerConfiguration, dto);
					configurationDTOS.add(dto);
				}
				printerConfigInfoDTO.setConfigurations(configurationDTOS);
				printerConfigInfoDTO.setEmployeeId(employeeId);
			}
		}
	}

	@Override
	public PrinterBatchConfigInfoDTO queryBatchPrinterInfo(PrinterBatchConfigInfoVO printerConfigInfoVO) {
		PrinterBatchConfigInfoDTO printerBatchConfigInfoDTO = new PrinterBatchConfigInfoDTO();
		List<String> employeeIds = printerConfigInfoVO.getEmployeeId();
		List<String> templateCodes = printerConfigInfoVO.getTemplateCode();
		Long warehouseId = printerConfigInfoVO.getWarehouseId();
		// 提供员工ID查询
		if (ObjectUtil.isNotEmpty(employeeIds)) {
			List<PrinterBatchConfigurationDTO> printerBatchConfigurationDTO = Lists.newArrayList();
			for (String employeeId : employeeIds) {
				List<PrinterConfigurationDTO> configurations = Lists.newArrayList();
				PrinterBatchConfigurationDTO printerConfigInfoDTO = new PrinterBatchConfigurationDTO();
				this.queryByEmployeeIdForBatch(employeeId, warehouseId, configurations);
				printerConfigInfoDTO.setConfigurations(configurations);
				printerConfigInfoDTO.setEmployeeId(employeeId);
				printerBatchConfigurationDTO.add(printerConfigInfoDTO);
			}
			printerBatchConfigInfoDTO.setPrinterBatchConfigurationDTO(printerBatchConfigurationDTO);

		}
		// 提供模版查询
		if (ObjectUtil.isNotEmpty(templateCodes)) {
			List<PrinterBatchTemplateDTO> printerBatchTemplateDTO = Lists.newArrayList();
			for (String templateCode : templateCodes) {
				this.queryByTemplateCodeForBatch(templateCode, warehouseId, printerBatchTemplateDTO, printerConfigInfoVO.getConsignorId());
			}
			printerBatchConfigInfoDTO.setPrinterBatchTemplateDTO(printerBatchTemplateDTO);
		}

		return printerBatchConfigInfoDTO;
	}

	private void queryByTemplateCodeForBatch(String templateCode, Long warehouseId, List<PrinterBatchTemplateDTO> printerBatchTemplateDTO, String consignorId) {
		List<PrinterTemplate> templates = printerTemplateService.findListByCode(templateCode, warehouseId, consignorId);
		if (ObjectUtil.isNotEmpty(templates)) {
			PrinterBatchTemplateDTO printerConfigInfoDTO = new PrinterBatchTemplateDTO();
			PrinterTemplate printerTemplate = templates.get(0);
			BeanUtils.copyProperties(printerTemplate, printerConfigInfoDTO);
			printerConfigInfoDTO.setTemplateCode(printerTemplate.getPlanCode());
			printerConfigInfoDTO.setTemplateName(printerTemplate.getPlanName());
			printerBatchTemplateDTO.add(printerConfigInfoDTO);
		}
	}

	private void queryByEmployeeIdForBatch(String employeeId, Long warehouseId, List<PrinterConfigurationDTO> configurationDTOS) {
		// 提供员工ID 获取到路由信息，对于的打印机信息
		List<PrinterRoute> printerRoutes = printerRouteService.findByEmployeeId(employeeId, warehouseId);
		if (ObjectUtil.isNotEmpty(printerRoutes)) {
			List<Long> printId = printerRoutes.stream().map(PrinterRoute::getPrinterId).collect(Collectors.toList());
			// 通过打印机ID 获取打印机信息
			List<PrinterConfiguration> printerConfigurations = service.findConfigurationByIds(printId);
			if (ObjectUtil.isNotEmpty(printerConfigurations)) {
				for (PrinterConfiguration printerConfiguration : printerConfigurations) {
					PrinterConfigurationDTO dto = new PrinterConfigurationDTO();
					BeanUtils.copyProperties(printerConfiguration, dto);
					configurationDTOS.add(dto);
				}
			}
		}
	}
}