package com.diagbot.facade;

import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.AuthDetailDTO;
import com.diagbot.dto.ProductAuthProgressDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.UserOrgDTO;
import com.diagbot.dto.WaitExamOrderCouDTO;
import com.diagbot.entity.LantoneProduct;
import com.diagbot.entity.OrderDetailStatus;
import com.diagbot.entity.OrderDetails;
import com.diagbot.entity.ProductOrder;
import com.diagbot.entity.ProductOrderIndex;
import com.diagbot.entity.wrapper.ProductOrderWrapper;
import com.diagbot.enums.AuditStatusEnum;
import com.diagbot.enums.VisibleIdTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.idc.VisibleIdCreater;
import com.diagbot.service.impl.ProductOrderServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.AddOrderVO;
import com.diagbot.vo.ProductOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单业务
 *
 * @author Administrator
 */
@Component
public class ProductOrderFacade extends ProductOrderServiceImpl {
    @Autowired
    private VisibleIdCreater visibleIdCreater;
    @Autowired
    private OrderDetailsFacade orderDetailsFacade;
    @Autowired
    private ServiceInfoFacade serviceInfoFacade;
    @Autowired
    private LantoneProductFacade lantoneProductFacade;
    @Autowired
    private ProductServiceFacade productServiceFacade;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private ProductOrderFacade productOrderFacade;
    @Autowired
    private OpenedProductsFacade openedProductsFacade;


    /**
     * 获取产品的认证进度
     *
     * @return 包含产品当前的认证状态
     */
    public List<ProductAuthProgressDTO> productAuthProgress() {
        List<ProductAuthProgressDTO> retList = new ArrayList<ProductAuthProgressDTO>();
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        List<ProductOrder> orderList = baseMapper.getUserProductOrder(userId);
        List<String> nums = new ArrayList<>();
        for (ProductOrder i : orderList) {
            nums.add(i.getNum());
        }
        
        if(nums.size()==0){
        	return retList;
        }
        
        List<AuthDetailDTO> detailList = baseMapper.getOrderDetailsByNums(nums);
        List<AuthDetailDTO> products = null;
        Map<String, List<AuthDetailDTO>> detailMap = detailList.stream().collect(Collectors.groupingBy(AuthDetailDTO::getNum));
        for (String num : detailMap.keySet()) {
            ProductAuthProgressDTO productAuthProgressDTO = new ProductAuthProgressDTO();
            productAuthProgressDTO.setNum(num);
            products = detailMap.get(num);
            for(AuthDetailDTO i : products){
            	i.setAuditStatusMsg(AuditStatusEnum.getName(i.getAuditStatus()));
            }
            productAuthProgressDTO.setProducts(products);
            retList.add(productAuthProgressDTO);
        }

        return retList;
    }


