package com.weaver.seconddev.interfaces.workflow.action;

import javax.xml.namespace.QName;
import java.math.*;
import java.text.*;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.ebuilder.form.client.ebform.data.EbFormDataDubboService;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.seconddev.interfaces.htjt.util.LogUtil;
import com.weaver.seconddev.interfaces.htjt.util.WebApi;
import com.weaver.seconddev.interfaces.htjt.workflow.hr.HrUtil;
import com.weaver.seconddev.interfaces.workflow.util.CommonDevUtil;
import com.weaver.teams.domain.user.SimpleEmployee;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.conn.RecordSetDataSource;
import com.weaver.verupgrade.file.Prop;
import com.weaver.verupgrade.general.TimeUtil;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.interfaces.workflow.action.Action;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.general.BaseBean;

@org.springframework.stereotype.Service("workflow_action_ChuChaiShenQingNewAction")
public class ChuChaiShenQingNewAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    private static final Logger logger_fee0cda9 = LoggerFactory.getLogger(ChuChaiShenQingNewAction.class);

    @Autowired
    private CommonDevUtil commonDevUtil;

    @RpcReference(group = "ebuilderform")
    private EbFormDataDubboService ebFormDataDubboService;

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        // ChuChaiShenQing po = new ChuChaiShenQing();
        // String str = po.Getexecute(requestid,GH,QJLB,beginDateTime,endDateTime,QJSS);
        try {
            logger_fee0cda9.error(String.valueOf("ChuChaiShenQingNewAction request:" + request.getRequestid()));
            String requestid = request.getRequestid();
//            String lastoperator = request.getLastoperator();
            // TODO 有参构造 :new RecordSetDataSource("hr") 实例化方式改变,请检查是否有对应有参实现
            RecordSet rdsd = I18nContextUtil.getBean(RecordSet.class);
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            String workflowid = request.getWorkflowid();
            String requestname = request.getRequestManager().getRequestname();
            // 工号
            String GH = "";
            // 请假类别
            String QJLB = "";
            // 请假日期
            String SQRQ = "";
            // 开始时间
            String KSSJ = "";
            // 结束日期
            String JSRQ = "";
            // 结束时间
            String JSSJ = "";
            // 几小时
            String JXS = "";
            // 几天
            String JT = "";
            // 出差随行人员
            String CCSXRY = "";
            // 工号
            String CODE = "";
            // 获取表单主字段信息
            Property[] properties = request.getMainTableInfo().getProperty();
            for (int i = 0; i < properties.length; i++) {
                // 主表数据
                // 字段名
                String name = properties[i].getName().toUpperCase();
                // 值
                String value = Util.null2String(properties[i].getValue());
                if (name.equals("GH")) {
                    GH = value;
                } else if (name.equals("CCLB")) {
                    String poolname = "";
                    // TODO E10必须指定poolname数据源
                    String sql = "select classcode from e10_common.dbo.ht_ATDATTENDANCECLASS where ID='" + value + "'";

                    logger_fee0cda9.error("sql == " + sql );
                    rdsd.executeSql(sql, "hr");
                    rdsd.next();
                    QJLB = Util.null2String(rdsd.getString("classcode"));
                    logger_fee0cda9.error("QJLB == " + QJLB );
                } else if (name.equals("KSRQ")) {
                    SQRQ = value;
                } else if (name.equals("KSSJ")) {
                    KSSJ = value;
                } else if (name.equals("JSRQ")) {
                    JSRQ = value;
                } else if (name.equals("JSSJ")) {
                    JSSJ = value;
                } else if (name.equals("TS")) {
                    JT = value;
                } else if (name.equals("CCSXRY")) {
                    CCSXRY = value;
                }
            }
            String beginDateTime = SQRQ + " " + KSSJ;
            String endDateTime = JSRQ + " " + JSSJ;
            double QJSS = 0;
            QJSS = Double.parseDouble(JT) * 24;
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                Date d1 = df.parse(beginDateTime);
                Date d2 = df.parse(endDateTime);
                double diff = d2.getTime() - d1.getTime();
                double xs = diff / (1000 * 60 * 60);
                DecimalFormat ss = new DecimalFormat("#.00");
                String strss = ss.format(xs);
                QJSS = Double.parseDouble(strss);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
            // ChuChaiShenQing po = new ChuChaiShenQing();
            // String str = po.Getexecute(requestid,GH,QJLB,beginDateTime,endDateTime,QJSS);
            // /推送E-HR
            LogUtil logUtil = new LogUtil();
            logUtil.setJklm("ChuChaiShenQingNewAction");
            logUtil.setLx("1");
            logUtil.setBt(requestname);
            logUtil.setLcid(requestid);
            logUtil.setLclxid(workflowid);
            HrUtil hu = new HrUtil();
            BaseBean log = new BaseBean();
            Map<String, String> xtpz = hu.getHrurl(GH, rs);
            String hrapiurl = xtpz.get("hrapiurl");
            String hrtoken = xtpz.get("hrtoken");
            String hrloginname = xtpz.get("hrloginname");
            String hrygwcid = xtpz.get("hrygwcid");
            logger_fee0cda9.error(String.valueOf(requestid + " hrapiurl:" + hrapiurl));
            JSONObject hrparam = new JSONObject();
            hrparam.put("AccessToken", hrtoken);
            hrparam.put("LogonInfo", "LoginName=" + hrloginname + "&BusinessUnit=0&LogonRegion=zh-CN&ExpiredDate=" + hu.getExpiredDate() + "&ServiceCode=createleave");
            JSONObject data = new JSONObject();
            data.put("formno", getForm(requestid));
            JSONArray detail = new JSONArray();
            JSONObject jo = new JSONObject();
            jo.put("Employeeid", GH);
            jo.put("leavetypeid", hrygwcid);
            jo.put("begindate", beginDateTime.substring(0, 10));
            jo.put("begintime", beginDateTime.substring(11, 16));
            jo.put("enddate", endDateTime.substring(0, 10));
            jo.put("endtime", endDateTime.substring(11, 16));
            detail.add(jo);
            if (CCSXRY != null && !CCSXRY.equals("")) {
                String[] aa = CCSXRY.split(",");
                for (int i = 0; i < aa.length; i++) {
                    CODE = "";
                    String poolname_lv = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b = rs.executeSql("select job_num from eteams.dbo.employee as  HrmResource where id = " + aa[i], poolname_lv);
                    logger_fee0cda9.error("b--"+b);
                    if (rs.next()) {
                        CODE = Util.null2String(rs.getString("workcode"));
                        jo = new JSONObject();
                        jo.put("Employeeid", CODE);
                        jo.put("leavetypeid", hrygwcid);
                        jo.put("begindate", beginDateTime.substring(0, 10));
                        jo.put("begintime", beginDateTime.substring(11, 16));
                        jo.put("enddate", endDateTime.substring(0, 10));
                        jo.put("endtime", endDateTime.substring(11, 16));
                        detail.add(jo);
                    }
                    // str = po.Getexecute(requestid,CODE,QJLB,beginDateTime,endDateTime,QJSS);
                    // 
                    // if(!str.equals("SUCCESS")){
                    // request.getRequestManager().setMessageid("100001");
                    // request.getRequestManager().setMessagecontent(CODE + str);
                    // continue;
                    // }
                }
            }
            String str = "failed";
            String hrstate = "E";
            data.put("detail", detail);
            hrparam.put("Data", data);
            logger_fee0cda9.error(requestid + " ChuChaiShenQingNewAction param:" + hrparam.toJSONString());
            logUtil.setTscs(hrparam.toJSONString());
            try {
                String result = WebApi.postConnection(hrapiurl, hrparam.toJSONString(), "POST");
                logger_fee0cda9.error(String.valueOf(requestid + " result:" + result));
                logUtil.setFhxx(result);
                JSONObject json = JSON.parseObject(result);
                boolean IsSuccess = json.getBoolean("IsSuccess");
                String Message = json.getString("Message");
                if (!IsSuccess) {
                    logUtil.setJkzt("1");
                    logUtil.insertLog();
                    str = Message;
                } else {
                    str = "SUCCESS";
                    hrstate = "S";
                }
            } catch (Exception e) {
                logUtil.setFhxx("异常信息：" + e.getMessage());
                logUtil.setJkzt("2");
                logUtil.insertLog();
                logger_fee0cda9.error(String.valueOf(requestid + " ChuChaiShenQingNewAction error:" + e.getMessage()));
                logger_fee0cda9.error(String.valueOf(e));
                str = e.toString();
            }
            if (str.length() > 150) {
                str = str.substring(0, 150);
            }
//            String sql = "insert into e10_common.dbo.chuchai_qingjia_log(id, requestId,gh,lbbh,kssj,jssj,message,state,qjss) values(? , '" + requestid + "','','A11','" + beginDateTime + "','" + endDateTime + "','" + str + "','" + hrstate + "','" + QJSS + "')";
//            String poolname_bv = CONN_TYPE.workflow.getType();
//            /* *TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//            long generate = IdGenerator.generate();
//
//            rs.executeSql(sql, poolname_bv,generate);
            Long uf_CustomFlow_formId1 = commonDevUtil.getObjId("chuchai_qingjia_log");
            logger_fee0cda9.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId1);
            SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
            Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId1, currentEmployee);
            String poolname1 = CONN_TYPE.workflow.getType();
            String sql = "update e10_common.dbo.chuchai_qingjia_log set requestId = '" + requestid + "',gh = '',lbbh='A11',kssj='" + beginDateTime + "',jssj='" + endDateTime + "',message='" + str + "',state='" + hrstate + "',qjss='" + QJSS + "' where id = " + recodId;
            boolean b1 = rs.executeSql(sql, poolname1);
            logger_fee0cda9.error(String.valueOf("sql2:" + sql));
            logger_fee0cda9.error(String.valueOf("b1:" + b1));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_fee0cda9.error("ChuChaiShenQingNewAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ChuChaiShenQingNewAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
        }
    }

    private static String getForm(String requestid){
        String newform = "";
        if(requestid.length()>8){
            newform = "1"+requestid.substring(requestid.length()-8);
        }
        return newform;
    }
    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
