<%
__header("Content-Type","text/html; charset=gb2312");
var serr="{\"op\":\"op err\"}";
var sd = 0;
if (op=="")
  write(serr);
else
{
var iupd=-1;
db_Open("/NandFlash/dbCfg.db3");
if (op=="qry")
  db_QryAdv("select * from tbSMType order by Type");
if (op=="qry2")
  db_QryAdv("select Type,t.Kind,t.Name,t.Note,Tag1,Port,k.Name as KName from tbSMType t left join tbSMKind k on k.Kind=t.Kind order by Type,Tag1");
if (op=="del")
{
  iupd=db_UpdAdv("delete from tbSMType where Type="+type);
  sd=db_QryInt("select count(*) from tbSMType where Type="+type,1);
  if (sd == 0)
	db_UpdAdv("delete from tbSMDef where Type="+type);
}
if (op=="del2")
{
    db_UpdAdv("delete from tbAIDef where Type="+type+" and Tag1="+tag1);
	db_UpdAdv("delete from tbSMAI where Type="+type+" and Tag1="+tag1);
  iupd=db_UpdAdv("delete from tbSMType where Type="+type+" and Tag1="+tag1);
  
  sd=db_QryInt("select count(*) from tbSMType where Type="+type,1);
  if (sd == 0)
	db_UpdAdv("delete from tbSMDef where Type="+type);
	
  sd=db_QryInt("select count(*) from tbSMDefVal where SID in (select SID from tbSM where type="+type+" and Tag1="+tag1+")",1);
  if (sd > 0)
    db_UpdAdv("delete from tbSMDefVal where SID in (select SID from tbSM where type="+type+" and Tag1="+tag1+")");
	
  sd=db_QryInt("select count(*) from tbSM where type="+type+" and Tag1="+tag1,1);
  if (sd > 0)
    db_UpdAdv("delete from tbSM where Type="+type+ " and tag1="+tag1);
}
if (op=="ins")
  iupd=db_UpdAdv("insert into tbSMType values("+type+","+kind+",'"+name+"','"+note+"')",1);
if (op=="ins2"){
  if (db_QryInt("select count(*) from tbSMType where Type="+type+" and Tag1="+tag1,1)>0)
    write(serr);
  else
    iupd=db_UpdAdv("insert into tbSMType values("+insval+")",1);
}
if (op=="insaism"){
  if (db_QryInt("select count(*) from tbAIDef where Type="+type+" and Tag1="+tag1,1)>0)
    write(serr);
  else
    iupd=db_UpdAdv("insert into tbAIDef values("+insval+")",1);
}
if (op=="upd")
  iupd=db_UpdAdv("update tbSMType set Kind="+kind+",Name='"+name+"',Note='"+note+"' where Type="+type,1);
if (op=="upd2")
 {
  db_UpdAdv("update tbAIDef set Unit="+unit+" where Type="+type+" and Tag1="+tag1,1);
  iupd=db_UpdAdv("update tbSMType set Name='"+name+"',Note='"+note+"',Ext1="+ext1+",Port="+port+",PortDef='"+portdef+"',Addr="+addr+",AddrMax="+addrx+",AddrNext="+addrn+",ExtDi="+extdi+",ExtDo="+extdo+",ExtSer="+extser+",ASubSys="+subsys+" where Type="+type+" and Tag1="+tag1,1);
 }
  
if (iupd<0 && iupd!=-1)
  write(serr);
if (iupd>=0)
{
  var lastId = db_QryLastRowId();
  write("{\"op\":\"ok\",\"tid\":"+lastId+"}");
}
db_Close();
}
%>