package com.lemon.lifecenter.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lemon.lifecenter.common.LifeCenterConfigVO;
import com.lemon.lifecenter.common.LifeCenterController;
import com.lemon.lifecenter.common.LifeCenterFunction;
import com.lemon.lifecenter.common.LifeCenterPaging;
import com.lemon.lifecenter.common.LifeCenterSessionController;
import com.lemon.lifecenter.dto.CenterInfoDTO;
import com.lemon.lifecenter.dto.PatientDTO;
import com.lemon.lifecenter.service.CenterService;
import com.lemon.lifecenter.service.PatientService;

@Controller
@RequestMapping("/patient")
//@DependsOn(value = {"LifeCenterPaging"})
public class PatientController extends LifeCenterController {
    @Autowired
    private PatientService patientService;
    
    @Autowired
    private CenterService centerService;
    
    @Autowired
    private LifeCenterConfigVO config;
    
    private LifeCenterPaging paging;
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/list")
//    @ModelAttribute("dto") final ASiboDTO dto,
//    @RequestParam( value="k", required=true ) String k
//    @RequestParam( value="type", required=false, defaultValue="" ) String type
    public ModelAndView patientList(
            @RequestParam(value="inputState", required=false, defaultValue="ALL") String inputState,
            @RequestParam(value="patientName", required=false, defaultValue="") String patientName,
            @RequestParam(value="startDate", required=false, defaultValue="") String startDate,
            @RequestParam(value="endDate", required=false, defaultValue="") String endDate,
            @RequestParam(value="page", required=false, defaultValue="1") int page ) {
        
        System.err.println( "page : " + page );
        
        PatientDTO dto = new PatientDTO();
        dto.setPatientName(patientName);
        dto.setState(inputState);
        dto.setStartDate(startDate);
        dto.setEndDate(endDate);
        dto.setLimit( ( Integer.valueOf( page ) - 1 ) * config.pageDataSize );
        dto.setLimitMax( config.pageDataSize );
        
        int total = patientService.selectPatientCount(dto);
        List<PatientDTO> result = new ArrayList<PatientDTO>();

        if (total > 0) {
            result = patientService.selectPatietList(dto);
        }
        
        ModelAndView mv = setMV("patient/list");
        
        System.out.println( "PatientController config.pageGroupSize : " + config.pageGroupSize );
        
        String param = "patientName=" + patientName + "&inputState=" + inputState + "&startDate=" + startDate + "&endDate=" + endDate;
        paging = LifeCenterPaging.getInstance();
        paging.paging(config, total, page, param);
        
        startDate = startDate.equals( "" ) ? LifeCenterFunction.getNow( "yyyy-MM-dd" ) : startDate;
        endDate   = endDate.equals( "" )   ? LifeCenterFunction.getNow( "yyyy-MM-dd" ) : endDate;
        
        mv.addObject("inputState", inputState);
        mv.addObject("patientName", patientName);
        mv.addObject("total", total);
        mv.addObject("item", result);
        mv.addObject("paging", paging);
        
        mv.addObject( "startDate", startDate );
        mv.addObject( "endDate", endDate );
        mv.addObject( "page", page );
        mv.addObject( "pageSize", dto.getLimitMax() );
        
        return mv;
    }

    @RequestMapping("/new")
    public ModelAndView patientNew( HttpServletRequest request,HttpServletResponse response ) {
        ModelAndView mv = setMV("patient/new");
        String sesCenterCode  = LifeCenterSessionController.getSession( request, "sesCenterCode" );
        String sesId  = LifeCenterSessionController.getSession( request, "sesId" );
        
        // 세션의 센터코드 들고와서 치료센터명 조회후 view 전달
        CenterInfoDTO dto = new CenterInfoDTO();
        dto.setCenterCode( Integer.valueOf( sesCenterCode ) );
        dto.setStaffId( sesId );
        
        int centerCount   = centerService.selectCenterCount( dto );
        
        String centerName = "";
        
        if( centerCount > 0 ) {
            centerName = centerService.selectCenterInfoOne( dto ).getCenterName();
        }
        
        mv.addObject( "centerName", centerName );
        mv.addObject( "centerCount", centerCount );
        mv.addObject( "actionType", "new" );
        
        return mv;
    }
    
