package com.yem.wm.task;

import com.yem.wm.utils.RequestEAS;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
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.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 同步组织职能
 */

public class OrgPropertyTask extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        DynamicObject[] orgColl = BusinessDataServiceHelper.load("bos_org", "id",
//                new QFilter[]{new QFilter("number", QCP.equals,"010100")});
                null);
        for (DynamicObject org : orgColl) {
            org = BusinessDataServiceHelper.loadSingle(org.get("id"),"bos_org");
            String orgNum = org.getString("number");
            //财务
            String cwsql = "SELECT f.FISBIZUNIT b FROM t_org_baseunit o " +
                    "LEFT OUTER JOIN T_ORG_OUPARTFI f ON O.FPARTFIID = F.FID where o.fnumber = '"+orgNum+"'";
            List<Map<String, Object>> list1 = RequestEAS.exeSql(cwsql);
            setOrg(org,"yem_fisaccounting",list1);
            //采购
            String cgsql = "select p.FISBIZUNIT b from T_ORG_BaseUnit o " +
                    "LEFT OUTER JOIN T_ORG_OUPartPurchase p ON O.FPARTPURCHASEID = p.FID where o.fnumber = '"+orgNum+"'";
            list1 = RequestEAS.exeSql(cgsql);
            setOrg(org,"yem_fispurchase",list1);
            //销售
            String xssql = "select s.FISBIZUNIT b from T_ORG_BaseUnit o " +
                    "LEFT OUTER JOIN T_ORG_OUPartSale s ON O.FPARTSALEID = S.FID where o.fnumber = '"+orgNum+"'";
            list1 = RequestEAS.exeSql(xssql);
            setOrg(org,"yem_fissale",list1);
            //库存
            String kcsql = "select s.FISBIZUNIT b from T_ORG_BaseUnit o " +
                    "LEFT OUTER JOIN T_ORG_OUPARTSTORAGE s ON O.FPARTSTORAGEID = S.FID where o.fnumber = '"+orgNum+"'";
            list1 = RequestEAS.exeSql(kcsql);
            setOrg(org,"yem_fisinventory",list1);
            SaveServiceHelper.update(org);
        }
    }

    /**
     * 构建是否实体
     * @param org 组织对象
     * @param flag 字段标识
     * @param list1 结果
     */
    private void setOrg(DynamicObject org, String flag, List<Map<String, Object>> list1) {
        for (Map<String, Object> map : list1) {
            BigDecimal b = (BigDecimal) map.get("b");
            if (b!=null&&b.equals(BigDecimal.ONE)){
                org.set(flag,true);
            }else{
                org.set(flag,false);
            }
        }
    }
}
