package com.prolog.cs.biz.inbound.controller.rqc;

import cn.hutool.core.date.DateUtil;
import com.prolog.common.util.ToolKits;
import com.prolog.cs.basic.item.model.BaseMtlItemMst;
import com.prolog.cs.basic.item.model.BaseMtlItemUomConversions;
import com.prolog.cs.biz.inbound.dao.task.TaskQcDetailMapper;
import com.prolog.cs.biz.inbound.dto.PageParam;
import com.prolog.cs.biz.inbound.dto.rcv.RcvHDTO;
import com.prolog.cs.biz.inbound.dto.rqc.RqcDTO;
import com.prolog.cs.biz.inbound.dto.task.TaskQcDetailDTO;
import com.prolog.cs.biz.inbound.dto.task.TaskQcDetailRFDTO;
import com.prolog.cs.biz.inbound.remote.BaseItemRemoteCaller;
import com.prolog.cs.biz.inbound.service.rqc.RqcHeadersService;
import com.prolog.cs.biz.inbound.utils.UserUtils;
import com.prolog.cs.biz.inbound.vo.RcvQueryVO;
import com.prolog.cs.biz.inbound.vo.task.TaskQcDetailQueryVO;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.utils.StringUtils;
import com.prolog.wms.base.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 质检单主表
 * @Date 2021-03-24
 */

@Api(tags = "质检单")
@RestController
@RequestMapping("/rqcHeadersRF")
public class RqcHeadersRFController {

	@Resource
	private RqcHeadersService rqcHeadersService;
	@Resource
	private TaskQcDetailMapper taskQcDetailMapper;
	@Resource
	private UserUtils userUtils;
	@Resource
	private BaseItemRemoteCaller baseItemRemoteCaller;
	/**
	 * 提取质检池中的任务
	 */
	@ApiOperation("提取质检池中的任务(条件分页)")
	@GetMapping("/extractRqcTask")
	public RestMessage<Page<TaskQcDetailRFDTO>> extractRqcTask(TaskQcDetailQueryVO taskQcDetailQueryVO) {
		String status = taskQcDetailQueryVO.getStatus();
		if(StringUtils.isBlank(status)) {
			taskQcDetailQueryVO.setStatus("1");  // pc默认提取状态为未完成的任务
		}
		taskQcDetailQueryVO.setPageNum(1);
		taskQcDetailQueryVO.setPageSize(100000);
		Page<TaskQcDetailDTO> page=rqcHeadersService.extractRqcTask(taskQcDetailQueryVO);
		Page<TaskQcDetailRFDTO>  pageRF=PageUtil.newPage(page, TaskQcDetailRFDTO.class);
		if(pageRF.getList()==null){
			pageRF.setList(Lists.newArrayList());
		}
		List<BaseMtlItemMst> data = new ArrayList<>();
		if(pageRF.getList().size()>0){
			Set<String> itemIds = pageRF.getList().stream().map(x -> x.getItemId()).collect(Collectors.toSet());
			RestMessage<List<BaseMtlItemMst>> listByIds = baseItemRemoteCaller.getListByIds(itemIds);
			if(listByIds.getData()==null||!listByIds.isSuccess()){
				throw new BizException("商品信息查询失败");
			}
			data = listByIds.getData();
		}
		for(TaskQcDetailRFDTO dto : pageRF.getList()){
			String batchProductionDate = dto.getBatchProductionDate();
			if(ToolKits.isNotEmpty(batchProductionDate)&&!batchProductionDate.equals("*") ){
				dto.setBatchProductionDate(DateUtil.date(new Date(batchProductionDate)).toString("yyyy-MM-dd"));
			}else {
				String productionDate=dto.getShowProductionDate();
				if(!StringUtils.isBlank(productionDate)&&!productionDate.equals("*")&&productionDate.length()==8){
					dto.setBatchProductionDate(productionDate.substring(0,4).concat("-").concat(productionDate.substring(4,6).concat("-").concat(productionDate.substring(6,8))));
				}else if (!StringUtils.isBlank(productionDate)&&!productionDate.equals("*")&&productionDate.length()==6){
					dto.setBatchProductionDate(productionDate.substring(0,4).concat("-").concat(productionDate.substring(4,6).concat("-").concat("01")));
				}else {
					throw new BizException("显示生产日期格式有误");
				}
			}

			String expiredDate = dto.getBatchExpiredDate();
			if(!StringUtils.isBlank(expiredDate)&&!expiredDate.equals("*")){
				dto.setBatchExpiredDate(DateUtil.date(new Date(expiredDate)).toString("yyyy-MM-dd"));
			}
			BaseMtlItemMst itemMst = data.stream().filter(x -> x.getItemId().equals(dto.getItemId())).findFirst().orElse(null);
			if(itemMst!=null){
				List<BaseMtlItemUomConversions> baseMtlItemUomConversionsList = itemMst.getBaseMtlItemUomConversionsList();
				if(baseMtlItemUomConversionsList.size()>0){
					BaseMtlItemUomConversions itemUomConversions = baseMtlItemUomConversionsList.get(0);
					dto.setLength(itemUomConversions.getLength());
					dto.setWidth(itemUomConversions.getWidth());
					dto.setHeight(itemUomConversions.getHeight());
				}
			}
		}
		return RestMessage.newInstance(true, "extractRqcTask", pageRF);
	}

