package com.diagbot.facade;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import com.diagbot.dto.EnShowOptionDTO;
import com.diagbot.dto.GetConsoleOnTrialDTO;
import com.diagbot.dto.GetConsoleOpenedDTO;
import com.diagbot.dto.OpenUpOnTrialDTO;
import com.diagbot.dto.ProductServiceDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.UserAndProdutDTO;
import com.diagbot.entity.OpenedProducts;
import com.diagbot.entity.ProductService;
import com.diagbot.entity.ServiceInfo;
import com.diagbot.enums.AccessTypeEnum;
import com.diagbot.enums.StatusEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.OpenedProductsServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.ModifyOpeningTimeVO;
import com.diagbot.vo.OpenUpOnTrialVO;
import com.diagbot.vo.ProductServiceSaveVO;
import com.diagbot.vo.StartAndendByUserIdVO;

/**
 * @Description:已开通产品业务层
 * @author: zhaops
 * @time: 2018/9/19 16:55
 */
@Component
public class OpenedProductsFacade extends OpenedProductsServiceImpl {
    @Autowired
    private ServiceInfoFacade serviceInfoFacade;
    @Autowired
    private ProductServiceFacade productServiceFacade;

    public List<OpenedProducts> getByAppkeyAndSecretFac(Map map) {
        return this.getByAppkeyAndSecret(map);
    }

    /**
     * 得到所有已开通的产品
     *
     * @return 所有已经开通的产品
     */
    public List<GetConsoleOpenedDTO> getConsoleOpened() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        
        List<GetConsoleOpenedDTO> retList = baseMapper.getConsoleOpened(userId);
        for(GetConsoleOpenedDTO i : retList){
        	String accessTypeMsg = "";
        	for(String j:i.getAccessType().split(",")){
        		accessTypeMsg+=AccessTypeEnum.getName(Integer.parseInt(j))+" ";
        	}
        	i.setAccessTypeMsg(accessTypeMsg);
        	i.setServiceStatusMsg(StatusEnum.getName(i.getServiceStatus()));
        }
        
