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

import javax.xml.namespace.QName;
import java.text.*;
import java.util.*;

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.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.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_QingJiaShenQingAction")
public class QingJiaShenQingAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_13aa9db7 = LoggerFactory.getLogger(QingJiaShenQingAction.class);

    @Autowired
    private CommonDevUtil commonDevUtil;

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

    /*
    private Log log = LogFactory.getLog(QingJiaShenQingAction.class.getName());

    public Log getLog() {
        return log;
    } 
    public void setLog(Log log) {
        this.log = log;
    } 
	*/
    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);
        // RecordSet rs = new RecordSet();
        // RecordSet rs2 = new RecordSet();
        // String workflowid = request.getWorkflowid();
        // String maintable = "";
        // String sql = "select b.tablename from workflow_base a,workflow_bill b where a.formid = b.id and a.id = " + workflowid;
        // String createsqlString = "select d.id,h.loginid,h.lastname,d.departmentmark from workflow_requestbase t,hrmresource h,hrmdepartment d where  h.id = t.creater and h.departmentid=d.id and t.requestid = "+requestid;
        // rs2.execute(createsqlString);
        // rs2.next();
        // String createrNameId = rs2.getString("loginid");
        // int departmentId = Util.getIntValue(rs2.getString("id"));
        // String creater = rs2.getString("departmentmark") + "_" + rs2.getString("lastname");
        // rs.executeSql(sql);
        // while(rs.next()){
        // maintable = rs.getString("tablename");
        // }
        try {
            logger_13aa9db7.error(String.valueOf("do QingJiaShenQingAction on request:" + request.getRequestid()));
            String requestid = request.getRequestid();
            /*String lastoperator = request.getLastoperator();
 TODO 有参构造 :new RecordSetDataSource("hr") 实例化方式改变,请检查是否有对应有参实现 */
//            RecordSetDataSource rdsd = I18nContextUtil.getBean(RecordSetDataSource.class).setPoolname("hr");
            RecordSet rdsd = I18nContextUtil.getBean(RecordSet.class);
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            String state = "E";
            String str = "failed";
            // RecordSet rs = new RecordSet();
            // RecordSet rs2 = new RecordSet();
            // String workflowid = request.getWorkflowid();
            // String maintable = "";
            // String sql = "select b.tablename from workflow_base a,workflow_bill b where a.formid = b.id and a.id = " + workflowid;
            // String createsqlString = "select d.id,h.loginid,h.lastname,d.departmentmark from workflow_requestbase t,hrmresource h,hrmdepartment d where  h.id = t.creater and h.departmentid=d.id and t.requestid = "+requestid;
            // rs2.execute(createsqlString);
            // rs2.next();
            // String createrNameId = rs2.getString("loginid");
            // int departmentId = Util.getIntValue(rs2.getString("id"));
            // String creater = rs2.getString("departmentmark") + "_" + rs2.getString("lastname");
            // rs.executeSql(sql);
            // while(rs.next()){
            // maintable = rs.getString("tablename");
            // }
            // 工号
            String GH = "";
            // 请假类别
            String QJLB = "";
            // 请假日期
            String SQRQ = "";
            // 开始时间
            String KSSJ = "";
            // 结束日期
            String JSRQ = "";
            // 结束时间
            String JSSJ = "";
            // 几小时
            String JXS = "";
            // 几天
            String JT = "";
            // 小计天数
            String XJTS = "";
            // 获取表单主字段信息
            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("QJLB2")) {
                    String poolname = "";
                    // TODO E10必须指定poolname数据源
                    boolean b = rdsd.executeSql("select classcode from ht_ATDATTENDANCECLASS where ID='" + value + "'", "hr");
                    logger_13aa9db7.error("b == " + b);
                    rdsd.next();
                    QJLB = Util.null2String(rdsd.getString("classcode"));
                } else if (name.equals("SQRQ")) {
                    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("JXS1")) {
                    JXS = value;
                } else if (name.equals("JT1")) {
                    JT = value;
                } else if (name.equals("XJTS")) {
                    XJTS = value;
                }
                // log.error("main:"+requestid+"	"+name+"	"+value);
            }
            // double QJSS = Double.parseDouble(JT)*24+Double.parseDouble(JXS);
            double QJSS = 9.00;
            String beginDateTime = SQRQ + " " + KSSJ;
            String endDateTime = JSRQ + " " + JSSJ;
            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());
            }
            try {
                // LeaveApplyFormWS (GH,QJLB,beginDateTime,endDateTime,QJSS);
                String endPoint = "http://10.6.2.12/hengtongws/HengtongWebService.asmx";
                String soapaction = "http://tempuri.org/";
                Service service = new Service();
                Call call1 = (Call) service.createCall();
                call1.setTimeout(Integer.valueOf(30000));
                call1.setTargetEndpointAddress(new java.net.URL(endPoint));
                call1.setOperationName(new QName(soapaction, "LeaveApplyFormWS"));
                call1.addParameter(new QName(soapaction, "PersonID"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "AttendanceType"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "BeginDateTime"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "EndDateTime"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "Hours"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.setReturnType(new QName(soapaction, "LeaveApplyFormWS"), String.class);
                call1.setUseSOAPAction(true);
                call1.setSOAPActionURI(soapaction + "LeaveApplyFormWS");
                logger_13aa9db7.error(String.valueOf("GH:----" + GH));
                logger_13aa9db7.error(String.valueOf("QJLB:----" + QJLB));
                logger_13aa9db7.error(String.valueOf("beginDateTime:----" + beginDateTime));
                logger_13aa9db7.error(String.valueOf("endDateTime:----" + endDateTime));
                logger_13aa9db7.error(String.valueOf("QJSS:----" + QJSS));
                str = (String) call1.invoke(new Object[] { GH, QJLB, beginDateTime, endDateTime, QJSS + "" });
                logger_13aa9db7.error(String.valueOf("str:" + str));
                if (!str.equals("SUCCESS")) {
                    request.getRequestManager().setMessageid("100001");
                    request.getRequestManager().setMessagecontent(GH + "----" + str);
                    return  WeaResult.fail(500, GH + "----" + str, getResultMapForAction(weaverResultMap, "result",GH + "----" + str, request.getRequestManager()));

                } else {
                    state = "S";
                }
                String qjss = QJSS + "";
//                String sql = "insert into chuchai_qingjia_log(requestId,gh,lbbh,kssj,jssj,message,state,qjss) values('" + requestid + "','" + GH + "','" + QJLB + "','" + beginDateTime + "','" + endDateTime + "','" + str + "','" + state + "','" + qjss + "')";
//                String poolname_t3 = CONN_TYPE.workflow.getType();
//                /*String sql = "insert into chuchai_qingjia_log(reqid,gh,lbbh,kssj,jssj,message,state,qjss) values('"+ requestid +"','"+ GH +"','"+QJLB+"','"+beginDateTime+"','"+endDateTime+"','"+str+"','"+state+"','"+qjss+"')";
// 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_t3,generate);
                String poolname = CONN_TYPE.hrm.getType();
                Long uf_CustomFlow_formId = commonDevUtil.getObjId("chuchai_qingjia_log");
                logger_13aa9db7.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId);
                SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
                Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);// 获取插入的空的建模id
                String sql3 = "update e10_common.dbo.chuchai_qingjia_log set requestId='" + requestid + "',gh='" + GH + "',lbbh='" + QJLB + "',kssj='" + beginDateTime + "',jssj='" + endDateTime + "',message='" + str + "',state='" + state + "',qjss='" + qjss + "' where id  =  " + recodId + " and delete_type = 0 ";
                boolean b1 = rs.executeSql(sql3, poolname);
                logger_13aa9db7.error("sql3 = " + sql3);
                logger_13aa9db7.error("添加 = " + b1);
                // System.out.println(str);
            } catch (Exception e) {
                System.err.println(e.toString());
                // str = e.toString();
                // writeLog("QingJiaShenQingAction--exception:"+str);
                str = e.getMessage();
                String qjss = QJSS + "";
//                String sql = "insert into chuchai_qingjia_log(requestId,gh,lbbh,kssj,jssj,message,state,qjss) values('" + requestid + "','" + GH + "','" + QJLB + "','" + beginDateTime + "','" + endDateTime + "','" + str + "','" + state + "','" + qjss + "')";
//                String poolname_ft = 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_ft,generate);
//                logger_13aa9db7.error(String.valueOf(requestid + "QingJiaShenQingAction--exception:" + str));
                String poolname = CONN_TYPE.hrm.getType();
                Long uf_CustomFlow_formId = commonDevUtil.getObjId("chuchai_qingjia_log");
                SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
                Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);
                String sql3 = "update e10_common.dbo.chuchai_qingjia_log set requestId='" + requestid + "',gh='" + GH + "',lbbh='" + QJLB + "',kssj='" + beginDateTime + "',jssj='" + endDateTime + "',message='" + str + "',state='" + state + "',qjss='" + qjss + "' where id  =  " + recodId + " and delete_type = 0 ";
                boolean b1 = rs.executeSql(sql3, poolname);
                logger_13aa9db7.error("sql3 = " + sql3);
                logger_13aa9db7.error("添加 = " + b1);
                return  WeaResult.fail(500, "QingJiaShenQingAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_13aa9db7.error("QingJiaShenQingAction e: {}", e);
            return  WeaResult.fail(500, "QingJiaShenQingAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));
        }
    }

    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;
    }
}
