package com.prolog.cs.biz.inbound.service.impl.rcv;

import com.prolog.cs.biz.inbound.constant.VaildateConstant;
import com.prolog.cs.biz.inbound.constant.ValidatorGroup.validAdd;
import com.prolog.cs.biz.inbound.constant.ValidatorGroup.validEdit;
import com.prolog.cs.biz.inbound.dao.rcv.RcvLinesProfilesMapper;
import com.prolog.cs.biz.inbound.dto.PageParam;
import com.prolog.cs.biz.inbound.dto.rcv.RcvLinesProfilesDTO;
import com.prolog.cs.biz.inbound.model.rcv.RcvLinesProfiles;
import com.prolog.cs.biz.inbound.service.rcv.RcvLinesProfilesService;
import com.prolog.cs.biz.inbound.utils.ObjectUtils;
import com.prolog.cs.biz.inbound.utils.UserUtils;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.beans.BeanUtils;
import com.prolog.framework.core.exception.BizException;
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.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.framework.utils.AssertUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RcvLinesProfilesServiceImpl implements RcvLinesProfilesService {

	@Resource
	private RcvLinesProfilesMapper mapper;

	@Resource
	private UserUtils userUtils;

	@Override
	public Object add(RcvLinesProfilesDTO rcvLinesProfilesDTO) {
		// TODO vaildate
		UserDTO userDTO = userUtils.getUserDTO();
		return this.add(rcvLinesProfilesDTO, userDTO, 0);
	}

	@Override
	public Object edit(String pkId, RcvLinesProfilesDTO rcvLinesProfilesDTO) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		RcvLinesProfiles rcvLinesProfiles = new RcvLinesProfiles();
		BeanUtils.copyProperties(rcvLinesProfilesDTO, rcvLinesProfiles);
		this.vaildateModel(rcvLinesProfiles, true, userDTO);
		this.buildField(rcvLinesProfiles, true, userDTO);
		this.mapper.updateWithValidate(rcvLinesProfiles,
				p -> ObjectUtils.isNotNull(p) && ObjectUtils.isNotNull(p.getValue()));
		return "";
	}

	@Override
	@Transactional
	public Object delIds(List<String> pkIdList) {
		// TODO
		pkIdList.stream().filter(p -> canEdit(p)).forEach(p -> this.mapper.deleteById(p, RcvLinesProfiles.class));
		return "";
	}

	@Override
	public Object deletePkId(String pkId) {
		// TODO
		if (canEdit(pkId))
			throw new BizException("can not del");
		this.mapper.deleteById(pkId, RcvLinesProfiles.class);
		return "";
	}

	@Override
	public Page<RcvLinesProfilesDTO> findList(RcvLinesProfilesDTO rcvLinesProfilesDTO, PageParam pageParam) {
		Criteria criteria = Criteria.forClass(RcvLinesProfiles.class);
		Integer pageNum = null;
		Integer pageSize = null;
		Restriction r = null;
		if (pageParam == null) {
			pageNum = PageParam.DEFAULT_PAGE_NUM;
			pageSize = PageParam.DEFAULT_PAGE_SIZE;
		} else {
			pageNum = pageParam.getPageNum();
			pageSize = pageParam.getPageSize();
			RcvLinesProfilesDTO condition = rcvLinesProfilesDTO;
			r = buildCondition(condition);
		}
		if (pageNum == null || pageNum == 0) {
			pageNum = PageParam.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null || pageSize == 0) {
			pageSize = PageParam.DEFAULT_PAGE_SIZE;
		}
		criteria.setRestriction(r);
		Order order = Order.newInstance().desc("gmtModified");
		criteria.setOrder(order);
		PageUtils.startPage(pageNum, pageSize);
		List<RcvLinesProfiles> list = this.mapper.findByCriteria(criteria);
		List<RcvLinesProfilesDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream()
				.map(p -> {
					RcvLinesProfilesDTO target = new RcvLinesProfilesDTO();
					BeanUtils.copyProperties(p, target);
					return target;
				}).collect(Collectors.toList());
		Page<RcvLinesProfiles> page = PageUtils.getPage(list);
		Page<RcvLinesProfilesDTO> page2 = new Page<>();
		page2.setStartRow(page.getStartRow());
		page2.setEndRow(page.getEndRow());
		page2.setPageCount(page.getPageCount());
		page2.setPageNum(page.getPageNum());
		page2.setPageSize(page.getPageSize());
		page2.setTotalCount(page.getTotalCount());
		page2.setList(collect);
		return page2;
	}

	@Override
	@Transactional
	public Object batchAdd(List<RcvLinesProfilesDTO> rcvLinesProfilesDTOList) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		for (RcvLinesProfilesDTO rcvLinesProfilesDTO : rcvLinesProfilesDTOList) {
			RcvLinesProfiles rcvLinesProfiles = new RcvLinesProfiles();
			BeanUtils.copyProperties(rcvLinesProfilesDTO, rcvLinesProfiles);
			this.vaildateModel(rcvLinesProfiles, false, userDTO);
			this.buildField(rcvLinesProfiles, false, userDTO);
			this.mapper.save(rcvLinesProfiles);
		}
		return "";
	}

	@Override
	@Transactional
	public Object batchEdit(List<RcvLinesProfilesDTO> rcvLinesProfilesDTOList) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		for (RcvLinesProfilesDTO rcvLinesProfilesDTO : rcvLinesProfilesDTOList) {
			RcvLinesProfiles rcvLinesProfiles = new RcvLinesProfiles();
			BeanUtils.copyProperties(rcvLinesProfilesDTO, rcvLinesProfiles);
			this.vaildateModel(rcvLinesProfiles, true, userDTO);
			this.buildField(rcvLinesProfiles, true, userDTO);
			this.mapper.updateWithValidate(rcvLinesProfiles,
					p -> ObjectUtils.isNotNull(p) && ObjectUtils.isNotNull(p.getValue()));
		}
		return "";
	}

	@Override
	public List<RcvLinesProfilesDTO> findAll(RcvLinesProfilesDTO rcvLinesProfilesDTO) {
		// TODO
		Criteria criteria = Criteria.forClass(RcvLinesProfiles.class);
		RcvLinesProfilesDTO condition = rcvLinesProfilesDTO;
		Restriction r = buildCondition(condition);
		criteria.setRestriction(r);
		Order order = Order.newInstance().desc("gmtModified");
		criteria.setOrder(order);
		List<RcvLinesProfiles> list = this.mapper.findByCriteria(criteria);
		List<RcvLinesProfilesDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream()
				.map(p -> {
					RcvLinesProfilesDTO target = new RcvLinesProfilesDTO();
					BeanUtils.copyProperties(p, target);
					return target;
				}).collect(Collectors.toList());
		return collect;
	}

	@Override
	public RcvLinesProfilesDTO findByPkId(String pkId) {
		// TODO
		RcvLinesProfiles rcvLinesProfiles = this.findById(pkId);
		AssertUtils.notNull(rcvLinesProfiles, "model empty!");
		RcvLinesProfilesDTO rcvLinesProfilesDTO = new RcvLinesProfilesDTO();
		BeanUtils.copyProperties(rcvLinesProfiles, rcvLinesProfilesDTO);
		return rcvLinesProfilesDTO;
	}

	private RcvLinesProfiles findById(String id) {
		return this.mapper.findById(id, RcvLinesProfiles.class);
	}

	private void vaildateModel(RcvLinesProfiles rcvLinesProfiles, Boolean editFlag, UserDTO userDTO) {
		if (!editFlag) {
			// TODO add
		} else {
			// TODO
		}
	}

	private void buildField(RcvLinesProfiles rcvLinesProfiles, Boolean editFlag, UserDTO userDTO) {
		this.buildField(rcvLinesProfiles, editFlag, userDTO, new Date());
	}

	private void buildField(RcvLinesProfiles rcvLinesProfiles, Boolean editFlag, UserDTO userDTO, Date now) {
		Date gmtCreate = rcvLinesProfiles.getGmtCreate();
		Date gmtModified = rcvLinesProfiles.getGmtModified();
		String creator = rcvLinesProfiles.getCreator();
		String creatorName = rcvLinesProfiles.getCreatorName();
		String modifier = rcvLinesProfiles.getModifier();
		String modifierName = rcvLinesProfiles.getModifierName();
		String enterpriseId2 = rcvLinesProfiles.getEnterpriseId();
		String id = userDTO.getId();
		String enterpriseId = userDTO.getEnterpriseId();
		String username = userDTO.getUsername();
		if (null == now)
			now = new Date();
		if (!editFlag) {
			if (ObjectUtils.isNull(creator))
				rcvLinesProfiles.setCreator(id);
			if (ObjectUtils.isNull(creatorName))
				rcvLinesProfiles.setCreatorName(username);
			if (ObjectUtils.isNull(gmtCreate))
				rcvLinesProfiles.setGmtCreate(now);
			if (ObjectUtils.isNull(enterpriseId2))
				rcvLinesProfiles.setEnterpriseId(enterpriseId);
		}
		if (ObjectUtils.isNull(modifier))
			rcvLinesProfiles.setModifier(id);
		if (ObjectUtils.isNull(modifierName))
			rcvLinesProfiles.setModifierName(username);
		if (ObjectUtils.isNull(gmtModified))
			rcvLinesProfiles.setGmtModified(now);
		vaildateModelRepeated(rcvLinesProfiles, editFlag, userDTO);
	}

	private void vaildateModelRepeated(RcvLinesProfiles rcvLinesProfiles, Boolean editFlag, UserDTO userDTO) {
		if (!editFlag) {
			// TODO add
		} else {
			// TODO
		}
	}

	private boolean canEdit(String pkId) {
		boolean flag = true;
		RcvLinesProfiles rcvLinesProfiles = this.findById(pkId);
		AssertUtils.notNull(rcvLinesProfiles, "model empty!");
		// TODO
		if (true)
			flag = false;
		return flag;
	}

	private Restriction buildCondition(RcvLinesProfilesDTO rcvLinesProfilesDTO) {
		// TODO
		return null;
	}

	@Override
	public Object add(RcvLinesProfilesDTO rcvLinesProfilesDTO, UserDTO userDTO, int row) {
		if (ObjectUtils.isNull(userDTO))
			userDTO = userUtils.getUserDTO();
		boolean editFlag = Boolean.FALSE;
		this.buildDefaultField(rcvLinesProfilesDTO, editFlag, userDTO);
		this.vaildateModel(rcvLinesProfilesDTO, editFlag, userDTO, row);
		RcvLinesProfiles rcvLinesProfiles = new RcvLinesProfiles();
		BeanUtils.copyProperties(rcvLinesProfilesDTO, rcvLinesProfiles);
		this.buildField(rcvLinesProfiles, editFlag, userDTO);
		this.mapper.save(rcvLinesProfiles);
		return true;

	}

	private void buildDefaultField(RcvLinesProfilesDTO rcvLinesProfilesDTO, boolean editFlag, UserDTO userDTO) {
		// 构建默认字段
	}

	private void vaildateModel(RcvLinesProfilesDTO rcvLinesProfilesDTO, boolean editFlag, UserDTO userDTO, int row) {
		// 校验数据
		Set<ConstraintViolation<RcvLinesProfilesDTO>> validate = null;
		if (!editFlag) {
			// 添加校验
			validate = validator.validate(rcvLinesProfilesDTO, validAdd.class);
		} else {
			validate = validator.validate(rcvLinesProfilesDTO, validEdit.class);
		}
		if (validate != null && !validate.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			if (row > 0)
				sb.append(String.format(VaildateConstant.ERROR_ROW_FORMAT2, "新增收货行额外属性操作", row));
			validate.forEach((validation) -> {
				String errorMsg = validation.getMessage();
				String propertyName = validation.getPropertyPath().toString();
				sb.append(String.format(VaildateConstant.ERROR_FIELD_FORMAT, propertyName))
						.append(String.format(VaildateConstant.ERROR_MSG_FORMAT, errorMsg));
			});
			throw new ParameterException(sb.toString());
		}

	}

	@Resource
	private Validator validator;

	/**
	 * 根据rcvLineId的集合获取拓展集合
	 */
	@Override
	public List<RcvLinesProfilesDTO> searchByIdList(List<String> rcvLineIdList) {
		if (ObjectUtils.isNull(rcvLineIdList))
			return null;
		String[] array = rcvLineIdList.toArray(new String[rcvLineIdList.size()]);
		List<RcvLinesProfiles> list = this.mapper.findByIds(RcvLinesProfiles.class, array, null);
		List<RcvLinesProfilesDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream()
				.map(p -> {
					RcvLinesProfilesDTO target = new RcvLinesProfilesDTO();
					BeanUtils.copyProperties(p, target);
					return target;
				}).collect(Collectors.toList());
		return collect;
	}

}
