package jp.co.sint.servlet.api;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import jp.co.sint.basic.SICartManager;
import jp.co.sint.basic.SICmdty;
import jp.co.sint.basic.SINameValue;
import jp.co.sint.basic.SINews;
import jp.co.sint.basic.SINewsManager;
import jp.co.sint.basic.SIUserInfo;
import jp.co.sint.beans.front.UICampaign;
import jp.co.sint.beans.front.UICmdtyRanking;
import jp.co.sint.config.SIApiConf;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.servlet.SIServlet;
import jp.co.sint.tools.SICheckDataConf;
import jp.co.sint.tools.SICheckValid;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIURLMap;
import jp.co.sint.tools.SIURLParameter;
import jp.co.sint.tools.SIUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Category;
import org.json.simple.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @version $Id: SIApiSrv.java,v 1.0 2014/12/01 Exp $
 * @author  r.kamata
 * <br>Description:
 * <p>History</p>
 * <p>Author&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reason</p>
 *  ============&nbsp;&nbsp;&nbsp;==========&nbsp;&nbsp;===========================<br>
 * r.kamata   2014/12/01 18:00:00  Original
 */
public class SIApiSrv extends SIServlet {
  
  /** serialVersionUID **/
  private static final long serialVersionUID = -6613836442810968998L;
  
  // ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  
  /**
   * <b>doUpdate</b> HTTP リクエストの処理
   *
   * @param request リクエスト
   * @param response
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doUpdate(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();// DBへのコネクションの作成
    SIURLParameter urlParam = new SIURLParameter(request);
    
    JSONObject obj = null;
    
    // INPUT PARAMETER:API名
    String apiname = "";
    
    //INPUT PARAMETER:取得件数
    String count = "";
    
    //INPUT PARAMETER:カテゴリグループ
    String group = "";
    
    //INPUT PARAMETER:カテゴリコード
    String ctgry = "";
    
    //INPUT PARAMETER:JANコード
    String jan = "";
    
    //INPUT PARAMETER:ログインID
    String loginid = "";
    
    //INPUT PARAMETER:パスワード
    String loginpass = "";
    
    try {
      apiname = (String) urlParam.getParam(SIApiConf.PARAMETER_API_NAME);
      count = (String) urlParam.getParam(SIApiConf.PARAMETER_COUNT);
      group = (String) urlParam.getParam(SIApiConf.PARAMETER_GROUP);
      ctgry = (String) urlParam.getParam(SIApiConf.PARAMETER_CTGRY);
      jan = (String) urlParam.getParam(SIApiConf.PARAMETER_JAN);
      loginid = (String) urlParam.getParam(SIApiConf.PARAMETER_LOGINID);
      loginpass = (String) urlParam.getParam(SIApiConf.PARAMETER_LOGINPASS);
      if (apiname == null) {
        apiname = "";
      }
      if (count == null) {
        count = "";
      }
      if (group == null) {
        group = "";
      }
      if (ctgry == null) {
        ctgry = "";
      }
      if (jan == null) {
        jan = "";
      }
      if (loginid == null) {
        loginid = "";
      }
      if (loginpass == null) {
        loginpass = "";
      }
      
      log.debug("[start]doUpdate:apiname="+apiname+",count="+count+",group="+group+",ctgry="+ctgry+",jan="+jan+",loginid="+loginid+",loginpass="+loginpass);
      
      SICustomErrors errors = new SICustomErrors();
      SICheckValid.checkValid(errors,"API名","",apiname,"",SICheckDataConf.SICHECK_DATA_EMPTY_TYPE);
      if (!errors.isEmpty()) {
        obj = returnError("E-00-01","API名を指定してください。");
        returnJsonData(response,obj);
        return;
      }
      
      String apinameForCheck = StringUtils.replace(apiname,"_","");
      SICheckValid.checkValid(errors,"API名","",apinameForCheck,"",SICheckDataConf.SICHECK_DATA_ALPHA_TYPE);
      if (!errors.isEmpty()) {
        obj = returnError("E-00-02","API名が不正です。");
        returnJsonData(response,obj);
        return;
      }
      
      if (apiname.equals(SIApiConf.GET_COMMON_FOOTER)) {
        // 件数出力API
        obj = this.getCommonFooter(request,databaseConnection);
      } else if (apiname.equals(SIApiConf.GET_LOGIIN_INFO)) {
        // ログイン状態判別API
        obj = this.getLoginInfo(request);
      } else if (apiname.equals(SIApiConf.GET_CTGRY)) {
        // カテゴリ一覧出力API
        obj = this.getCtgry(request,databaseConnection,group,ctgry);
      } else if (apiname.equals(SIApiConf.GET_RECOMMEND)) {
        // 新着商品情報出力API
        obj = this.getRecommend(request,databaseConnection,count);
      } else if (apiname.equals(SIApiConf.GET_NEWS)) {
        // ニュース情報出力API
        obj = this.getNews(databaseConnection,count);
      } else if (apiname.equals(SIApiConf.GET_CAMPAIGN)) {
        // キャンペーン・特集情報出力API
        obj = this.getCampaign(count);
      } else if (apiname.equals(SIApiConf.GET_MENU_LINK)) {
        // メニュー用リンク一覧出力API
        obj = this.getMenuLink(request);
      } else if (apiname.equals(SIApiConf.GET_FOOTER_LINK)) {
        // 共通フッタ用リンク一覧出力API
        obj = this.getFooterLink(request);
      } else if (apiname.equals(SIApiConf.GET_CMDTY_PAGE)) {
        // 遷移先URL出力用API
        obj = this.getCmdtyPage(request,databaseConnection,jan);
      } else if (apiname.equals(SIApiConf.GET_NOTICE)) {
        // キャンペーン・告知情報出力API
        obj = this.getNotice(count);
      } else if (apiname.equals(SIApiConf.GET_CUST_INFO)) {
        // 顧客情報参照API
        obj = this.getCustInfo(databaseConnection, loginid, loginpass);
      }
      
      if (obj == null) {
        // API名が不正な場合
        obj = returnError("E-00-03","API名を正しく指定してください。");
      }
      
      returnJsonData(response,obj);
      
    } catch (SQLException e) {
      e.printStackTrace();
      this.returnErrorForExcetion(response,"E-00-99",e.toString());
    } catch (NamingException e) {
      e.printStackTrace();
      this.returnErrorForExcetion(response,"E-00-99",e.toString());
    } catch (Exception e) {
      e.printStackTrace();
      this.returnErrorForExcetion(response,"E-00-99",e.toString());
    } finally {
      databaseConnection.close();
      log.debug("[end]doUpdate:apiname="+apiname+",count="+count);
    }
  }
  
  /**
   * 件数出力API
   * @param request                       リクエスト
   * @param databaseConnection            コネクション
   * @return                              JSONデータ
   * @throws UnsupportedEncodingException 例外
   * @throws SQLException                 例外
   * @throws NamingException              例外
   * @throws SIDBAccessException          例外
   */
  private JSONObject getCommonFooter(HttpServletRequest request,SIDatabaseConnection databaseConnection) throws UnsupportedEncodingException,SQLException,NamingException,SIDBAccessException {
    log.debug("[start]getCommonFooter");
    HttpSession session = request.getSession(true);// セッションの取得
    
    Cookie[] cookies = request.getCookies();
    Cookie cmdtyCookieOrgFavoriteBG = null;
    Cookie cmdtyCookieOrgHistoryBG  = null;
    
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals(SIApiConf.COOKIE_NAME_WS_FAVORITEBG)){
          cmdtyCookieOrgFavoriteBG = cookies[i];
        }
        if (cookies[i].getName().equals(SIApiConf.COOKIE_NAME_WS_HISTORYBG)){
          cmdtyCookieOrgHistoryBG = cookies[i];
        }
        if (cmdtyCookieOrgFavoriteBG != null && cmdtyCookieOrgHistoryBG != null) {
          break;
        }
      }
    }
    
    // お気に入り
    String mycatalogCnt = "0";
    if (cmdtyCookieOrgFavoriteBG != null) {
      String cookieStr = cmdtyCookieOrgFavoriteBG.getValue();
      if (SIUtil.isNotNull(cookieStr)) {
        String[] favoriteItems = URLDecoder.decode(cmdtyCookieOrgFavoriteBG.getValue(),"Shift_JIS").split(",");
        mycatalogCnt = String.valueOf(favoriteItems.length);
      }
    }
    // 最近見た商品
    String historyCnt = "0";
    if (cmdtyCookieOrgHistoryBG != null) {
      String cookieStr = cmdtyCookieOrgHistoryBG.getValue();
      if (SIUtil.isNotNull(cookieStr)) {
        String[] historyItems = URLDecoder.decode(cmdtyCookieOrgHistoryBG.getValue(),"Shift_JIS").split(",");
        historyCnt = String.valueOf(historyItems.length);
      }
    }
    // よく購入する商品
    SIUserInfo lUserInfo = SIHTMLUtil.getUserInfo(request);
    Collection favoriteColl2 = null;
    if (lUserInfo.isNotLogin(request)) {
      favoriteColl2 = new ArrayList();
    }else {
      Connection connection = databaseConnection.getConnection();
      favoriteColl2 = UICampaign.getFavoriteItems(connection,request,200);
      if (favoriteColl2 == null) favoriteColl2 = new ArrayList();
    }
    
    String favoriteCnt = String.valueOf(favoriteColl2.size());
    // カート投入数
    SICartManager headerCart = (SICartManager) session.getAttribute(SIConfig.SISESSION_CART_INFO_NAME);
    if (headerCart == null) headerCart = new SICartManager();
    String cartCnt = headerCart.getAmount();
    
    JSONObject obj = new JSONObject();
    obj.put("result",SIApiConf.RESULT_OK);
    obj.put("mypage_id","1");
    obj.put("mycatalog_id","2");
    obj.put("mycatalog_count",mycatalogCnt);
    obj.put("history_id","3");
    obj.put("history_count",historyCnt);
    obj.put("favorite_id","4");
    obj.put("favorite_count",favoriteCnt);
    obj.put("cart_id","5");
    obj.put("cart_count",cartCnt);
    
    log.debug("[end]getCommonFooter");
    return obj;
  }
  
  /**
   * ログイン状態判別API
   * @param request リクエスト
   * @return        JSONデータ
   */
  private JSONObject getLoginInfo(HttpServletRequest request) {
    log.debug("[start]getLoginInfo");
    JSONObject obj = new JSONObject();
    
    // ログイン未／済チェック
    SIUserInfo lUserInfo = SIHTMLUtil.getUserInfo(request);
    if (lUserInfo.isNotLogin(request)) {
      // ログイン未の場合
      obj.put("result",SIApiConf.RESULT_OK);
      obj.put("login_status",SIApiConf.LOGIN_STATUS_IS_NOT_LOGIN);
      obj.put("img_about_vip_url","");
      obj.put("max_point","");
      obj.put("vip_comment","");
      obj.put("cust_name","");
      return obj;
    }
    
    // 会員ランク
    String img_about_vip_url = "";
    String vip_point = "0";
    boolean vipFlg = false;
    if(SIApiConf.MEMBER_LEVEL_CODE_DIA.equals(lUserInfo.getMemberLevelCode())){
      img_about_vip_url = "/sp/lib_image/mypage/img_icon_vip_dia.png";
      vip_point = "100";
      vipFlg = true;
    }else if(SIApiConf.MEMBER_LEVEL_CODE_PLA.equals(lUserInfo.getMemberLevelCode())){
      img_about_vip_url = "/sp/lib_image/mypage/img_icon_vip_pla.png";
      vip_point = "50";
      vipFlg = true;
    }else if(SIApiConf.MEMBER_LEVEL_CODE_GOLD.equals(lUserInfo.getMemberLevelCode())){
      img_about_vip_url = "/sp/lib_image/mypage/img_icon_vip_gold.png";
      vip_point = "20";
      vipFlg = true;
    }
    if (SIUtil.isNotNull(img_about_vip_url)) {
      // フルパスにする
      img_about_vip_url = SIHTMLUtil.consURL(request,SIHTMLUtil.getRootPath(request)+img_about_vip_url,false);
    }
    StringBuffer vipComment = new StringBuffer();
    if (vipFlg) {
      vipComment.append("<b>");
      vipComment.append("<font size=\"2\">全商品<font color=\"red\">").append(lUserInfo.getDiscountRate()).append("％OFF</font></font><br>");
      vipComment.append("<span class\"txt_small\">さらに</span>ポイント<span class=\"txt_red\">").append(vip_point).append("％増</font></font>");
      vipComment.append("</b>");
    }
    
    // JSONデータ作成
    obj.put("result",SIApiConf.RESULT_OK);
    obj.put("login_status",SIApiConf.LOGIN_STATUS_IS_LOGIN);
    obj.put("img_about_vip_url",img_about_vip_url);
    obj.put("max_point",lUserInfo.getMaxPoint());
    obj.put("vip_comment",vipComment.toString());
    obj.put("cust_name",lUserInfo.getCustName());
    log.debug("[end]getLoginInfo");
    return obj;
  }
  
  /**
   * カテゴリ情報出力API
   */
  private JSONObject getCtgry(HttpServletRequest request,SIDatabaseConnection databaseConnection,String group,String ctgry) throws SQLException,NamingException,IOException,SIDBAccessException {
    log.debug("[start]getCtgry");
    JSONObject obj = new JSONObject();
    StringBuffer sql = new StringBuffer();
    String webshopSite = SIHTMLUtil.getRootPath(request);
    DecimalFormat exFormat = new DecimalFormat("00");
    
    Connection connection = databaseConnection.getConnection();
    
    if (SIUtil.isNotNull(group)&&!SIDBUtil.hasData(connection, "SELECT * FROM ctgrygrouptbl WHERE ctgrygroup="+SIDBUtil.SQL2Str(group))) {
      log.error("getCtgry:apiname="+SIApiConf.GET_CTGRY+",group="+group+",ctgry="+ctgry);
      return returnError("E-03-01","該当のカテゴリグループが存在しません。");
    }
    
    Collection res = new ArrayList();
    
    if (SIUtil.isNull(group)) {// グループNULLの場合、グループ一覧を出力
      for (int i=0;i<SIConfig.ctgryGroupCode.length;i++){
        res.add(new SINameValue(SIConfig.ctgryGroupName[i],SIConfig.ctgryGroupCode[i]+"~0"));
      }
    } else if (SIUtil.isNull(ctgry)){// グループNOTNULL、カテゴリNULLの場合、対象グループのトップレベル一覧を出力
      sql.append("SELECT c.ctgryName,c.ctgryCode || '~' ||c.cmdtyAmount ");
      sql.append("FROM ctgryMTbl c,ctgryGroupTbl g ");
      sql.append("WHERE c.ctgrycode=g.ctgrycode AND g.ctgrygroup=").append(SIDBUtil.SQL2Str(group," "));
      for (int i=0;i<SIConfig.INVISIBLECTGRYS.length;i++){
        sql.append("AND c.ctgrycode<>").append(SIDBUtil.SQL2Str(SIConfig.INVISIBLECTGRYS[i]," "));
      }
      sql.append("ORDER BY g.disporder");
      res=SIDBUtil.getCollection(connection, sql.toString());
    } else {// グループNOTNULL、カテゴリNOTNULLの場合、対象カテゴリの小カテゴリ一覧を出力
      sql.append("SELECT c.ctgryName,c.ctgryCode || '~' ||c.cmdtyAmount ");
      sql.append("FROM ctgryMTbl c,ctgryGroupTbl g ");
      sql.append("WHERE c.parentctgrycode=g.ctgrycode AND g.ctgrygroup=").append(SIDBUtil.SQL2Str(group," "));
      sql.append("AND g.ctgrycode=").append(SIDBUtil.SQL2Str(ctgry," "));
      for (int i=0;i<SIConfig.INVISIBLECTGRYS.length;i++){
        sql.append("AND c.ctgrycode<>").append(SIDBUtil.SQL2Str(SIConfig.INVISIBLECTGRYS[i]," "));
      }
      sql.append("ORDER BY c.abbvctgryname");
      res=SIDBUtil.getCollection(connection, sql.toString());
    }
    
    if (res == null) {
      res = new ArrayList();
    }
    
    List list = new ArrayList();
    JSONObject obj2 = null;
    SINameValue lCtgry = null;
    obj.put("result",SIApiConf.RESULT_OK);
    Iterator lCtgryIte = res.iterator();
    
    String ctgryName  = "";
    String ctgryCode = "";
    String cmdtyAmount = "";
    long count=1;
    
    while(lCtgryIte.hasNext()) {
      obj2 = new JSONObject();
      lCtgry = (SINameValue)lCtgryIte.next();
      
      ctgryName = lCtgry.getName();
      ctgryCode = lCtgry.getValue().split("~")[0];
      cmdtyAmount = lCtgry.getValue().split("~")[1];
      
      obj2.put("ctgrycode",ctgryCode);
      obj2.put("ctgryname",ctgryName);
      obj2.put("cmdtyamount",cmdtyAmount);
      if (SIUtil.isNull(group)) {
        obj2.put("imageurl",SIHTMLUtil.consURL(request,webshopSite+"/sp/lib_image/category/img_cat_"+ctgryCode+".gif",false));
      } else if (SIUtil.isNull(ctgry)){
        obj2.put("imageurl",SIHTMLUtil.consURL(request,webshopSite+"/img/"+group+"/img_category"+exFormat.format(count)+".jpg",false));
      } else {
        obj2.put("imageurl","");
      }
      
      list.add(obj2);
      count++;
    }
    
    obj.put("ctgry_list",list);
    
    log.debug("[end]getCtgry");
    return obj;
  }
  
  /**
   * 新着商品情報出力API
   * @param request            リクエスト
   * @param databaseConnection コネクション
   * @param count              取得件数
   * @return                   JSONデータ
   * @throws SQLException      例外
   * @throws NamingException   例外
   * @throws IOException       例外
   */
  private JSONObject getRecommend(HttpServletRequest request,SIDatabaseConnection databaseConnection,String count) throws SQLException,NamingException,IOException {
    log.debug("[start]getRecommend");
    JSONObject obj = new JSONObject();
    
    SICustomErrors errors = new SICustomErrors();
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_EMPTY_TYPE);
    if (!errors.isEmpty()) {
      log.error("getRecommend:apiname="+SIApiConf.GET_RECOMMEND+",count="+count);
      return returnError("E-05-01","取得件数を指定してください。");
    }
    
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_DIGIT_TYPE);
    if (!errors.isEmpty()) {
      log.error("getRecommend:apiname="+SIApiConf.GET_RECOMMEND+",count="+count);
      return returnError("E-05-02","取得件数は数字で指定してください。");
    }
    
    Connection connection = databaseConnection.getConnection();
    int limit = NumberUtils.toInt(count,0);
    Collection res = UICmdtyRanking.getCollection(connection,request,SIConfig.CTGRYGROUP_INX_ALL,limit);
    if (res == null) {
      res = new ArrayList();
    }
    
    List list = new ArrayList();
    JSONObject obj2 = null;
    SICmdty lCmdty = null;
    obj.put("result",SIApiConf.RESULT_OK);
    Iterator lCmdtyIte = res.iterator();
    
    String webshopSite  = SIHTMLUtil.consURL(request,SIHTMLUtil.getRootPath(request),false);
    String cmdtySrvSite = SIURLMap.getUrl(request,"webshop.servlet.front.commodity");
    
    String itemURL = "";
    String imgURL  = "";
    
    String priceText = "";
    
    while(lCmdtyIte.hasNext()) {
      obj2 = new JSONObject();
      lCmdty = (SICmdty)lCmdtyIte.next();
      
      priceText = this.setPriceText(request,connection,lCmdty);
      itemURL = cmdtySrvSite+"/"+lCmdty.getCmdtyCode()+"/"+lCmdty.getIndividualCode();
      imgURL  = webshopSite+"/image/cmdty/"+lCmdty.getCmdtyCode()+"/"+lCmdty.getCmdtyCode()+"_"+lCmdty.getIndividualCode()+"_t.jpg";
      
      obj2.put("cmdty_name",lCmdty.getCmdtyName());
      obj2.put("price_text",priceText);
      obj2.put("item_url",itemURL);
      obj2.put("img_url",imgURL);
      
      list.add(obj2);
    }
    
    obj.put("recommend_list_count",new Integer(list.size()));
    obj.put("recommend_list",list);
    obj.put("update_date",UICmdtyRanking.getLastUpdateTop(connection));
    
    log.debug("[end]getRecommend");
    return obj;
  }
  
  /**
   * ニュース情報出力API
   * @param databaseConnection コネクション
   * @param count              取得件数
   * @return                   JSONデータ
   * @throws SQLException      例外
   * @throws NamingException   例外
   * @throws IOException       例外
   */
  private JSONObject getNews(SIDatabaseConnection databaseConnection,String count) throws SQLException,NamingException,IOException {
    log.debug("[start]getNews");
    JSONObject obj = new JSONObject();
    
    SICustomErrors errors = new SICustomErrors();
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_EMPTY_TYPE);
    //errors.getErrorMsg();
    if (!errors.isEmpty()) {
      log.error("doUpdate:apiname="+SIApiConf.GET_NEWS+",count="+count);
      return returnError("E-06-01","取得件数を指定してください。");
    }
    
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_DIGIT_TYPE);
    if (!errors.isEmpty()) {
      log.error("doUpdate:apiname="+SIApiConf.GET_NEWS+",count="+count);
      return returnError("E-06-02","取得件数は数字で指定してください。");
    }
    
    Collection res = new SINewsManager(databaseConnection.getConnection()).getCollection();
    if (res == null) {
      res = new ArrayList();
    }
    Iterator newsIte = res.iterator();
    
    List list = new ArrayList();
    JSONObject obj2 = null;
    int disp_no = 1;
    obj.put("result",SIApiConf.RESULT_OK);
    
    int limit = NumberUtils.toInt(count,0);
    while (newsIte.hasNext()) {
      if (limit != 0 && limit < disp_no) {
        break;
      }
      obj2 = new JSONObject();
      SINews lNews = (SINews)newsIte.next();
      obj2.put("news_id",lNews.getNewsCode());
      obj2.put("news_start_date_time",lNews.getStartDateTime().substring(0,10));
      obj2.put("news_description",lNews.getDescription());
      obj2.put("news_disp_no",new Integer(disp_no));
      disp_no++;
      list.add(obj2);
    }
    obj.put("news_list_count",new Integer(list.size()));
    obj.put("news_list",list);
    
    log.debug("[end]getNews");
    return obj;
  }
  
  /**
   * キャンペーン・特集情報出力API
   */
  private JSONObject getCampaign(String count) throws IOException {
    log.debug("[start]getCampaign");
    JSONObject obj = new JSONObject();
    
    SICustomErrors errors = new SICustomErrors();
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_EMPTY_TYPE);
    if (!errors.isEmpty()) {
      log.error("doUpdate:apiname="+SIApiConf.GET_CAMPAIGN+",count="+count);
      return returnError("E-07-01","取得件数を指定してください。");
    }
    
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_DIGIT_TYPE);
    if (!errors.isEmpty()) {
      log.error("doUpdate:apiname="+SIApiConf.GET_CAMPAIGN+",count="+count);
      return returnError("E-07-02","取得件数は数字で指定してください。");
    }
    
    try {
      DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docbuilder = dbfactory.newDocumentBuilder();
      Document doc = docbuilder.parse(new File(getServletContext().getRealPath("pickup/campaign.xml")));
      
      NodeList items = doc.getFirstChild().getFirstChild().getChildNodes().item(1).getChildNodes();
      List list = new ArrayList();
      JSONObject obj2 = null;
      for (int i=0;i<Integer.parseInt(count);i++) {
       Node item = items.item(i);
       if (item == null) break;
        obj2 = new JSONObject();
        obj2.put("page_title",item.getChildNodes().item(0).getFirstChild().getNodeValue());
        obj2.put("page_url",item.getChildNodes().item(1).getFirstChild().getNodeValue());
        obj2.put("img_url",item.getChildNodes().item(2).getFirstChild().getNodeValue());
        list.add(obj2);
      }
      
      obj.put("result",SIApiConf.RESULT_OK);
      obj.put("campaign_list_count",new Integer(list.size()));
      obj.put("lastupdate",doc.getFirstChild().getFirstChild().getChildNodes().item(0).getFirstChild().getNodeValue());
      obj.put("campaign_list",list);
      
    } catch (Exception e) {
      obj = new JSONObject();
      obj.put("result",SIApiConf.RESULT_NG);
      return obj;
    }
    
    log.debug("[end]getCampaign");
    return obj;
  }
  
  /**
   * メニュー用リンク一覧出力API
   * @param request リクエスト
   * @return        JSONデータ
   */
  private JSONObject getMenuLink(HttpServletRequest request) {
    log.debug("[start]getMenuLink");
    JSONObject obj = new JSONObject();
    String webshopSite = SIHTMLUtil.getRootPath(request);
    
    obj.put("result",SIApiConf.RESULT_OK);
    
    String loginStatusUrl = "";
    String loginStatusName = "";
    SIUserInfo lUserInfo = SIHTMLUtil.getUserInfo(request);
    if (lUserInfo.isLogin(request)) {
      loginStatusUrl = SIURLMap.getHttpsUrl(request,"webshop.servlet.front.user.logout");
      loginStatusName = SIApiConf.LOGIN_STATUS_NAME_LOGOUT;
    } else {
      loginStatusUrl = SIURLMap.getHttpsUrl(request,"webshop.servlet.front.user.login");
      loginStatusName = SIApiConf.LOGIN_STATUS_NAME_LOGIN;
    }
    obj.put("header_login_status_name",loginStatusName);
    obj.put("header_login_status_url",loginStatusUrl);
    obj.put("header_first_name",SIApiConf.FIRST_NAME);
    obj.put("header_first_url",SIHTMLUtil.consURL(request,webshopSite+"/guide/first.jsp",false));
    obj.put("header_showroom_name",SIApiConf.SHOWROOM_NAME);
    obj.put("header_showroom_url",SIHTMLUtil.consURL(request,webshopSite+"/showroom/index.html",false));
    obj.put("header_catalog_name",SIApiConf.CATALOG_NAME);
    obj.put("header_catalog_url",SIHTMLUtil.consURL(request,webshopSite+"/catalog",false));
    obj.put("header_guide_name1",SIApiConf.GUIDE_NAME1);
    obj.put("header_guide_url1",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/index.html",false));
    obj.put("header_support_name",SIApiConf.SUPPORT_NAME);
    obj.put("header_support_url","");
    obj.put("header_guarantee_name",SIApiConf.GUARANTEE_NAME);
    obj.put("header_guarantee_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/guarantee.html",false));
    obj.put("header_search_name",SIApiConf.SEARCH_NAME);
    obj.put("header_search_url",SIURLMap.getHttpsUrl(request,"webshop.servlet.front.search"));
    obj.put("header_repair_name",SIApiConf.REPAIR_NAME);
    obj.put("header_repair_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/repair.html",false));
    obj.put("header_setting_name",SIApiConf.SETTING_NAME);
    obj.put("header_setting_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/setting.html",false));
    obj.put("header_catalog_request_name",SIApiConf.CATALOG_REQUEST_NAME);
    obj.put("header_catalog_request_url",SIHTMLUtil.consURL(request,webshopSite+"/catalog_request",false));
    obj.put("header_kaitori_name",SIApiConf.KAITORI_NAME);
    obj.put("header_kaitori_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/kaitori.html",false));
    obj.put("header_srent_name",SIApiConf.SRENT_NAME);
    obj.put("header_srent_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/srent.html",false));
    obj.put("header_overseas_shipping_name",SIApiConf.OVERSEAS_SHIPPING_NAME);
    obj.put("header_overseas_shipping_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/guide/overseas_shipping.html",false));
    obj.put("header_q_and_a_name",SIApiConf.Q_AND_A_NAME);
    obj.put("header_q_and_a_url",SIHTMLUtil.consURL(request,webshopSite+"/guide/faq.html",false));
    obj.put("header_contact_name",SIApiConf.CONTACT_NAME);
    obj.put("header_contact_url",SIHTMLUtil.consURL(request,"/form/sp/contact/",true));
    obj.put("header_listpickup_name",SIApiConf.LISTPICKUP_NAME);
    obj.put("header_listpickup_url",SIHTMLUtil.consURL(request,webshopSite+"/listpickup/listpickup.html",true));
    obj.put("header_infomation_name",SIApiConf.INFORMATION_NAME);
    obj.put("header_infomation_url",SIHTMLUtil.consURL(request,webshopSite+"/main?actionNameTxt=news&inx=0",true));
    obj.put("header_how_to_use_app_name",SIApiConf.HOW_TO_USE_APP_NAME);
    obj.put("header_how_to_use_app_url",SIHTMLUtil.consURL(request,webshopSite+"/sp/app/how_to_use_app/index.html",true));
    obj.put("header_guide_name2",SIApiConf.GUIDE_NAME2);
    obj.put("header_guide_url2",SIHTMLUtil.consURL(request,webshopSite+"/guide/index.html",true));
    obj.put("header_agreement_name",SIApiConf.AGREEMENT_NAME);
    obj.put("header_agreement_url",SIHTMLUtil.consURL(request,"/agreement/index.php",true));
    
    log.debug("[end]getMenuLink");
    return obj;
  }
  
  /**
   * 共通フッタ用リンク一覧出力API
   * @param request リクエスト
   * @return        JSONデータ
   */
  private JSONObject getFooterLink(HttpServletRequest request) {
    log.debug("[start]getFooterLink");
    JSONObject obj = new JSONObject();
    String webshopSite = SIHTMLUtil.getRootPath(request);
    
    obj.put("result",SIApiConf.RESULT_OK);
    obj.put("footer_mypage_id","1");
    obj.put("footer_mypage_name",SIApiConf.MYPAGE_NAME);
    obj.put("footer_mypage_url",SIURLMap.getUrl(request,"webshop.servlet.front.mypage"));
    obj.put("footer_mycatalog_id","2");
    obj.put("footer_mycatalog_name",SIApiConf.MYCATALOG_NAME);
    obj.put("footer_mycatalog_url",SIHTMLUtil.consURL(request,webshopSite+"/mypage/a/list",true));
    obj.put("footer_history_id","3");
    obj.put("footer_history_name",SIApiConf.HISTORY_NAME);
    obj.put("footer_history_url",SIHTMLUtil.consURL(request,webshopSite+"/mypage/a/list2",true));
    obj.put("footer_favorite_id","4");
    obj.put("footer_favorite_name",SIApiConf.FAVORITE_NAME);
    obj.put("footer_favorite_url",SIHTMLUtil.consURL(request,webshopSite+"/mypage/a/list3",true));
    obj.put("footer_cart_id","5");
    obj.put("footer_cart_name",SIApiConf.CART_NAME);
    obj.put("footer_cart_url",SIURLMap.getUrl(request,"webshop.servlet.front.cart"));
    
    log.debug("[end]getFooterLink");
    return obj;
    
  }
  
  /**
   * 遷移先URL出力API
   */
  private JSONObject getCmdtyPage(HttpServletRequest request,SIDatabaseConnection databaseConnection,String jan) throws SQLException,NamingException,IOException,SIDBAccessException {
    log.debug("[start]getCmdtyPage");
    JSONObject obj = new JSONObject();
    StringBuffer sql = new StringBuffer();
    String webshopSite = SIHTMLUtil.getRootPath(request);
    
    if (SIUtil.isNull(jan)) {
      log.error("getCmdtyURL:apiname="+SIApiConf.GET_CMDTY_PAGE+",jan="+jan);
      return returnError("E-10-01","JANコードを指定してください。");
    }
    
    Connection connection = databaseConnection.getConnection();
    Collection res = new ArrayList();
    
    sql.append("SELECT unit.CmdtyCode,unit.IndividualCode ");
    sql.append("FROM CmdtyUnitTbl unit ");
    sql.append("WHERE unit.JancodeIndividual=").append(SIDBUtil.SQL2Str(jan," "));
    sql.append("AND unit.FrontDispFlg='1' ");
    sql.append("AND NOT(unit.UsedNewFlg!='1' AND unit.UsedNewFlg!='7' AND unit.AmountFlg='1' AND unit.Amount-unit.BGPAmount='0' ");
    sql.append(" AND (unit.RsrvEnableFlg='0' OR (unit.RsrvAmount IS NOT NULL AND unit.RsrvAmount='0')) ");
    sql.append(" AND (unit.SoldoutDate IS NULL OR unit.SoldoutDate + 7 <= CURRENT_DATE)) ");
    sql.append("UNION ");
    sql.append("SELECT DISTINCT individual1.CmdtyCode,individual1.IndividualCode ");
    sql.append("FROM IndividualTbl individual1,IndividualTbl individual2,CompositionGroupDetailTbl comp ");
    sql.append("WHERE individual1.IndividualCode=comp.IndividualCode AND individual2.IndividualCode=comp.DetailIndividualCode ");
    sql.append("AND individual1.frontDispFlg='1' AND individual2.JancodeIndividual=").append(SIDBUtil.SQL2Str(jan," "));
    sql.append("UNION ");
    sql.append("SELECT DISTINCT individual1.CmdtyCode,individual1.IndividualCode ");
    sql.append("FROM IndividualTbl individual1,IndividualTbl individual2,CompositionOptionTbl option ");
    sql.append("WHERE individual1.IndividualCode=option.IndividualCode AND individual2.IndividualCode=option.DetailIndividualCode ");
    sql.append("AND individual1.frontDispFlg='1' AND individual2.JancodeIndividual=").append(SIDBUtil.SQL2Str(jan," "));
    sql.append("UNION ");
    sql.append("SELECT DISTINCT individual1.CmdtyCode,individual1.IndividualCode ");
    sql.append("FROM IndividualTbl individual1,IndividualTbl individual2,AppendedCmdtyTbl append ");
    sql.append("WHERE individual1.IndividualCode=append.IndividualCode AND individual2.IndividualCode=append.DetailIndividualCode ");
    sql.append("AND individual1.frontDispFlg='1' AND individual2.JancodeIndividual=").append(SIDBUtil.SQL2Str(jan," "));
    sql.append("LIMIT 20");
    log.debug("getCmdtyPage(jancode):"+jan);
    res=SIDBUtil.getCollection(connection, sql.toString());
    
    if (res == null) {
      res = new ArrayList();
    }
    
    SINameValue lCtgry = null;
    obj.put("result",SIApiConf.RESULT_OK);
    Iterator lCmdtyIte = res.iterator();
    
    String cmdtyCode  = "";
    String individualCode = "";
    String url = "";
    
    while(lCmdtyIte.hasNext()) {
      lCtgry = (SINameValue)lCmdtyIte.next();
      cmdtyCode = lCtgry.getName();
      individualCode = lCtgry.getValue();
      
      if (res.size()==1) {// 1件ヒット時
        url = SIHTMLUtil.consURL(request,webshopSite+"/search_cmdty/"+cmdtyCode+"/"+individualCode,false);
      } else {// 複数件ヒット時
        if (SIUtil.isNull(url)) {// 複数件：初回
          url = SIHTMLUtil.consURL(request,webshopSite+"/advancedsearch?a=list&dispModeTxt=2&codes=",false);
        } else { //複数件：2回目以降
          url = url + ",";
        }
        url = url + individualCode;
      }
    }
    obj.put("link_url",url);
    
    
    log.debug("[end]getCmdtyPage");
    return obj;
  }
  
  /**
   * キャンペーン・告知情報出力API
   */
  private JSONObject getNotice(String count) throws IOException {
    log.debug("[start]getNotice");
    JSONObject obj = new JSONObject();
    
    SICustomErrors errors = new SICustomErrors();
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_EMPTY_TYPE);
    if (!errors.isEmpty()) {
      log.error("doUpdate:apiname="+SIApiConf.GET_NOTICE+",count="+count);
      return returnError("E-11-01","取得件数を指定してください。");
    }
    
    SICheckValid.checkValid(errors,"取得件数","",count,"",SICheckDataConf.SICHECK_DATA_DIGIT_TYPE);
    if (!errors.isEmpty()) {
      log.error("doUpdate:apiname="+SIApiConf.GET_NOTICE+",count="+count);
      return returnError("E-11-02","取得件数は数字で指定してください。");
    }
    
    try {
      DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docbuilder = dbfactory.newDocumentBuilder();
      Document doc = docbuilder.parse(new File(getServletContext().getRealPath("pickup/notice.xml")));
      
      NodeList items = doc.getFirstChild().getFirstChild().getChildNodes().item(1).getChildNodes();
      List list = new ArrayList();
      JSONObject obj2 = null;
      for (int i=0;i<Integer.parseInt(count);i++) {
       Node item = items.item(i);
       if (item == null) break;
        obj2 = new JSONObject();
        obj2.put("page_url",item.getChildNodes().item(0).getFirstChild().getNodeValue());
        obj2.put("img_url",item.getChildNodes().item(1).getFirstChild().getNodeValue());
        list.add(obj2);
      }
      
      obj.put("result",SIApiConf.RESULT_OK);
      obj.put("notice_list_count",new Integer(list.size()));
      obj.put("lastupdate",doc.getFirstChild().getFirstChild().getChildNodes().item(0).getFirstChild().getNodeValue());
      obj.put("notice_list",list);
      
    } catch (Exception e) {
      obj = new JSONObject();
      obj.put("result",SIApiConf.RESULT_NG);
      return obj;
    }
    
    log.debug("[end]getNotice");
    return obj;
  }
  
  /**
   * 遷移先URL出力API
   */
  private JSONObject getCustInfo(SIDatabaseConnection databaseConnection,String loginid,String loginpass) throws SQLException,NamingException,IOException,SIDBAccessException {
    log.debug("[start]getCustInfo");
    JSONObject obj = new JSONObject();
    StringBuffer sql = new StringBuffer();
    
    if (SIUtil.isNull(loginid)) {
      log.error("getCmdtyURL:apiname="+SIApiConf.GET_CUST_INFO+",loginid="+loginid);
      return returnError("E-12-01","ログインIDを指定してください。");
    }
    
    if (SIUtil.isNull(loginpass)) {
      log.error("getCmdtyURL:apiname="+SIApiConf.GET_CUST_INFO+",loginpass="+loginpass);
      return returnError("E-12-02","パスワードを指定してください。");
    }
    
    sql.append("SELECT corporationname,custname,custpronname,storetel,postcode1||postcode2 AS postcode,storetel,address1,address2,coalesce(address3,'') AS address3 ");
    sql.append("FROM custtbl WHERE delflg=0 AND email=").append(SIDBUtil.SQL2Str(loginid," "));
    sql.append("AND password=").append(SIDBUtil.SQL2Str(loginpass));
    log.debug("getCustInfo(loginid):"+loginid);
    log.debug("getCustInfo(loginpass):"+loginpass);
    
    Connection connection = databaseConnection.getConnection();
    Statement lStatement = null;
    ResultSet lResultSet = null;
    
    try{
      lStatement = connection.createStatement();
      lResultSet = lStatement.executeQuery(sql.toString());
      
      if (lResultSet.next()) {
        obj.put("result",SIApiConf.RESULT_OK);
        obj.put("corporationname",lResultSet.getString("corporationname"));
        obj.put("custname",lResultSet.getString("custname"));
        obj.put("custpronname",lResultSet.getString("custpronname"));
        obj.put("storetel",lResultSet.getString("storetel"));
        obj.put("postcode",lResultSet.getString("postcode"));
        obj.put("address1",lResultSet.getString("address1"));
        obj.put("address2",lResultSet.getString("address2"));
        obj.put("address3",lResultSet.getString("address3"));
      }else{
        log.error("getCmdtyURL:apiname="+SIApiConf.GET_CUST_INFO+",loginid="+loginid+",loginpass="+loginpass);
        return returnError("E-12-03","該当する顧客データが存在しません。");
      }
    } catch (Exception e) {
      obj = new JSONObject();
      obj.put("result",SIApiConf.RESULT_NG);
      return obj;
    }finally{
      SIDBUtil.close(lResultSet, lStatement);
    }
    
    log.debug("[end]getCustInfo");
    return obj;
  }
  
  /**
   * 商品価格表示をセット
   * @param lCmdty 商品レコード
   * @return       商品価格表示
   */
  private String setPriceText(HttpServletRequest request,Connection connection,SICmdty lCmdty) {
    String result = "";
    
    if (lCmdty.isContractFlg()) {
      result = SIApiConf.PRICE_TEXT_CONTRACT;
    } else if (lCmdty.getBGPriceDispFlg().equals("2")) {
      result = SIApiConf.PRICE_TEXT_CONTACT;
    } else if (lCmdty.getBGPriceDispFlg().equals("1") && SIHTMLUtil.getUserInfo(request).isNotLogin(request)) {
      result = SIApiConf.PRICE_TEXT_NOTLOGIN;
    } else {
      if (!lCmdty.isCmdtyComposition()) {
        result = lCmdty.getFinalUnitPriceWithoutTax();
      } else {
        String setUnitPrice = lCmdty.getSetUnitPriceWithoutTax(connection); 
        String setDiscountUnitPrice = lCmdty.getSetDiscountUnitPriceWithoutTax(connection); 
        if (setUnitPrice.equals(setDiscountUnitPrice)) {
          result = setUnitPrice;
        } else {
          result = setDiscountUnitPrice;
        }
      }
    }
    return result;
  }
  
  /**
   * エラー用のJSONデータを作成、呼び出し元へ返却
   * @param response      レスポンス
   * @param error_code    エラーコード
   * @param error_message エラーメッセージ
   * @throws IOException  例外
   */
  private JSONObject returnError(String error_code,String error_message) throws IOException {
    JSONObject obj = new JSONObject();
    obj.put("result",SIApiConf.RESULT_NG);
    JSONObject errObj = new JSONObject();
    List errList = new ArrayList();
    
    errObj.put("error_code",error_code);
    errObj.put("error_message",error_message);
    errList.add(errObj);
    obj.put("error_list",errList);
    
    log.error(error_code+":"+error_message);
    
    return obj;
  }
  
  /**
   * JSONデータを返却
   * @param response     レスポンス
   * @param obj          JSONデータ
   * @throws IOException 例外
   */
  private void returnJsonData(HttpServletResponse response,JSONObject obj) throws IOException {
    response.setContentType("application/json; charset=utf-8");
    PrintWriter out = response.getWriter();
    obj.writeJSONString(out);
  }
  
  /**
   * システムエラー発生時、JSONデータを返却
   * @param response      レスポンス
   * @param error_code    エラーコード
   * @param error_message エラーメッセージ
   * @throws IOException  例外
   */
  private void returnErrorForExcetion(HttpServletResponse response,String error_code,String error_message) throws IOException {
      JSONObject obj = returnError(error_code,error_message);
      this.returnJsonData(response,obj);
  }
}
