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 kd.bos.servicehelper.operation.SaveServiceHelper;

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

public class SynWareHouseCMMPTask extends AbstractTask {

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //查询CMMP链接
        DynamicObjectCollection connObjs = QueryServiceHelper.query("yem_cmmpconfig", "id", 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 WH_CODE,WH_NAME,ENABLE_FLAG,ORG_CODE,wh_fid from VIEW_WAREHOUSE_WM 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("wh_code")));
                DynamicObjectCollection whs = QueryServiceHelper.query("yem_warehouse", "id", qFilters.toArray(new QFilter[0]));
                if (whs.size() > 0) {
                    //如果存在
                    DynamicObject wh = BusinessDataServiceHelper.loadSingle(whs.get(0).getString("id"), "yem_warehouse");
                    createWH(map1, wh, connObj);
                    wh.set("enable", map1.get("enable_flag"));//是否启用
                    SaveServiceHelper.save(new DynamicObject[]{wh});
//                    OperationResult result = OperationServiceHelper.executeOperate("save", "yem_warehouse", new DynamicObject[]{wh}, OperateOption.create());
                    System.out.printf("wh_code %s, enable_flag %s %n", map1.get("wh_code"), map1.get("enable_flag"));
                } else {
                    MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_warehouse");
                    DynamicObject wh = new DynamicObject(entityType);
                    wh.getDataEntityType().getPrimaryKey().setValueFast(wh, ID.genLongId());
                    createWH(map1, wh, connObj);
                    wh.set("enable", map1.get("enable_flag"));//是否启用
                    OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_warehouse", new DynamicObject[]{wh}, OperateOption.create());
//                    System.out.printf("wh_code %s, enable_flag %s result %s %n", map1.get("wh_code"), map1.get("enable_flag"), operationResult);
                    if (!operationResult.isSuccess()) {
                        for (IOperateInfo errInfo1 : operationResult.getAllErrorOrValidateInfo()) {
                            String detailMessage1 = errInfo1.getMessage();
                            throw new KDBizException(ResManager.loadKDString("生成时保存失败：", "EtcmanualList_2", "createEcatalog_res") + detailMessage1+"值：【"+map1.toString()+"】");
                        }
                    }
                }
            }
        }
    }

    /**
     * 创建仓库
     *
     * @param map1
     * @param wh
     * @param connObj
     */
    private static void createWH(Map map1, DynamicObject wh, DynamicObject connObj) {
        wh.set("number", map1.get("wh_code").toString());//仓库编码
        wh.set("name", map1.get("wh_name").toString());//仓库名称
        wh.set("status", "C");//数据状态
        wh.set("yem_transstate", 1);//业务状态
//        wh.set("enable", 1);//是否启用
        wh.set("yem_easid", map1.get("wh_fid"));//EASID
        //库存组织获取
        DynamicObject orgObj = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, map1.get("org_code".toLowerCase()))});
        wh.set("useorg", orgObj);
        DynamicObject createorg = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("id", QCP.equals,100000l)});
        wh.set("createorg", createorg);
        connObj = BusinessDataServiceHelper.loadSingle(connObj.get("id"), "yem_cmmpconfig");
        wh.set("yem_belong", connObj.getString("yem_belong"));//仓库所属
        wh.set("yem_cmmpconfig", connObj);
        wh.set("ctrlstrategy", 7);
    }
}