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.dataentity.entity.DynamicObjectCollection;
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 shkd.utils.OAUtils;

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

/**
 * 人员修改后台任务插件 yxl 20240910
 */
public class DobeDWpersonUpdateTask 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 final String proficientName = "rebm_proficient";//供应链库 评标专家库 表名 t_bid_proficient
    private static final String proficientTypeName = "rebm_proficienttype";//供应链库 专家专业分类 表名 t_bid_majortype
    private static Log log = LogFactory.getLog(DobeDWpersonUpdateTask.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);
        }
        boolean personoabid = false;
        if(map != null && "yes".equals(map.get("personoabid"))){
            personoabid = true;
        }
        JSONObject json_body = JSON.parseObject(resultData);
        //接口返回的数据进行了分页
        int totalNum = json_body.getIntValue("totalNum");//分页-SQL查询总数据量
        handleUser(json_body,personoabid);
        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,personoabid);
            }
        }

    }

    private void handleUser(JSONObject json_body,boolean personoabid) {
        //解析接口返回值,与系统数据比较
        JSONArray detailsJson = json_body.getJSONArray("data");
//        String userID = null;
        String number = null;
        String name = 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> updateList = new ArrayList<>();
        List<DynamicObject> userinfos = new ArrayList<>();
        UserParam user = null;
        DynamicObject currentUser = null;
        DynamicObject deptOrg = null;
        DynamicObject personbank = null;
        Map<String, Object> dataMap = null;
        DynamicObject proficientInfo = null;//评标专家库
        DynamicObject ptinfo = BusinessDataServiceHelper.loadSingleFromCache(proficientTypeName,"id,number,name",new QFilter[]{new QFilter("number","=","00")});
        DynamicObjectCollection ptcoll = 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;
            }
            currentUser = QueryServiceHelper.queryOne(entityName,"id,number,name",new QFilter[]{new QFilter("number","=",number)});
            if(currentUser != null){
                user = new UserParam();//常用或者重要的参数,详情请查看参数对象UserParam
                dataMap = new HashMap<>();
                //修改 姓名、是否启用、手机、邮箱、职位、部门等情况
                user.setId(currentUser.getLong("id"));
                dataMap.put("name", name);//姓名
                dataMap.put("phone", phone);//手机号
                dataMap.put("email", email);//电子邮箱
                user.setDataMap(dataMap);
                updateList.add(user);
                //组装要与OA绑定的人员集合
                if(personoabid){
                    userinfos.add(currentUser);
                }
                //处理部门和职位
                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));
                    }
                }
                //处理新增 评标专家库
                proficientInfo = BusinessDataServiceHelper.loadSingle(proficientName,new QFilter[]{new QFilter("billno","=",number)});
                if(proficientInfo == null && deptOrg != null && ptinfo != null){
                    proficientInfo = BusinessDataServiceHelper.newDynamicObject(proficientName);
                    proficientInfo.set("billno",number);//专家编号
                    proficientInfo.set("name",name);//专家姓名
                    proficientInfo.set("type","internalExperts");//专家来源--默认内部专家
                    proficientInfo.set("telephone",phone);//手机号
                    ptcoll = proficientInfo.getDynamicObjectCollection("majortype");
                    DynamicObject newptinfo = new DynamicObject(ptcoll.getDynamicObjectType());
                    newptinfo.set("fbasedataId", ptinfo);
                    ptcoll.add(newptinfo);
                    proficientInfo.set("majortype",ptcoll);//专业分类
                    proficientInfo.set("org",deptOrg.getLong("id"));//采购组织
                    proficientInfo.set("userdstatus","Enable"); //使用状态--默认可用
                    proficientInfo.set("billstatus","C"); //使用状态--默认已审核
                    proficientInfo.set("politicalstatus","other"); //政治面貌--默认其他
                    proficientInfo.set("majortypenames",ptinfo.getString("name")); //专业分类名称字符串
                    proficientInfo.set("entitytypeid",proficientName); //实体类型ID
                    //保存数据:直接保存入库,不走操作校验
                    SaveServiceHelper.save(new DynamicObject[]{proficientInfo});
                }
                //处理人员收款银行账户的修改,银行账户为空时,不处理
                if(DobeDWUtils.isEmpty(bank_account)){
                    continue;
                }
                personbank = BusinessDataServiceHelper.loadSingle(personEntityName,new QFilter[]{new QFilter("number","=",number)});
                if(personbank != null){
                    if(isNeedUpdate(personbank,name,bank,bank_branch,bank_account)){
                        //姓名、银行账户、开户银行任意一个不相同则更新
                        personbank.set("name",name);
                        personbank.set("qeug_banknumber",bank_account);//银行账户
                        personbank.set("qeug_bankname",bank_branch);//开户银行(支行)
                        personbank.set("qeug_bank",bank);//银行
                        SaveServiceHelper.update(personbank);
                    }
                }else{
                    //新增
                    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(updateList.size() > 0){
            UserServiceHelper.update(updateList);
            //判断执行结果
            for (UserParam result : updateList) {
                if (!result.isSuccess()) {
                    log.info(String.format("人员修改异常:%s", result.getMsg()));
                }
            }
        }
        //调用OA人员绑定
        if(userinfos.size() > 0){
            String billNo = "person-first-all-bid";
            //获取token
            String oaToken = OAUtils.getOaToken(billNo);
            if (!DobeDWUtils.isEmpty(oaToken)) {
                OAUtils.thirdpartyUser(userinfos, oaToken, billNo);
            }
        }
    }
    private boolean isNeedUpdate(DynamicObject personbank,String name,String bank,String bank_branch,String bank_account){
        if(!name.equals(personbank.getString("name"))){
            return true;
        }else if(!bank_account.equals(personbank.getString("qeug_banknumber"))){
            return true;
        }else if(DobeDWUtils.isEmpty(bank) || !bank.equals(personbank.getString("qeug_bank"))){
            return true;
        }else if(DobeDWUtils.isEmpty(bank_branch) || !bank_branch.equals(personbank.getString("qeug_bankname"))){
            return true;
        }
        return false;
    }
}