    @RequestMapping("/new/insert")
    public String patientNewInsert(
            @ModelAttribute("dto") final PatientDTO dto,
            HttpServletRequest request,HttpServletResponse response ) throws Exception {
        int sesCenterCode = Integer.valueOf( LifeCenterSessionController.getSession( request, "sesCenterCode" ) ) ;
        String sesId  = LifeCenterSessionController.getSession( request, "sesId" );
        
        //patientCare Insert
        System.out.println( "dto.getJumin().substring(2) : " + dto.getJumin().replace( "-" , "" ).substring(2) );
        String jumin = dto.getJumin().replace( "-" , "" );
        
        dto.setId( dto.getWardNumber().trim() + dto.getRoomNumber().trim() );
        dto.setPw( LifeCenterFunction.aesEncrypt( config.aesKey, config.IV, jumin.substring(2) ) );
        dto.setJumin( jumin );
        dto.setCenterCode( sesCenterCode );
        dto.setState( "H" ); // H : 입소
        dto.setCreateBy( sesId );
        
        patientService.insertPatientCare( dto );  // 환지 기본정보 insert
        
        int patientIdx = dto.getPatientIdx();
        dto.setPatientIdx( patientIdx );
        
        //patientDisease Insert
        dto.setEtcCheck( dto.getEtcCheckDisease() );
        dto.setEtcContent( dto.getEtcContentDisease() );
        
        patientService.insertPatientDisease( dto );
        
        
        //patientSymptom Insert
        dto.setEtcCheck( dto.getEtcCheckSymptom() );
        dto.setEtcContent( dto.getEtcContentSymptom() );
        dto.setBloodPressureLevel( dto.getBloodPressureLevelCon() + "|" + dto.getBloodPressureLevelRel() );
        
        patientService.insertPatientSymptom( dto );
        
        return "redirect:/patient/info?patientIdx=" + patientIdx;
    }

    @RequestMapping("/info")
    public ModelAndView patientInfo( @ModelAttribute("dto") PatientDTO dto ) {
        ModelAndView mv = setMV("patient/info");

        int patientIdx = dto.getPatientIdx();
        dto = patientService.selectPatientOne(dto);
        
        String jumin = dto.getJumin();
        jumin = jumin.substring(0, 4) + "년 " + jumin.substring(4, 6) + "월 " + jumin.substring(6, 8) + "일";
        dto.setJumin(jumin);
        
        dto.setPatientPhone(LifeCenterFunction.phone(dto.getPatientPhone()));
        dto.setGuardianPhone(LifeCenterFunction.phone(dto.getGuardianPhone()));
        
        String bloodPress = dto.getBloodPressureLevel();
        
        if (!bloodPress.equals("")) {
            String[] bloodPressureLevel = dto.getBloodPressureLevel().split("[|]");
            dto.setBloodPressureLevelCon(bloodPressureLevel[0]);
            dto.setBloodPressureLevelRel(bloodPressureLevel[0]);
        }
        
        String strDisease = getDisease(dto);
        String strSymptom = getSymptom(dto);
        
        mv.addObject("disease", strDisease);
        mv.addObject("symptom", strSymptom);
        mv.addObject("patientIdx", patientIdx);
        mv.addObject("info", dto);
        return mv;
    }

    @RequestMapping("/edit")
    public ModelAndView patientEdit( 
            @ModelAttribute("dto") PatientDTO patientDTO,
            HttpServletRequest request,HttpServletResponse response ) {
        String sesCenterCode  = LifeCenterSessionController.getSession( request, "sesCenterCode" );
        String sesId  = LifeCenterSessionController.getSession( request, "sesId" );
        
        int patientIdx = patientDTO.getPatientIdx();
        patientDTO = patientService.selectPatientOne( patientDTO );
        
        
        // 세션의 센터코드 들고와서 치료센터명 조회후 view 전달
        // 센터가 존재하는지 체크
        CenterInfoDTO dto = new CenterInfoDTO();
        dto.setCenterCode( Integer.valueOf( sesCenterCode ) );
        dto.setStaffId( sesId );
        String centerName = "";
        int centerCount   = centerService.selectCenterCount( dto );
        
        if( centerCount > 0 ) {
            centerName = centerService.selectCenterInfoOne( dto ).getCenterName();
        } else {
            LifeCenterFunction.scriptMessage(response, "alert('삭제되었거나 존재하지않는 치료센터입니다.');" );
            // return ""; 아직처리안함
        }
        
        ModelAndView mv = setMV("patient/edit");
        
        mv.addObject( "centerName", centerName );
        mv.addObject( "centerCount", centerCount );
        
        mv.addObject( "patientIdx", patientIdx );
        mv.addObject( "patientData", patientDTO );
        mv.addObject( "actionType", "edit" );
        
        return mv;
    }
    
