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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
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.LocationDTO;
import com.lemon.lifecenter.dto.StaffDTO;
import com.lemon.lifecenter.service.CenterService;
import com.lemon.lifecenter.service.StaffService;

// 생활치료센터관리 contorller
@Controller
@RequestMapping("/center")
public class CenterController extends LifeCenterController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private CenterService centerService;
    @Autowired
    private StaffService memberService;
    @Autowired
    private LifeCenterConfigVO config;
    private LifeCenterPaging paging;
    
    @RequestMapping("/new")
    public ModelAndView centerNew() {
        List<LocationDTO> list = centerService.selectLocation();
        
        ModelAndView mv = setMV("center/new");
        mv.addObject("locationList", list);
        return mv;
    }
    
    @RequestMapping("/new/regist")
    @Transactional(propagation=Propagation.REQUIRED)
    public String centerNewRegist(
            @ModelAttribute("dto") final CenterInfoDTO dto,
            @RequestParam(value="detailAddr", required=true) String detailAddr,
            @RequestParam(value="staffId", required=true) String staffId,
            @RequestParam(value="staffPw", required=true) String staffPw,
            @RequestParam(value="staffName", required=true) String staffName,
            @RequestParam(value="staffPhoneNumber", required=true) String staffPhoneNumber) throws Exception {

        String centerAddress = dto.getCenterAddress() + "|" + detailAddr;
        dto.setCenterAddress(centerAddress);
        StaffDTO mDto = new StaffDTO();
        
        centerService.insertCenter(dto);
        
        mDto.setCenterCode(dto.getCenterCode());
        mDto.setId(staffId);
        mDto.setPassword(LifeCenterFunction.aesEncrypt(config.aesKey, config.IV, staffPw));
        mDto.setName(staffName);
        mDto.setPhoneNumber(staffPhoneNumber);
        mDto.setGroupIdx( 2 ); // 1: 시스템관리자 2:관리자 3:일반사용자, 센터신규등록시 아이디생성은 관리자 권한으로 생성, 센터하나에 관리자 1명으로 개발진행
        
        memberService.inserMember(mDto);
        
        return "redirect:/center/info?centerCode=" + dto.getCenterCode();
    }
    
    @RequestMapping("/info")
    public ModelAndView centerInfo(
            @RequestParam(value="centerCode", required=true) int centerCode) {
        CenterInfoDTO dto = new CenterInfoDTO();
        dto.setCenterCode(centerCode);
        dto = centerService.selectCenterInfo(dto);
        ModelAndView mv = setMV("center/info");
        mv.addObject("centerInfo", dto);
        mv.addObject("centerCode", centerCode);
        return mv;
    }

    @RequestMapping("/edit/update")
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor = { RuntimeException.class, Error.class })
    public String centerEditUpdate(
            @ModelAttribute("dto") final CenterInfoDTO dto,
            @RequestParam(value="detailAddr", required=true) String detailAddr,
            @RequestParam(value="staffId", required=true) String staffId,
            @RequestParam(value="staffPw", required=true) String staffPw,
            @RequestParam(value="staffNewPw", required=false, defaultValue="") String staffNewPw,
            @RequestParam(value="staffNewPwConfirm", required=false, defaultValue="") String staffNewPwConfirm,
            @RequestParam(value="staffName", required=true) String staffName,
            @RequestParam(value="staffPhoneNumber", required=true) String staffPhoneNumber,
            HttpServletRequest request, HttpServletResponse response ) throws Exception {
        
        System.out.println( "staff Id : " + staffId );
        
        StaffDTO mDto = new StaffDTO();
        
        mDto.setId(staffId);
        mDto.setPassword(LifeCenterFunction.aesEncrypt(config.aesKey, config.IV, staffPw));
        int mCnt = memberService.selectMemberCount(mDto);
        
        if( mCnt == 1 ) {
            String address = dto.getCenterAddress() + "|" + detailAddr;
            dto.setCenterAddress(address);
            int result = centerService.updateCenterInfo(dto);
            
            System.out.println( "result cnt : " + result  );
            
            if (result > 0) {
                mDto.setName(staffName);
                mDto.setPhoneNumber(staffPhoneNumber);
                mDto.setPassword("");
                
                try {
                    if (!staffNewPw.equals("")) {
                        if( staffNewPw.equals( staffNewPwConfirm ) ) {
                            mDto.setPassword(LifeCenterFunction.aesEncrypt(config.aesKey, config.IV, staffNewPw));
                        } else {
                            // not match password.
                            throw new Exception();
                        }
                    }
                } catch( Exception e ) {
                    throw new RuntimeException(e);
                }
                
                memberService.updateMember(mDto);
            }
        } else {
            LifeCenterFunction.scriptMessage( response, "alert( '비밀번호가 일치하지않습니다.' );location.href='../edit?centerCode="+dto.getCenterCode()+"';" );
            return "/common/blank";
        }
        
        return "redirect:/center/info?centerCode=" + dto.getCenterCode();
    }
    
    @RequestMapping("/edit")
    public ModelAndView centerEdit(
            @RequestParam(value="centerCode", required=true) int centerCode) {
        
        List<LocationDTO> list = centerService.selectLocation();
        
        CenterInfoDTO dto = new CenterInfoDTO();
        dto.setCenterCode(centerCode);
        dto = centerService.selectCenterInfo(dto);
        
        String address = dto.getCenterAddress();
        String mainAddr = "";
        String detailAddr = "";
        if (address.contains("|") == true) {
            String[] strAr = dto.getCenterAddress().split("[|]");
            mainAddr = strAr[0];
            detailAddr = strAr[1];
        } else {
            mainAddr = address;
        }
        
        ModelAndView mv = setMV("center/edit");
        mv.addObject("locationList", list);
        mv.addObject("centerInfo", dto);
        mv.addObject("mainAddr", mainAddr);
        mv.addObject("detailAddr", detailAddr);
        
        return mv;
    }

    @RequestMapping("/list")
    public ModelAndView centerList(
            @ModelAttribute("dto") final CenterInfoDTO dto,
            @RequestParam(value="page", required=false, defaultValue="1") int page,
            @RequestParam(value="centerName", required=false, defaultValue="") String centerName,
            @RequestParam(value="locationCode", required=false, defaultValue="") String locationCode,
            @RequestParam(value="startDate", required=false, defaultValue="") String startDate,
            @RequestParam(value="endDate", required=false, defaultValue="") String endDate) {
        
        dto.setLimit( ( Integer.valueOf( page ) - 1 ) * config.pageDataSize );
        dto.setLimitMax( config.pageDataSize );
        
        List<LocationDTO> list = centerService.selectLocation();
        
        int total = centerService.selectCenterCount(dto);
        List<CenterInfoDTO> result = new ArrayList<CenterInfoDTO>();
        if (total > 0) {
            result = centerService.selectCenterList(dto);
        }
        
        String param = "centerName=" + dto.getCenterName() + "&locationCode=" + dto.getLocationCode() + "&startDate=" + dto.getStartDate() + "&endDate=" + dto.getEndDate();
        paging = LifeCenterPaging.getInstance();
        paging.paging(config, total, page, param);
        
        ModelAndView mv = setMV("center/list");
        
        startDate = startDate.equals( "" ) ? LifeCenterFunction.getNow( "yyyy-MM-dd" ) : startDate;
        endDate   = endDate.equals( "" )   ? LifeCenterFunction.getNow( "yyyy-MM-dd" ) : endDate;
        
        mv.addObject("locationList", list);
        mv.addObject("locationCode", locationCode);
        mv.addObject("startDate", startDate);
        mv.addObject("endDate", endDate);
        mv.addObject("centerName", centerName);
        mv.addObject("total", total);
        mv.addObject("item", result);
        mv.addObject("paging", paging);
        mv.addObject("page", page);
        mv.addObject("pageSize", dto.getLimitMax());
        
        return mv;
    }
}
