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

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.rqc.RqcLinePicMapper;
import com.prolog.cs.biz.inbound.dto.PageParam;
import com.prolog.cs.biz.inbound.dto.rqc.RqcLinePicDTO;
import com.prolog.cs.biz.inbound.model.rqc.RqcLinePic;
import com.prolog.cs.biz.inbound.service.rqc.RqcLinePicService;
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 com.prolog.framework.utils.StringUtils;
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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RqcLinePicServiceImpl implements RqcLinePicService {

	@Resource
	private RqcLinePicMapper mapper;

	@Resource
	private UserUtils userUtils;

	@Override
	public Object add(RqcLinePicDTO rqcLinePicDTO) {
		// TODO vaildate
		UserDTO userDTO = userUtils.getUserDTO();
		RqcLinePic rqcLinePic = new RqcLinePic();
		BeanUtils.copyProperties(rqcLinePicDTO, rqcLinePic);
//		this.vaildateModel(rqcLinePic, false, userDTO);
		this.buildField(rqcLinePic, false, userDTO);
		this.mapper.save(rqcLinePic);
		return true;
	}

	@Override
	public Object edit(String pkId, RqcLinePicDTO rqcLinePicDTO) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		RqcLinePic rqcLinePic = new RqcLinePic();
		BeanUtils.copyProperties(rqcLinePicDTO, rqcLinePic);
		this.vaildateModel(rqcLinePic, true, userDTO);
		this.buildField(rqcLinePic, true, userDTO);
		this.mapper.updateWithValidate(rqcLinePic,
				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, RqcLinePic.class));
		return "";
	}

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

	@Override
	public Page<RqcLinePicDTO> findList(RqcLinePicDTO rqcLinePicDTO, PageParam pageParam) {
		Criteria criteria = Criteria.forClass(RqcLinePic.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();
			RqcLinePicDTO condition = rqcLinePicDTO;
			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<RqcLinePic> list = this.mapper.findByCriteria(criteria);
		List<RqcLinePicDTO> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(p -> {
			RqcLinePicDTO target = new RqcLinePicDTO();
			BeanUtils.copyProperties(p, target);
			return target;
		}).collect(Collectors.toList());
		Page<RqcLinePic> page = PageUtils.getPage(list);
		Page<RqcLinePicDTO> 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<RqcLinePicDTO> rqcLinePicDTOList) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
//		for (RqcLinePicDTO rqcLinePicDTO : rqcLinePicDTOList) {
//			this.vaildateModel(rqcLinePicDTO, false, userDTO);
//			RqcLinePic rqcLinePic = new RqcLinePic();
//			BeanUtils.copyProperties(rqcLinePicDTO, rqcLinePic);
//			this.buildField(rqcLinePic, false, userDTO);
//			this.mapper.save(rqcLinePic);
//		}
		return this.batchAdd(rqcLinePicDTOList, null, userDTO, null);
	}

	@Override
	@Transactional
	public Object batchEdit(List<RqcLinePicDTO> rqcLinePicDTOList) {
		// TODO
		UserDTO userDTO = userUtils.getUserDTO();
		int row = 0;
		for (RqcLinePicDTO rqcLinePicDTO : rqcLinePicDTOList) {
			row ++ ;
			this.vaildateModel(rqcLinePicDTO, true, userDTO,row);
			RqcLinePic rqcLinePic = new RqcLinePic();
			BeanUtils.copyProperties(rqcLinePicDTO, rqcLinePic);
			this.buildField(rqcLinePic, true, userDTO);
			this.mapper.updateWithValidate(rqcLinePic,
					p -> ObjectUtils.isNotNull(p) && ObjectUtils.isNotNull(p.getValue()));
		}
		return true;
	}

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

	@Override
	public RqcLinePicDTO findByPkId(String pkId) {
		// TODO
		RqcLinePic rqcLinePic = this.findById(pkId);
		AssertUtils.notNull(rqcLinePic, "model empty!");
		RqcLinePicDTO rqcLinePicDTO = new RqcLinePicDTO();
		BeanUtils.copyProperties(rqcLinePic, rqcLinePicDTO);
		return rqcLinePicDTO;
	}

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

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

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

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

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

	private Restriction buildCondition(RqcLinePicDTO rqcLinePicDTO) {
		// TODO
		return null;
	}

	@Override
	@Transactional
	public Object batchAdd(List<RqcLinePicDTO> rqcLinePicDTOList, String masterId, UserDTO userDTO, Date now) {
		// 批量添加
		if (null == userDTO)
			userDTO = userUtils.getUserDTO();
		if (ObjectUtils.isNull(now))
			now = new Date();
		int row = 0;
		boolean editFlag = Boolean.FALSE;
		for (RqcLinePicDTO rqcLinePicDTO : rqcLinePicDTOList) {
			String rqcHeaderId = rqcLinePicDTO.getRqcHeaderId();
			if (ObjectUtils.isNull(rqcHeaderId))
				rqcLinePicDTO.setRqcHeaderId(masterId);
			rqcLinePicDTO.setLineNum(BigDecimal.valueOf(row));
			this.buildDefaultField(rqcLinePicDTO, editFlag, userDTO);
			this.vaildateModel(rqcLinePicDTO, editFlag, userDTO, row);
			RqcLinePic linePic = new RqcLinePic();
			BeanUtils.copyProperties(rqcLinePicDTO, linePic);
			this.buildField(linePic, editFlag, userDTO, now);
			this.mapper.save(linePic);
		}

		return true;
	}

	private void buildField(RqcLinePic linePic, boolean editFlag, UserDTO userDTO, Date now) {
		// 构建系统基础字段
		Date gmtCreate = linePic.getGmtCreate();
		Date gmtModified = linePic.getGmtModified();
		String creator = linePic.getCreator();
		String creatorName = linePic.getCreatorName();
		String modifier = linePic.getModifier();
		String modifierName = linePic.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))
				linePic.setCreator(id);
			if (ObjectUtils.isNull(creatorName))
				linePic.setCreatorName(username);
			if (ObjectUtils.isNull(gmtCreate))
				linePic.setGmtCreate(now);
			linePic.setEnterpriseId(enterpriseId);

		}
		if (ObjectUtils.isNull(modifier))
			linePic.setModifier(id);
		if (ObjectUtils.isNull(modifierName))
			linePic.setModifierName(username);
		if (ObjectUtils.isNull(gmtModified))
			linePic.setGmtModified(now);
		vaildateModelRepeated(linePic, editFlag, userDTO);

	}

	private void vaildateModel(RqcLinePicDTO rqcLinePicDTO, boolean editFlag, UserDTO userDTO, int row) {
		// 校验数据
		Set<ConstraintViolation<RqcLinePicDTO>> validate = null;
		if (!editFlag) {
			// 添加校验
			validate = validator.validate(rqcLinePicDTO, validAdd.class);
		} else {
			validate = validator.validate(rqcLinePicDTO, validEdit.class);
		}
		if (validate != null && !validate.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			if (row > 0)
				sb.append(String.format(VaildateConstant.ERROR_ROW_FORMAT, 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(RqcLinePicDTO rqcLinePicDTO, boolean editFlag, UserDTO userDTO) {
		// 构建默认字段
		if (!editFlag) {
			Date opDate = rqcLinePicDTO.getOpDate();
			String opUserid = rqcLinePicDTO.getOpUserid();
			if (opDate == null) {
				rqcLinePicDTO.setOpDate(new Date());
			}
			if (StringUtils.isBlank(opUserid)) {
				rqcLinePicDTO.setOpUserid(userDTO.getUsername());
			}
		}
		
	}

	@Resource
	private Validator validator;
}
