package com.dgtis.dorm.manager.wx.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.dgtis.dorm.manager.db.domain.AlumniUser;
import com.dgtis.dorm.manager.db.domain.QuestionsAnswers;
import com.dgtis.dorm.manager.db.service.QuestionsAnswersService;
import com.dgtis.dorm.manager.db.service.UserService;
import com.dgtis.dorm.manager.db.util.JacksonUtil;
import com.dgtis.dorm.manager.db.util.PYIndexStrUtil;
import com.dgtis.dorm.manager.db.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

@RestController
@RequestMapping("/wx/user")
public class WxUserController {

    private final Log logger = LogFactory.getLog(WxAuthController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private QuestionsAnswersService questionsAnswersService;

    /**
     * 提交待审核认证
     *
     * @return
     */
    @RequestMapping(value = "submitAudit")
    public Object submitAudit(Integer userId, String formId) {
        if (userId == null || formId == null) {
            return ResponseUtil.fail402();
        }
        Map<String, Object> result = userService.submitAudit(userId, formId);
        return ResponseUtil.ok(result);
    }


    /**
     * 查询是否关注
     *
     * @param userId
     * @param friUserId
     * @return
     */
    @RequestMapping("checkFollowed")
    public Object checkFollowed(Integer userId, Integer friUserId) {
        if (userId == null || friUserId == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = userService.checkFollowed(userId, friUserId);
        return ResponseUtil.ok(result);
    }

    /**
     * 点击关注用户
     *
     * @param userId
     * @param friUserId
     * @return
     */
    @RequestMapping("alreadyFollowed")
    public Object alreadyFollowed(Integer userId, Integer friUserId) {
        if (userId == null || friUserId == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = userService.alreadyFollowed(userId, friUserId);
        return ResponseUtil.ok(result);
    }

    /**
     * 取消关注
     *
     * @param userId
     * @param friUserId
     * @return
     */
    @RequestMapping("cancelAlreadyFollowed")
    public Object cancelAlreadyFollowed(Integer userId, Integer friUserId) {
        if (userId == null || friUserId == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = userService.cancelAlreadyFollowed(userId, friUserId);
        return ResponseUtil.ok(result);
    }

    /**
     * 查询我关注的用户列表
     *
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("getUserConcernedList")
    public Object getUserConcernedList(Integer userId,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (userId == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = userService.findUserConcernedByUserId(userId, page, size);
        return ResponseUtil.ok(result);
    }

    /**
     * 搜索查询关注的用户
     *
     * @param userId
     * @param userId
     * @param valString
     * @return
     */
    @RequestMapping("searchUserConcerned")
    public Object searchUserConcerned(Integer userId, String valString) {
        if (userId == null || valString == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = userService.findUserConcerned(userId, valString);
        return ResponseUtil.ok(result);
    }

    /**
     * 查询校友录列表
     *
     * @param userId
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("getAlumniRecordList")
    public Object getAlumniRecordList(Integer userId,
                                      @RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (userId == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = new HashMap<String, Object>();
        AlumniUser user = userService.findById(userId);
        if (user.getRoleType() != null && !"游客".equals(user.getRoleType()) && !"非清华公管人".equals(user.getRoleType())) {
            result = userService.findAlumniRecordById(userId, page, size);
            result.put("state", "success");
            result.put("massege", "查询成功");
        } else {
            result.put("state", "failuren");
            result.put("massege", "您目前的角色没有权限查看校友录");
        }
        return ResponseUtil.ok(result);
    }

    /**
     * 搜索查询校友
     *
     * @param userId
     * @param valString
     * @return
     */
    @RequestMapping("searchAlumniRecord")
    public Object searchAlumniRecord(Integer userId, String valString) {
        if (userId == null || valString == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = new HashMap<String, Object>();
        AlumniUser user = userService.findById(userId);
        if (user.getRoleType() != null && !"游客".equals(user.getRoleType()) && !"非清华公管人".equals(user.getRoleType())) {
            boolean flag = PYIndexStrUtil.isNumeric(valString);
            if (flag)
                result = userService.findAlumniRecord(userId, valString, Integer.valueOf(valString));
            else
                result = userService.findAlumniRecord(userId, valString, null);
            result.put("state", "success");
            result.put("massege", "查询成功");
        } else {
            result.put("state", "failuren");
            result.put("massege", "您目前的角色没有权限查看校友录");
        }
        return ResponseUtil.ok(result);
    }

    /**
     * 更新用户信息
     *
     * @param body
     * @return
     */
    @RequestMapping("updateUserInfo")
    public Object updateUserInfo(@RequestBody String body) {
        AlumniUser userInfo = JacksonUtil.parseObject(body, "userInfo", AlumniUser.class);
        if (userInfo.getId() == null)
            return ResponseUtil.fail402();
        //不允许直接改角色，需要经过审核验证
        userInfo.setRoleType(null);
        userInfo.setAuditStatus(null);
        userInfo.setIsRealname("1");
        String userName = userInfo.getUserName();
        if (StringUtils.isNoneBlank(userName)) {
            String strFirst = userName.substring(0, 1).toUpperCase();
            String pinyin = "";
            if (PYIndexStrUtil.isChinese(strFirst)) {
                pinyin = PYIndexStrUtil.getPYIndexStr(strFirst, true);
            } else if (strFirst.matches("[a-zA-Z]+")) {
                pinyin = strFirst.toUpperCase();
            } else {
                pinyin = strFirst;
            }
            userInfo.setEnUserName(pinyin);
        }
        userService.updateUser(userInfo);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("state", "success");
        result.put("massege", "更新成功");
        return ResponseUtil.ok(result);
    }

    /**
     * 根据id查询个人基本信息
     */
    @RequestMapping(value = "getUserInfo")
    public Object getUserInfo(Integer userId) {
        if (userId == null)
            return ResponseUtil.fail402();
        Map<String, Object> result = new HashMap<String, Object>();
        AlumniUser user = userService.findById(userId);
        if (user.getIdentity().equals("0") && user.getpDocumentNum() == null) {
            user.setIsRealname("2");
        }
        if (user.getIdentity().equals("1") && user.getlInstitutionNum() == null) {
            user.setIsRealname("2");
        }
        result.put("user", user);
        return ResponseUtil.ok(result);
    }

    /**
     * 查询“我”提出的问题
     *
     * @return
     */
    @RequestMapping(value = "getMyQuestion")
    public Object getMyQuestion(Integer userId,
                                @RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "size", defaultValue = "10") Integer size) {
        QuestionsAnswers questionsAnswers = new QuestionsAnswers();
        if (userId != null) {
            questionsAnswers.setCreatorId(userId);
        }
        questionsAnswers.setIsAnswer(true);
        Map<String, Object> result = questionsAnswersService.findByCreateBy(questionsAnswers, page, size);
        return ResponseUtil.ok(result);
    }

    /**
     * 用户提出问题，保存到数据库
     *
     * @param questions
     * @param userId
     * @return
     */
    @RequestMapping(value = "submitQuestion")
    public Object submitQuestion(String questions, Integer userId) {
        if (userId == null || questions == null)
            return ResponseUtil.fail402();
        QuestionsAnswers question = new QuestionsAnswers();
        question.setCreatorId(userId);
        question.setQuestions(questions);
        question.setCreateDate(new Date());
        question.setIsAnswer(false);
        Map<String, Object> result = questionsAnswersService.submitQuestion(question);
        return ResponseUtil.ok(result);

    }


    /**
     * 更新用户邮编和邮寄地址
     *
     * @param userId
     * @param address
     * @param postcode
     * @return
     */
    @RequestMapping(value = "saveUserAddressPostcode")
    public Object saveUserAddressPostcode(Integer userId, String address, String postcode, String annotation) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (userId != null && StringUtils.isNotBlank(address) && StringUtils.isNotBlank(postcode)) {
            result.put("state", "success");
            AlumniUser user = userService.findById(userId);
            if (user != null) {
                user.setAddress(address);
                user.setPostcode(postcode);
                user.setAnnotation(annotation);
                userService.updateUser(user);
                result.put("massege", "更新成功");
            } else {
                result.put("state", "failuren");
                result.put("massege", "用户不存在");
            }
        } else {
            result.put("state", "failuren");
            result.put("massege", "参数缺失");
        }

        return ResponseUtil.ok(result);
    }

}
