package p2.application.site;

import p2.pao.PaoRemote;
import p2.pao.PaoSet;
import p2.pao.PaoSetRemote;
import p2.util.P2AppException;
import p2.util.P2Exception;

public class SiteCust extends Site {

    public SiteCust(PaoSet paoSet) throws P2Exception {
        super(paoSet);
    }

    @Override
    public void add() throws P2Exception {
        super.add();
    }

    @Override
    protected void save() throws P2Exception {
        super.save();
        if(getString("siteid").length()<3||getString("siteid").length()>10){
            throw new P2AppException("","企业ID必须长度在3-10位之间的纯英文字符");
        }
        PaoSetRemote tenterpriseSet = getPaoSet("$tenterprise", "tenterprise", "siteid=:siteid");
        PaoRemote tenterprise = null;
        if (tenterpriseSet.isEmpty()) {
            tenterprise = tenterpriseSet.addAtEnd();
            tenterprise.setValue("siteid", getString("siteid"), 11L);
            tenterprise.setValue("fcompname", getString("description"), 11L);
        } else {
            tenterprise = tenterpriseSet.getPao(0);
            tenterprise.setValue("fcompname", getString("description"), 11L);
        }
        setValue("prefix",getString("siteid").toLowerCase(),11L);

        PaoSetRemote sysvarsSet = getPaoSet("$sysvars", "sysvars", "siteid=:siteid");

        PaoRemote sysvars = null;
        if (sysvarsSet.isEmpty()) {
            sysvars = sysvarsSet.addAtEnd();
            sysvars.setValue("siteid", getString("siteid"), 11L);
        }

        PaoSetRemote tobsSet = getPaoSet("$tobs", "tobsmag", "siteid=:siteid");

        PaoRemote tobs = null;
        if (tobsSet.isEmpty()) {
            tobs = tobsSet.addAtEnd();
            tobs.setValue("siteid", getString("siteid"), 11L);
        }
        setValue("prefix", getString("siteid").toLowerCase(), 11L);
    }

    @Override
    public void canDelete() throws P2Exception {
        super.canDelete();
        PaoSetRemote tenterprise = getPaoSet("$tenterprise", "tenterprise", "siteid=:siteid");
        if (!tenterprise.isEmpty()) {
            throw new P2AppException("", "存在企业档案不可删除！");
        }
        if ("GEN".equals(getString("siteid"))) {
            throw new P2AppException("", "当前站点不可删除！");
        }
    }


}
