package nckd.jimin.jyyy.bd.mservice;

import kd.bos.SessionIdUtils;
import kd.bos.context.RequestContext;
import kd.bos.context.RequestContextThreadBinder;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.db.tx.TX;
import kd.bos.db.tx.TXHandle;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.lang.Lang;
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.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.trace.util.TraceIdUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SaveTravleLogServiceImpl {
    private static final Log logger = LogFactory.getLog(SaveTravleLogServiceImpl.class);

    /**
     * 保存日志
     * @param logInfo
     * @return
     */
    public Map<String, Object> saveTravelLogData(DynamicObject logInfo){
        Map<String, Object> result = new HashMap();
        boolean success = true;
        String message = "";
        TXHandle h = TX.requiresNew();
        Throwable localThrowable4 = null;
        try
        {
            try
            {
                SaveServiceHelper.save(new DynamicObject[]{logInfo});
            }
            catch (Throwable e)
            {
                h.markRollback();
                success = false;
                message = "代他人出差申请日志保存失败," + e.getMessage();
                logger.error("代他人出差申请日志保存失败", e);
                throw e;
            }
        }
        catch (Throwable localThrowable2)
        {
            localThrowable4 = localThrowable2;throw localThrowable2;
        }
        finally
        {
            if (h != null) {
                if (localThrowable4 != null) {
                    try
                    {
                        h.close();
                    }
                    catch (Throwable localThrowable3)
                    {
                        localThrowable4.addSuppressed(localThrowable3);
                    }
                } else {
                    h.close();
                }
            }
        }
        result.put("message", message);
        result.put("success", Boolean.valueOf(success));
        return result;
    }


    /**
     * 生成HR代他人申请出差
     * @param tripInfo
     * @return
     */
    public Map<String, Object> saveHRTripData(DynamicObject tripInfo, String opKey, String operationKey){
        Map<String, Object> result = new HashMap();
        boolean success = true;
        String message = "";
        TXHandle h = TX.requiresNew();
        Throwable localThrowable4 = null;

        try{
            if("submiteffect".equals(opKey)){
                OperateOption option = OperateOption.create();
                option.setVariableValue(OperateOptionConst.ISHASRIGHT, "true");//不验证权限
                option.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true)); // 不执行警告级别校验器

                String currentUserId = RequestContext.get().getUserId();
                String creatorId = tripInfo.getDynamicObject("creator").getString("id");

                //撤销变更时，因为没有走流程，所欲需要重置当前用户。
                if(!currentUserId.equals(creatorId)) {
                    String tenantId = RequestContext.get().getTenantId();
                    // 直接从环境中获取数据中心id
                    String accountId = RequestContext.get().getAccountId();

                    Lang lang = Lang.defaultLang();
                    String traceId = TraceIdUtil.createTraceIdString();
                    RequestContext rc = RequestContext.create(true);
                    rc.setUserAgent("Guard_DB");
                    rc.setClient("Guard_DB");
                    rc.setTraceId(traceId);
                    rc.setTenantId(tenantId);
                    rc.setAccountId(accountId);
                    rc.setUserId(creatorId);
                    rc.setLang(lang);
                    rc.setGlobalSessionId(SessionIdUtils.newSessionId());
                    RequestContextThreadBinder.bind(rc);
                }

                OperationResult saveResult = OperationServiceHelper.executeOperate("save", "wtam_busitripbill", new DynamicObject[]{tripInfo}, option);

                if (!saveResult.isSuccess()) {
                    message = "生成对他人申请失败:{}" + saveResult;
                    logger.error("生成对他人申请失败:{}" + saveResult);
                } else {
                    Object pkId = saveResult.getSuccessPkIds().toArray()[0];

                    OperationResult submiteffect = OperationServiceHelper.executeOperate("submiteffect", "wtam_busitripbill", new Object[]{pkId}, option);

                    if (!submiteffect.isSuccess()) {
                        tripInfo.set("billstatus", "A");
                        SaveServiceHelper.save(new DynamicObject[]{tripInfo});

                        message = "生成对他人申请失败:{}" + submiteffect;
                        logger.error("生成对他人申请失败:{}" + submiteffect);
                    }
                }
            }
        } catch (Throwable e){
            h.markRollback();
            success = false;
            message = "代他人出差申请日志保存失败," + e.getMessage();
            logger.error("代他人出差申请日志保存失败", e);
            throw e;
        } finally {
            if (h != null) {
                if (localThrowable4 != null) {
                    try{
                        h.close();
                    }
                    catch (Throwable localThrowable3){
                        localThrowable4.addSuppressed(localThrowable3);
                    }
                } else {
                    h.close();
                }
            }
        }

        result.put("message", message);
        result.put("success", Boolean.valueOf(success));
        return result;
    }

    /**
     * 生成HR代他人申请出差
     * @param ids
     * @return
     */
    public Map<String, Object> deleteHRTripData(ArrayList<Long> ids){
        Map<String, Object> result = new HashMap();
        boolean success = true;
        String message = "";
        TXHandle h = TX.requiresNew();
        Throwable localThrowable4 = null;

        try{
            QFilter qFilter = new QFilter("nckd_tripreqbillid", QCP.in, ids);
            // 调用作废操作
            int deleteResult = DeleteServiceHelper.delete("wtam_busitripbill", new QFilter[]{qFilter});
        } catch (Throwable e){
            h.markRollback();
            success = false;
            message = "删除代他人出差申请日志失败," + e.getMessage();
            logger.error("删除代他人出差申请日志失败", e);

//            throw e;
        } finally {
            if (h != null) {
                if (localThrowable4 != null) {
                    try{
                        h.close();
                    }
                    catch (Throwable localThrowable3){
                        localThrowable4.addSuppressed(localThrowable3);
                    }
                } else {
                    h.close();
                }
            }
        }

        result.put("message", message);
        result.put("success", Boolean.valueOf(success));
        return result;
    }
}
