package com.yem.wm.task;

import com.yem.ensign.common.DateUtils;
import com.yem.wm.utils.RequestCmmp;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.id.ID;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 库位
 */

public class SynWhLocationCMMPTask extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
//查询CMMP链接
        DynamicObjectCollection connObjs = QueryServiceHelper.query("yem_cmmpconfig", "id,yem_belong", new QFilter[]{new QFilter("yem_num", QCP.in, new String[]{"ZZJ", "CC", "NZ"})});
        for (DynamicObject connObj : connObjs) {
            long id = connObj.getLong("id");
//            StringBuilder sql = new StringBuilder("SELECT area_code,position_code,position_name from VIEW_POSITION_WM where 1 = 1");//测试
            StringBuilder sql = new StringBuilder("SELECT area_code,position_code,position_name from VIEW_BASE_POSITION_DMS where 1 = 1");//正式
            String isInit = (String) map.get("isInit");
            if (!"true".equals(isInit)) {
                Date dateed = new Date();
                dateed = DateUtils.getBeginTime(dateed);
                Date datebg = DateUtils.getAddDay(dateed, -2);
                dateed = DateUtils.getEndTime(dateed);
                sql.append(" and plmlastupdate>=to_date('" + DateUtils.formatString(datebg) + "','yyyy-mm-dd')" + " and plmlastupdate<=to_date('" + DateUtils.formatString(dateed) + "','yyyy-mm-dd')");
            }
            sql.append(" order by plmlastupdate");
            //执行sql
            List<Map> fromCmmpWithConnId = RequestCmmp.getFromCmmpWithConnId(id, sql.toString());
            for (Map map1 : fromCmmpWithConnId) {
                //先查询是否存在
                ArrayList<QFilter> qFilters = new ArrayList<>();
                qFilters.add(new QFilter("number", QCP.equals, map1.get("position_code")));
                qFilters.add(new QFilter("group.number", QCP.equals, map1.get("position_code")));
                qFilters.add(new QFilter("group.yem_belong", QCP.equals, connObj.getString("yem_belong")));
                qFilters.add(new QFilter("yem_belong", QCP.equals, connObj.getString("yem_belong")));
                DynamicObjectCollection whs = QueryServiceHelper.query("yem_whlocation", "id", qFilters.toArray(new QFilter[0]));
                if (whs.size() > 0) {
                    //如果存在
                    DynamicObject wh = BusinessDataServiceHelper.loadSingle(whs.get(0).getString("id"), "yem_whlocation");
                    createWL(map1, wh, connObj);
                    OperationServiceHelper.executeOperate("save", "yem_whlocation", new DynamicObject[]{wh}, OperateOption.create());
                } else {
                    MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_whlocation");
                    DynamicObject wh = new DynamicObject(entityType);
                    wh.getDataEntityType().getPrimaryKey().setValueFast(wh, ID.genLongId());
                    createWL(map1, wh, connObj);
                    if (wh.get("group") == null) {
                        continue;
                    }
                    OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_whlocation", new DynamicObject[]{wh}, OperateOption.create());
                    if (!operationResult.isSuccess()) {
                        for (IOperateInfo errInfo1 : operationResult.getAllErrorOrValidateInfo()) {
                            String detailMessage1 = errInfo1.getMessage();
                            throw new KDBizException(ResManager.loadKDString("生成时保存失败：", "EtcmanualList_2", "createEcatalog_res") + detailMessage1);
                        }
                    }
                }
            }
        }
    }

    private static void createWL(Map map1, DynamicObject wh, DynamicObject connObj) {
        wh.set("number", map1.get("position_code").toString());//仓库编码
        wh.set("name", map1.get("position_name").toString());//仓库名称
        wh.set("status", "C");//数据状态
        wh.set("enable", 1);//是否启用
        wh.set("yem_belong", connObj.getString("yem_belong"));//仓库所属
        //库区获取
        DynamicObject waObj = BusinessDataServiceHelper.loadSingle("yem_warearea",
                new QFilter[]{new QFilter("number", QCP.equals, map1.get("area_code")),
                        new QFilter("yem_belong", QCP.equals, connObj.getString("yem_belong"))});
        wh.set("group", waObj);
    }
}
