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

import com.ace.cache.annotation.Cache;
import com.github.wxiaoqi.security.admin.biz.*;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.admin.vo.AppUserGroups;
import com.github.wxiaoqi.security.admin.vo.AppUserInfoVo;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.admin.vo.UserMemberVo;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.feign.OrderFeign;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import java.util.List;
import java.util.Map;

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

/**
 * @author keliii
 */
@RestController
@RequestMapping("app/user")
@Slf4j
public class AppUserController extends CommonBaseController{

    @Autowired
    AppUserBiz appUserBiz;

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    AppUserDetailBiz userDetailBiz;

    @Autowired
    AppUserLoginBiz appUserLoginBiz;

    @Autowired
    private BaseUserMemberBiz userMemberBiz;

    @Autowired
    AppUserPositionBiz positionBiz;

    @Autowired
    private UserMemberLevelBiz userMemberLevelBiz;

    @Autowired
    private MyWaterBiz myWaterBiz;

    @Autowired
    private OrderFeign orderFeign;



    @GetMapping("page")
    public TableResultResponse list(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        try {
            return appUserBiz.selectPage(query,
                    appUserBiz.getUserByUsername(userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request)).getUniqueName()));
        }catch (Exception e) {
            log.error(e.getMessage());
            return new TableResultResponse<User>();
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<AppUser> get(@PathVariable int id){
        ObjectRestResponse<AppUser> entityObjectRestResponse = new ObjectRestResponse<>();
        AppUser o = appUserBiz.selectById(id);
        entityObjectRestResponse.data(o);
        return entityObjectRestResponse;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<AppUser> update(@RequestBody AppUser entity){
        appUserBiz.updateSelectiveById(entity);
        return new ObjectRestResponse<AppUser>();
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ObjectRestResponse<AppUser> remove(@PathVariable int id){
        appUserBiz.deleteById(id);
        return new ObjectRestResponse<AppUser>();
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<AppUser> all(){
        return appUserBiz.selectListAll();
    }

    @GetMapping("groups/{id}")
    public List<Group> groups(@PathVariable Integer id) {
        return appUserBiz.selectGroupsByAppUserId(id);
    }

    @PostMapping("groups")
    public ObjectRestResponse insertAppUserGroups(@RequestBody AppUserGroups appUserGroups) {
        appUserBiz.insertAppUserGroup(appUserGroups.getAppUserId(), appUserGroups.getGroups());
        return new ObjectRestResponse();
    }

    /**
     * 获取用户信息
     * @return
     * @throws Exception
     */
    @GetMapping("/info")
    public ObjectRestResponse<AppUserDTO> getUserInfo()throws Exception {
        String username = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request)).getId();
        if (username == null) {
            throw new Exception();
        }
        AppUserDTO userDTO=new AppUserDTO();
        Integer userid=Integer.parseInt(username);
        AppUserVo userVo = userDetailBiz.getUserInfoById(userid);
        if (userVo == null) {
            throw new Exception();
        }
        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.setPayCount(orderFeign.baseOrderCount(SYS_TRUE, "4,5,6,7", null, userid).getData());
                Integer level=memberVo.getMemberLevel();
                BaseUserMemberLevel memberLevel=userMemberLevelBiz.getLevel(level);
                if (memberLevel!=null){
                    String icon=memberLevel.getIcon();
                    userDTO.setIcon(icon);
                }
            }
        }
        AppUserPosition userPosition=positionBiz.selectById(positionId);
        if (userPosition!=null&&userPosition.getLevel()>0){
            userDTO.setPositionName(userPosition.getName());
        }
        userDTO.setId(id);
        return ObjectRestResponse.succ(userDTO);
    }


    @ApiOperation("获取用户收益")
    @GetMapping("/profit")
    public ObjectRestResponse profit() throws Exception{
        String username = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request)).getId();
        if (username == null) {
            throw new Exception();
        }
        Integer userid=Integer.parseInt(username);
        return myWaterBiz.getUserProfit(userid);
    }
    /**
     * 更新用户信息
     * @param userVo
     * @return
     * @throws Exception
     */
    @PostMapping("/edit")
    public ObjectRestResponse edit(@RequestBody AppUserVo userVo)throws Exception {
        if(userVo==null||userVo.getId()==null){
            return   ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        userDetailBiz.updUuserInfoById(userVo);
        Integer userid=userVo.getUserid();
        if (userid!=null){
            AppUserLogin appUserLogin=new AppUserLogin();
            appUserLogin.setWxOpenid(userVo.getWxOpenid());
            appUserLogin.setUnionid(userVo.getUnionid());
            appUserLogin.setOpenid(userVo.getOpenid());
            appUserLogin.setId(userid);
            appUserLogin.setUsername(userVo.getUsername());
            appUserLoginBiz.bindOpenid(appUserLogin);
        }
        return ObjectRestResponse.succ();
    }

    /**
     * 第三方登录绑定
     * @param wxOpenId
     * @param wxUnionId
     * @param openId
     * @param request
     * @return
     */
    @PutMapping("/third_party_binding")
    public ObjectRestResponse bindingThirdParty(@RequestParam(value = "wxOpenId",required = false) String wxOpenId,
                                                @RequestParam(value="wxUnionId",required = false) String wxUnionId,
                                                @RequestParam(value = "openId",required = false) String openId,
                                                HttpServletRequest request){
        try {
            IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request));
            String userId = infoFromToken.getId();
            boolean isBinding = appUserLoginBiz.checkThirdPartyBindingState(wxOpenId,wxUnionId,openId);
            if (isBinding){
                return  ObjectRestResponse.createFailedResult(400,"该微信已经绑定过");
            }else {
                AppUserLogin appUserLogin = new AppUserLogin();
                appUserLogin.setId(Integer.valueOf(userId));
                appUserLogin.setWxOpenid(wxOpenId);
                appUserLogin.setUnionid(wxUnionId);
                appUserLogin.setOpenid(openId);
                appUserLoginBiz.bindOpenid(appUserLogin);
            }
        } catch (Exception e) {
            throw  new BaseException(e);
        }

        return ObjectRestResponse.succ();
    }

    /**
     * 第三方登录解绑
     * @param request
     * @return
     */
    @PutMapping("third_party_unbind")
    public ObjectRestResponse unBindingThirdParty(@RequestParam("type") String type , HttpServletRequest request){
        try {
            IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request));
            appUserLoginBiz.unBindThirdPartyByType(type,infoFromToken.getUniqueName(),Integer.valueOf(infoFromToken.getId()));
        } catch (Exception e) {
            throw  new BaseException(e);
        }
        return ObjectRestResponse.succ();
    }



    /**
     * 更新用户信息
     * @param username
     * @return
     */
    @GetMapping("/one")
    public AppUserLogin one(@RequestParam(value = "username")String username){
        return appUserLoginBiz.getUserByUsername(username);
    }

    @GetMapping("/findusersByIds")
    public Map<Integer,AppUserLogin> findAppUsersByUserIds(@RequestParam(value = "userIds") List<Integer> userIds){
     return appUserLoginBiz.findUserIdAndUserLoginMapByMemberIds(userIds);
    }

    @GetMapping("/finduserIdsByphones")
    Map<String, Integer> findAppusersByUserNames(@RequestParam(value = "phones") List<String> phones){
        return appUserLoginBiz.findPhoneAndUserIdMapByPhones(phones);
    }

    @GetMapping("/app/unauth/user_info/{code}")
    @IgnoreUserToken
    @IgnoreClientToken
    public ObjectRestResponse<AppUserInfoVo> findUserInfoByCode(@PathVariable("code") String code){
         AppUserInfoVo appUserInfoVo = userDetailBiz.findUserInfoByCode(code);
         return ObjectRestResponse.succ(appUserInfoVo);
    }
}