    @RequestMapping("/edit/update")
    public String patientEditUpdate(
            @ModelAttribute("dto") final PatientDTO dto,
            HttpServletRequest request,HttpServletResponse response ) throws Exception {
        int sesCenterCode = Integer.valueOf( LifeCenterSessionController.getSession( request, "sesCenterCode" ) ) ;
        String sesId  = LifeCenterSessionController.getSession( request, "sesId" );
        
        int patientIdx = dto.getPatientIdx();
        dto.setPatientIdx( patientIdx );
        
        //patientCare Update
        String jumin = dto.getJumin().replace( "-" , "" );
        
        dto.setId( dto.getWardNumber().trim() + dto.getRoomNumber().trim() );
        dto.setPw( LifeCenterFunction.aesEncrypt( config.aesKey, config.IV, jumin.substring(2) ) );
        dto.setJumin( jumin );
        dto.setCenterCode( sesCenterCode );
        dto.setCreateBy( sesId );
        
        patientService.updatePatientCare( dto );  // 환지 기본정보 insert
        
        //patientDisease Insert
        dto.setEtcCheck( dto.getEtcCheckDisease() );
        dto.setEtcContent( dto.getEtcContentDisease() );
        
        patientService.updatePatientDisease( dto );
        
        
        //patientSymptom Insert
        dto.setEtcCheck( dto.getEtcCheckSymptom() );
        dto.setEtcContent( dto.getEtcContentSymptom() );
        dto.setBloodPressureLevel( dto.getBloodPressureLevelCon() + "|" + dto.getBloodPressureLevelRel() );
        
        patientService.updatePatientSymptom( dto );
        
        return "redirect:/patient/info?patientIdx=" + patientIdx;
    }

    @RequestMapping("/privacy")
    public ModelAndView patientPrivacy() {
        ModelAndView mv = setMV("patient/privacy");

        return mv;
    }
    
    @RequestMapping( value="/nonFaceStart", method = RequestMethod.POST )
    @ResponseBody
    public String nonFaceStart(
            @RequestParam( value="pId", required = true ) String pId,
            @RequestParam( value="roomId", required = true ) String roomId,
            @RequestParam( value="pName", required = true ) String pName,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        String salt = LifeCenterFunction.getSalt();
        String timeStamp = LifeCenterFunction.getTimestamp();
        String signature = LifeCenterFunction.getSignature(config.nonFaceApiSecret, salt, timeStamp);
        
        String userId = LifeCenterSessionController.getSession(request, "sesId");
        String userNm = LifeCenterSessionController.getSession(request, "sesName");
        
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("api_key", config.nonFaceApiKey);
        data.put("salt", salt);
        data.put("timestamp", timeStamp);
        data.put("signature", signature);
        data.put("client_id", config.nonFaceClientId);
        data.put("member_id", userId);
        
        String result = LifeCenterFunction.httpUrlConnection(config.nonFaceApiTokenUrl, data);
        
        JSONObject object = new JSONObject(result);
        String message = "";
        String token = "";
        for(String key : object.keySet()) {
            logger.error("key -- > " + key);
            if (key.equals("errorCode")) {
                message = object.getString("message");
            } else if (key.equals("token")){
                token = object.getString("token");
            }
        }
        
        if (!message.equals("")) {
            //error
        }
        String hashData = LifeCenterFunction.getSignature(config.nonFaceApiSecret, config.nonFaceApiKey, roomId + userId); //"1011503101"
        
        object.put("api_key", config.nonFaceApiKey);
        object.put("member_id", userId);
        object.put("token", token);
        object.put("room_id", roomId);
        object.put("member_name", userNm);
        object.put("classify", "d"); // p이면 환자 d이면 의사
        object.put("hashData", hashData);
        logger.error("pid -- > " + hashData);
        
        return object.toString();
    }
    
    
    private String getDisease(PatientDTO dto) {
        String highBloodPressureCheck = dto.getHighBloodPressureCheck().equals("Y") ? "고혈압" : "";
        String lowBloodPressureCheck = dto.getLowBloodPressureCheck().equals("Y") ? "저혈압" : "";
        String organTransplantCheck = dto.getOrganTransplantCheck().equals("Y") ? "장기이식(신장, 간 등)" : "";
        String diabetesCheck = dto.getDiabetesCheck().equals("Y") ? "당뇨" : "";
        String respiratoryDiseaseCheck = dto.getRespiratoryDiseaseCheck().equals("Y") ? "호흡기질환" : "";
        String immunologicalDiseaseCheck = dto.getImmunologicalDiseaseCheck().equals("Y") ? "면역질환(류마티스 등)" : "";
        String heartDisease = dto.getHeartDisease().equals("Y") ? "심장질환" : "";
        String liverDisease = dto.getLiverDisease().equals("Y") ? "간질환" : "";
        String operation = dto.getOperation().equals("Y") ? "수술(" + dto.getOperationContent() + ")" : "";
        String allergyCheck = dto.getAllergyCheck().equals("Y") ? "알레르기" : "";
        String kidneyDisease = dto.getKidneyDisease().equals("Y") ? "신장질환" : "";
        String cancerName = dto.getCancerName() == null ? "" : dto.getCancerName();
        String cancerCheck = dto.getCancerCheck().equals("Y") ? "암(" + cancerName + ")" : "";
        String etcContent = dto.getEtcContentDisease() == null ? "" : dto.getEtcContentDisease();
        String ectCheckDisease = dto.getEtcCheckDisease().equals("Y") ? "기타(" + etcContent + ")" : "";
        
        ArrayList<String> disease = new ArrayList<String>();
        disease.add(highBloodPressureCheck);
        disease.add(lowBloodPressureCheck);
        disease.add(organTransplantCheck);
        disease.add(diabetesCheck);
        disease.add(respiratoryDiseaseCheck);
        disease.add(immunologicalDiseaseCheck);
        disease.add(heartDisease);
        disease.add(liverDisease);
        disease.add(operation);
        disease.add(allergyCheck);
        disease.add(kidneyDisease);
        disease.add(cancerCheck);
        disease.add(ectCheckDisease);
        
        String strDisease = "";
        for (int i = 0; i < disease.size(); i++) {
            String str = disease.get(i);
            if (!str.equals("")) {
                strDisease += str;
                strDisease += ", ";
            }
        }
        
        strDisease = strDisease.trim();
        strDisease = strDisease.substring(0, strDisease.length()-1);
        return strDisease;
    }
    
