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

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

import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
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 com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import java.util.*;
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 com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.soa.workflow.request.*;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.soa.workflow.request.Cell;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

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

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

    private static final Logger logger_eae3b780 = LoggerFactory.getLogger(NewBuKaAction.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);
        try {
            String requestid =String.valueOf(requestIdTemp);
            try {
                logger_eae3b780.error(String.valueOf("NewBuKaAction--start--" + requestid));
                String creater = request.getCreatorid();
                logger_eae3b780.error(String.valueOf("creater:" + creater));
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
//                String createsqlString = "select id  from  eteams.dbo.employee as  hrmresource where lastname ='" + creater + "'";
                String createsqlString = "select id  from  eteams.dbo.employee as  hrmresource where id ='" + creater + "'";
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(createsqlString, poolname);
                logger_eae3b780.error("b--"+b);
                rs.next();
                String createrId = rs.getString("id");
                Map<String, String> mainTableDataMap = new HashMap<String, String>();
                // 获取表单主字段信息
                Property[] properties = request.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    // 主表数据
                    // 字段名
                    String name = properties[i].getName().toLowerCase();
                    // 值
                    String value = Util.null2String(properties[i].getValue());
                    mainTableDataMap.put(name, value);
                }
                String BKRQ = Util.null2String((String) mainTableDataMap.get("sqrq"));
                DetailTable[] detailtable = request.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    Cell[] cq = rq.getCell();
                    String qksj = "";
                    String GH = "";
                    String bkrq = "";
                    String bksj = "";
                    String kz = "";
                    String bkyy = "";
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toLowerCase();
                        String valueq = Util.null2String(cq1.getValue());
                        if ("qksj".equals(nameq)) {
                            qksj = valueq;
                        }
                        if ("gh".equals(nameq)) {
                            GH = valueq;
                        }
                        if ("bkrq".equals(nameq)) {
                            bkrq = valueq;
                        }
                        if ("bksj".equals(nameq)) {
                            bksj = valueq;
                        }
                        if ("kz".equals(nameq)) {
                            kz = valueq;
                        }
                        if ("bkyy".equals(nameq)) {
                            bkyy = valueq;
                        }
                    }
//                    long generate = IdGenerator.generate();
                    String poolname_g0 = CONN_TYPE.workflow.getType();
                    String newIdSql = "SELECT ISNULL((SELECT TOP 1 id FROM e10_common.dbo.buka_log_new ORDER BY id DESC), 0) + 1 AS id";
                    logger_eae3b780.error("newIdSql-----------  " + newIdSql);
                    boolean flag = rs.executeSql(newIdSql, poolname_g0);
                    logger_eae3b780.error("getExecuteResult---"+rs.getExecuteResult());
                    logger_eae3b780.error("flag---"+flag);
                    long newId = 0;
                    if (rs.next()) {
                        newId = Long.parseLong(rs.getString("id"));
                    }
                    String insertsql = "insert into  e10_common.dbo.buka_log_new(id,requestid,gh,punchreason,punchtype,TimeCardDate,TimeCardTime,createrId,BKRQ) values(" + newId + ",'"+ requestid + "','" + GH + "','" + bkyy + "','" + kz + "','" + qksj + "','" + bkrq + " " + bksj + "','" + createrId + "','" + BKRQ + "')";
                    logger_eae3b780.error("newId:"+newId+",poolname_g0:"+poolname_g0+",sql1:" + insertsql);
                    boolean b1 = rs.executeSql(insertsql, poolname_g0);
                    logger_eae3b780.error("b1--"+b1);
//                    /* *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(insertsql, poolname_g0,generate);

                    /*
                    Long uf_CustomFlow_formId = commonDevUtil.getObjId("buka_log_new");
                    logger_eae3b780.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId);
                    SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
                    Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);// 获取插入的空的建模id
                    String sql = "update e10_common.dbo.buka_log_new set requestid = " + requestid + ",gh = '" + GH + "',punchreason='" + bkyy + "',punchtype='" + kz + "',TimeCardDate='" + qksj + "',TimeCardTime='" + bkrq + " " + bksj + "',createrId='" + createrId + "',BKRQ='" + BKRQ + "' where id  =  " + recodId + " and delete_type = 0 ";
                    boolean b1 = rs.executeSql(sql, poolname);
                    logger_eae3b780.error("b1--"+b1);
                    logger_eae3b780.error(String.valueOf("sql1:" + sql));
                     */
                }
                logger_eae3b780.error(String.valueOf("NewBuKaAction--end--" + requestid));
            } catch (Exception e) {
                logger_eae3b780.error(String.valueOf("NewBuKaAction--error--" + requestid + "--" + e.toString()));
                return  WeaResult.fail(500, "NewBuKaAction 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_eae3b780.error("NewBuKaAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "NewBuKaAction 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;
    }
}
