package com.diagbot.facade;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.ProductLineDTO;
import com.diagbot.dto.RenewalsInfosDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.UserOrgDTO;
import com.diagbot.entity.LantoneProduct;
import com.diagbot.entity.OpenedProducts;
import com.diagbot.entity.User;
import com.diagbot.entity.UserRenewals;
import com.diagbot.entity.wrapper.UserRenewalsWrapper;
import com.diagbot.enums.CancelRenewalsEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.RenewalsEnum;
import com.diagbot.enums.StatusEnum;
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.UserRenewalsServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.AddRenewalsInfoVO;
import com.diagbot.vo.DeleteRenewalsInfoVO;
import com.diagbot.vo.RenewalsInfosVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: wangyu
 * @time: 2018/10/12 15:31
 */
@Component
public class UserRenewalsFacade extends UserRenewalsServiceImpl {

    @Autowired
    private VisibleIdCreater visibleIdCreater;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private LantoneProductFacade lantoneProductFacade;
    @Autowired
    private OpenedProductsFacade openedProductsFacade;
    @Autowired
    private UserRenewalsFacade userRenewalsFacade;

    /**
     * 产品续费
     * @param addRenewalsInfoVO 参数
     * @return Boolean
     */
    public RespDTO<Boolean> addRenewalsInfos(AddRenewalsInfoVO addRenewalsInfoVO){
        LantoneProduct lantoneProduct = lantoneProductFacade.getById(addRenewalsInfoVO.getProductId());
        if(lantoneProduct.getIsDeleted().equals(IsDeleteEnum.Y.getKey())){
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "【"+lantoneProduct.getName()+"】已删除,请刷新页面");
        }
        if(lantoneProduct.getServiceStatus().intValue() == StatusEnum.Disable.getKey()){
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "【"+lantoneProduct.getName()+"】已停用,请刷新页面");
        }
        UserRenewals userRenewals =new UserRenewals();
        Map map =new HashMap();
        String user = UserUtils.getCurrentPrincipleID();
        map.put("productId",addRenewalsInfoVO.getProductId());
        map.put("userId",user);
        Long userId = Long.parseLong(user);
        userRenewals.setCreator(user);
        userRenewals.setUserId(userId);
        userRenewals.setApplyTime(DateUtil.now());
        userRenewals.setGmtCreate(DateUtil.now());
        userRenewals.setRenewalsNo(visibleIdCreater.getNextId(VisibleIdTypeEnum.IS_RENEWALS.getKey()).toString());
        List<OpenedProducts> openedProductsList = openedProductsFacade.selectOpenedProducts(map);
        if(ListUtil.isEmpty(openedProductsList)){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "该产品未开通，不能续费");
        }
        if(this.selectProductIdByUserId(map).contains(addRenewalsInfoVO.getProductId())){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请勿重复提交申请");
        }
        for (OpenedProducts openedProducts:openedProductsList) {
            if(openedProducts.getServiceStatus().intValue() == StatusEnum.Disable.getKey()){
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "您的产品已停用，请刷新页面");
            }
        }
        userRenewals.setProductId(addRenewalsInfoVO.getProductId());
        return RespDTO.onSuc(this.save(userRenewals));
    }

    /**
     * 续费列表显示
     * @param renewalsInfosVO
     * @return
     */
    public IPage renewalsInfo(RenewalsInfosVO renewalsInfosVO){
        Page page =new Page();
        BeanUtil.copyProperties(renewalsInfosVO,page);
        UserRenewalsWrapper userRenewalsWrapper =new UserRenewalsWrapper();
        BeanUtil.copyProperties(renewalsInfosVO,userRenewalsWrapper);
        userRenewalsWrapper.setCancelRenewals(CancelRenewalsEnum.NOT_CANCEL.getKey());
        if(StringUtil.isNotBlank(renewalsInfosVO.getOrgName())){
            RespDTO<List<Long>> rlist = userServiceClient.getUserByOrgName(renewalsInfosVO.getOrgName());
            if(rlist.data.size() == 0){
                rlist.data.add(-1L);
            }
            userRenewalsWrapper.setUserId(rlist.data);
        }else{
            RespDTO<List<User>> userInfiList = userServiceClient.getUserAllInfo();
            if(userInfiList == null || !"0".equals(userInfiList.code) ) {
                throw new CommonException(CommonErrorCode.RPC_ERROR,
                        "获取用户和机构信息失败");
            }
            List<Long> userIds =new ArrayList<>();
            for (User user:userInfiList.data) {
                userIds.add(user.getId());
            }
            userRenewalsWrapper.setUserId(userIds);
        }
        List<RenewalsInfosDTO> list = this.selectUserRenewals(page,userRenewalsWrapper).getRecords();
        List<ProductLineDTO> productList =lantoneProductFacade.productLinesB();
        Map<Long, ProductLineDTO> productMap = EntityUtil.makeEntityMap(productList,"id");
        List<Long> userIds =new ArrayList<>();
        for (RenewalsInfosDTO renewalsInfosDTO:list) {
            Long userId = renewalsInfosDTO.getUserId();
            userIds.add(userId);
        }
        List<OpenedProducts> opendList = openedProductsFacade.getOpendInfos();
        RespDTO<Map<Long, UserOrgDTO>> mapRespDTO = userServiceClient.getUserAndOrg(userIds);
        if(mapRespDTO == null || !"0".equals(mapRespDTO.code) ) {
            throw new CommonException(CommonErrorCode.RPC_ERROR,
                    "获取用户和机构信息失败");
        }
        Map<Long, UserOrgDTO> dataMap = mapRespDTO.data;
        for(RenewalsInfosDTO bean : list) {
            UserOrgDTO uo = dataMap.get(bean.getUserId());
            bean.setRenewalsStatusName(RenewalsEnum.getName(bean.getRenewalsStatus()));
//            for (ProductLineDTO productLineDTO:productList) {
//                if (productLineDTO.getId()==bean.getProductId()){
//                    bean.setProductName(productLineDTO.getName());
//                }
//            }
            if(bean.getRenewalsStatus().intValue() == RenewalsEnum.NOT_RENEWALS.getKey()){
                for (OpenedProducts openedProducts:opendList) {
                    if(openedProducts.getUserId().longValue() == bean.getUserId().longValue()&&openedProducts.getProductId().longValue() == bean.getProductId().longValue()){
                        bean.setEndTime(openedProducts.getEndTime());
                    }
                }
            }
            if (null != productMap && null != productMap.get(bean.getProductId())){
                bean.setProductName(productMap.get(bean.getProductId()).getName());
            }
            if(uo != null) {
                bean.setUsername(uo.getUsername());
                bean.setLinkman(uo.getLinkman());
                bean.setOrgName(uo.getOrgName());
            }
        }
        return page;
    }

    /**
     * 删除续费信息
     * @param deleteRenewalsInfoVO
     * @return Boolean
     */
    public Boolean deleteRenewalsInfo(DeleteRenewalsInfoVO deleteRenewalsInfoVO){
        UserRenewals userRenewals =this.getById(deleteRenewalsInfoVO.getId());
        userRenewals.setIsDeleted(IsDeleteEnum.Y.getKey());
        userRenewals.setModifier(UserUtils.getCurrentPrincipleID());
        userRenewals.setGmtModified(DateUtil.now());
        if(!this.updateById(userRenewals)){
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL,
                    "删除失败");
        }
        return true;
    }

    /**
     * 取消续费
     * @param deleteRenewalsInfoVO
     * @return Boolean
     */
    public Boolean cancelRenewalsInfo(DeleteRenewalsInfoVO deleteRenewalsInfoVO){
        UserRenewals userRenewals =this.getById(deleteRenewalsInfoVO.getId());
        userRenewals.setCancelRenewals(CancelRenewalsEnum.CANCEL_RENEWALS_ENUM.getKey());
        userRenewals.setModifier(UserUtils.getCurrentPrincipleID());
        userRenewals.setGmtModified(DateUtil.now());
        Map map =new HashMap();
        map.put("userId",userRenewals.getUserId());
        map.put("productId",userRenewals.getProductId());
        List<Long> renewalsList = userRenewalsFacade.selectProductIdByUserId(map);
        if(!renewalsList.contains(userRenewals.getProductId())){
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "续费单已审核,请刷新重试");
        }
        if(!this.updateById(userRenewals)){
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL,
                    "取消失败");
        }
        return true;
    }
}
