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

import cn.ey.biz.common.exception.ErrorCode;
import cn.ey.biz.module.weaver.common.AppIdConfig;
import cn.ey.biz.module.weaver.common.Constants;
import cn.ey.biz.module.weaver.common.HrmGetter;
import cn.ey.biz.module.weaver.common.TokenGetter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 人力资源
 *
 */
@Service
@Validated
@Slf4j
public class HrmUserInfoWithServicelmpl implements HrmUserInfoWithService {

    @Value("${weaver.service.url}")
    String url;
    @Resource
    TokenGetter tokenGetter;
    @Resource
    AppIdConfig appIdConfig;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Item getWeaverUser(String userCode) {
        HttpServletRequest  servletRequest=getRequest();
        String sysCode=(String)servletRequest.getAttribute("sysCode");
        Map<String, String>  appIdMap=appIdConfig.getAppId();
        String app=appIdMap.get(sysCode);
        if(app==null){
            throw exception(new ErrorCode(-1,"获取不到泛微appId信息"));
        }

        String spk = stringRedisTemplate.opsForValue().get(Constants.SERVER_PUBLIC_KEY+app);
        RSA rsa = new RSA(null, spk);
        //对用户信息进行加密传输,暂仅支持传输OA用户ID
        String encryptUserid = rsa.encryptBase64("1", CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        //获取人员信息
        HrmUserInfoRequest params = new HrmUserInfoRequest();
        Param param = new Param();
        param.setWorkcode(userCode);
        params.setParams(param);

        //调用接口获取数据
        HttpRequest.closeCookie();
        String data = HttpRequest.post(url + "/api/hrm/resful/getHrmUserInfoWithPage")
                .header("Content-Type", "application/json; charset=utf-8")
                .header("appid", app)
                //.header("skipsession", "1")
                .header("token", tokenGetter.token(app))
                .header("userid",encryptUserid )
                .body(JSON.toJSONString(params))
                .execute().body();
        Response rsp = JSON.parseObject(data, Response.class);
        if(rsp.isSuccess()){
            Item item = rsp.getData()
                    .dataList
                    .stream()
                    .findFirst()
                    .orElseThrow(()->exception(new ErrorCode(-1, "获取不到用户信息")));
            if(item != null){
                return item;
            }else{
                log.error("Get hrm error:{}.", rsp);
            }
        }
        return null;
    }

    protected HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }
    //获取heard中的参数
    protected Map<String, String> getRequestHeaderMap() {
        HttpServletRequest request = getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headerMap = new HashMap<>(8);
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            headerMap.put(name, request.getHeader(name));
        }
        return headerMap;
    }

    @Data
    class HrmUserInfoRequest{
        Param params;
    }
    @Data
    class Param{
        String workcode;
    }
    @Data
    class Response{
        String code;
        HrmUserInfoResponse data;
        public boolean isSuccess(){
            return "1".equals(this.code);
        }
    }
    @Data
    class HrmUserInfoResponse{
        List<Item> dataList;
    }
    @Data
    public class Item{
        String companystartdate;
        String tempresidentnumber;
        String createdate;
        String language;
        String  workstartdate;
        String  subcompanyid1;
        String  subcompanyname;
        String joblevel;
        String  startdate;
        String  subcompanycode;
        String jobactivitydesc;
        String  bememberdate;
        String  modified;
        String  id;
        String  mobilecall;
        String  nativeplace;
        String certificatenum;
        String height;
        String loginid;
        String created;
        String  degree;
        String  bepartydate;
        String  weight;
        String telephone;
        String residentplace;
        String  lastname;
        String  healthinfo;
        String enddate;
        String maritalstatus;
        String  departmentname;
        String folk;
        String status;
        String  birthday;
        String isadaccount;
        String accounttype;
        String jobcall;
        String managerid;
        String  assistantid;
        String departmentcode;
        String belongto;
        String  email;
        String seclevel;
        String policy;
        String  jobtitle;
        String  workcode;
        String  sex;
        String departmentid;
        String  homeaddress;
        String mobile;
        String lastmoddate;
        String  educationlevel;
        String  islabouunion;
        String  locationid;
        String regresidentplace;
        String  dsporder;
    }

}
