package shkd.bamp.base.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.permission.model.UserParam;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import shkd.utils.DobeDWUtils;

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

/**
 * 人员新增后台任务插件 yxl 20240830
 */
public class DobeDWpersonTask extends AbstractTask implements Plugin {
    private static final String entityName = "bos_user";//系统库 表名 t_sec_user
    private static final String personEntityName = "qeug_recon_personbank";//供应链库 人员收款银行账户 表名 tk_qeug_recon_personbank
    private static Log log = LogFactory.getLog(DobeDWpersonTask.class);
    private static final String dw_menthod = "mdm_user";

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(DobeDWUtils.dwUrl+dw_menthod)
                .post(DobeDWUtils.createRequestBody("person",1))
                .header("Content-Type", "application/json")
                .header("Authorization", DobeDWUtils.appCode)
                .build();

        String resultData = null;
        Response response = null;
        try {
            response = client.newCall(request).execute();
            resultData = response.body().string();
            log.info("人员接口返回结果:\n{}", resultData);
        } catch (IOException e) {
            log.info(String.format("人员接口异常:%s", e.getMessage()));
            throw new RuntimeException(e);
        }
        JSONObject json_body = JSON.parseObject(resultData);
        //接口返回的数据进行了分页
        int totalNum = json_body.getIntValue("totalNum");//分页-SQL查询总数据量
        List<String> exprtNumber = new ArrayList<>();//存储此次入参的所有工号,用于后续排除
        handleUser(json_body,exprtNumber);
        int queryCount = DobeDWUtils.getQueryCount(totalNum);
        if(queryCount > 1){
            //查询次数不止一次,需要分页查询
            for (int i = 2; i <= queryCount; i++) {
                request = new Request.Builder().url(DobeDWUtils.dwUrl+dw_menthod)
                        .post(DobeDWUtils.createRequestBody("person",i))
                        .header("Content-Type", "application/json")
                        .header("Authorization", DobeDWUtils.appCode)
                        .build();
                try {
                    response = client.newCall(request).execute();
                    resultData = response.body().string();
//                    log.info("人员接口返回结果:\n{}", resultData);
                } catch (IOException e) {
                    log.info(String.format("人员接口异常:%s", e.getMessage()));
                    throw new RuntimeException(e);
                }
                json_body = JSON.parseObject(resultData);
                handleUser(json_body,exprtNumber);
            }
        }
        //处理离职人员
        QFilter exprtFilter = new QFilter("number", QCP.not_in, exprtNumber);
        QFilter dwFilter = new QFilter("source", QCP.equals, "dw");
        QFilter enableFilter = new QFilter("enable", QCP.equals, "1");
        DynamicObject[] dos = BusinessDataServiceHelper.load("bos_user","id,enable,isforbidden",new QFilter[]{exprtFilter.and(dwFilter).and(enableFilter)});
        if(dos.length > 0){
            DynamicObject currentUser = null;
            for (int i = 0; i < dos.length; i++) {
                currentUser = dos[i];
                currentUser.set("enable", "0");//人员禁用
                currentUser.set("isforbidden", true);//用户禁用
            }
            //保存数据:直接保存入库,不走操作校验
            SaveServiceHelper.save(dos);
        }
    }

    private void handleUser(JSONObject json_body,List<String> exprtNumber) {
        //解析接口返回值,与系统数据比较
        JSONArray detailsJson = json_body.getJSONArray("data");
//        String userID = null;
        String number = null;
        String name = null;
//        String usertype = null;
        String phone = null;
        String email = null;
        String deptid = null;
        String jobposition = null;
        String bank = null;
        String bank_branch = null;
        String bank_account = null;

        List<UserParam> addList = new ArrayList<>();
//        List<UserParam> updateList = new ArrayList<>();
        UserParam user = null;
        DynamicObject personbank = null;
        DynamicObject deptOrg = null;
        Map<String, Object> dataMap = null;
        for (int i = 0; i < detailsJson.size(); i++) {
            json_body = detailsJson.getJSONObject(i);
//            userID = json_body.getString("user_id");
            number = json_body.getString("user_code");//工号,作为唯一值?
            name = json_body.getString("user_name");
            email = json_body.getString("email");
            phone = json_body.getString("mobile_phone");
            deptid = json_body.getString("department_id");//部门id
            jobposition = json_body.getString("jobposition");//职位
            bank = json_body.getString("bank");//银行
            bank_branch = json_body.getString("bank_branch");//支行
            bank_account = json_body.getString("bank_account");//账号
            if(DobeDWUtils.isEmpty(number) || DobeDWUtils.isEmpty(name)){
                log.info(String.format("人员入参为空异常:%s", json_body.toJSONString()));
                continue;
            }
            //根据叶经理要求:人员新增时判断工号是否以wb开头(代表编外人员),如果是则不同步 yxl 20241009
            if(number.startsWith("wb")){
                continue;
            }
            exprtNumber.add(number);
//            currentUser = QueryServiceHelper.queryOne(entityName,"id,number,name",new QFilter[]{new QFilter("number","=",number)});
            if(!QueryServiceHelper.exists(entityName,new QFilter[]{new QFilter("number","=",number)})){
                //根据工号来查询是否存在此用户,不存在时,新增用户
                user = new UserParam();//常用或者重要的参数,详情请查看参数对象UserParam
                dataMap = new HashMap<>();
                //user.setCustomUserId(123456780L); 外部系统的id作为本系统的id
                dataMap.put("number", number);//人员编码,即是工号
                dataMap.put("name", name);//姓名
                dataMap.put("username", number);//数仓的工号作为星瀚的用户名
                dataMap.put("usertype", "1");//用户类型 1-职员
                dataMap.put("phone", phone);//手机号
                dataMap.put("email", email);//电子邮箱
                dataMap.put("source", "dw");//数据来源于数仓
//                dataMap.put("fuid", userID);//云之家账号内码
//                dataMap.put("idcard", "");//身份证
//                dataMap.put("birthday", "1993-8-8");//生日
//                dataMap.put("gender", "1");//性别1男 0女
                user.setDataMap(dataMap);
                addList.add(user);
                //处理部门和职位
                if(!DobeDWUtils.isEmpty(deptid)){
                    deptOrg = QueryServiceHelper.queryOne("bos_org","id,number,name",new QFilter[]{new QFilter("fyzjorgid","=",deptid)});
                    if(deptOrg != null){
                        List<Map<String, Object>> posList = new ArrayList<>();
                        Map<String, Object> entryentity = new HashMap<>();
                        entryentity.put("dpt", deptOrg.getLong("id"));//设置部门ID
                        //职位名称 为空时,默认为编外人员
                        if(DobeDWUtils.isEmpty(jobposition)){
                            entryentity.put("position", "编外人员");//职位名称
                        }else{
                            entryentity.put("position", jobposition);//职位名称
                        }
                        entryentity.put("isincharge", false);//是否负责人
                        entryentity.put("ispartjob", false);//是否兼职
                        entryentity.put("seq", 1);//职位顺序号 1
                        posList.add(entryentity);
                        dataMap.put("entryentity", posList);
                    }else{
                        log.info(String.format("数仓的部门在金蝶中未找到对应组织:%s", deptid));
                    }
                }
                //处理新增人员收款银行账户
                if(DobeDWUtils.isEmpty(bank_account)){
                    continue;
                }
                personbank = BusinessDataServiceHelper.newDynamicObject(personEntityName);
                personbank.set("number",number);
                personbank.set("name",name);
                personbank.set("qeug_banknumber",bank_account);//银行账户
                personbank.set("qeug_bankname",bank_branch);//开户银行(支行)
                personbank.set("qeug_bank",bank);//银行
                personbank.set("status","C"); //单据状态默认为已审核
                personbank.set("enable",1);//默认可用
                //保存数据:直接保存入库,不走操作校验
                SaveServiceHelper.save(new DynamicObject[]{personbank});
            }
        }
        if(addList.size() > 0){
            UserServiceHelper.add(addList);
            //判断执行结果
            for (UserParam result : addList) {
                if (!result.isSuccess()) {
                    log.info(String.format("人员新增异常:%s", result.getMsg()));
                }
            }
        }
//        if(updateList.size() > 0){
//            UserServiceHelper.update(updateList);
//            //判断执行结果
//            for (UserParam result : updateList) {
//                if (!result.isSuccess()) {
//                    log.info(String.format("人员修改异常:%s", result.getMsg()));
//                }
//            }
//        }
    }
}