package com.style24.admin.biz.web;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.biz.service.TsaSystemService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Alarm;
import com.style24.persistence.domain.AlarmReceiver;
import com.style24.persistence.domain.Batch;
import com.style24.persistence.domain.BatchLog;
import com.style24.persistence.domain.CommonCode;
import com.style24.persistence.domain.Menu;
import com.style24.persistence.domain.SampleFile;
import com.style24.persistence.domain.User;
import com.style24.persistence.domain.UserMenu;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.rest.server.GagaResponse;
import com.gagaframework.web.security.GagaPasswordEncoder;

/**
 * 운영관리 Controller
 *
 * @author gagamel
 * @since 2020. 10. 7
 */
@Controller
@RequestMapping("/system")
@Slf4j
public class TsaSystemController extends TsaBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TsaSystemService systemService;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private GagaPasswordEncoder passwordEncoder;

	@Value("${upload.default.target.path}")
	private String uploadTargetPath;

	/**
	 * 사용자관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/user/form")
	public ModelAndView userForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체 콤보박스 목록
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));

		// 권한 콤보박스 목록
		mav.addObject("roleList", rendererService.getCommonCodeList("G001"));

		mav.setViewName("system/UserForm");

		return mav;
	}

	/**
	 * 사용자 목록
	 * @param user - 사용자 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/user/list")
	@ResponseBody
	public Collection<User> getUserList(@RequestBody User user) {
		return systemService.getUserList(user);
	}

	/**
	 * 사용자 목록 삭제 처리
	 * @param userList - 사용자 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/user/list/delete")
	@ResponseBody
	public GagaResponse deleteUserList(@RequestBody Collection<User> userList) {
		if (userList == null || userList.isEmpty())
			throw new IllegalStateException(message.getMessage("FAIL_1001"));

		systemService.deleteUserList(userList);

		return super.ok(message.getMessage("SUCC_0003"));
	}

	/**
	 * 사용자 정보 조회
	 * @param mode   - 모드(N:신규, U:상세/수정, C:복사)
	 * @param userNo - 사용자번호
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/user/info/form")
	public ModelAndView getUser(@RequestParam(value = "mode") String mode,
		@RequestParam(value = "userNo", required = false) Integer userNo) {
		ModelAndView mav = new ModelAndView();

		// 권한 콤보박스 목록
		if (!TsaSession.getInfo().getRoleCd().equals("0000")) {
			mav.addObject("roleList", rendererService.getCommonCodeList("G001", "Y", new String[] {"0000"}));
		} else {
			mav.addObject("roleList", rendererService.getAvailCommonCodeList("G001"));
		}

		// 공급업체 콤보박스 목록
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd()));

		// 외부몰벤더 콤보박스 목록
		mav.addObject("vendorList", rendererService.getCommonCodeList("G003", "Y", TsaSession.getInfo().getSupplyCompCd()));

		if (mode.equals("U")) {
			// 어드민사용자정보
			mav.addObject("userInfo", systemService.getUser(userNo));
		} else {
			mav.addObject("userInfo", new User());
		}

		mav.addObject("mode", mode);

		mav.setViewName("system/UserDetailForm");

		return mav;
	}

	/**
	 * 사용자ID 조회
	 * @param userId - 사용자ID
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/user/id/{userId}")
	@ResponseBody
	public int getUserIdCount(@PathVariable("userId") String userId) {
		return systemService.getUserIdCount(userId);
	}

	/**
	 * 사용자 저장 처리
	 * @param user - 사용자 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/user/save")
	@ResponseBody
	public GagaResponse saveUser(@RequestBody User user) {
		if (user.getMode().equals("N")) { // 신규등록
			user.setPasswd(passwordEncoder.encode(user.getPasswd()));
		}

		systemService.saveUser(user);

		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 사용자 비밀번호 변경
	 * @param user - 사용자 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/user/password/change")
	@ResponseBody
	public GagaResponse changePassword(@RequestBody User user) {
		user.setPasswd(passwordEncoder.encode(user.getPasswd()));
		user.setUpdNo(TsaSession.getInfo().getUserNo());
		log.info("user: {}", user);

		// 어드민사용자 비밀번호 수정
		systemService.updateUserPassword(user);

		return super.ok(message.getMessage("SUCC_0009"));
	}

	/**
	 * 사용자 메뉴 관리 화면
	 * @param userNo - 사용자번호
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/user/menu/{userNo}")
	public ModelAndView getAdminUserMenu(@PathVariable("userNo") Integer userNo) {
		ModelAndView mav = new ModelAndView();

		// 사용자 메뉴 목록
		mav.addObject("userMenuList", systemService.getUserMenuList(userNo));

		mav.setViewName("system/UserMenuForm");

		return mav;
	}

	/**
	 * 사용자 메뉴 목록 저장 처리
	 * @param menuList - 사용자 메뉴 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/user/menu/list/save")
	@ResponseBody
	public GagaResponse saveUserMenuList(@RequestBody Collection<UserMenu> menuList) {
		systemService.saveUserMenuList(menuList);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 비밀번호 변경 팝업
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 30
	 */
	@GetMapping("/password/change/form")
	public ModelAndView passwordChangeForm() {
		ModelAndView mav = new ModelAndView();

		mav.setViewName("system/PasswordChangeForm");

		return mav;
	}

	/**
	 * 메뉴관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/menu/form")
	public ModelAndView menuListForm() {
		ModelAndView mav = new ModelAndView();

		// 최상위메뉴 콤보박스 목록
		mav.addObject("topMenuList", rendererService.getTopMenuList(""));

		// 전체메뉴 콤보박스 목록
		mav.addObject("allMenuList", rendererService.getAllMenuList());

		// 권한 콤보박스 목록
		mav.addObject("roleList", rendererService.getCommonCodeList("G001"));

		mav.setViewName("system/MenuForm");

		return mav;
	}

	/**
	 * 메뉴 목록
	 * @param pmenuId - 상위메뉴ID
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/menu/list")
	@ResponseBody
	public Collection<Menu> getMenuList(@RequestParam(value = "pmenuId", required = false) String pmenuId) {
		return systemService.getMenuList(pmenuId);
	}

	/**
	 * 메뉴 사용안함 처리
	 * @param menuList - 메뉴 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/menu/list/save")
	@ResponseBody
	public GagaResponse saveMenuList(@RequestBody Collection<Menu> menuList) {
		systemService.saveMenuList(menuList);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 메뉴 등록/수정 처리
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/menu/save")
	@ResponseBody
	public GagaResponse saveMenu(@RequestBody Menu menu) {
		systemService.saveMenu(menu);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 공통코드관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/commoncode/form")
	public ModelAndView commoncodeListForm() {
		ModelAndView mav = new ModelAndView();

//		// 코드구분 콤보박스 목록
//		mav.addObject("cdGbList", rendererService.getCommonCodeList("ROOT"));

		mav.setViewName("system/CommoncodeForm");

		return mav;
	}

	/**
	 * 공통코드 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/commoncode/list")
	@ResponseBody
	public Collection<CommonCode> getCommonCodeList(@RequestParam(value = "cdGb", required = false) String cdGb) {
		CommonCode commoncode = new CommonCode();
		commoncode.setCdGb(cdGb);
		return systemService.getCommonCodeList(commoncode);
	}

	/**
	 * 공통코드 목록 저장 처리
	 * @param commonCodeList - 공통코드 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/commoncode/list/save")
	@ResponseBody
	public GagaResponse saveCommonCodeList(@RequestBody Collection<CommonCode> commonCodeList) {
		systemService.saveCommonCodeList(commonCodeList);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 공통코드 저장 처리
	 * @param commonCode - 공통코드 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/commoncode/save")
	@ResponseBody
	public GagaResponse saveCommonCode(@RequestBody CommonCode commonCode) {
		systemService.saveCommonCode(commonCode);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 샘플양식관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 3
	 */
	@GetMapping("/sample/file/form")
	public ModelAndView sampleFileForm() {
		ModelAndView mav = new ModelAndView();

		mav.setViewName("system/SampleFileForm");

		return mav;
	}

	/**
	 * 샘플파일 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 3
	 */
	@GetMapping("/sample/file/list")
	@ResponseBody
	public Collection<SampleFile> getSampleFileList() {
		return systemService.getSampleFileList();
	}

	/**
	 * 샘플파일 등록/수정 처리
	 * @param sampleFile - 샘플파일 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 3
	 */
	@PostMapping("/sample/file/save")
	@ResponseBody
	public GagaResponse saveSampleFile(@RequestBody SampleFile sampleFile) {
		sampleFile.setRegNo(TsaSession.getInfo().getUserNo());
		sampleFile.setUpdNo(TsaSession.getInfo().getUserNo());
		systemService.saveSampleFile(sampleFile);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 시스템알람관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@GetMapping("/alarm/form")
	public ModelAndView systemAlarmForm() {
		ModelAndView mav = new ModelAndView();

		mav.setViewName("system/SystemAlarmForm");

		return mav;
	}

	/**
	 * 시스템알람 목록
	 * @param alarm - 알람 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@PostMapping("/alarm/list")
	@ResponseBody
	public Collection<Alarm> getAlarmList(@RequestBody Alarm alarm) {
		return systemService.getAlarmList(alarm);
	}

	/**
	 * 알람 저장
	 * @param alarm - 시스템알람 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@PostMapping("/alarm/save")
	@ResponseBody
	public GagaResponse saveAlarm(@RequestBody Alarm alarm) {
		alarm.setRegNo(TsaSession.getInfo().getUserNo());
		alarm.setUpdNo(TsaSession.getInfo().getUserNo());
		systemService.saveAlarm(alarm);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 알람 삭제
	 * @param alarm - 알람 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@PostMapping("/alarm/delete")
	@ResponseBody
	public GagaResponse deleteAlarm(@RequestBody Alarm alarm) {
		alarm.setUpdNo(TsaSession.getInfo().getUserNo());
		systemService.deleteAlarm(alarm);
		return super.ok(message.getMessage("SUCC_0003"));
	}

	/**
	 * 알람수신자 목록
	 * @param alarmId - 알람ID
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@GetMapping("/alarm/receiver/list/{alarmId}")
	@ResponseBody
	public Collection<AlarmReceiver> getAlarmReceiverList(@PathVariable String alarmId) {
		return systemService.getAlarmReceiverList(alarmId);
	}

	/**
	 * 알람수신자 목록 저장
	 * @param alarmReceiverList - 알람수신자 목록
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@PostMapping("/alarm/receiver/list/save")
	@ResponseBody
	public GagaResponse saveAlarmReceiverList(@RequestBody Collection<AlarmReceiver> alarmReceiverList) {
		systemService.saveAlarmReceiverList(alarmReceiverList);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 알람수신자 삭제
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 13
	 */
	@PostMapping("/alarm/receiver/delete")
	@ResponseBody
	public GagaResponse deleteAlarmReceiverList(@RequestBody Collection<AlarmReceiver> alarmReceiverList) {
		systemService.deleteAlarmReceiverList(alarmReceiverList);
		return super.ok(message.getMessage("SUCC_0003"));
	}

	/**
	 * 배치관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 2
	 */
	@GetMapping("/batch/form")
	public ModelAndView batchForm() {
		ModelAndView mav = new ModelAndView();

		// 업무구분
		mav.addObject("bizGbList", rendererService.getTopMenuList(""));

		mav.setViewName("system/BatchForm");

		return mav;
	}

	/**
	 * 배치 목록
	 * @param batch - 배치 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 2
	 */
	@PostMapping("/batch/list")
	@ResponseBody
	public Collection<Batch> getBatchList(@RequestBody Batch batch) {
		return systemService.getBatchList(batch);
	}

	/**
	 * 배치 저장
	 * @param batch - 배치 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 2
	 */
	@PostMapping("/batch/save")
	@ResponseBody
	public GagaResponse saveBatch(@RequestBody Batch batch) {
		batch.setRegNo(TsaSession.getInfo().getUserNo());
		batch.setUpdNo(TsaSession.getInfo().getUserNo());
		systemService.saveBatch(batch);

		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 배치 로그 목록
	 * @param batch - 배치 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 3
	 */
	@PostMapping("/batch/log/list")
	@ResponseBody
	public Collection<BatchLog> getBatchLogList(@RequestBody Batch batch) {
		return systemService.getBatchLogList(batch);
	}

}
