package com.github.wxiaoqi.security.admin.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.biz.*;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.entity.AppUserPosition;
import com.github.wxiaoqi.security.admin.entity.User;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.admin.vo.UserMemberVo;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.CompanySearchDTO;
import com.xxfc.platform.vehicle.pojo.CompanySearchVO;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 11:51
 */
@RestController
@RequestMapping("public")
public class PublicController {

    @Autowired
    private UserBiz userBiz;

    @Autowired
    private AppUserDetailBiz detailBiz;

    @Autowired
    private AppUserLoginBiz appUserLoginBiz;

    @Autowired
    private BaseUserMemberBiz userMemberBiz;

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    AppUserPositionBiz positionBiz;

    @Autowired
    private AppUserRelationBiz relationBiz;

    @Autowired
    VehicleFeign vehicleFeign;

    @Autowired
    BranchCompanyBiz branchCompanyBiz;

    @RequestMapping(value = "/userinfo-by-token", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse userinfoByToken(String token) throws Exception {
        String username = userAuthUtil.getInfoFromToken(token).getUniqueName();
        //String userIdStr = userAuthUtil.getInfoFromToken(token).getId();
        if (username == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        User user = userBiz.getUserByUsername(username);
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        return new ObjectRestResponse<User>().rel(true).data(user);
    }

    @RequestMapping(value = "v2/userinfo-by-token", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse userinfoByTokenV2(String token,boolean flag) throws Exception {
        String username = userAuthUtil.getInfoFromToken(token).getUniqueName();
        //String userIdStr = userAuthUtil.getInfoFromToken(token).getId();
        if (username == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        User user = userBiz.getUserByUsername(username);
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        if (user.getDataCorporation() != null){
            com.github.wxiaoqi.security.admin.dto.CompanySearchDTO companySearchDTO =new com.github.wxiaoqi.security.admin.dto.CompanySearchDTO();
            companySearchDTO.setDataCorporationIds(Arrays.asList(user.getDataCorporation().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList()));
            List<com.github.wxiaoqi.security.admin.vo.CompanySearchVO> companySearchVOList=branchCompanyBiz.getList(companySearchDTO);
            if(companySearchVOList != null && companySearchVOList.size() > 0){
                List<Integer> companyIds = companySearchVOList.stream().map(com.github.wxiaoqi.security.admin.vo.CompanySearchVO::getId).distinct().collect(Collectors.toList());
                user.setCompanyIds(companyIds);
            }
        }else if (StrUtil.isNotBlank(user.getDataCompany()) ){
            List<Integer> companyIds = Arrays.asList(user.getDataCompany().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            user.setCompanyIds(companyIds);
        }
        return new ObjectRestResponse<User>().rel(true).data(user);
    }


    @RequestMapping(value = "/userinfo-by-uid", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse<User> userinfoByUid(Integer uid) throws Exception {
        if (uid == null||uid==0) {
            return ObjectRestResponse.paramIsEmpty();
        }
        User user = userBiz.getUserByUid(uid);
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        return ObjectRestResponse.succ(user);
    }

    @RequestMapping(value = "v2/userinfo-by-uid", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse userinfoByUidV2(Integer uid) throws Exception {
        User user = userBiz.selectOne(new User(){{
            setId(uid);
            setIsDel(SYS_FALSE);
            setStatus(SYS_TRUE);
        }});
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        if (user.getDataCorporation() != null){
            com.github.wxiaoqi.security.admin.dto.CompanySearchDTO companySearchDTO =new com.github.wxiaoqi.security.admin.dto.CompanySearchDTO();
            companySearchDTO.setDataCorporationIds(Arrays.asList(user.getDataCorporation().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList()));
            List<com.github.wxiaoqi.security.admin.vo.CompanySearchVO> companySearchVOList=branchCompanyBiz.getList(companySearchDTO);
            if(companySearchVOList != null && companySearchVOList.size() > 0){
                List<Integer> companyIds = companySearchVOList.stream().map(com.github.wxiaoqi.security.admin.vo.CompanySearchVO::getId).distinct().collect(Collectors.toList());
                user.setCompanyIds(companyIds);
            }
        }else if (user.getDataCompany() != null ){
            List<Integer> companyIds = Arrays.asList(user.getDataCompany().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            user.setCompanyIds(companyIds);
        }
        return new ObjectRestResponse<User>().rel(true).data(user);
    }


    @RequestMapping(value = "v2/userinfo-by-appUserId", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse userinfoByAppUserIdV2(Integer appUserId){
      return userBiz.userinfoByAppUserIdV2(appUserId);
    }

    @RequestMapping(value = "business/userinfo-by-mobilePhone", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse userinfoByAppUserIdV2(String mobilePhone){
        User user = userBiz.selectOne(new User(){{
            setMobilePhone(mobilePhone);
            setIsDel(SYS_FALSE);
            setStatus(SYS_TRUE);
        }});
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        if (user.getDataCorporation() != null){
            com.github.wxiaoqi.security.admin.dto.CompanySearchDTO companySearchDTO =new com.github.wxiaoqi.security.admin.dto.CompanySearchDTO();
            companySearchDTO.setDataCorporationIds(Arrays.asList(user.getDataCorporation().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList()));
            List<com.github.wxiaoqi.security.admin.vo.CompanySearchVO> companySearchVOList=branchCompanyBiz.getList(companySearchDTO);
            if(companySearchVOList != null && companySearchVOList.size() > 0){
                List<Integer> companyIds = companySearchVOList.stream().map(com.github.wxiaoqi.security.admin.vo.CompanySearchVO::getId).distinct().collect(Collectors.toList());
                user.setCompanyIds(companyIds);
            }
        }else if (user.getDataCompany() != null ){
            List<Integer> companyIds = Arrays.asList(user.getDataCompany().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            user.setCompanyIds(companyIds);
        }
        return new ObjectRestResponse<User>().rel(true).data(user);
    }

    @RequestMapping(value = "/app/userinfo-by-token", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse userDetailByToken(String token) throws Exception {
        String username = userAuthUtil.getInfoFromToken(token).getId();
        if (username == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        Integer userid = Integer.parseInt(username);
        return ObjectRestResponse.succ(getAppUserInfoById(userid));
    }

    @RequestMapping(value = "/app/userinfo-by-id", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse<AppUserDTO> userDetailById(Integer id) throws Exception {
        if (id == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        return ObjectRestResponse.succ(getAppUserInfoById(id));
    }

    @RequestMapping(value = "/app/userinfo-by-username", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse<AppUserDTO> userDetailByUsername(String name) throws Exception {
        AppUserLogin appUserLogin;
        if (StrUtil.isBlank(name)) {
            return ObjectRestResponse.paramIsEmpty();
        }else {
            appUserLogin = appUserLoginBiz.selectOne(new AppUserLogin(){{setUsername(name);}});
            if(null == appUserLogin) {
                return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
            }
        }
        return ObjectRestResponse.succ(getAppUserInfoById(appUserLogin.getId()));
    }

    @RequestMapping(value = "/app/business/userinfo-by-username", method = RequestMethod.GET)
    public @ResponseBody
    ObjectRestResponse<AppUserDTO> userDetailByUsernameBusiness(String name) throws Exception {
        AppUserLogin appUserLogin;
        if (StrUtil.isBlank(name)) {
            return ObjectRestResponse.paramIsEmpty();
        }else {
            appUserLogin = appUserLoginBiz.selectOne(new AppUserLogin(){{
                setUsername(name);
                setIsdel(SYS_FALSE);
                setStatus(SYS_TRUE);
            }});
            if(null == appUserLogin) {
                return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
            }
        }
        return ObjectRestResponse.succ(getAppUserInfoById(appUserLogin.getId()));
    }

    private AppUserDTO getAppUserInfoById(Integer userid) throws IllegalAccessException, InvocationTargetException {
        AppUserDTO userDTO=new AppUserDTO();
        //获取用户基础信息
        AppUserVo userVo = detailBiz.getUserInfoById(userid);
        if (userVo == null) {
            return null;
        }
        Integer id= userVo.getId();
        Integer positionId=userVo.getPositionId();
        BeanUtils.copyProperties(userDTO,userVo);
        if(userVo.getIsMember()!=null&&userVo.getIsMember()>0){
            //获取用户会员信息
            UserMemberVo memberVo=userMemberBiz.getMemberInfoByUserId(userid);
            if(memberVo!=null){
                BeanUtils.copyProperties(userDTO,memberVo);
                userDTO.setMemberType(memberVo.getMemberType());
            }
        }
        AppUserPosition userPosition=positionBiz.selectById(positionId);
        if (userPosition!=null&&userPosition.getLevel()>0){
            userDTO.setPositionName(userPosition.getName());
        }

        userDTO.setId(id);

        //设置上级
        relationBiz.initParentId(userDTO, userid);
        return userDTO;
    }

    @GetMapping("/getByUserIds")
    public ObjectRestResponse<List<AppUserVo>> getByUserIds(@RequestParam("ids") List<Integer> ids) {
        if(ids == null) {
            return ObjectRestResponse.createFailedResult(500, "参数id为空");
        }
        List<AppUserVo> appUserVos = new ArrayList<>();
        for (Integer id : ids) {
            AppUserVo userVo = detailBiz.getUserInfoById(id);
            appUserVos.add(userVo);
        }
        return ObjectRestResponse.succ(appUserVos);
    }


    @GetMapping("/getUsersByUserIds")
    public ObjectRestResponse<List<AppUserVo>> getUsersByUserIds(@RequestParam("ids") List<Integer> ids) {
        if(CollectionUtil.isEmpty(ids)) {
            return ObjectRestResponse.createFailedResult(500, "参数id为空");
        }

        List<AppUserVo>  appUserVos =   detailBiz.getUserByUserIds(ids);
        if(CollectionUtil.isEmpty(appUserVos)) {
            return ObjectRestResponse.succ(new ArrayList<AppUserVo>());
        }
        return ObjectRestResponse.succ(appUserVos);
    }

    @GetMapping("/getUsersByUserIdList")
    ObjectRestResponse<List<AppUserVo>> getByUserIdList(@RequestParam("userIds") List<Integer> userIds){
        List<AppUserVo>  appUserVos =   detailBiz.getUserByUserIdList(userIds);
       return ObjectRestResponse.succ(appUserVos);
    }
}
