package kr.co.jinwoosi.clfd.clfd.user.web;

import kr.co.jinwoosi.clfd.clfd.site.service.ClfdSiteService;
import kr.co.jinwoosi.clfd.clfd.user.service.ClfdUserService;
import kr.co.jinwoosi.clfd.conts.company.model.Company;
import kr.co.jinwoosi.clfd.conts.company.service.CompanyService;
import kr.co.jinwoosi.clfd.framework.cd.model.CdDtl;
import kr.co.jinwoosi.clfd.framework.cd.service.CdDtlService;
import kr.co.jinwoosi.clfd.framework.security.model.User;
import kr.co.jinwoosi.clfd.framework.security.model.UserSearch;
import kr.co.jinwoosi.clfd.framework.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ClfdUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ClfdUserService clfdUserService;

    @Autowired
    private ClfdSiteService clfdSiteService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CdDtlService cdDtlService;

    @RequestMapping("/clfd/user/join.do")
    public String joinPage(HttpServletRequest request, HttpServletResponse response, Model model) {
        if (clfdUserService.getUserId() != null) {
            return "redirect:/";
        }

        if (clfdSiteService.visitClfdSite(request, response, model) == null) {
            return "";
        }
        return "clfd/user/join";
    }

    @RequestMapping("/clfd/user/joinCorp.do")
    public String joinCorpPage(HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("companyGbnList", cdDtlService.selectList(new CdDtl("companyGbn")));
        if (clfdUserService.getUserId() != null) {
            return "redirect:/";
        }

        if (clfdSiteService.visitClfdSite(request, response, model) == null) {
            return "";
        }
        return "clfd/user/joinCorp";
    }

    @RequestMapping("/clfd/pr/myPage.do")
    public String myPage(HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = (User) request.getSession().getAttribute("user");
        if (clfdSiteService.visitClfdSite(request, response, model) == null) {
            return "";
        }
        model.addAttribute("user", user);
        return "clfd/pr/myPage";
    }

    @RequestMapping(value = "/clfd/pr/pwd/update.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> pwdUpdate(HttpServletRequest request, @RequestBody HashMap<String, Object> requestParam) throws Exception {
        Map<String, String> result = new HashMap<String, String>();

        User sessionUser = (User) request.getSession().getAttribute("user");
        if (sessionUser == null) {
            result.put("result", "fail");
            result.put("message", "사용자를 찾을 수 없습니다.");
            return result;
        }

        Long userId = sessionUser.getUserId();
        String userLoginId = sessionUser.getUserLoginId();
        String password = (String) requestParam.get("password");
        String newPassword = (String) requestParam.get("newPassword");

        return clfdUserService.updatePwd(userId, userLoginId, password, newPassword);
    }

    @RequestMapping("/clfd/pr/myPage.json")
    @ResponseBody
    public Map<String, Object> myPageApi(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();

        User sessionUser = (User) request.getSession().getAttribute("user");
        if (sessionUser == null) {
            result.put("result", "fail");
            result.put("message", "사용자를 찾을 수 없습니다.");
            return result;
        }

        return clfdUserService.selectUser(new UserSearch(sessionUser.getUserId()));
    }

    @RequestMapping("/clfd/pr/myPage/update.json")
    @ResponseBody
    public Map<String, String> myPageUpdateApi(HttpServletRequest request, User user) {
        Map<String, String> result = new HashMap<String, String>();
        User sessionUser = (User) request.getSession().getAttribute("user");
        if (sessionUser == null) {
            result.put("result", "fail");
            result.put("message", "사용자를 찾을 수 없습니다.");
            return result;
        }

        user.setUpdId(sessionUser.getUserId());
        user.setUserId(sessionUser.getUserId());
        clfdUserService.updateUser(user);

        result.put("result", "success");
        result.put("message", "정보가 수정되었습니다.");
        return result;
    }

    @RequestMapping(value = "/clfd/user/join/duplicate.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> checkIdDuplicate(UserSearch userSearch) {
        Map<String, String> result = new HashMap<String, String>();
        if (userService.checkIdDuplicate(userSearch) > 0) {
            result.put("result", "exist");
            result.put("message", "사용 중인 아이디입니다. 다른 아이디를 입력해주세요.");
        } else {
            result.put("result", "nonExist");
            result.put("message", "사용 가능합니다.");
        }
        return result;

    }

    @RequestMapping(value = "/clfd/user/join/join.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> join(HttpServletRequest request, User user) {
        Map<String, Object> result = new HashMap<String, Object>();

        /*
         * SMS 인증 시 적용
         */
        HttpSession session = request.getSession();
        String sessionSmsAuthKey = (String) session.getAttribute("smsAuthKey");
        if (sessionSmsAuthKey == null && !sessionSmsAuthKey.equals(user.getSmsAuthKey())) {
            result.put("result", "fail");
            result.put("message", "인증 번호가 다릅니다.");
            return result;
        }

        try {
            user.setUserTyCd("U");
            clfdUserService.join(user);
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/clfd/user/join/joinCorp.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> joinCorp(HttpServletRequest request, User user, Company company) {
        Map<String, Object> result = new HashMap<String, Object>();

        /*
         * SMS 인증 시 적용
         */
        HttpSession session = request.getSession();
        String sessionSmsAuthKey = (String) session.getAttribute("smsAuthKey");
        if (sessionSmsAuthKey == null && !sessionSmsAuthKey.equals(user.getSmsAuthKey())) {
            result.put("result", "fail");
            result.put("message", "인증 번호가 다릅니다.");
            return result;
        }

        try {
            user.setUserTyCd("M");
            companyService.insert(company);
            clfdUserService.join(user);
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping("/clfd/user/findId.do")
    public String findId(HttpServletRequest request, HttpServletResponse response, Model model) {
        if (clfdUserService.getUserId() != null) {
            return "redirect:/";
        }

        if (clfdSiteService.visitClfdSite(request, response, model) == null) {
            return "";
        }
        return "clfd/user/findId";
    }

    @RequestMapping("/clfd/user/findPassword.do")
    public String findPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
        if (clfdUserService.getUserId() != null) {
            return "redirect:/";
        }

        if (clfdSiteService.visitClfdSite(request, response, model) == null) {
            return "";
        }
        return "clfd/user/findPassword";
    }

    @RequestMapping(value = "/clfd/company/list.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> list(Company company) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("data", companyService.select(company));
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("message", e.getMessage());
        }
        return result;
    }

}
