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.getEctCheckDisease() );
        dto.setEtcContent( dto.getEtcContentDisease() );
        
        patientService.insertPatientDisease( dto );
        
        
        //patientSymptom Insert
        dto.setEtcCheck( dto.getEctCheckSymptom() );
        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("[|]");
            logger.error("bloodPress -- > " + bloodPressureLevel[0]);
            logger.error("bloodPress -- > " + bloodPressureLevel[1]);
        }
        
        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("/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();
    }
}