    private String getSymptom(PatientDTO dto) {
        String feverCheck = dto.getFeverCheck().equals("Y") ? "열감(열나는 느낌)" : "";
        String coughCheck = dto.getCoughCheck().equals("Y") ? "기침" : "";
        String colic = dto.getColic().equals("Y") ? "복통(배아픔)" : "";
        String coldFitCheck = dto.getColdFitCheck().equals("Y") ? "오한(추운 느낌)" : "";
        String sputumCheck = dto.getSputumCheck().equals("Y") ? "가래" : "";
        String ocinCheck = dto.getOcinCheck().equals("Y") ? "오심(구역질)" : "";
        String chestPain = dto.getChestPain().equals("Y") ? "흉통" : "";
        String noseCheck = dto.getNoseCheck().equals("Y") ? "콧물 또는 코 막힘" : "";
        String vomitingCheck = dto.getVomitingCheck().equals("Y") ? "구토" : "";
        String musclePainCheck = dto.getMusclePainCheck().equals("Y") ? "근육통(몸살)" : "";
        String soreThroatCheck = dto.getSoreThroatCheck().equals("Y") ? "인후통(목 아픔)" : "";
        String diarrheaCheck = dto.getDiarrheaCheck().equals("Y") ? "설사" : "";
        String headacheCheck = dto.getHeadacheCheck().equals("Y") ? "두통(머리아픔)" : "";
        String dyspneaCheck = dto.getDyspneaCheck().equals("Y") ? "호흡곤란(숨가쁨)" : "";
        String fatigueCheck = dto.getFatigueCheck().equals("Y") ? "권태감(피로감)" : "";
        String etcContent = dto.getEtcContentSymptom() == null ? "" : dto.getEtcContentSymptom();
        String ectCheckSymptom = dto.getEtcCheckSymptom().equals("Y") ? "기타(" + etcContent + ")" : "";
        
        String strSymptom = "";
        ArrayList<String> symptom = new ArrayList<String>();
        symptom.add(feverCheck);
        symptom.add(coughCheck);
        symptom.add(colic);
        symptom.add(coldFitCheck);
        symptom.add(sputumCheck);
        symptom.add(ocinCheck);
        symptom.add(chestPain);
        symptom.add(noseCheck);
        symptom.add(vomitingCheck);
        symptom.add(musclePainCheck);
        symptom.add(soreThroatCheck);
        symptom.add(diarrheaCheck);
        symptom.add(headacheCheck);
        symptom.add(dyspneaCheck);
        symptom.add(fatigueCheck);
        symptom.add(ectCheckSymptom);
        
        for (int i = 0; i < symptom.size(); i++) {
            String str = symptom.get(i);
            if (!str.equals("")) {
                strSymptom += str;
                strSymptom += ", ";
            }
        }
        
        strSymptom = strSymptom.trim();
        strSymptom = strSymptom.substring(0, strSymptom.length() - 1);
        
        return strSymptom;
    }
}
