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

import  com.weaver.seconddev.interfaces.k3.TransferBillService;
import  com.weaver.seconddev.interfaces.k3.TransferBillServiceStub.ArrayOfTransferBillDt;
import  com.weaver.seconddev.interfaces.k3.TransferBillServiceStub.TransferBillDt;
import  com.weaver.seconddev.interfaces.k3.TransferBillServiceStub.TransferBillReq;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.text.SimpleDateFormat;
import java.util.*;
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.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.hrm.company.DepartmentComInfo;
import com.weaver.verupgrade.hrm.company.SubCompanyComInfo;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
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_TransferBillToK3Action")
public class TransferBillToK3Action extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private TransferBillService service ;

    private static final Logger logger_1a36f94a = LoggerFactory.getLogger(TransferBillToK3Action.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_1a36f94a.error("TransferBillToK3Action start");
        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 requestinfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestid = requestinfo.getRequestid();
            String workflowid = requestinfo.getWorkflowid();
            String message = "";
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            BillFieldUtil util = new BillFieldUtil();
//            String tablename = util.getTablename(workflowid);
            String tablename = requestinfo.getRequestManager().getBillTableName();
            try {
                logger_1a36f94a.error(String.valueOf("TransferBillToK3Action--start-" + requestid));
                Property[] aproperty = requestinfo.getMainTableInfo().getProperty();
                Map<String, String> map = new HashMap<String, String>();
                for (int j = 0; j < aproperty.length; j++) {
                    String name = aproperty[j].getName().toUpperCase();
                    String value = Util.null2String(aproperty[j].getValue());
                    map.put(name, value);
                }
                if ("0".equals(map.get("SFTBK3"))) {
                    TransferBillReq req = new TransferBillReq();
                    req.setUser("oa");
                    req.setPwd("k3cloud_htgd");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    req.setFDate(sdf.format(new Date()));
                    // 是否退库
                    String sftk = "N";
                    if ("0".equals(map.get("SFTK"))) {
                        sftk = "Y";
                    }
                    req.setFIsReturn(sftk);
                    SubCompanyComInfo com = I18nContextUtil.getBean(SubCompanyComInfo.class);
                    DepartmentComInfo dept = I18nContextUtil.getBean(DepartmentComInfo.class);
                    ResourceComInfo res = I18nContextUtil.getBean(ResourceComInfo.class);
                    String sqr = res.getLastname(map.get("SQR"));
                    String sqdw = "";
                    String sqbm = "";
                    if ("0".equals(map.get("FYPD"))) {
                        sqdw = com.getSubCompanyname(map.get("SQDW"));
                        sqbm = dept.getDepartmentname(map.get("SQBM"));
                    } else {
                        sqdw = com.getSubCompanyname(map.get("JSDW"));
                        sqbm = dept.getDepartmentname(map.get("JSBM"));
                    }
                    req.setFNote(sqdw + "," + sqbm + "," + sqr + "," + map.get("LCBH") + "," + requestid);
                    // 传明细
                    ArrayOfTransferBillDt dt = new ArrayOfTransferBillDt();
                    DetailTable[] detailtable = requestinfo.getDetailTableInfo().getDetailTable();
                    DetailTable dtq = detailtable[0];
                    Row[] sq = dtq.getRow();
                    List<TransferBillDt> list = new ArrayList<TransferBillDt>();
                    for (int j = 0; j < sq.length; j++) {
                        Row rq = sq[j];
                        Cell[] cq = rq.getCell();
                        TransferBillDt param = new TransferBillDt();
                        String tbzt = "";
                        for (int k = 0; k < cq.length; k++) {
                            Cell cq1 = cq[k];
                            String nameq = cq1.getName().toUpperCase();
                            String valueq = Util.null2String(cq1.getValue());
                            if ("LPBM".equals(nameq)) {
                                param.setFNumber(valueq);
                            }
                            if ("MXSL".equals(nameq)) {
                                param.setFQty(valueq);
                            }
                            if ("CKBM".equals(nameq)) {
                                param.setFStockNumber(valueq);
                            }
                            if ("MXYGDJ".equals(nameq)) {
                                param.setFTaxPrice(valueq);
                            }
                            if ("MXYGJE".equals(nameq)) {
                                param.setFTaxAmount(valueq);
                            }
                            if ("TBZT".equals(nameq)) {
                                tbzt = valueq;
                            }
                            if ("GSBM".equals(nameq)) {
                                // 公司编码
                                param.setFCompNumber(valueq);
                            }
                        }
                        if (!"1".equals(tbzt)) {
                            list.add(param);
                        }
                    }
                    dt.setTransferBillDt(list.toArray(new TransferBillDt[list.size()]));
                    req.setLstTransferdt(dt);
                    String sql = "";
//                    TransferBillService service = new TransferBillService();
                    String[] str = service.call(req);
                    logger_1a36f94a.error(String.valueOf("TransferBillToK3Action--info-" + requestid + " [" + str[0] + "," + str[1] + "]"));
                    message = str[1];
                    if ("0".equals(str[0])) {
                        requestinfo.getRequestManager().setMessageid("ERROR");
                        requestinfo.getRequestManager().setMessagecontent("K3系统返回错误信息：" + str[1]);
                        return  WeaResult.fail(500, "TransferBillToK3Action  str[1]"+  str[1], getResultMapForAction(weaverResultMap, "result", str[1], requestinfo.getRequestManager()));
                    }
                    if (str[3].length() > 0) {
                        sql = "update e10_core_business.dbo." + tablename + "_dt1 set tbzt=1 where ckbm in (" + str[3].substring(0, str[3].length() - 1) + ") and form_data_id =(select form_data_id from e10_core_business.dbo." + tablename + " where id=" + requestid + ")";
                        logger_1a36f94a.error("sql--"+sql);
                        String poolname = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql(sql, poolname);
                        logger_1a36f94a.error(String.valueOf(requestid + "调拨单成功的：" + b));
                        logger_1a36f94a.error(String.valueOf(requestid + "调拨单成功的：" + sql));
                    }
                    if (str[2].length() > 0) {
                        sql = "update e10_core_business.dbo." + tablename + "_dt1 set tbzt=0 where ckbm in (" + str[2].substring(0, str[2].length() - 1) + ") and form_data_id =(select form_data_id from e10_core_business.dbo." + tablename + " where id=" + requestid + ")";
                        logger_1a36f94a.error("sql--"+sql);
                        String poolname_ji = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql(sql, poolname_ji);
                        logger_1a36f94a.error(String.valueOf(requestid + "调拨单失败的：" + b));
                        logger_1a36f94a.error(String.valueOf(requestid + "调拨单失败的：" + sql));
                    }
                    if (str[2].length() == 0 && str[3].length() == 0) {
                        sql = "update e10_core_business.dbo." + tablename + "_dt1 set tbzt=0 where (tbzt is null or tbzt !=1) and form_data_id =(select form_data_id from e10_core_business.dbo." + tablename + " where id=" + requestid + ")";
                        logger_1a36f94a.error("sql--"+sql);
                        String poolname_19 = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql(sql, poolname_19);
                        logger_1a36f94a.error(String.valueOf(requestid + "调拨单全失败：" + b));
                        logger_1a36f94a.error(String.valueOf(requestid + "调拨单全失败：" + sql));
                    }
                }
            } catch (Exception e) {
                message = e.toString();
                logger_1a36f94a.error(String.valueOf("TransferBillToK3Action--error-" + requestid + "-" + message));
                requestinfo.getRequestManager().setMessageid("ERROR");
                requestinfo.getRequestManager().setMessagecontent("K3系统返回错误信息：" + e.toString());
                return  WeaResult.fail(500, "TransferBillToK3Action err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.getRequestManager()));
            }
            String poolname_sn = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean b = rs.executeSql("update e10_core_business.dbo." + tablename + " set message=isnull(message,'')+'" + message + "' where id =" + requestid, poolname_sn);
            logger_1a36f94a.error(String.valueOf(requestid + "调拨单消息：" + b));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_1a36f94a.error("TransferBillToK3Action e: {}", e.getMessage());
            return  WeaResult.fail(500, "TransferBillToK3Action e {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestinfo.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;
    }
}