        return retList;
    }

    /**
     * 得到所有可试用的产品
     *
     * @return 所有可试用的产品
     */
    public List<GetConsoleOnTrialDTO> getConsoleOnTrial() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        List<GetConsoleOnTrialDTO> retList = baseMapper.getConsoleOnTrial(userId);
        
        Date now = new Date();
        Date expirTime = null;
        for(GetConsoleOnTrialDTO i : retList){
        	String accessTypeMsg = "";
        	for(String j:i.getAccessType().split(",")){
        		accessTypeMsg+=AccessTypeEnum.getName(Integer.parseInt(j))+" ";
        	}
        	i.setAccessTypeMsg(accessTypeMsg);
        	i.setServiceStatusMsg(StatusEnum.getName(i.getServiceStatus()));
        	
        	if(StringUtil.isBlank(i.getAppKeyId())){
        		i.setIsUsed("N");
        	}else{
        		expirTime = DateUtil.parseDateTime(i.getExpiringDate());
        		if(expirTime.getTime()<now.getTime()
            			||i.getServiceStatus()==StatusEnum.Disable.getKey()
            			||i.getTokenStatus()==StatusEnum.Disable.getKey()){
            		i.setIsUsed("N");
            	}else{
            		i.setIsUsed("Y");
            	}
        		i.setSurplusTime(getDatePoor(expirTime, now));
        		i.setTokenStatusMsg(StatusEnum.getName(i.getTokenStatus()));
        	}
        	
        }
        
        return retList;
    }

    /**
     * 产品立即试用接口，返回所需要的token
     *
     * @param openUpOnTrialVO 产品立即试用接口请求参数
     * @return 包含token
     */
    public OpenUpOnTrialDTO openUpOnTrial(OpenUpOnTrialVO openUpOnTrialVO) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        String userName = UserUtils.getCurrentPrinciple();
        Date now = new Date();
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setType(2);
        serviceInfo.setUserId(userId);
        serviceInfo.setDescription("用户试用产品-虚拟服务");
        serviceInfo.setName("虚拟服务");
        serviceInfo.setCreator(userName);
        serviceInfo.setGmtCreate(now);
        serviceInfo.setIsDeleted("N");
        serviceInfoFacade.save(serviceInfo);

        ProductService productService = new ProductService();
        productService.setServiceId(serviceInfo.getId());
        productService.setProductId(openUpOnTrialVO.getProductId());
        productService.setCreator(userName);
        productService.setGmtCreate(now);
        productService.setIsDeleted("N");
        productServiceFacade.save(productService);

        ProductServiceSaveVO productServiceSaveVO = new ProductServiceSaveVO();
        productServiceSaveVO.setProductId(openUpOnTrialVO.getProductId());
        productServiceSaveVO.setServiceId(serviceInfo.getId());
        productServiceSaveVO.setType(3);
        ProductServiceDTO poroductServiceDTO = productServiceFacade.genProductService(productServiceSaveVO);

        OpenUpOnTrialDTO openUpOnTrialDTO = new OpenUpOnTrialDTO();
        openUpOnTrialDTO.setServiceToken(poroductServiceDTO.getServiceToken());

        return openUpOnTrialDTO;
    }

    /**
     * 计算可展示的选项卡
     *
     * @return 可展是的选项卡
     */
    public EnShowOptionDTO enShowOption() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        int openedCount = baseMapper.getConsoleOpenedCount(userId);
        int onTrialCount = baseMapper.getConsoleOnTrialCount(userId);

        EnShowOptionDTO enShowOptionDTO = new EnShowOptionDTO();
        enShowOptionDTO.setOpenedCount(openedCount);
        enShowOptionDTO.setOnTrialCount(onTrialCount);

        return enShowOptionDTO;
    }

    /**
     * @param startAndendByUserIdVO
     * @return 根据用户id和产品id，删除开通信息
     */
    public RespDTO<StartAndendByUserIdVO> startAndendByuserIds(StartAndendByUserIdVO startAndendByUserIdVO) {
        OpenedProducts openedProducts = new OpenedProducts();
        openedProducts.setUserId(startAndendByUserIdVO.getUserId());
        openedProducts.setProductId(startAndendByUserIdVO.getProductId());
        openedProducts.setCreator(UserUtils.getCurrentPrincipleID());
        openedProducts.setGmtCreate(DateUtil.now());
        openedProducts.setServiceStatus(startAndendByUserIdVO.getServiceStatus());
        boolean res = startAndendByuserId(openedProducts);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    /**
     * @param userId
     * @param productId
     * @return 根据用户id和产品id，删除开通信息
     */
    public RespDTO delInformationAvailables(Long userId, Long productId) {
        OpenedProducts openedProducts = new OpenedProducts();
        openedProducts.setUserId(userId);
        openedProducts.setProductId(productId);
        openedProducts.setCreator(UserUtils.getCurrentPrincipleID());
        openedProducts.setGmtCreate(DateUtil.now());
        boolean res = delInformationAvailable(openedProducts);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }

    /**
     * @param modifyOpeningTimeVO
     * @return 根据用户id和产品id，修改开通时间
     */
    public RespDTO<ModifyOpeningTimeVO> modifyOpeningTimes(ModifyOpeningTimeVO modifyOpeningTimeVO) {
        OpenedProducts openedProducts = new OpenedProducts();
        openedProducts.setUserId(modifyOpeningTimeVO.getUserId());
        openedProducts.setProductId(modifyOpeningTimeVO.getProductId());
        openedProducts.setStartTime(DateUtil.parseDate(modifyOpeningTimeVO.getStartTime()));
        openedProducts.setEndTime(DateUtil.parseDate(modifyOpeningTimeVO.getEndTime()));
        openedProducts.setCreator(UserUtils.getCurrentPrincipleID());
        openedProducts.setGmtCreate(DateUtil.now());
        boolean res = modifyOpeningTime(openedProducts);
        if (!res) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        return RespDTO.onSuc(res);
    }
    private String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
    
}
