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.RqcRechekHeadersMapper;
import com.prolog.cs.biz.inbound.dto.PageParam;
import com.prolog.cs.biz.inbound.dto.rqc.RqcReDTO;
import com.prolog.cs.biz.inbound.dto.rqc.RqcRechekHeadersDTO;
import com.prolog.cs.biz.inbound.dto.task.TaskQcRecheckDetailDTO;
import com.prolog.cs.biz.inbound.model.rqc.RqcRechekHeaders;
import com.prolog.cs.biz.inbound.service.rqc.RqcRechekHeadersService;
import com.prolog.cs.biz.inbound.service.rqc.RqcRechekLinesService;
import com.prolog.cs.biz.inbound.service.task.TaskQcRecheckDetailService;
import com.prolog.cs.biz.inbound.utils.ObjectUtils;
import com.prolog.cs.biz.inbound.utils.UserUtils;
import com.prolog.cs.biz.inbound.vo.TaskQcDQueryVO;
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 RqcRechekHeadersServiceImpl implements RqcRechekHeadersService {

	@Resource
	private RqcRechekHeadersMapper mapper;

	@Resource
	private UserUtils userUtils;

	@Resource
	private TaskQcRecheckDetailService taskQcRecheckDetailService;

	@Resource
	private Validator validator;
	
	@Resource
	private RqcRechekLinesService rqcRechekLinesService;

	@Override
	public Object add(RqcRechekHeadersDTO rqcRechekHeadersDTO) {
		// TODO vaildate
		UserDTO userDTO = userUtils.getUserDTO();
		RqcRechekHeaders rqcRechekHeaders = new RqcRechekHeaders();
		BeanUtils.copyProperties(rqcRechekHeadersDTO, rqcRechekHeaders);
		this.vaildateModel(rqcRechekHeaders, false, userDTO);
		this.buildField(rqcRechekHeaders, false, userDTO);
		this.mapper.save(rqcRechekHeaders);
		return "";
	}

	private Object add(RqcRechekHeadersDTO rqcRechekHeadersDTO, boolean vaildateFlag, UserDTO userDTO, Date now) {
		// TODO vaildate
		if (ObjectUtils.isNull(userDTO))
			userDTO = userUtils.getUserDTO();
		boolean editFlag = Boolean.FALSE;
		if (vaildateFlag) {
			int row = 0;
			this.vaildateModel(rqcRechekHeadersDTO, editFlag, userDTO, row);
		}
		RqcRechekHeaders rqcRechekHeaders = new RqcRechekHeaders();
		BeanUtils.copyProperties(rqcRechekHeadersDTO, rqcRechekHeaders);
		this.buildField(rqcRechekHeaders, editFlag, userDTO, now);
		this.mapper.save(rqcRechekHeaders);
		return rqcRechekHeaders.getBillno(); // 质检单号
	}

	private void buildField(RqcRechekHeaders rqcRechekHeaders, boolean editFlag, UserDTO userDTO, Date now) {
//		Date gmtCreate = rqcRechekHeaders.getGmtCreate();
//		Date gmtModified = rqcRechekHeaders.getGmtModified();
//		String creator = rqcRechekHeaders.getCreator();
//		String creatorName = rqcRechekHeaders.getCreatorName();
//		String modifier = rqcRechekHeaders.getModifier();
//		String modifierName = rqcRechekHeaders.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))
//				rqcHeaders.setCreator(id);
//			if (ObjectUtils.isNull(creatorName))
//				rqcHeaders.setCreatorName(username);
//			if (ObjectUtils.isNull(gmtCreate))
//				rqcHeaders.setGmtCreate(now);
//			rqcHeaders.setEnterpriseId(enterpriseId);
//
//		}
//		if (ObjectUtils.isNull(modifier))
//			rqcHeaders.setModifier(id);
//		if (ObjectUtils.isNull(modifierName))
//			rqcHeaders.setModifierName(username);
//		if (ObjectUtils.isNull(gmtModified))
//			rqcHeaders.setGmtModified(now);
//		vaildateModelRepeated(rqcHeaders, editFlag, userDTO);
		
	}

	private void vaildateModel(RqcRechekHeadersDTO rqcRechekHeadersDTO, boolean editFlag, UserDTO userDTO, int row) {
		// 校验数据
		Set<ConstraintViolation<RqcRechekHeadersDTO>> validate = null;
		if (!editFlag) {
			// 添加校验
			validate = validator.validate(rqcRechekHeadersDTO, validAdd.class);
		} else {
			validate = validator.validate(rqcRechekHeadersDTO, 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());
		}
	}

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

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

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

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

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

	@Override
	public RqcRechekHeadersDTO findByPkId(String pkId) {
		// TODO
		RqcRechekHeaders rqcRechekHeaders = this.findById(pkId);
		AssertUtils.notNull(rqcRechekHeaders, "model empty!");
		RqcRechekHeadersDTO rqcRechekHeadersDTO = new RqcRechekHeadersDTO();
		BeanUtils.copyProperties(rqcRechekHeaders, rqcRechekHeadersDTO);
		return rqcRechekHeadersDTO;
	}

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

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

	private void buildField(RqcRechekHeaders rqcRechekHeaders, Boolean editFlag, UserDTO userDTO) {
		if (!editFlag) {
			// TODO add
		} else {
			// TODO edit
		}
		vaildateModelRepeated(rqcRechekHeaders, editFlag, userDTO);
	}

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

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

	private Restriction buildCondition(RqcRechekHeadersDTO rqcRechekHeadersDTO) {
		// TODO
		return null;
	}

	@Override
	public Page<TaskQcRecheckDetailDTO> extractRqcReTask(TaskQcDQueryVO taskQcDQueryVO, PageParam pageParam) {
		// 提取质检任务池中数据
		TaskQcRecheckDetailDTO rd = new TaskQcRecheckDetailDTO();
		BeanUtils.copyProperties(taskQcDQueryVO, rd);
		return taskQcRecheckDetailService.findList(rd, pageParam);
	}

	@Override
	public Object addWithRelated(RqcReDTO rqcReDTO) {
		// 极联保存
//		RqcRechekHeadersDTO rqcRechekHeadersDTO = rqcReDTO.getRqcRechekHeadersDTO();
//		AssertUtils.notNull(rqcRechekHeadersDTO,"新增复检单对象不可为空!");
//		List<RqcRechekLinesDTO> rqcRechekLinesDTOList = rqcReDTO.getRqcRechekLinesDTOList();
//		AssertUtils.notNull(rqcRechekLinesDTOList,"新增的复检明细行数据为空!");
//		UserDTO userDTO = userUtils.getUserDTO();
//		Date now = new Date();
//		String masterId = (String)this.add(rqcRechekHeadersDTO, true, userDTO, now);
//		
//		rqcRechekLinesService.batchAdd(rqcRechekLinesDTOList,masterId,userDTO,now);
		return true;
	}

}
