package com.lemon.lifecenter.controller;

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

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.dto.CenterInfoDTO;
import com.lemon.lifecenter.dto.GroupListDTO;
import com.lemon.lifecenter.dto.LoginDTO;
import com.lemon.lifecenter.dto.StaffDTO;
import com.lemon.lifecenter.service.GroupListService;
import com.lemon.lifecenter.service.LoginService;
import com.lemon.lifecenter.service.StaffService;

// 의료진관리 contorller
@Controller
@RequestMapping("/staff")
public class StaffController extends LifeCenterController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private LifeCenterPaging paging;
    
    @Autowired
    private LoginService loginService;
    
    @Autowired
    private StaffService memberService;
    
    @Autowired
    private LifeCenterConfigVO config;
    
    @Autowired
    private GroupListService groupListService;
    
    @RequestMapping("/new")
    public ModelAndView staffNew() throws Exception {
        List<CenterInfoDTO> centerList = memberService.selectCenterList();
        
        ModelAndView mv = setMV("staff/new");
        
        GroupListDTO dto = new GroupListDTO();
        List<GroupListDTO> groupList = groupListService.selectGroupList(dto);
        
        for( GroupListDTO data : groupList ) {
//            data.setPermissions( LifeCenterFunction.aesEncrypt( config.aesKey, config.IV, data.getPermissions() ) );
            data.setEncryptIdx( LifeCenterFunction.aesEncrypt( config.aesKey, config.IV, String.valueOf( data.getIdx() ) ) );
        }
        
        
        mv.addObject( "centerList", centerList );
        mv.addObject( "groupList", groupList );
        
        return mv;
    }
    
    @RequestMapping("/new/regist")
    public String staffNewRegist(
            @ModelAttribute("dto") final StaffDTO dto,
            @RequestParam(value="encryptIdx", required=true) String encryptIdx,
            @RequestParam(value="passwordConfirm", required=true) String passwordConfirm ) throws Exception {
        
        // 의료진 관리 -> 의료진 신규등록 컨트롤러
        // 의료진 신규등록시 -> 계정 권한은 일반사용자 권한으로 생성? -> 관리자로도 생성?
        // 센터하나당 관리자 권한 계정은 1개임 (시스템관리자가 센터생성할때 관리자 계정 1개 발급)
//        System.out.println( "permissions : " + permissions );
//        System.out.println( "permissions : " + LifeCenterFunction.aesDecrypt( config.aesKey, config.IV, permissions ) );
        System.out.println( "encIdx : " + encryptIdx );
        
        String decryptIdx = LifeCenterFunction.aesDecrypt( config.aesKey, config.IV, encryptIdx );
        
        // password 일치확인
        String password = dto.getPassword();
        
        if( !password.equals( passwordConfirm ) ) {
            // redirect page back
        }
        
        dto.setGroupIdx( Integer.valueOf( decryptIdx ) );
        dto.setPassword( LifeCenterFunction.aesEncrypt( config.aesKey, config.IV, password ) );
        
        memberService.insertStaff( dto );
        
        return "redirect:../info?staffId=" + dto.getId();
    }
    
    @RequestMapping("/info")
    public ModelAndView staffInfo(
            @RequestParam(value="staffId", required=false, defaultValue="") String staffID) {
        
        StaffDTO dto = new StaffDTO();
        dto.setId(staffID);
        
        dto = memberService.selectMemberInfo(dto);
        
        ModelAndView mv = setMV("staff/info");
        mv.addObject("info", dto);

        return mv;
    }

    @RequestMapping("/edit")
    public ModelAndView staffEdit(
            @RequestParam(value="staffId", required=false, defaultValue="") String staffId,
            @RequestParam(value="centerCode", required=false, defaultValue="") String centerCode,
            @RequestParam(value="groupIdx", required=false, defaultValue="") String groupIdx) {
        
        List<CenterInfoDTO> centerList = memberService.selectCenterList();
        StaffDTO dto = new StaffDTO();
        dto.setId(staffId);
        dto = memberService.selectMemberInfo(dto);
        
        ModelAndView mv = setMV("staff/edit");
        mv.addObject("info", dto);
        mv.addObject("centerCode", centerCode);
        mv.addObject("groupIdx", groupIdx);
        mv.addObject("centerList", centerList);

        return mv;
    }
    
    @RequestMapping("/myinfo")
    public ModelAndView staffMyinfo() {
        ModelAndView mv = setMV("staff/myinfo");

        return mv;
    }

    @RequestMapping("/list")
    public ModelAndView staffList(
            @ModelAttribute("dto") final StaffDTO dto,
            @RequestParam(value="selectState", required=false, defaultValue="") String selectState,
            @RequestParam(value="sData", required=false, defaultValue="") String sData,
            @RequestParam(value="useYn", required=false, defaultValue="") String useYn,
            @RequestParam(value="page", required=false, defaultValue="1") int page) {
        
        logger.error("selectState -- > " + selectState);
        logger.error("sData -- > " + sData);
        logger.error("useYn -- > " + useYn);
        
        if (selectState.equals("sId")) {
            dto.setId(sData);
        } else if (selectState.equals("sName")) {
            dto.setName(sData);
        } else {
            dto.setCenterName(sData);
        }
        
        dto.setLimit( ( Integer.valueOf( page ) - 1 ) * config.pageDataSize );
        dto.setLimitMax( config.pageDataSize );
        
        int total = memberService.selectMemeberListCount(dto);
        List<StaffDTO> list = new ArrayList<StaffDTO>();
        if (total > 0) {
            list = memberService.selectMemberList(dto);
        }
        String param = "";
        paging = LifeCenterPaging.getInstance();
        paging.paging(config, total, page, param);
        
        ModelAndView mv = setMV("staff/list");
        mv.addObject("total", total);
        mv.addObject("selectState", selectState);
        mv.addObject("sData", sData);
        mv.addObject("useYn", useYn);
        mv.addObject("item", list);
        mv.addObject("paging", paging);
        
        return mv;
    }
    
    
    @RequestMapping( value="/duplicateIdCheck", method = RequestMethod.POST )
    @ResponseBody
    public boolean duplicateIdCheck( @RequestParam( value="staffId", required = false, defaultValue = "" ) String id ) {
        boolean result = false; // false : 중복 , true : 중복아님
        JSONObject obj = new JSONObject();
        LoginDTO dto   = new LoginDTO();
        
        if( id.trim().equals( "" ) ) {
            result = false;
        } else {
            dto.setId( id.trim() );
            int count = loginService.selectMemberIdCount( dto );
            
            if( count == 0 ) {
                result = true;
            }
        }
        
//        obj.put( "result" , result );
        
        return result;
    }
}