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

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.product.core.tools.util.JsonMapper;
import com.prolog.rdc.tms.config.enums.ImportObjEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.FieldSelector;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
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.BussinessConstant;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.dao.mapper.SysImportTempletdMapper;
import com.prolog.rdc.tms.dao.mapper.SysImportTemplethMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.ImportStdFeildQueryDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.StandardTemplateDetailsListDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysImportColDto;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysImportTempletdQueryDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysImportTemplethPageDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysImportTemplethQueryHdDTO;
import com.prolog.rdc.tms.model.entity.SysImportTempletdModel;
import com.prolog.rdc.tms.model.entity.SysImportTemplethModel;
import com.prolog.rdc.tms.model.vo.SysImportTempletdAddVO;
import com.prolog.rdc.tms.model.vo.SysImportTempletdUpdateVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.SysImportTemplethAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.SysImportTemplethPageVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.SysImportTemplethUpdateVO;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.basicConfigure.ImportStdFeildService;
import com.prolog.rdc.tms.service.basicConfigure.SysImportTemplethService;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.bean.BeanUtil;

/**
 *
 * 导入配置模板汇总 IMPL
 *
 *
 * @className: SysImportTemplethServiceImpl
 * @author: kh
 * @creationTime: 2022-01-12 10:12:37
 * @description:
 * @modifier:
 * @modifyTime:
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Service
public class SysImportTemplethServiceImpl implements SysImportTemplethService {

	@Resource
	private SysImportTempletdMapper sysImportTempletdMapper;

	@Resource
	private SysImportTemplethMapper sysImportTemplethMapper;

	@Autowired
	private SysCodeengineService sysCodeengineService;

	@Autowired
	private ImportStdFeildService importStdFeildService;

	@Autowired
	private SysRefdatadService sysRefdatadService;

	/**
	 * 根据汇总主键查询导入模板汇总和明细
	 *
	 * @param id
	 * @return {@link SysImportTemplethQueryHdDTO}
	 * @throws @date 2022/1/12 14:33
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public SysImportTemplethQueryHdDTO queryHd(Long id) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.WHETHER, null, null, null);

		// 查询汇总
		Criteria criteria = Criteria.forClass(SysImportTemplethModel.class);
		Restriction r1 = Restrictions.eq("hid", id);
		Restriction r2 = Restrictions.eq("templetStatus", BussinessConstant.ONE);
		Restriction r3 = ToolKits.isEmpty(user.getEnterpriseId()) ? null : Restrictions.eq("enterpriseId", user.getEnterpriseId());

		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		List<SysImportTemplethModel> hModels = sysImportTemplethMapper.findByCriteria(criteria);
		ToolKits.isParamNull(hModels, "导入模板不存在");

		SysImportTemplethQueryHdDTO hdto = new SysImportTemplethQueryHdDTO();
		BeanUtil.copyProperties(hModels.get(0), hdto);
		hdto.setStatusName(PublicMethods.change(restMessage1, String.valueOf(hdto.getStatus())));
		hdto.setId(hdto.getHid());

		// 查询明细，根据汇总主键
		Criteria dcriteria = Criteria.forClass(SysImportTempletdModel.class);
		Restriction dr1 = Restrictions.eq("hid", id);
		Restriction dr2 = Restrictions.eq("templetStatus", BussinessConstant.ONE);
		Restriction dr3 = ToolKits.isEmpty(user.getEnterpriseId()) ? null : Restrictions.eq("enterpriseId", user.getEnterpriseId());
		dcriteria.setRestriction(Restrictions.and(dr1, dr2, dr3));
		dcriteria.setOrder(Order.newInstance().asc(new String[] { "sort" }));
		List<SysImportTempletdModel> dmodels = sysImportTempletdMapper.findByCriteria(dcriteria);
		ToolKits.isParamNull(dmodels, "导入模板明细不存在");
		List<SysImportTempletdQueryDTO> ddtos = dmodels.stream().map(m -> {
			SysImportTempletdQueryDTO ddto = new SysImportTempletdQueryDTO();
			BeanUtil.copyProperties(m, ddto);
			ddto.setStatusName(PublicMethods.change(restMessage1, String.valueOf(ddto.getStatus())));
			ddto.setFieldid(m.getDid());
			return ddto;
		}).collect(Collectors.toList());
		hdto.setList(ddtos);
		return hdto;
	}

	/**
	 * 根据对象编号查询当前用户下，启用的导入模板汇总信息
	 *
	 * @param importObjNo 导入对象
	 * @return {@link SysImportTemplethQueryHdDTO}
	 * @throws @date 2022/1/17 10:37
	 */
	@Override
	public SysImportTemplethQueryHdDTO queryTempleteh(String importObjNo, Long enterpriseId) {
		// 查询汇总
		Criteria criteria = Criteria.forClass(SysImportTemplethModel.class);
		Restriction r1 = Restrictions.eq("importObjNo", importObjNo);
		Restriction r2 = Restrictions.eq("status", BussinessConstant.ONE);
		Restriction r3 = Restrictions.eq("templetStatus", BussinessConstant.ONE);
		Restriction r4 = Restrictions.eq("enterpriseId", enterpriseId);

		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
		List<SysImportTemplethModel> hModels = sysImportTemplethMapper.findByCriteria(criteria);

		ToolKits.isParamNull(hModels, "导入模板不存在，请配置！");
		SysImportTemplethQueryHdDTO dto = new SysImportTemplethQueryHdDTO();
		BeanUtil.copyProperties(hModels.get(0), dto);
		return dto;
	}

	/**
	 * 分页查询导入模板汇总
	 *
	 * @param vo 分页查询条件vo
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Page<SysImportTemplethPageDTO> listPage(SysImportTemplethPageVO vo) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.WHETHER, null, null, null);

		Criteria criteria = Criteria.forClass(SysImportTemplethModel.class);
		Restriction r1 = ToolKits.isEmpty(vo.getImportObjNo()) ? null : Restrictions.eq("importObjNo", vo.getImportObjNo());
		Restriction r2 = ToolKits.isEmpty(vo.getImportObjName()) ? null : Restrictions.like("importObjName", "%" + vo.getImportObjName() + "%");
		Restriction r3 = ToolKits.isEmpty(user.getEnterpriseId()) ? null : Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r4 = Restrictions.eq("templetStatus", BussinessConstant.ONE);
		Restriction r5 = ToolKits.isEmpty(vo.getStatus()) ? null : Restrictions.eq("status", vo.getStatus());
		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));

		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		List<SysImportTemplethModel> models = sysImportTemplethMapper.findByCriteria(criteria);
		List<SysImportTemplethPageDTO> sysImportTemplethPageDTOs = Lists.newArrayList();
		for (SysImportTemplethModel sysImportTemplethModel : models) {
			SysImportTemplethPageDTO sysImportTemplethPageDTO = new SysImportTemplethPageDTO();
			BeanUtil.copyProperties(sysImportTemplethModel, sysImportTemplethPageDTO);
			sysImportTemplethPageDTO.setStatusName(PublicMethods.change(restMessage1, String.valueOf(sysImportTemplethPageDTO.getStatus())));
			sysImportTemplethPageDTO.setId(sysImportTemplethPageDTO.getHid());

			sysImportTemplethPageDTOs.add(sysImportTemplethPageDTO);
		}

		Page<SysImportTemplethPageDTO> page = PageUtils.getPage(sysImportTemplethPageDTOs);
		if (models instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<SysImportTemplethModel> p0 = (com.github.pagehelper.Page<SysImportTemplethModel>) models;
			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;
	}

	/**
	 * 保存导入模板明细和汇总
	 *
	 * @param vo
	 * @return
	 * @throws @date 2022/1/12 15:11
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(SysImportTemplethAddVO vo) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		if (!ImportObjEnum.SHIPBILL_IMPORT.name().equals(vo.getImportObjNo())) {
			Map<String, Long> validCustNameMap = vo.getList().stream().collect(Collectors.groupingBy(SysImportTempletdAddVO::getCustColName, Collectors.counting()));
			for (Map.Entry<String, Long> longEntry : validCustNameMap.entrySet()) {
				if (longEntry.getValue() > 1) {
					throw new ParameterException(String.format("自定义列名称，[%s]重复", longEntry.getKey()));
				}
			}
			if (vo.getStatus().equals(BussinessConstant.ONE)) {
				// 如果是开启，查询该用户下的同一个企业下，是否有开启并且导入对象相同的数据。
				this.queryValidRepeat(user, vo.getImportObjNo(), vo.getTempleteName(), vo.getImportObjName(), null);
			}
		}
		// 验证名称是否重复
		this.queryValidTemplteName(vo.getTempleteName(), "");
		SysImportTemplethModel hmodel = new SysImportTemplethModel();
		BeanUtil.copyProperties(vo, hmodel);
		// 获取 汇总主键
		String code = sysCodeengineService.getCodeNumberByCode(BussinessConstant.SYS_IMPORT_TEMPLETH_ID, "L");
		// 获取明细主键
		List<String> dcodes = sysCodeengineService.getCodeNumberByCodes(BussinessConstant.SYS_IMPORT_TEMPLETD_ID, "L", vo.getList().size());
		ToolKits.isParamNull(dcodes, "获取导入模板明细主键失败");
		hmodel.setHid(code);
		hmodel.setTempletStatus(BussinessConstant.ONE);
		hmodel.setCreateby(user.getUserid());
		hmodel.setCreateperson(user.getNickname());
		hmodel.setCreatetime(new Date());
		hmodel.setUpdateby(hmodel.getCreateby());
		hmodel.setUpdateperson(hmodel.getCreateperson());
		hmodel.setUpdatetime(hmodel.getCreatetime());
		hmodel.setEnterpriseId(user.getEnterpriseId());
		hmodel.setEnterpriseName(user.getEnterpriseName());
		// 保存导入模板汇总数据
		sysImportTemplethMapper.save(hmodel);
		// 保存导入模板明细
		List<SysImportTempletdModel> dmodels = new ArrayList<>();
		int didx = 0;
		for (SysImportTempletdAddVO sysImportTempletdAddVO : vo.getList()) {
			SysImportTempletdModel dmodel = new SysImportTempletdModel();
			BeanUtil.copyProperties(sysImportTempletdAddVO, dmodel);
			dmodel.setDid(dcodes.get(didx));
			dmodel.setHid(hmodel.getHid());
			dmodel.setStatus(hmodel.getStatus());
			dmodel.setImportObjNo(hmodel.getImportObjNo());
			dmodel.setImportObjName(hmodel.getImportObjName());
			dmodel.setTempletStatus(BussinessConstant.ONE);
			dmodel.setCreateby(hmodel.getCreateby());
			dmodel.setCreateperson(hmodel.getCreateperson());
			dmodel.setCreatetime(hmodel.getCreatetime());
			dmodel.setUpdateby(hmodel.getCreateby());
			dmodel.setUpdateperson(hmodel.getCreateperson());
			dmodel.setUpdatetime(hmodel.getCreatetime());
			dmodel.setEnterpriseId(user.getEnterpriseId());
			dmodel.setEnterpriseName(user.getEnterpriseName());
			dmodel.setRequired(sysImportTempletdAddVO.getRequired());
			dmodel.setLabelType(sysImportTempletdAddVO.getLabelType());
			dmodel.setDefaultId(sysImportTempletdAddVO.getDefaultId());
			dmodel.setDefaultCode(sysImportTempletdAddVO.getDefaultCode());
			dmodel.setDefaultName(sysImportTempletdAddVO.getDefaultName());
			dmodel.setSort(didx + 1);
			didx++;
			dmodels.add(dmodel);
		}
		sysImportTempletdMapper.saveBatch(dmodels);
	}

	/**
	 * 更新导入模板汇总和明细
	 *
	 * @param vo
	 * @return
	 * @throws @date 2022/1/12 16:15
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysImportTemplethUpdateVO vo) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		SysImportTemplethModel hmodelByid = sysImportTemplethMapper.findById(vo.getHid(), SysImportTemplethModel.class);
		ToolKits.isParamNull(hmodelByid, "当前导入模板不存在");
		if (!ImportObjEnum.SHIPBILL_IMPORT.name().equals(hmodelByid.getImportObjNo())) {
			Map<String, Long> validCustNameMap = vo.getList().stream().collect(Collectors.groupingBy(SysImportTempletdUpdateVO::getCustColName, Collectors.counting()));
			for (Map.Entry<String, Long> longEntry : validCustNameMap.entrySet()) {
				if (longEntry.getValue() > 1) {
					throw new ParameterException(String.format("自定义列名称，[%s]重复", longEntry.getKey()));
				}
			}
			if (vo.getStatus().equals(BussinessConstant.ONE)) {
				// 如果是开启，查询该用户下的同一个企业下，是否有开启并且导入对象相同的数据。
				this.queryValidRepeat(user, hmodelByid.getImportObjNo(), hmodelByid.getTempleteName(), hmodelByid.getImportObjName(), vo.getHid());
			}
		}
		SysImportTemplethModel hmodel = new SysImportTemplethModel();
		BeanUtil.copyProperties(vo, hmodel);
		hmodel.setUpdateby(user.getUserid());
		hmodel.setUpdateperson(user.getNickname());
		hmodel.setUpdatetime(new Date());
		FieldSelector hfield = FieldSelector.newInstance().include(new String[] { "status", "updatetime", "updateby", "updateperson" });
		Criteria hupdate = Criteria.forClass(SysImportTemplethModel.class);
		hupdate.setRestriction(Restrictions.eq("hid", vo.getHid()));
		sysImportTemplethMapper.updateFieldsByCriteria(hmodel, hfield, hupdate);
		FieldSelector dfield = FieldSelector.newInstance().include(new String[] { "custColName", "status", "updatetime", "updateby", "updateperson", "defaultId", "defaultCode", "defaultName" });
		Criteria dupdate = Criteria.forClass(SysImportTempletdModel.class);
		for (SysImportTempletdUpdateVO dvo : vo.getList()) {
			SysImportTempletdModel dmodel = new SysImportTempletdModel();
			BeanUtil.copyProperties(dvo, dmodel);
			dmodel.setStatus(hmodel.getStatus());
			dmodel.setUpdateby(hmodel.getCreateby());
			dmodel.setUpdateperson(hmodel.getCreateperson());
			dmodel.setUpdatetime(hmodel.getCreatetime());
			dupdate.setRestriction(Restrictions.eq("did", dvo.getFieldid()));
			sysImportTempletdMapper.updateFieldsByCriteria(dmodel, dfield, dupdate);
		}

	}

	/**
	 * 验证是否重复
	 *
	 * @param user          用户
	 * @param importObjNo   导入对象编号
	 * @param templeteName  模板名称
	 * @param importObjName 导入对象名称
	 * @param hid           汇总主键
	 * @return
	 * @throws @date 2022/1/12 16:23
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void queryValidRepeat(UserEntity user, String importObjNo, String templeteName, String importObjName, Long hid) throws Exception {
		Criteria validCriteria = Criteria.forClass(SysImportTemplethModel.class);
		Restriction r1 = Restrictions.eq("importObjNo", importObjNo);
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r3 = Restrictions.eq("status", BussinessConstant.ONE);
		Restriction r4 = Restrictions.eq("templetStatus", BussinessConstant.ONE);
		validCriteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
		List<SysImportTemplethModel> hlist = sysImportTemplethMapper.findByCriteria(validCriteria);

		if (ToolKits.isNotEmpty(hlist)) {
			// 如果当前修改的是启用，则通过校验
			List<SysImportTemplethModel> idExistList = hlist.stream().filter(e -> e.getHid().equals(hid)).collect(Collectors.toList());
			if (ToolKits.isNotEmpty(idExistList)) {
				return;
			}

			throw new ParameterException(ToolKits.isEmpty(importObjName) ? String.format("模板%s已存在", templeteName) : String.format("【%s】已存在启用的导入模板【%s】，请先停用！", importObjName, hlist.get(0).getTempleteName()));
		}
	}

	/**
	 * 删除汇总和明细，逻辑删除，更新templetStatus为0
	 *
	 * @param ids
	 * @return
	 * @throws @date 2022/1/12 16:51
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String ids) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		String[] idarr = ids.split(",");
		for (String id : idarr) {
			SysImportTemplethModel hmodel = new SysImportTemplethModel();
			hmodel.setStatus(BussinessConstant.ZERO);
			hmodel.setTempletStatus(BussinessConstant.ZERO);
			hmodel.setUpdateby(user.getUserid());
			hmodel.setUpdateperson(user.getNickname());
			hmodel.setUpdatetime(new Date());
			FieldSelector hfield = FieldSelector.newInstance().include(new String[] { "status", "templetStatus", "updatetime", "updateby", "updateperson" });

			Criteria hupdate = Criteria.forClass(SysImportTemplethModel.class);
			hupdate.setRestriction(Restrictions.and(Restrictions.eq("hid", id), Restrictions.eq("templetStatus", BussinessConstant.ONE)));
			long h = sysImportTemplethMapper.updateFieldsByCriteria(hmodel, hfield, hupdate);
			if (h != 1) {
				throw new ParameterException("删除汇总异常");
			}

			FieldSelector dfield = FieldSelector.newInstance().include(new String[] { "status", "templetStatus", "updatetime", "updateby", "updateperson" });
			Criteria dupdate = Criteria.forClass(SysImportTempletdModel.class);
			dupdate.setRestriction(Restrictions.and(Restrictions.eq("hid", id), Restrictions.eq("templetStatus", BussinessConstant.ONE)));

			SysImportTempletdModel dmodel = new SysImportTempletdModel();
			dmodel.setStatus(BussinessConstant.ZERO);
			dmodel.setTempletStatus(BussinessConstant.ZERO);
			dmodel.setUpdateby(user.getUserid());
			dmodel.setUpdateperson(user.getNickname());
			dmodel.setUpdatetime(new Date());
			long d = sysImportTempletdMapper.updateFieldsByCriteria(dmodel, dfield, dupdate);

			if (d < 1) {
				throw new ParameterException("删除明细异常");
			}
		}

	}

	/**
	 * 启用或停用导入模板
	 *
	 * @param id     主键
	 * @param status 状态 0停用，1启用
	 * @return
	 * @throws @date 2022/1/12 17:14
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void enable(Long id, Integer status) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		SysImportTemplethModel valid = sysImportTemplethMapper.findById(id, SysImportTemplethModel.class);
		ToolKits.isParamNull(valid, "导入模板不存在");

		if (!ImportObjEnum.SHIPBILL_IMPORT.name().equals(valid.getImportObjNo())) {
			if (status.equals(BussinessConstant.ONE)) {
				this.queryValidRepeat(user, valid.getImportObjNo(), valid.getTempleteName(), valid.getImportObjName(), id);
			}
		}

		SysImportTemplethModel hmodel = new SysImportTemplethModel();
		hmodel.setStatus(status);
		hmodel.setUpdateby(user.getUserid());
		hmodel.setUpdateperson(user.getNickname());
		hmodel.setUpdatetime(new Date());
		FieldSelector hfield = FieldSelector.newInstance().include(new String[] { "status", "updatetime", "updateby", "updateperson" });

		Criteria hupdate = Criteria.forClass(SysImportTemplethModel.class);
		hupdate.setRestriction(Restrictions.and(Restrictions.eq("hid", id), Restrictions.eq("templetStatus", BussinessConstant.ONE)));
		long h = sysImportTemplethMapper.updateFieldsByCriteria(hmodel, hfield, hupdate);
		if (h != 1) {
			throw new ParameterException("更新汇总异常");
		}

		FieldSelector dfield = FieldSelector.newInstance().include(new String[] { "status", "updatetime", "updateby", "updateperson" });
		Criteria dupdate = Criteria.forClass(SysImportTempletdModel.class);
		dupdate.setRestriction(Restrictions.and(Restrictions.eq("hid", id), Restrictions.eq("templetStatus", BussinessConstant.ONE)));

		SysImportTempletdModel dmodel = new SysImportTempletdModel();
		dmodel.setStatus(status);
		dmodel.setUpdateby(user.getUserid());
		dmodel.setUpdateperson(user.getNickname());
		dmodel.setUpdatetime(new Date());
		long d = sysImportTempletdMapper.updateFieldsByCriteria(dmodel, dfield, dupdate);
		if (d < 1) {
			throw new ParameterException("更新明细异常");
		}
	}

	/**
	 * 验证同一公司下模板名称是否重复
	 *
	 * @param templeteName
	 * @return
	 * @throws @date 2022/1/12 17:53
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void queryValidTemplteName(String templeteName, String hid) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 验证同一公司下，模板名称是否已存在
		Criteria validCriteria = Criteria.forClass(SysImportTemplethModel.class);
		Restriction r2 = ToolKits.isEmpty(user.getEnterpriseId()) ? null : Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r4 = Restrictions.eq("templetStatus", BussinessConstant.ONE);
		Restriction r5 = Restrictions.eq("templeteName", templeteName);
		validCriteria.setRestriction(Restrictions.and(r2, r4, r5));

		List<SysImportTemplethModel> hlist2 = sysImportTemplethMapper.findByCriteria(validCriteria);
		if (ToolKits.isEmpty(hlist2)) {
			return;
		}
		// 当为新增时
		if (ToolKits.isEmpty(hid)) {
			if (ToolKits.isNotEmpty(hlist2)) {
				throw new ParameterException(String.format("模板%s已存在", templeteName));
			}
		} else {
			// 当为更新时，去除当前自己的
			long count = hlist2.stream().filter(m -> !m.getHid().equals(hid)).count();
			if (count > 0) {
				throw new ParameterException(String.format("模板%s已存在", templeteName));
			}
		}

	}

	/**
	 * 标准版模板详情查询
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<StandardTemplateDetailsListDTO> listStandardTemplateDetailsData(String importObjNo) {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Map<String, Object> queryMap = Maps.newHashMap();
		queryMap.put("importObjNo", importObjNo);
		queryMap.put("enterpriseid", user.getEnterpriseId());
		queryMap.put("status", BussinessConstant.ONE);
		List<SysImportTempletdModel> models = sysImportTempletdMapper.findByMap(queryMap, SysImportTempletdModel.class);
		ToolKits.isParamNull(models, "未查询到导入模板明细数据");

		return models.stream().sorted(Comparator.comparing(SysImportTempletdModel::getSort)).map(m -> {
			StandardTemplateDetailsListDTO standardTemplateDetailsListDTO = new StandardTemplateDetailsListDTO();
			BeanUtil.copyProperties(m, standardTemplateDetailsListDTO);
			return standardTemplateDetailsListDTO;
		}).collect(Collectors.toList());
	}

	/**
	 * 根据导入对象编号，查询标准导入字段列表，转换成界面表头对象
	 *
	 * @param importObjNo
	 * @return {@link List< SysImportColDto>}
	 * @throws @date 2022/1/17 15:22
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<SysImportColDto> listColumns(String importObjNo) throws Exception {
		List<ImportStdFeildQueryDTO> list = importStdFeildService.list(importObjNo);
		return list.stream().map(m -> {
			SysImportColDto dto = new SysImportColDto();
			dto.setText(m.getStdColName());
			dto.setValue(m.getStdColNo());
			return dto;
		}).collect(Collectors.toList());
	}

	@Override
	public void downloadTemplateById(Long templateId, HttpServletResponse response) throws Exception {
		SysImportTemplethQueryHdDTO dto = queryHd(templateId);
		List<SysImportTempletdQueryDTO> standardTemplateDetailsListDTOList = dto.getList();
		List<List<String>> headList = standardTemplateDetailsListDTOList.stream().map(SysImportTempletdQueryDTO::getCustColName).
				filter(StrUtil::isNotBlank).distinct().map(Lists::newArrayList).collect(Collectors.toList());
		try {
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			String realFileName = URLEncoder.encode(dto.getTempleteName(), "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + realFileName + ".xlsx");
			EasyExcel.write(response.getOutputStream()).head(headList).autoCloseStream(Boolean.FALSE).sheet(dto.getTempleteName()).doWrite(Lists.newArrayList());
		} catch (Exception var10) {
			var10.printStackTrace();
			response.reset();
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().println(JsonMapper.toJsonString(RestMessage.newInstance(Boolean.FALSE, "下载文件失败" + var10.getMessage(), (Object)null)));
			response.getWriter().flush();
		}
	}

	@Override
	public List<StandardTemplateDetailsListDTO> templateDetail(String templateId) {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Map<String, Object> queryMap = Maps.newHashMap();
		queryMap.put("hid", templateId);
		queryMap.put("enterpriseid", user.getEnterpriseId());
		queryMap.put("status", BussinessConstant.ONE);
		List<SysImportTempletdModel> models = sysImportTempletdMapper.findByMap(queryMap, SysImportTempletdModel.class);
		ToolKits.isParamNull(models, "未查询到导入模板明细数据");
		return models.stream().sorted(Comparator.comparing(SysImportTempletdModel::getSort)).map(m -> {
			StandardTemplateDetailsListDTO standardTemplateDetailsListDTO = new StandardTemplateDetailsListDTO();
			BeanUtil.copyProperties(m, standardTemplateDetailsListDTO);
			return standardTemplateDetailsListDTO;
		}).collect(Collectors.toList());
	}
}
