package nc.bs.so.m30.rule.approve;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.bs.trade.business.HYPubBO;
import nc.bs.uapbd.util.MyHelper;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.so.m30.entity.SaleOrderBVO;
import nc.vo.so.m30.entity.SaleOrderHVO;
import nc.vo.so.m30.entity.SaleOrderVO;
import nc.vo.vorg.DeptVersionVO;
import nccloud.baseapp.core.log.NCCForUAPLogger;
import nccloud.pubift.commen.itf.utils.IHttpPostOtherSys;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 销售订单推送mes
 */
public class AfterApprovingSynchronizeRuleQMS implements IRule<SaleOrderVO> {
    private static final String LOG_INFO_NAME = "qyMesLog";
    private static final Log logger = Log.getInstance(LOG_INFO_NAME);
    private static final String reqUrl = "/IF_QyErpApi.ashx?action=addxsht";
    private Map<String, String> configParams;


    public AfterApprovingSynchronizeRuleQMS() {
    }

    @Override
    public void process(SaleOrderVO[] saleOrderVOs) {
        try {
            if (saleOrderVOs == null || saleOrderVOs.length == 0) {

                return;
            }
            configParams = MyHelper.getConfigParams("xb-config", null);
            if (configParams.isEmpty()) {
                throw new BusinessException("箱变的QMS接口缺少配置");
            }
            buildSyncData(saleOrderVOs);
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }
    }
    /**
     * 构建同步数据
     */
    private void buildSyncData(SaleOrderVO[] useVOs) throws BusinessException {
        BaseDAO baseDAO = new BaseDAO();
        Date now= new Date();
        HYPubBO hybo = new HYPubBO();
        for (SaleOrderVO vo : useVOs) {
            // 判断物料的业务单元是否是箱变公司，不是则跳过
            String pkOrg = vo.getParentVO().getPk_org();
            String orgCode = MyHelper.transferField(OrgVO.getDefaultTableName(), OrgVO.CODE, OrgVO.PK_ORG, pkOrg);
            if (checkIfOrg(orgCode, configParams)) {
                continue;
            }
            // 组装数据
            JSONObject singleObj = new JSONObject();

            SaleOrderHVO pmoHeadVO = vo.getParentVO();
            SaleOrderBVO[] itemVOS=vo.getChildrenVO();
            singleObj.put("batchid",now);
            singleObj.put("hth",pmoHeadVO.getVdef6());
            singleObj.put("fplx",pmoHeadVO.getDbilldate().toString().substring(0,10));
            if(null !=pmoHeadVO.getCemployeeid()){
                String sql = " select name from bd_psndoc where cuserid = '" + pmoHeadVO.getCemployeeid() + "' ";
                String billmakerName = (String) baseDAO.executeQuery(sql, new ColumnProcessor());

                singleObj.put("xsy",billmakerName);
            }else{
                singleObj.put("xsy","");
            }

            singleObj.put("dhdwid",pmoHeadVO.getCcustomerid());
            String customersql = " select name from bd_customer where pk_customer = '" + pmoHeadVO.getCcustomerid() + "' ";
            String customerName = (String) baseDAO.executeQuery(customersql, new ColumnProcessor());
            singleObj.put("dhdw",customerName);


            String lrrsql = " select user_name from sm_user where cuserid = '" + pmoHeadVO.getBillmaker() + "' ";
            String lrrName = (String) baseDAO.executeQuery(lrrsql, new ColumnProcessor());

            singleObj.put("lrr",lrrName);
            singleObj.put("lrrq",pmoHeadVO.getDmakedate().toString().substring(0,10));
            singleObj.put("bz",pmoHeadVO.getVnote());
            // 处理Content数组
            JSONArray contentArray = new JSONArray();
            for (SaleOrderBVO item : itemVOS) {
                JSONObject itemObj = new JSONObject();
//                itemObj.put("sgdh", item.getSgdh());
//                itemObj.put("xshth", item.getVdef1());
//                itemObj.put("htqdxh", item.getHtqdxh());
//                Object no = hybo.findColValue("bd_material", "code", "pk_material = '"+item.getCmaterialvid()+"' ");
//
//                Object name = hybo.findColValue("bd_material", "name", "pk_material = '"+item.getCmaterialvid()+"' ");
                String wlsql = " select code,name,materialspec,materialtype from bd_material where pk_material = '" + item.getCmaterialvid() + "' ";
                Map<String,Object> mrlmap = (Map<String, Object>) baseDAO.executeQuery(wlsql, new MapProcessor());

                itemObj.put("wlbh", mrlmap.get("code"));
                itemObj.put("wlmc", mrlmap.get("name"));
                itemObj.put("wlxhgg", ((String)mrlmap.get("materialspec")!=null ? mrlmap.get("materialspec").toString() : "" )+((String)mrlmap.get("materialtype")!=null ? mrlmap.get("materialtype").toString() : "" ));
                itemObj.put("dhsl", item.getNastnum().doubleValue());
                itemObj.put("xsj", item.getNqtorigtaxprice().doubleValue());
                itemObj.put("bxzje", item.getNqtorigtaxprice().doubleValue());
                itemObj.put("jhrq", item.getDsenddate().toString().substring(0,10));
                itemObj.put("bz", item.getVrownote());
                Object pk_project = hybo.findColValue("bd_project", "project_name", " pk_project = '" + item.getCprojectid() + "' ");
                itemObj.put("xmmc", pk_project);

                contentArray.add(itemObj);
            }

            singleObj.put("Content", contentArray);

            /*
             {
              "batchid": "XS202408001",
              "hth": "HT202408001",
              "fplx": "增值税专用发票",
              "xsy": "张三",
              "xmmc": "某项目供电设备采购",
              "dhdwid": "C001",
              "dhdw": "某电力公司",
              "lrr": "李四",
              "lrrq": "2024-08-21",
              "bz": "需加急处理",
              "Content": [
                {
                  "wlbh": "ACC26711",
                  "wlmc": "铜排",
                  "wlxhgg": "15558190831",
                  "dhsl": "200",
                  "xsj": "50.00",
                  "bxzje": "10000.00",
                  "jhrq": "2024-09-30",
                  "bz": "需符合国标材质"
                }
              ]
            }

             */
            pushData(singleObj);
        }
    }

