package com.diagbot.facade;

import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.OrderDetialsDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.UserAndProdutDTO;
import com.diagbot.dto.UserOrgDTO;
import com.diagbot.entity.LantoneProduct;
import com.diagbot.entity.OpenedProducts;
import com.diagbot.entity.OrderDetails;
import com.diagbot.entity.OrderDetailsIndex;
import com.diagbot.entity.ProductOrder;
import com.diagbot.entity.ServiceInfo;
import com.diagbot.entity.wrapper.OrderDetailsWapper;
import com.diagbot.enums.AuditStatusEnum;
import com.diagbot.enums.NotPassEnum;
import com.diagbot.enums.PaymentMethodEnum;
import com.diagbot.enums.ServiceTypeEnum;
import com.diagbot.enums.TokenTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.OrderDetailsServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.AuditStatusVO;
import com.diagbot.vo.OrderDetialsVO;
import com.diagbot.vo.ProductServiceSaveVO;
import com.diagbot.vo.ServiceSaveVO;
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.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 订单明细
 * @author: wangyu
 * @time: 2018/9/19 20:22
 */
@Component
public class OrderDetailsFacade extends OrderDetailsServiceImpl {
    @Autowired
    private OpenedProductsFacade openedProductsFacade;
    @Autowired
    private LantoneProductFacade lantoneProductFacade;
    @Autowired
    private ServiceInfoFacade serviceInfoFacade;
    @Autowired
    private ProductServiceFacade productServiceFacade;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private ProductOrderFacade productOrderFacade;


