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.RcvHeadersSrcBillsMapper;
import com.prolog.cs.biz.inbound.dto.PageParam;
import com.prolog.cs.biz.inbound.dto.rcv.RcvHeadersSrcBillsDTO;
import com.prolog.cs.biz.inbound.model.rcv.RcvHeadersSrcBills;
import com.prolog.cs.biz.inbound.service.rcv.RcvHeadersSrcBillsService;
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 RcvHeadersSrcBillsServiceImpl implements RcvHeadersSrcBillsService {

	@Resource
	private RcvHeadersSrcBillsMapper mapper;

	@Resource
	private UserUtils userUtils;

	@Override
	public Object add(RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO) {
		// TODO vaildate
		UserDTO userDTO = userUtils.getUserDTO();
		// TODO 这里后期判断是否是更新或者更新
		boolean editFlag = false;
		this.buildDefaultField(rcvHeadersSrcBillsDTO, editFlag, userDTO);
//		this.vaildateModel(rcvHeadersSrcBillsDTO, editFlag, userDTO, 0);
		RcvHeadersSrcBills srcBills = new RcvHeadersSrcBills();
		BeanUtils.copyProperties(rcvHeadersSrcBillsDTO, srcBills);
		this.buildField(srcBills, editFlag, userDTO, new Date());
		this.mapper.save(srcBills);
		return true;
	}

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

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

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

	@Override
	public Page<RcvHeadersSrcBillsDTO> findList(RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO, PageParam pageParam) {
		Criteria criteria = Criteria.forClass(RcvHeadersSrcBills.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();
			RcvHeadersSrcBillsDTO condition = rcvHeadersSrcBillsDTO;
			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<RcvHeadersSrcBills> list = this.mapper.findByCriteria(criteria);
		List<RcvHeadersSrcBillsDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream()
				.map(p -> {
					RcvHeadersSrcBillsDTO target = new RcvHeadersSrcBillsDTO();
					BeanUtils.copyProperties(p, target);
					return target;
				}).collect(Collectors.toList());
		Page<RcvHeadersSrcBills> page = PageUtils.getPage(list);
		Page<RcvHeadersSrcBillsDTO> 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<RcvHeadersSrcBillsDTO> rcvHeadersSrcBillsDTOList) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		this.batchAdd(rcvHeadersSrcBillsDTOList, null, userDTO);
		return true;
	}

	@Override
	@Transactional
	public Object batchEdit(List<RcvHeadersSrcBillsDTO> rcvHeadersSrcBillsDTOList) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		for (RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO : rcvHeadersSrcBillsDTOList) {
			RcvHeadersSrcBills rcvHeadersSrcBills = new RcvHeadersSrcBills();
			BeanUtils.copyProperties(rcvHeadersSrcBillsDTO, rcvHeadersSrcBills);
			this.vaildateModel(rcvHeadersSrcBills, true, userDTO);
			this.buildField(rcvHeadersSrcBills, true, userDTO);
			this.mapper.updateWithValidate(rcvHeadersSrcBills,
					p -> ObjectUtils.isNotNull(p) && ObjectUtils.isNotNull(p.getValue()));
		}
		return true;
	}

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

	@Override
	public RcvHeadersSrcBillsDTO findByPkId(String pkId) {
		// TODO
		RcvHeadersSrcBills rcvHeadersSrcBills = this.findById(pkId);
		AssertUtils.notNull(rcvHeadersSrcBills, "model empty!");
		RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO = new RcvHeadersSrcBillsDTO();
		BeanUtils.copyProperties(rcvHeadersSrcBills, rcvHeadersSrcBillsDTO);
		return rcvHeadersSrcBillsDTO;
	}

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

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

	private void buildField(RcvHeadersSrcBills rcvHeadersSrcBills, boolean editFlag, UserDTO userDTO) {
		buildField(rcvHeadersSrcBills, editFlag, userDTO, new Date());
	}

	private void buildField(RcvHeadersSrcBills rcvHeadersSrcBills, Boolean editFlag, UserDTO userDTO, Date now) {
		Date gmtCreate = rcvHeadersSrcBills.getGmtCreate();
		Date gmtModified = rcvHeadersSrcBills.getGmtModified();
		String creator = rcvHeadersSrcBills.getCreator();
		String creatorName = rcvHeadersSrcBills.getCreatorName();
		String modifier = rcvHeadersSrcBills.getModifier();
		String modifierName = rcvHeadersSrcBills.getModifierName();

		String id = userDTO.getId();
		String enterpriseId = userDTO.getEnterpriseId();
		String username = userDTO.getUsername();
		if (null == now)
			now = new Date();
		if (!editFlag) {
			if (ObjectUtils.isNull(creator))
				rcvHeadersSrcBills.setCreator(id);
			if (ObjectUtils.isNull(creatorName))
				rcvHeadersSrcBills.setCreatorName(username);
			if (ObjectUtils.isNull(gmtCreate))
				rcvHeadersSrcBills.setGmtCreate(now);
			rcvHeadersSrcBills.setEnterpriseId(enterpriseId);
		}
		if (ObjectUtils.isNull(modifier))
			rcvHeadersSrcBills.setModifier(id);
		if (ObjectUtils.isNull(modifierName))
			rcvHeadersSrcBills.setModifierName(username);
		if (ObjectUtils.isNull(gmtModified))
			rcvHeadersSrcBills.setGmtModified(now);
		vaildateModelRepeated(rcvHeadersSrcBills, editFlag, userDTO);
	}

	private void vaildateModelRepeated(RcvHeadersSrcBills rcvHeadersSrcBills, Boolean editFlag, UserDTO userDTO) {
		// 重复性校验
		if (!editFlag) {
			// TODO add
		} else {
			// TODO
		}
	}

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

	private Restriction buildCondition(RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO) {
		// TODO
		return null;
	}

	@Override
	public Object batchAdd(List<RcvHeadersSrcBillsDTO> rcvHeadersSrcBillsDTOList, String masterId, UserDTO userDTO) {
		// 批量添加
		// 批量保存
		if (null == userDTO)
			userDTO = userUtils.getUserDTO();
		int i = 0;
		boolean editFlag = Boolean.FALSE;
		Date now = new Date();
		for (RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO : rcvHeadersSrcBillsDTOList) {
			i++;
			// TODO 这里后期判断是否是更新或者更新
			// 头表id
			String rcvHeaderId = rcvHeadersSrcBillsDTO.getRcvHeaderId();
			if (ObjectUtils.isNull(rcvHeaderId) && !ObjectUtils.isNull(masterId))
				rcvHeadersSrcBillsDTO.setRcvHeaderId(masterId);

			this.buildDefaultField(rcvHeadersSrcBillsDTO, editFlag, userDTO);
			this.vaildateModel(rcvHeadersSrcBillsDTO, editFlag, userDTO, i);
			RcvHeadersSrcBills srcBills = new RcvHeadersSrcBills();
			BeanUtils.copyProperties(rcvHeadersSrcBillsDTO, srcBills);
			this.buildField(srcBills, editFlag, userDTO, now);
			this.mapper.save(srcBills);
		}

		return true;
	}

	private void vaildateModel(RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO, boolean editFlag, UserDTO userDTO,
			int row) {
		// 校验数据
		Set<ConstraintViolation<RcvHeadersSrcBillsDTO>> validate = null;
		if (!editFlag) {
			// 添加校验
			validate = validator.validate(rcvHeadersSrcBillsDTO, validAdd.class);
		} else {
			validate = validator.validate(rcvHeadersSrcBillsDTO, validEdit.class);
		}
		if (validate != null && !validate.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			if (row > 0)
				sb.append(String.format(VaildateConstant.ERROR_ROW_FORMAT2, "保存原srcAsn单操作", 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());
		}

	}

	private void buildDefaultField(RcvHeadersSrcBillsDTO rcvHeadersSrcBillsDTO, boolean editFlag, UserDTO userDTO) {
		// 构建基础字段

	}

	@Resource
	private Validator validator;

}
