package com.dbs.consentServer.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import com.dbs.consentServer.VO.consentVO.CodeVO;
import com.dbs.consentServer.VO.consentVO.ConsentFormListVO;
import com.dbs.consentServer.service.ConsentService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestParam;


@Api(tags = { "1. ConsentService " })
@RestController
@RequestMapping("/ConsentSvc")
public class ConsentSvc {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private ConsentService consentService;

  // @RequestMapping("/")
  // public String index() {
  // return "";
  // }

  // @Autowired
  // TestService testService;

  // @RequestMapping(value = "/test")
  // public void test() throws Exception {
  // logger.error("test");
  // TestVO testList = testService.selectTest();

  @ApiOperation(value = "테스트 URI", notes = "테스트 URI 입니다.")
  @RequestMapping(value = "/test", method = RequestMethod.GET)
  public void test() throws Exception {
    logger.error("test");
    // TestVO testList = testService.selectTest();

    // logger.error("sadfkljhasdf lasdfkj -- > " + testList.getId());
    // logger.error("sadfkljhasdf lasdfkj -- > " + testList.getName());
    // }
  }

  /**
   * 동의서 조회 (미작성, 환자별, 작성자별)
   * 
   * @param patientCode  환자 등록번호
   * @param startDt      조회 시작 일자
   * @param endDt        조회 마지막 일자
   * @param consentState 동의서 상태 인증 : CERTIFY_CMP, 임시 : TEMP, 확인 : ELECTR_CMP, 연동 :
   *                     UNFINISHED, 출력 : PAPER_OUT 받을때 형식
   *                     'CERTIFY_CMP','TEMP','ELECTR_CMP'
   * @param instCd       기관코드
   * @param userId       작성자별 검색시 로그인 사용자 아이디
   * @return
   */
  @RequestMapping(path = "getConsentList", method = RequestMethod.POST)
  public ArrayList<HashMap<String, Object>> getConsentList(String patientCode, String startDt, String endDt,
      String consentState, String instCd, String userId) {
    ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> map = new HashMap<String, Object>();
    HashMap<String, Object> params = new HashMap<String, Object>();

    String[] consentStateStrAr = {};

    if (!consentState.isEmpty()) {
      if (!consentState.equals("ALL")) {
        consentStateStrAr = consentState.trim().split(",");
        params.put("consentState", consentStateStrAr);
      } else {
        consentState = "ALL";
        params.put("consentState", consentState);
      }
    } else {
      consentState = "ALL";
      params.put("consentState", consentState);
    }

    params.put("patientCode", patientCode);
    params.put("startDt", startDt);
    params.put("endDt", endDt);

    params.put("instCd", instCd);
    params.put("userId", userId);

    ArrayList<ConsentFormListVO> consentList = consentService.getConsentList(params);

    if (consentList.size() == 0) {
      map.put("code", "01");
    } else {
      map.put("code", "00");
      map.put("data", consentList);
    }

    result.add(map);

    return result;
  }

  /**
   * 즐겨찾기 목록 리스트
   * 
   * @param userId 사용자 아이디
   * @param instCd 기관코드
   * @return
   */
  @RequestMapping(path = "getUserFormSetList", method = RequestMethod.POST)
  public ArrayList<HashMap<String, Object>> getUserFormSetList(String userId, String instCd) {
    ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> map = new HashMap<String, Object>();
    ArrayList<ConsentFormListVO> formList = new ArrayList<ConsentFormListVO>();
    HashMap<String, String> params = new HashMap<String, String>();

    params.put("userId", userId);
    params.put("instCd", instCd);

    formList = consentService.getUserFormSet(params);

    if (formList.size() == 0) {
      map.put("code", "01");
    } else {
      map.put("code", "00");
      map.put("data", formList);
    }

    result.add(map);

    return result;
  }

  /**
   * 동의서 찾기
   * 
   * @param categoryId 동의서 카테고리
   * @param keyWord    검색할 동의서 이름
   * @return
   */
  @RequestMapping(path = "getConsentBySearch", method = RequestMethod.POST)
  public ArrayList<HashMap<String, Object>> getConsentBySearch(String categoryId, String keyWord) {
    ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> map = new HashMap<String, Object>();
    ArrayList<ConsentFormListVO> formList = new ArrayList<ConsentFormListVO>();
    HashMap<String, String> params = new HashMap<String, String>();

    params.put("categoryId", categoryId);
    params.put("keyWord", "%" + keyWord + "%");

    formList = consentService.getConsentBySearch(params);
    if (formList.size() == 0) {
      map.put("code", "01");
    } else {
      map.put("code", "00");
      map.put("data", formList);
    }
    result.add(map);

    return result;
  }

  /** 
   * 임시저장 서식 삭제
   * @param userId
   * @param consentMstRid
   * @param reasonForUseN
   * @return
   */
  @RequestMapping(path="saveTempDelete", method=RequestMethod.GET)
  public ArrayList<HashMap<String, Object>> saveTempDelete(String userId, int consentMstRid, String reasonForUseN) {
    ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> map = new HashMap<String, Object>();
    HashMap<String, Object> params = new HashMap<String, Object>();

    int rCount = 0;
    String ocrTag = "";

    params.put("userId", userId);
    params.put("consentMstRid", consentMstRid);
    params.put("reasonForUseN", reasonForUseN);

    rCount = consentService.updateConsentMstForDelete(params);

    if (rCount == 0) {
      map.put("code", "01");
    } else {
      ocrTag = consentService.getConsentMstForDeleteOcrTag(params);

      if (!(ocrTag.equals("") || ocrTag.isEmpty())) {
        params.put("ocrTag", ocrTag);
        rCount = consentService.updateMrfhOcrPrntStatCd(params);

        if (rCount == 0) {
          map.put("code", "02");
        } else {
          map.put("code", "00");
          map.put("data", rCount);
        }
      }
    }
    result.add(map);

    return result;
  }
}
