<%
__header("Content-Type","text/html; charset=gb2312");
var serr="{\"op\":\"op err\"}";
if (op=="")
  write(serr);
else
{
var sql;
var iupd=-1;
var lastId=0;
db_Open("/NandFlash/dbCfg.db3");
if (op=="del")
{
  iupd=db_UpdAdv("delete from tbSM where SID="+sid);
  db_UpdAdv("delete from tbSMDefVal where SID="+sid);
  db_UpdAdv("delete from tbPort where SID="+sid);
}
if (op=="st")
  iupd=db_UpdAdv("update tbSM set State="+st+" where SID="+sid);
if (op=="stx")
{
  if (st==0 && db_QryInt("select count(*) from tbSM where State=0 and SerType="+ser+" and SID<>"+sid,1)>0)
    write(serr);
  else
    iupd=db_UpdAdv("update tbSM set State="+st+" where SID="+sid);
}
if (op=="ins")
{
  sql = "insert into tbSM values("+insval+")";
  iupd=db_UpdAdv(sql,1);
  lastID = db_QryLastRowId();
  if (iupd>=0 && ((type>2304 && type<2560) || type>=3584))
  {
    var idi=db_QryInt("select s.SID,t.ExtDi from tbSM s left join tbSMType t on (t.Type=s.Type and t.Tag1=s.Tag1) order by SID desc limit 1",2);
    var iser=db_QryInt("select s.SID,t.ExtSer from tbSM s left join tbSMType t on (t.Type=s.Type and t.Tag1=s.Tag1) order by SID desc limit 1",2);
    var asid=db_QryInt("select SID from tbSM order by SID desc limit 1",1);
    for (i=0;i<idi;i++)
      db_UpdAdv("insert into tbPort values('"+name+" Di"+(i+1)+"','',1,"+asid+"*256+"+(i+1)+","+asid+")",1);
    if (idi>0)
      db_UpdAdv("insert into tbSMDefVal select Type,"+lastID+",Fld,vmode,vref,vref2,0,'' from tbSMDef where vmode>=0 and Type="+type);
    if (iser==3 || iser==4)
      db_UpdAdv("insert into tbPort values('"+name+"','',"+iser+","+asid+"*256,"+asid+")",1);
  }
  if (addr>0){
    var iaddr0=db_QryInt("select Addr from tbSMType where Type="+type+" and Tag1="+tag1,1);
    if (iaddr0>0)
      db_UpdAdv("update tbSMType set AddrNext="+(addr+1)+" where Type="+type+" and Tag1="+tag1,1);
  }
}
if (op=="upd")
{
  sql = "update tbSM set "+setval+" where SID="+sid;
  iupd=db_UpdAdv(sql,1);
  if (name!="")
  {
    db_UpdAdv("update tbPort set Name='"+name+" Di'||(Val&255) where Type=1 and SID="+sid,1);
    db_UpdAdv("update tbPort set Name='"+name+"' where (Type=3 or Type=4) and SID="+sid,1);
  }
}
if (op=="updai")
{
  sql = "update tbAIDef set Unit="+unit+","+"Offset="+offset+" where Type="+type;
  iupd=db_UpdAdv(sql,1); 
}
if (iupd<0 && iupd!=-1)
  write(serr);
if (iupd>=0)
{
  lastId = db_QryLastRowId();
  write("{\"op\":\"ok\",\"sid\":"+lastId+"}");
}
db_Close();
}
%>