package com.diagbot.facade;

import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.RespDTO;
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.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 (orderDetails == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "订单明细不存在");
        }
        orderDetails.setGmtModified(DateUtil.now());
        orderDetails.setModifier(UserUtils.getCurrentPrincipleID());
        orderDetails.setAuditStatus(auditStatusVO.getAuditStatus());
        if(auditStatusVO.getAuditStatus()== AuditStatusEnum.Veto.getKey()){
            orderDetails.setRejectReason(auditStatusVO.getRejectReason());
            if(!this.updateById(orderDetails)){
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                        "审核状态修改失败");
            }
            return productOrderFacade.updateProductOrderStatus(orderDetails.getOrderNum());
        }
        if(!this.updateById(orderDetails)){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "审核状态修改失败");
        }
        Long userId =Long.parseLong(UserUtils.getCurrentPrincipleID());
        OpenedProducts openedProducts =new OpenedProducts();
        openedProducts.setGmtCreate(DateUtil.now());
        openedProducts.setCreator(UserUtils.getCurrentPrincipleID());
        openedProducts.setProductId(orderDetails.getProductId());
        openedProducts.setUserId(userId);
        openedProducts.setStartTime(auditStatusVO.getStartTime());
        openedProducts.setEndTime(auditStatusVO.getEndTime());
        openedProducts.setOrderId(productOrder.getId());
        openedProductsFacade.save(openedProducts);
        LantoneProduct lantoneProduct =new LantoneProduct();
        lantoneProduct.setId(orderDetails.getProductId());
        String accessType = lantoneProductFacade.getById(lantoneProduct).getAccessType();
        List<String> list = Arrays.asList(accessType.split(","));
        for (String s:list) {
            if(Integer.parseInt(s) ==(TokenTypeEnum.Online.getKey())){
                ServiceSaveVO serviceSaveVO =new ServiceSaveVO();
                serviceSaveVO.setDescription(lantoneProductFacade.getById(lantoneProduct).getDecription());
                serviceSaveVO.setName(lantoneProductFacade.getById(lantoneProduct).getName());
                serviceSaveVO.setType(TokenTypeEnum.Online.getKey());
                ServiceInfo serviceInfo = serviceInfoFacade.createService(serviceSaveVO);
                ProductServiceSaveVO productServiceSaveVO =new ProductServiceSaveVO();
                productServiceSaveVO.setProductId(lantoneProduct.getId());
                productServiceSaveVO.setServiceId(serviceInfo.getId());
                productServiceSaveVO.setType(TokenTypeEnum.Online.getKey());
                productServiceFacade.genProductService(productServiceSaveVO);
                break;
            }
        }
        return productOrderFacade.updateProductOrderStatus(orderDetails.getOrderNum());
    }


    /**
     * 产品申请查询所有订单明细
     *
     * @param orderDetialsVO 需要提供参数（付款状态，页数，每页条数默认显示10条）
     * @return 所有订单明细
     */
    public List<OrderDetailsWapper> getAllOrderDetials(OrderDetialsVO orderDetialsVO){
        OrderDetailsIndex orderDetailsIndex =new OrderDetailsIndex();
        Long curren = orderDetialsVO.getCurrent();
        Long size =orderDetialsVO.getSize();
        if(curren==null || curren==0){
            orderDetialsVO.setCurrent(1L);
        }
        if (size==null || size==0){
            orderDetialsVO.setSize(10L);
        }
        BeanUtil.copyProperties(orderDetialsVO, orderDetailsIndex);
        orderDetailsIndex.setIndex((orderDetialsVO.getCurrent().longValue()-1)*orderDetialsVO.getSize().longValue());
        List<OrderDetailsWapper> list =this.seleAllOrderDetials(orderDetailsIndex);
        List<Long> list1 =new ArrayList<>();
        for (OrderDetails 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.SERVER_IS_ERROR,
                    "获取用户和机构信息失败");
        }
        Map<Long, UserOrgDTO> dataMap = mapRespDTO.data;
        for(OrderDetailsWapper bean : list) {
            UserOrgDTO uo = dataMap.get(bean.getUserId());
            if(uo != null) {
                BeanUtil.copyProperties(uo,bean);
            }
        }
        return list;
    }
}
