package com.malk.xiaoliu.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import com.malk.xiaoliu.service.personService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能：
 * 作者：hanxue
 * 日期：2026/5/7 17:33
 */
@Slf4j
@Service
public class personServiceImpl implements personService {
    @Autowired
    private YDClient ydClient;
    @Value("${rhr.client_id}")
    private String clientId;
    @Value("${rhr.client_secret}")
    private String clientSecret;
    @Value("${rhr.corpId}")
    private String corpId;
    @Value("${rhr.scope}")
    private String scope;
    @Value("${rhr.host}")
    private String host;

    @Override
    public void syncPerson(String orgId, String orgName) {
        log.info("开始同步人员的部门名为:{}，部门编号为:{}", orgName, orgId);
//        获取该部门下面所有人员
//        /open/api/v1/employee/list
        Map employeeBody = new HashMap();
        employeeBody.put("employeeStatus", "working");
        List orgIds = new ArrayList();
        orgIds.add(orgId);
        employeeBody.put("orgIds",orgIds);
        List<Map> employeeList = callRhrApi("/open/api/v1/employee/list",employeeBody);
        if(employeeList.size()>0){
        log.info("该部门中在职员工数量为:{}", employeeList.size());
        List<String> validValues = Arrays.asList("保底计件两者就高", "固定加计件提成", "全面计件");
        for (Map employeeItem : employeeList) {
            if(employeeItem.containsKey("field_emp_sele_009") && validValues.contains(UtilMap.getString(employeeItem, "field_emp_sele_009"))){
                log.info("计薪员工姓名为:{}", UtilMap.getString(employeeItem, "name"));
//                符合条件推送宜搭
                Map yidaDormdata = new HashMap();
//                员工姓名
                yidaDormdata.put("textField_mo15j8ga",UtilMap.getString(employeeItem,"name"));
//                手机号
                yidaDormdata.put("textField_mo15j8gb",UtilMap.getString(employeeItem,"mobileNumber"));
//                身份证号
                yidaDormdata.put("textField_mo87l3gr",UtilMap.getString(employeeItem,"idNumber"));
////                围栏
//                yidaDormdata.put("textField_mo15j8gd",UtilMap.getString(employeeItem,"idNumber"));
////                站点
//                yidaDormdata.put("textField_mo15j8ge",UtilMap.getString(employeeItem,"idNumber"));
//                职位
                yidaDormdata.put("textField_mo15j8gf",UtilMap.getString(employeeItem,"jobTitle"));
//                任职状态
                yidaDormdata.put("textField_mo15j8gg",UtilMap.getString(employeeItem,"employeeType"));
//                计薪方式
                yidaDormdata.put("textField_mowlu94w",UtilMap.getString(employeeItem,"field_emp_sele_009"));
                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-EB1B4529794044CF920C8745AE7B4DAAMBHR")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(
                                new YDSearch("textField_mo87l3gr",UtilMap.getString(employeeItem,"idNumber"), "textField_mo87l3gr",
                                        YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ)
                        )))
                        .useLatestVersion(true)
                        .formDataJson(JSONObject.toJSONString(yidaDormdata))
                        .build(), YDConf.FORM_OPERATION.upsert);
            }
        }
    }else{
            log.info("该部门中在职员工数量为:{}", employeeList.size());
    }
//        获取子部门进行递归
        Map deptBody = new HashMap();
        List parentOrgIds = new ArrayList();
        parentOrgIds.add(orgId);
        deptBody.put("parentOrgIdList",parentOrgIds);
        List<Map> childOrgList = callRhrApi("/open/api/v1/org/getOrgChildList",deptBody);
        for (Map childOrgItem : childOrgList) {
            String orgChildId = UtilMap.getString(childOrgItem, "orgId");
            Map orgDetail=UtilMap.getMap(childOrgItem,"dataMap");
            String orgChildName = UtilMap.getString(orgDetail, "name");
//            log.info("开始同步部门的部门名为:{}，部门编号为:{}", orgChildName, orgChildId);
            syncPerson(orgChildId, orgChildName);
        }
    }

//    调用睿人事接口方法
    public List<Map> callRhrApi(String url, Map body) {
        String token = getAccessToken();
        Map headers = new HashMap();
        headers.put("Authorization", "Bearer " + token);
        body.put("corpId", corpId);
        int page = 1;
        int pageSize = 100;
        body.put("page", page);
        body.put("pageSize", pageSize);
        List<Map> apiResList = new ArrayList();
        List<Map> resDataItems= new ArrayList();
        int totalCount=0;
        do {
            String response = UtilHttp.doPost(host + url, headers, null, body);
            Map resData = JSONObject.parseObject(response, Map.class);
            Map resDataList = UtilMap.getMap(resData, "data");
            resDataItems = UtilMap.getList(resDataList, "list");
            totalCount = UtilMap.getInt(resDataList, "total");
            if (resDataItems.size() > 0) {
                apiResList.addAll(resDataItems);
            }
            page++;  // 准备查询下一页
        } while (resDataItems.size() > 0 && totalCount > (page - 1) * pageSize);
        return apiResList;
    }
    //    getAccessToken
    public String getAccessToken()  {
        String accessToken =UtilToken.get("invalid-token");
        if (StringUtils.isNotBlank(accessToken)) return accessToken;
        Map params = new HashMap();
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        params.put("scope", scope);
        params.put("grant_type", "client_credentials");
        try {
            String oauToken =  UtilHttp.doPost(host+"/oauth2/token", null, params,(Map)null);
            Map tokenMap = JSONObject.parseObject(oauToken.toString(), Map.class);
            accessToken = UtilMap.getString(tokenMap, "access_token");
            Long timeout = UtilMap.getLong(tokenMap, "expires_in");
            UtilToken.put("invalid-token", accessToken, timeout * 1000L);
            return accessToken;
        }catch (Exception e){
            log.error("获取accessToken失败",e);
            throw new RuntimeException("获取 access_token 失败: " + e.getMessage(), e);
        }
    }
}
