package cn.quantgroup.customer.rest;

import cn.quantgroup.customer.entity.User;
import cn.quantgroup.customer.enums.ErrorCodeEnum;
import cn.quantgroup.customer.model.pay.UserCardInfo;
import cn.quantgroup.customer.model.user.AuthBean;
import cn.quantgroup.customer.model.xyqbuser.UserBasicInfo;
import cn.quantgroup.customer.rest.enums.phone.ModifyPhoneApplyStatus;
import cn.quantgroup.customer.rest.enums.phone.ModifyPhoneAuditStatus;
import cn.quantgroup.customer.rest.enums.phone.ModifyPhoneProcessingStatus;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneAudit;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneFeedback;
import cn.quantgroup.customer.rest.param.phone.ModifyPhoneQuery;
import cn.quantgroup.customer.rest.param.user.UserCombinationParam;
import cn.quantgroup.customer.rest.param.user.UserQueryParam;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.MoResult;
import cn.quantgroup.customer.service.IUserService;
import cn.quantgroup.customer.service.IXyqbService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.quantgroup.customer.constant.Constant.GSON;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserRest {

    private final IUserService userService;
    private final IXyqbService xyqbService;


    @Autowired
    public UserRest(IUserService userService, IXyqbService xyqbService) {
        this.userService = userService;
        this.xyqbService = xyqbService;
    }

    @PostMapping(value = "/login")
    public JsonResult login(Principal principal, HttpServletRequest request) {
        if (principal == null) {
            throw new RuntimeException("账户名或密码不正确");
        }
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        if (!user.isEnable()) {
            throw new RuntimeException("账号已被禁用");
        }
        return new JsonResult(new AuthBean(request.getSession().getId(), user));
    }

    /**
     * 修改手机号-查询工单
     *
     * @param modifyPhoneQuery
     * @return
     */
    @GetMapping(value = "/modify/phone_no")
    public JsonResult modifyPhoneQuery(ModifyPhoneQuery modifyPhoneQuery) {
        LocalDate startAt = modifyPhoneQuery.getStartAt();
        LocalDate endAt = modifyPhoneQuery.getEndAt();
        JsonResult paramErrorResult = JsonResult.buildErrorStateResult(ErrorCodeEnum.PARAM_ERROR.getMessage(), ErrorCodeEnum.PARAM_ERROR.getCode());

        if (startAt == null && endAt != null) {
            return paramErrorResult;
        }
        if (startAt != null && endAt != null && startAt.isAfter(endAt)) {
            return paramErrorResult;
        }
        String applyStatus = modifyPhoneQuery.getApplyStatus();
        if (StringUtils.isNotEmpty(applyStatus) && !ModifyPhoneApplyStatus.validate(applyStatus)) {
            return paramErrorResult;
        }
        String processingStatus = modifyPhoneQuery.getProcessingStatus();
        if (StringUtils.isNotEmpty(processingStatus) && !ModifyPhoneProcessingStatus.validate(processingStatus)) {
            return paramErrorResult;
        }
        String response = userService.modifyPhoneQuery(modifyPhoneQuery);
        if (StringUtils.isEmpty(response)) {
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }
        return GSON.fromJson(response, JsonResult.class);
    }

    /**
     * 修改手机号-人工审核
     *
     * @param modifyPhoneAudit
     * @return
     */
    @PostMapping(value = "/modify/phone_no/audit")
    public JsonResult modifyPhoneAudit(@Valid ModifyPhoneAudit modifyPhoneAudit) {
        if (!ModifyPhoneAuditStatus.validate(modifyPhoneAudit.getApplyStatus(), modifyPhoneAudit.getApplyStatusReason())) {
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.PARAM_ERROR.getMessage(), ErrorCodeEnum.PARAM_ERROR.getCode());
        }
        String response = userService.modifyPhoneAudit(modifyPhoneAudit);
        if (StringUtils.isEmpty(response)) {
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }
        //修改手机号,只有审核通过时调用
        if(ModifyPhoneAuditStatus.PASS.equals(modifyPhoneAudit.getApplyStatus())){
            String response2 = userService.deleteToken(modifyPhoneAudit);
            if(StringUtils.isEmpty(response2)){
                return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
            }
        }
        return GSON.fromJson(response, JsonResult.class);
    }

    /**
     * 修改手机号-反馈跟进
     *
     * @param modifyPhoneFeedback
     * @return
     */
    @PostMapping(value = "/modify/phone_no/feedback")
    public JsonResult modifyPhoneFeedback(@Valid ModifyPhoneFeedback modifyPhoneFeedback) {
        String response = userService.modifyPhoneFeedback(modifyPhoneFeedback);
        if (StringUtils.isEmpty(response)) {
            return JsonResult.buildErrorStateResult(ErrorCodeEnum.RETURN_ERROR.getMessage(), ErrorCodeEnum.RETURN_ERROR.getCode());
        }
        return GSON.fromJson(response, JsonResult.class);
    }


    /**
     * 用户综合查询
     *
     * @param combinationParam
     * @return
     */
    @GetMapping(value = "/info")
    public JsonResult findUserCombination(UserCombinationParam combinationParam) {
        return userService.findUserCombination(combinationParam);

    }

    /**
     * 修改用户详细信息
     *
     * @return
     */
    @PostMapping(value = "/modify/user_detail")
    public JsonResult modifyUserDetail(@RequestParam(required = true) Long userId,
                                       @RequestParam(required = true) String realName,
                                       @RequestParam(required = true) String idNO) {
        //MoResult<String> result = userService.modifyUserDetail(userId, realName, idNO);
        return userService.modifyUserDetailNew(userId, realName, idNO);
    }

    /**
     * 重置密码
     *
     * @return
     */
    @PostMapping(value = "/pwd/reset")
    public JsonResult passwordReset(@RequestParam(required = true) String phone) {
        //MoResult<String> result  = userService.passwordRest(phone);
        return userService.passwordRestNew(phone);
    }

    /**
     * 修改用户账户状态(注销)--更新为禁用
     *
     * @return
     */
    @PostMapping(value = "/modify/account/status/disable")
    public JsonResult modifyAccountStatusDisable(@RequestParam(required = true) Long userId, @RequestParam(required = true) String reason, HttpServletRequest request) {
        //MoResult<Boolean> result = userService.modifyAccountStatusDisable(userId);
        return userService.modifyAccountStatusDisableNew(userId, reason, request);
    }

    /**
     * 新增接口
     * 注销账户，删除账户信息
     * @return
     */
    @PostMapping(value = "/modify/account/delete")
    public JsonResult deleteAccount(@RequestParam(required = true) Long userId) {
        return userService.deleteAccount(userId);
    }

    /**
     * 修改用户账户状态(激活)
     *
     * @return
     */
    @PostMapping(value = "/modify/account/status/active")
    public JsonResult modifyAccountStatusActive(@RequestParam(required = true) Long userId, HttpServletRequest request) {
        //MoResult<Boolean> result = userService.modifyAccountStatusActive(userId);
        return userService.modifyAccountStatusActiveNew(userId, request);
    }

    /**
     * 用户冻结解冻记录
     * @param userId
     * @param pageNo
     * @param pageSize
     * @param request
     * @return
     */
    @PostMapping(value = "/records")
    public JsonResult userRecords(@RequestParam Long userId,
                                  @RequestParam(defaultValue = "0") int pageNo,
                                  @RequestParam(defaultValue = "10") int pageSize,
                                  HttpServletRequest request) {
        return userService.userRecords(userId, pageNo, pageSize, request);
    }

    /**
     * 查询用户详细信息(根据手机号或身份证号查询)
     * @param userQueryParam
     * @return
     */
    @GetMapping(value = "/detail")
    public JsonResult findUserDetail(UserQueryParam userQueryParam) {
        JsonResult<UserBasicInfo> userInfo = userService.findUserInfo(userQueryParam);
        if (!userInfo.isSuccess()) {
            return JsonResult.buildErrorStateResult(userInfo.getMsg(), userInfo.getData());
        }
        return userInfo;
    }

    /**
     * 查询用户和绑卡信息
     *
     * @param userQueryParam
     * @return
     */
    @GetMapping(value = "/card_list")
    public JsonResult findUserCardList(UserQueryParam userQueryParam) {
        Map<String, Object> result = Maps.newHashMap();
        String phoneNo = userQueryParam.getPhoneNo();
        if (StringUtils.isNotEmpty(phoneNo)) {
            if (!(phoneNo.length() == 11 && StringUtils.isNumeric(phoneNo))) {
                return JsonResult.buildErrorStateResult("手机号错误", null);
            }
        }
        JsonResult<UserBasicInfo> userInfo = userService.findUserInfo(userQueryParam);
        if (userInfo != null && userInfo.isSuccess() && userInfo.getData() != null) {
            UserBasicInfo userBasicInfo = userInfo.getData();
            result.put("userInfo", userBasicInfo);
            Long userId = userBasicInfo.getUserId();
            List<UserCardInfo> userPayCardList = xyqbService.findUserPayCardList(userId);
            result.put("cardInfo", userPayCardList);
        } else {
            return JsonResult.buildErrorStateResult("查无此人", null);
        }
        return JsonResult.buildSuccessResult("success", result);
    }
    //add by wuq 2022-01-14 begin
    /**
     * 积分类型初始化
     * @return
     */
    @PostMapping(value = "/search/getRewardPointsType")
    public JsonResult getRewardPointsTypeInit() {
        MoResult<String> result = userService.getRewardPointsType();
        if(!"0000".equals(result.getCode())){
            return JsonResult.buildErrorStateResult(result.getMsg(),result.getData());
        }
        return JsonResult.buildSuccessResult("success", result.getData());
    }
    /**
     *根据userId和phoneNo查询基本信息
     */
    @PostMapping(value = "/search/userInfo")
    public JsonResult getBasicUserInfo(UserQueryParam userQueryParam) {
        //JsonResult result = userService.findUserInfoByUserParam(userQueryParam);
        JsonResult result = userService.findUserInfoByUserParamNew(userQueryParam);
        if(!result.isSuccess()){
            return JsonResult.buildErrorStateResult(result.getMsg(),result.getData());
        }
        return JsonResult.buildSuccessResult("success",result);
    }

    /**
     *根据userId查询优惠券信息(详情)
     */
    @RequestMapping(value = "/search/getUserCouponInfo")
    public JsonResult getUserCouponInfo(UserQueryParam userQueryParam) {
        MoResult<String> result = userService.queryUserCouponInfoByUserParam(userQueryParam);
        if(!"0000".equals(result.getCode())){
            return JsonResult.buildErrorStateResult(result.getMsg(),result.getData());
        }
        return JsonResult.buildSuccessResult("success",result);
    }


    /**
     *根据积分类型和操作时间查询积分明细
     */
    @PostMapping(value = "/search/queryPointDetailByPage")
    public JsonResult queryPointDetailByPage(UserQueryParam userQueryParam) {
        if(Objects.isNull(userQueryParam.getUserId())){
            return JsonResult.buildErrorStateResult("userId不能为空",null);
        }
        MoResult<String> result = userService.queryPointDetailByPage(userQueryParam);
        if(result == null || !"0000".equals(result.getCode())){
            return JsonResult.buildErrorStateResult(result.getMsg(),result.getData());
        }
        return JsonResult.buildSuccessResult("success", result.getData());
    }
}