    /**
     * 产品申请审核接口
     *
     * @param auditStatusVO 需要提供参数（订单明细id，审核状态，开始时间，结束时间）
     * @return Boolean true
     */
    @Transactional
    public Boolean updateAuditStatus(AuditStatusVO auditStatusVO) {
        OrderDetails orderDetails = this.getById(auditStatusVO.getId());
        ProductOrder productOrder =new ProductOrder();
        productOrder.setNum(orderDetails.getOrderNum());
        productOrder =productOrderFacade.selctOrderTimeByOrderNum(productOrder);
        if(auditStatusVO.getStartTime() !=null && auditStatusVO.getStartTime().equals("")){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "开始时间不能为空");
        }else if(auditStatusVO.getEndTime() !=null && auditStatusVO.getEndTime().equals("")){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "结束时间不能为空");
        }
        if (orderDetails == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "订单明细不存在");
        }
        if(orderDetails.getAuditStatus().intValue() != AuditStatusEnum.NotAudit.getKey()){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "该订单已被审核请勿重复操作");
        }
        orderDetails.setGmtModified(DateUtil.now());
        orderDetails.setModifier(UserUtils.getCurrentPrincipleID());
        orderDetails.setAuditStatus(auditStatusVO.getAuditStatus());
        if(auditStatusVO.getAuditStatus().intValue() == AuditStatusEnum.Veto.getKey()){
            if(auditStatusVO.getRejectReason() != null && !auditStatusVO.getRejectReason().equals("") ){
                orderDetails.setRejectType(-1);
                if(auditStatusVO.getRejectReason().length()>100){
                    throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                            "输入原因过长,请减少一些");
                }
                orderDetails.setRejectReason(auditStatusVO.getRejectReason());
            }else {
                orderDetails.setRejectType(auditStatusVO.getRejectType());
            }
            if(!this.updateById(orderDetails)){
                throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL,
                        "审核状态修改失败");
            }
            return productOrderFacade.updateProductOrderStatus(orderDetails.getOrderNum());
        }
        orderDetails.setStatus(PaymentMethodEnum.PAY.getKey());
        if(!this.updateById(orderDetails)){
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL,
                    "审核状态修改失败");
        }
        Long userId =Long.parseLong(UserUtils.getCurrentPrincipleID());
        OpenedProducts openedProducts =new OpenedProducts();
        openedProducts.setGmtCreate(DateUtil.now());
        openedProducts.setCreator(UserUtils.getCurrentPrincipleID());
        openedProducts.setProductId(orderDetails.getProductId());
        openedProducts.setUserId(orderDetails.getUserId());
        openedProducts.setStartTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil.getFirstTimeOfDay(DateUtil.parseDate(auditStatusVO.getStartTime())))));
        openedProducts.setEndTime(DateUtil.parseDateTime(DateUtil.formatDateTime(DateUtil.getLastTimeOfDay(DateUtil.parseDate(auditStatusVO.getEndTime())))));
        openedProducts.setOrderId(productOrder.getId());
        openedProductsFacade.save(openedProducts);
        LantoneProduct lantoneProduct =new LantoneProduct();
        lantoneProduct.setId(orderDetails.getProductId());
        LantoneProduct lantoneProducts = lantoneProductFacade.getById(lantoneProduct);
        String accessType = lantoneProducts.getAccessType();
        List<String> list = Arrays.asList(accessType.split(","));
        ServiceSaveVO serviceSaveVO =null;
        ProductServiceSaveVO productServiceSaveVO =null;
        for (String s:list) {
            if(Integer.parseInt(s) ==(TokenTypeEnum.Online.getKey())){
                serviceSaveVO =new ServiceSaveVO();
                serviceSaveVO.setDescription("用户线上产品-" + lantoneProducts.getDecription());
                serviceSaveVO.setName("用户线上产品-" + lantoneProducts.getName());
                serviceSaveVO.setType(ServiceTypeEnum.Sys_Create.getKey());
                serviceSaveVO.setUserId(productOrder.getUserId());
                ServiceInfo serviceInfo = serviceInfoFacade.createService(serviceSaveVO);
                productServiceSaveVO =new ProductServiceSaveVO();
                productServiceSaveVO.setProductId(lantoneProducts.getId());
                productServiceSaveVO.setServiceId(serviceInfo.getId());
                productServiceSaveVO.setType(TokenTypeEnum.Online.getKey());
                productServiceSaveVO.setUserId(productOrder.getUserId());
                productServiceFacade.genProductService(productServiceSaveVO);
                break;
            }
        }
        return productOrderFacade.updateProductOrderStatus(orderDetails.getOrderNum());
    }


    /**
     * 产品申请查询所有订单明细
     *
     * @param orderDetialsVO 需要提供参数（付款状态，页数，每页条数默认显示10条）
     * @return 所有订单明细
     */
    public List<OrderDetialsDTO> getAllOrderDetials(OrderDetialsVO orderDetialsVO){
        OrderDetailsIndex orderDetailsIndex =new OrderDetailsIndex();
        BeanUtil.copyProperties(orderDetialsVO, orderDetailsIndex);
        List<OrderDetialsDTO> list =this.seleAllOrderDetials(orderDetailsIndex);
        List<Long> list1 =new ArrayList<>();
        for (OrderDetialsDTO orderDetails:list) {
            Long longs = orderDetails.getUserId();
            list1.add(longs);
        }
        RespDTO<Map<Long, UserOrgDTO>> mapRespDTO = userServiceClient.getUserAndOrg(list1);
        if(mapRespDTO == null || !"0".equals(mapRespDTO.code) ) {
            throw new CommonException(CommonErrorCode.RPC_ERROR,
                    "获取用户和机构信息失败");
        }
        Map<Long, UserOrgDTO> dataMap = mapRespDTO.data;
        List<UserAndProdutDTO> openedProductTime =openedProductsFacade.getInformationAvailableByUserIdsB(list1);
        for(OrderDetialsDTO bean : list) {
            UserOrgDTO uo = dataMap.get(bean.getUserId());
            if(uo != null) {
                BeanUtil.copyProperties(uo,bean);
            }
            if(bean.getRejectType().intValue() != 0){
                bean.setRejectTypeName(NotPassEnum.getName(bean.getRejectType()));
            }
            if(bean.getAuditStatus().intValue() == AuditStatusEnum.Adopt.getKey()){
                for (UserAndProdutDTO openedProducts:openedProductTime) {
                    if(bean.getUserId().intValue() == openedProducts.getUserId().intValue() && bean.getProductId().intValue() == openedProducts.getProductId().intValue()){
                        bean.setStartTime(openedProducts.getStartTime());
                        bean.setEndTime(openedProducts.getEndTime());
                    }
                }
            }
            bean.setPayStatusName(PaymentMethodEnum.getName(bean.getStatus()));
        }
        return list;
    }
    /**
     * 根据用户id查询是否有在审核的数据数量
     */
	public int getOrderByUserToAudit(OrderDetailsWapper rderDetails) {
    	
		return baseMapper.getOrderByUserToAudit(rderDetails);
    }
}