    /**
     * 推送同步数据
     */
    private void pushData(JSONObject param) throws BusinessException {
        // String jsonString = param.toJSONString();
        // 转json字符串的时候保留null值
        String jsonStr = JSON.toJSONString(param,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );
        logger.error("QMS-SaleOrder-param = " + jsonStr);
        NCCForUAPLogger.debug("QMS-SaleOrder-param = " + jsonStr);
        String baseUrl = configParams.get("qmsBaseUrl");
        String requestUrl = baseUrl + reqUrl;
        logger.error("QMS-SaleOrder-url = " + requestUrl);
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, jsonStr);
        JSONObject resultObj = JSONObject.parseObject(result);
        logger.error("QMS-SaleOrder-res = " + result);

        if (!"true".equals(resultObj.getString("success"))) {
            logger.error("QMS-SaleOrder-error,result[" + resultObj.toJSONString() + "]");
            throw new BusinessException("QMS-SaleOrder-error:" + resultObj.getString("message"));
        }
    }

    private Map getGoodsInfo(String pkMaterial) throws BusinessException {
        String sql = " select a.pk_measdoc, c.name unitname, b.pk_measdoc deputyUnit, d.name deputy_unitname, nvl(b.measrate, '1/1') measrate " +
                "from bd_material a " +
                "left join bd_materialconvert b on a.pk_material = b.pk_material " +
                "left join bd_measdoc c on a.pk_measdoc = c.pk_measdoc " +
                "left join bd_measdoc d on b.pk_measdoc = d.pk_measdoc " +
                "where a.pk_material = '" + pkMaterial + "' ";
        // logDl.error("QMS-Material-getUnitInfo-sql = " + sql);
        Map map = (Map) new BaseDAO().executeQuery(sql, new MapProcessor());
        map.put("convertRate", MyHelper.transferSpecialField(map.get("measrate") + ""));
        return map;
    }

    private boolean checkIfOrg(String code, Map<String, String> configParams) throws BusinessException {
        String targetCode = configParams.get("xbOrg");
        if (targetCode == null || nc.vo.am.common.util.StringUtils.isEmpty(targetCode)) {
            throw new BusinessException("未配置组织参数");
        }
        String[] orgItem = targetCode.split(",");
        for (String orgCode : orgItem) {
            if (!orgCode.isEmpty() && orgCode.equals(code)) {
                return false;
            }
        }
        return true;
    }



}

