package com.yizhi.application.settlement.handler;

import com.yizhi.application.settlement.annotation.SettlementHandlerType;
import com.yizhi.application.settlement.vo.SettlementBaseVo;
import com.yizhi.application.settlement.vo.TrainingInfoVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.mall.application.feign.TokenControllerClient;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.util.application.domain.BizResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 结算台项目详情获取 结算台项目type=200  TokenLogType枚举
 */
@Component
@SettlementHandlerType(type = 200)
public class TrainingHandler implements SettlementBaseHandler{

    private static Logger logger = LoggerFactory.getLogger(TrainingHandler.class);

    @Autowired
    private TrainingProjectClient projectClient;
    @Autowired
    private TokenControllerClient tokenControllerClient;


    /**
     * 获取指定的类型详情
     *
     * @param id 需要获取的类型的id；例如 项目id
     */
    @Override
    public BizResponse<SettlementBaseVo> handler(Long id) {

        TrainingInfoVo trainingInfoVo = new TrainingInfoVo();
        BizResponse<TrainingProjectVo> response = projectClient.getProjectDescription(id);
        if (null == response || null == response.getData()){
            logger.error("结算台获取项目失败;id= {}",id);
            return BizResponse.fail(InternationalEnums.TPPLANCONTROLLER6.getCode());
        }
        TrainingProjectVo data = response.getData();

        trainingInfoVo.setName(data.getName());
        trainingInfoVo.setActualPrice(data.getActualPrice());
        trainingInfoVo.setStartTime(data.getStartTime());
        trainingInfoVo.setEndTime(data.getEndTime());
        trainingInfoVo.setImagePath(data.getLogoImg());
        //获取用户剩余金额
        BizResponse<Integer> tokenResponse = tokenControllerClient.getTokenAmount();
        if (null == tokenResponse || null == tokenResponse.getData()){
            logger.error("结算台获取用户剩余金币数失败;id= {},accountId = {}",id, ContextHolder.get().getAccountId());
            return BizResponse.fail(InternationalEnums.TPPLANCONTROLLER6.getCode());
        }
        Integer total = tokenResponse.getData();
        logger.info("结算台获取用户剩余金币数;trainingId= {},accountId = {},total = {}",id, ContextHolder.get().getAccountId(),total);
        if (null == total || total.compareTo(0) < 0){
            logger.error("结算台获取用户剩余金币数失败;id= {},accountId = {},total = {}",id, ContextHolder.get().getAccountId(),total);
            return BizResponse.fail(InternationalEnums.TPPLANCONTROLLER6.getCode());
        }
        trainingInfoVo.setAccountBalance(total);
        return BizResponse.ok(trainingInfoVo);
    }
}
