package cn.ey.biz.module.system.api.hrm;

import cn.ey.biz.common.exception.ErrorCode;
import cn.ey.biz.common.pojo.R;
import cn.ey.biz.module.system.api.hrm.dto.HrmSimpleInfoRespDTO;
import cn.ey.biz.module.system.api.hrm.dto.HrmUserInfoDTO;
import cn.ey.biz.module.system.convert.hrm.HrmConvert;
import cn.ey.biz.module.system.service.hrm.HrmUserInfoWithService;
import cn.ey.biz.module.system.service.hrm.HrmUserInfoWithServicelmpl;
import cn.ey.biz.module.weaver.api.hrm.GetHrmSimpleInfoService;
import cn.ey.biz.module.weaver.common.HrmGetter;
import cn.ey.biz.module.weaver.common.UserContextHolder;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;
import static cn.ey.biz.module.system.enums.ApiConstants.VERSION;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@DubboService(version = VERSION) // 提供 Dubbo RPC 接口，给 Dubbo Consumer 调用
@Validated
public class HrmApilmpl implements HrmApi{

    @Resource
    GetHrmSimpleInfoService getHrmSimpleInfoService;
    @Resource
    HrmUserInfoWithService hrmUserInfoWithService;

    @Override
    public R<HrmSimpleInfoRespDTO> getHrmSimpleInfo(@Valid String userid) {
        try {
            UserContextHolder.set(HrmGetter.USER_ID, userid);
            GetHrmSimpleInfoService.HrmSimpleInfoRequest response = getHrmSimpleInfoService.getHrmSimpleInfo(userid);
            if (response != null) {
                HrmSimpleInfoRespDTO result = HrmConvert.INSTANCE.convert(response);
                return R.success(result);
            } else {
                throw exception(new ErrorCode(-1, "无记录"));
            }
        }finally {
            UserContextHolder.remove(HrmGetter.USER_ID);
        }
    }

    @Override
    public R<HrmUserInfoDTO> getWeaverUser(@Valid String userCode,String sysCode) {
        HttpServletRequest servletRequest=getRequest();
        servletRequest.setAttribute("sysCode",sysCode);
        HrmUserInfoWithServicelmpl.Item item=hrmUserInfoWithService.getWeaverUser(userCode);
        HrmUserInfoDTO result=HrmConvert.INSTANCE.convert(item);
        return R.success(result);
    }

    protected HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }

}