    /**
     * 根据用户选择的产品生成订单
     *
     * @param addOrderVO 需要提供参数（产品id）
     * @return Boolean true
     */
    @Transactional
    public Boolean addOrders(AddOrderVO addOrderVO) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreator(UserUtils.getCurrentPrincipleID());
        productOrder.setGmtCreate(DateUtil.now());
        String orderNum = visibleIdCreater.getNextId(VisibleIdTypeEnum.IS_ORDER.getKey()).toString();
        productOrder.setNum(orderNum);
        productOrder.setUserId(userId);
        productOrder.setTime(DateUtil.now());
        if (!save(productOrder)) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "添加订单失败");
        }
        for (Long o : addOrderVO.getProductId()) {
            LantoneProduct lantoneProduct = lantoneProductFacade.selectLanProduct(o);
            if (null == lantoneProduct) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "获取产品信息失败:" + o);
            }
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setUserId(userId);
            orderDetails.setOrderNum(orderNum);
            orderDetails.setGmtCreate(DateUtil.now());
            orderDetails.setCreator(UserUtils.getCurrentPrincipleID());
            orderDetails.setProductId(o);
            orderDetailsFacade.save(orderDetails);
        }
        return true;
    }


    /**
     * 根据订单号查询订单信息
     *
     * @param productOrder 参数
     * @return 订单信息
     */
    public ProductOrder selectByOrderNum(ProductOrder productOrder) {
        return selctOrderTimeByOrderNum(productOrder);
    }


    /**
     * 计算待审核的订单数量
     *
     * @return 待审核的订单数量
     */
    public WaitExamOrderCouDTO waitExamOrderCou() {
        WaitExamOrderCouDTO waitExamOrderCouDTO = new WaitExamOrderCouDTO();
        waitExamOrderCouDTO.setCount(baseMapper.waitExamOrderCou());
        return waitExamOrderCouDTO;
    }


	/**
	 * 产品申请查询所有订单信息
     *
	 * @param productOrderVO （订单编号，机构名称，申请状态）
	 * @return 所有订单信息
	 */
	public RespDTO<List<ProductOrderWrapper>> selectAllProductOrder(ProductOrderVO productOrderVO){
		ProductOrderIndex productOrderIndex =new ProductOrderIndex();
		Long curren = productOrderVO.getCurrent();
		Long size =productOrderVO.getSize();
		if(curren==null){
			productOrderVO.setCurrent(1L);
		}
		if (size==null){
			productOrderVO.setSize(10L);
		}
		BeanUtil.copyProperties(productOrderVO, productOrderIndex);
		productOrderIndex.setIndex((productOrderVO.getCurrent().longValue()-1)*productOrderVO.getSize().longValue());
		//TODO
        if(productOrderVO.getOrgName()!=null&&productOrderVO.getOrgName()!=""){
            RespDTO<List<Long>> rlist = userServiceClient.getUserByOrgName(productOrderVO.getOrgName());
            productOrderIndex.setUserId(rlist.data);
        }
		List<ProductOrderWrapper> list =productOrderFacade.selectAllProductOrder(productOrderIndex);
		List<Long> list1 =new ArrayList<>();
		for (ProductOrderWrapper productOrderWrapper:list) {
			Long longs = productOrderWrapper.getUserId();
			list1.add(longs);
		}
		RespDTO<Map<Long, UserOrgDTO>> mapRespDTO = userServiceClient.getUserAndOrg(list1);
		if(mapRespDTO == null || !"0".equals(mapRespDTO.code) ) {
			throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
					"获取用户和机构信息失败");
		}
		Map<Long, UserOrgDTO> dataMap = mapRespDTO.data;
		for(ProductOrderWrapper bean : list) {
			UserOrgDTO uo = dataMap.get(bean.getUserId());
			if(uo != null) {
				bean.setUsername(uo.getUsername());
				bean.setLinkman(uo.getLinkman());
				bean.setEmail(uo.getEmail());
				bean.setOrgId(uo.getOrgId());
				bean.setOrgName(uo.getOrgName());
				bean.setIsReject(uo.getIsReject());
				bean.setAuStatus(uo.getAuStatus());
			}
		}
		return RespDTO.onSuc(list);
	}


    /**
     * 修改订单审核状态
     *
     * @param orderNum 参数
     * @return Boolean true
     */
	public Boolean updateProductOrderStatus(String orderNum){
        OrderDetailStatus  orderDetailStatus = orderDetailsFacade.selectAllOrderDetialsByOrderNum(orderNum);
        ProductOrder productOrder=new ProductOrder();
        productOrder.setNum(orderNum);
        productOrder= this.selctOrderTimeByOrderNum(productOrder);
        int satus =0;
        if(orderDetailStatus.getCt() == orderDetailStatus.getNotAudit()){
            satus = AuditStatusEnum.NotAudit.getKey();
            // ct == sh 待审核
        }else if(orderDetailStatus.getCt() > orderDetailStatus.getNotAudit() &&orderDetailStatus.getNotAudit() != 0){
            satus = AuditStatusEnum.Audit_Part.getKey();
            // ct > sh && sh != 0 部分审核
        }else if(orderDetailStatus.getCt() == orderDetailStatus.getPass()){
            satus = AuditStatusEnum.Adopt.getKey();
            // ct == pass 通过
        }else if(orderDetailStatus.getCt() == orderDetailStatus.getNotPass()){
            satus = AuditStatusEnum.Veto.getKey();
            // ct == not_pass 不通过
        }else {
            satus = AuditStatusEnum.Adopt_Part.getKey();
            // 其他 部分通过
        }
        productOrder.setAuditStatus(satus);
        productOrder.setGmtModified(DateUtil.now());
        productOrder.setModifier(UserUtils.getCurrentPrincipleID());
        if(!this.updateById(productOrder)){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "用户订单审核状态修改失败");
        }
        return true;
    }
}