	/**
	 * 找寻待质检的rcv头表
	 */
	@ApiOperation("提取待质检的rcv头表")
	@GetMapping("/extractRcvH")
	public RestMessage<Page<RcvHDTO>> extractRcvH(RcvQueryVO rcvQueryVO, PageParam pageParam) {
//		UserDTO userDTO = userUtils.getUserDTO();
//		UserBizModel userBizModel = userDTO.getUserBizModel();
//		Set<String> consignors = userBizModel.getConsignors();
//		if (!ObjectUtils.isNull(consignors)) {
//			List<String> list = new ArrayList<>(consignors);
//			String cid = list.get(0);
//			rcvQueryVO.setMtlOwnerId(cid);
//		}
		Page<RcvHDTO> page=rqcHeadersService.extractRcvHAndPro(rcvQueryVO, pageParam);
		if(page!=null && page.getList()!=null && page.getList().size()>0){
			for(RcvHDTO rcvHDTO : page.getList()){
				List<String> distCodes= Lists.newArrayList();
				distCodes.add("oms_asn_bill_type");
				distCodes.add("tempcontrol_mode");
				distCodes.add("tempcontrol_status");
				List<Map<String,String>> distInfos =taskQcDetailMapper.queryDictInfo(distCodes);
				if(distInfos!=null && distInfos.size()>0){
					List<Map<String,String>> billTypeList=distInfos.stream().filter(dist-> Objects.equals(dist.get("type_code"),"oms_asn_bill_type")).collect(Collectors.toList());
					for(Map<String,String> map : billTypeList){
						if(Objects.equals(map.get("dict_code"),rcvHDTO.getRcvType())){
							rcvHDTO.setRcvTypeName(map.get("dict_name"));
							break;
						}
					}
					List<Map<String,String>> tempControlModeList=distInfos.stream().filter(dist-> Objects.equals(dist.get("type_code"),"tempcontrol_mode")).collect(Collectors.toList());
					for(Map<String,String> map : tempControlModeList){
						if(Objects.equals(map.get("dict_code"),rcvHDTO.getTempcontrolMode())){
							rcvHDTO.setTempcontrolModeName(map.get("dict_name"));
							break;
						}
					}
					List<Map<String,String>> tempControlStatusList=distInfos.stream().filter(dist-> Objects.equals(dist.get("type_code"),"tempcontrol_status")).collect(Collectors.toList());
					for(Map<String,String> map : tempControlStatusList){
						if(Objects.equals(map.get("dict_code"),rcvHDTO.getTempcontrolStatus())){
							rcvHDTO.setTempcontrolStatusName(map.get("dict_name"));
							break;
						}
					}
				}
			}
		}

		return RestMessage.newInstance(true, "extractRcvH",page);
	}

	/**
	 * 极联新增
	 */
	@ApiOperation("新增(级联关联表)")
	@PostMapping("/addWithRelatedRf")
	public RestMessage<Object> addWithRelatedRf(@RequestBody RqcDTO rqcDTO) {
		return RestMessage.newInstance(true, "addSuccess", rqcHeadersService.addWithRelatedRf(rqcDTO));
	}

}
