package com.community.huiju.controller;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.huiju.common.code.cache.AppkeyCache;
import com.community.huiju.model.TaUser;
import com.community.huiju.model.TpTicket;
import com.community.huiju.service.ITaUserService;
import com.community.huiju.vo.TaUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.dsig.keyinfo.PGPData;
import java.util.List;

/**
 * 用户控制器
 * @author weiximei
 */
@RestController
@RefreshScope
@RequestMapping("/")
@Api(value = "用户相关操作的API",description = "用户相关操作的API")
public class UserController extends BaseController {

    @Autowired
    private ITaUserService iTaUserService;

    @ApiOperation(value = "登录", notes = "根据登录名和验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "loginName(登陆名(手机号)) code(验证码)")
    })
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    public ResponseBean login(@RequestBody String parameter,
                              HttpSession session){
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        ResponseBean responseBean = iTaUserService.login(jsonObject.getString("loginName"),jsonObject.getString("code"), session);
        TaUserVO userVO = (TaUserVO) responseBean.getData();
        if (null != userVO) {
            setUserElement(userVO, session);
        }
        return responseBean;

    }

    @ApiOperation(value = "注册", notes = "注册")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "userName用户姓名;idCard身份证;gender性别(1：男  2：女);loginName手机号;code验证码")
    })
    @RequestMapping(value = "/user/register",method = RequestMethod.POST)
    public ResponseBean register(@RequestBody String parameter) {
        ResponseBean responseBean = new ResponseBean();
        responseBean = iTaUserService.register(parameter);
        return responseBean;
    }

    @ApiOperation(value = "登录 绑定 房产", notes = "绑定选中的当前房产，进行登录 (在APP登录后，选择房产的时候)，还可以用于切换房产登录")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path",dataTypeClass = String.class, name = "userVerifyId",value = "审核 id"),
            @ApiImplicitParam(paramType = "header",dataTypeClass = String.class, name = "X-Auth-Token",value = "Token")
    })
    @RequestMapping(value = "/user/binding/login/{userVerifyId}",method = RequestMethod.POST)
    public ResponseBean login(@PathVariable("userVerifyId") Integer userVerifyId,
                              HttpSession session){
        UserElement userElement = getUserElement(session);
        ResponseBean responseBean = iTaUserService.bindingLoginAndHouse(userElement, userVerifyId);
        TaUserVO userVO = (TaUserVO) responseBean.getData();
        if (null != userVO) {
            setUserElement(userVO, session);
        }
        return responseBean;

    }

    @ApiOperation(value = "修改手机号", notes = "修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "paramets",value = "phone：登陆(手机号)，code：(手机验证码)"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
    })
            @RequestMapping(value = "/user/phone",method = RequestMethod.PUT)
    public ResponseBean update(@RequestBody String paramets, HttpSession session){
        ResponseBean responseBean = new ResponseBean();
        UserElement userElement = getUserElement(session);
        ResponseBean response=iTaUserService.updateLoginName(userElement, paramets);
        return response;
    }

    @ApiOperation(value = "查看房屋成员列表", notes = "查看房屋成员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
    })
    @RequestMapping(value = "/roomUserList", method = RequestMethod.GET)
    public ResponseBean accessTicket(HttpSession session){
        ResponseBean responseBean = new ResponseBean();
        UserElement userElement = getUserElement(session);
        responseBean = iTaUserService.getAllRoomUserList(userElement);
        return responseBean;
    }

    @ApiOperation(value = "修改用户名和性别和身份证", notes = "修改用户名和性别和身份证")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "userName用户民和gender性别和idCard身份证"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
    })
    @RequestMapping(value = "/user/update/info",method = RequestMethod.PUT)
    public ResponseBean updateUserNameAndGender(@RequestBody String parameter,
                                                HttpSession session){
        ResponseBean response = new ResponseBean();
        UserElement userElement = getUserElement(session);
        response = iTaUserService.modifyUser(userElement, parameter);
        return response;

    }

    @ApiOperation(value = "租客或家属 启用或者停用", notes = "租客或家属 启用或者停用")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "userId(租客或者家属) type(1启用 0停用)"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
    })
    @RequestMapping(value = "/user/dependentsOrTenants",method = RequestMethod.PUT)
    @Deprecated
    public ResponseBean updateDependentsOrTenants(@RequestBody String parameter,
                                                HttpSession session){
        ResponseBean response = new ResponseBean();

        UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        response = iTaUserService.startOrEndUsingUser(userElement.getId(),jsonObject.getInteger("userId"),jsonObject.getInteger("type"));

        return response;

    }


    @ApiOperation(value = "业主添加 租客或家属", notes = "业主添加 租客或家属")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "userName(租客或者家属 姓名) " +
                    "loginName(租客或者家属 手机号) " +
                    "gender(租客或者家属 性别 1男 2女) " +
                    "roleName(TENANT 租客 RELATION 家属)" +
                    "idCard(身份证号)" +
                    "code(验证码)"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token"),
    })
    @RequestMapping(value = "/user/addTenantsOrDependents",method = RequestMethod.POST)
    public ResponseBean addTenantsOrDependents(@RequestBody String parameter,
                                               HttpSession session){
        ResponseBean response = new ResponseBean();

        UserElement userElement = getUserElement(session);
        response = iTaUserService.addTenantsOrDependents(userElement, parameter);
        return response;

    }


    @ApiOperation(value = "业主修改 租客或家属", notes = "业主修改 租客或家属")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "id(租客或者家属 ID) userName(租客或者家属 姓名) " +
                    "phone(租客或者家属 手机号) " +
                    "gender(租客或者家属 性别 1男 2女) " +
                    "type(2租客 3家属)" +
                    "idCard(身份证号)"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token"),
    })
    @RequestMapping(value = "/user/updateTenantsOrDependents",method = RequestMethod.POST)
    @Deprecated
    public ResponseBean updateTenantsOrDependents(@RequestBody String parameter,
                                               HttpSession session){
        ResponseBean response = new ResponseBean();

        UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        response = iTaUserService.updateTenantsOrDependents(jsonObject.getString("userName"),
                jsonObject.getString("phone"),jsonObject.getString("gender"),
                userElement.getId(),
                jsonObject.getInteger("type"),
                jsonObject.getInteger("id"),
                jsonObject.getString("idCard"));

        return response;

    }



    @ApiOperation(value = "修改用户头像", notes = "修改用户头像")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body",dataType = "String",name = "parameter",value = "headPortrait(用户头像)"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token"),
    })
    @RequestMapping(value = "/user/modifyUserHeadPortrait",method = RequestMethod.PUT)
    public ResponseBean modifyUserHeadPortrait(@RequestBody String parameter,
                                               HttpSession session){

        UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
        JSONObject jsonObject = JSONObject.parseObject(parameter);
        ResponseBean response = iTaUserService.modifyUserHeadPortrait(userElement.getId(),jsonObject.getString("headPortrait"));

        return response;

    }

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息, 携带userId表示查询租客或者家属")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token"),
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "userId",value = "租客或者家属的ID(可选值)"),
            @ApiImplicitParam(paramType = "query",dataType = "String",name = "userVerifyId",value = "审核id，只有在 userId 参数生效才有效")
    })
    @RequestMapping(value = "/user/info",method = RequestMethod.GET)
    public ResponseBean getUserInfo(@RequestParam(value = "userId",required = false) Integer userId, @RequestParam(value = "userVerifyId", required = false) Integer userVerifyId,
                                    HttpSession session){
        ResponseBean response = new ResponseBean();
        UserElement userElement = getUserElement(session);
        response = iTaUserService.getUserInfo(userElement,userId, userVerifyId, session);
        Object data = response.getData();
        if ("1".equals(response.getCode()) && null == data) {
            // 清空 session
            removeUserElement(session);
            return response;
        }
        if (null == userId && null != data && data instanceof TaUserVO) {
            setUserElement((TaUserVO) data, session);
        }
        TaUserVO userVO = (TaUserVO) data;
        userVO.setToken(session.getId());

        return response;

    }


    @ApiOperation(value = "游客登录", notes = "游客登录")
    @RequestMapping(value = "/user/temporary/{communityId}", method = RequestMethod.POST)
    public ResponseBean temporaryLogin(HttpSession session) {
        ResponseBean responseBean = new ResponseBean();
        responseBean = iTaUserService.temporaryLogin(session);
        TaUserVO userVO = (TaUserVO) responseBean.getData();
        if (null != userVO) {
            setUserElement(userVO, session);
        }
        return responseBean;
    }

    @ApiOperation(value = "迎宾系统添加人员", notes = "迎宾系统添加人员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataTypeClass = String.class, value = "userName人员名称"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token"),
    })
    @RequestMapping(value = "/user/welcome/add", method = RequestMethod.POST)
    public ResponseBean welcomeAddUser(@RequestParam("userName") String userName, HttpSession session) {
        ResponseBean responseBean = new ResponseBean();
        UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
        TaUser user = new TaUser();
        user.setUserName(userName);
        responseBean = iTaUserService.addWelcomeUser(userElement, user);
        return responseBean;
    }

    @RequestMapping(value = "/user/has/phone", method = RequestMethod.GET)
    @ApiOperation(value = "校验 手机号是否注册", notes = "校验 手机号是否注册")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "phone", value = "手机号"),
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token")
    })
    public ResponseBean hasUserPhone(HttpSession session, @RequestParam("phone") String phone) {
        ResponseBean responseBean = new ResponseBean();
        UserElement userElement = getUserElement(session);
        responseBean = iTaUserService.hasUserPhoneVerify(phone, userElement);
        return responseBean;
    }

    @RequestMapping(value = "/user/tenantAndRelation/delete/{userVerifyId}", method = RequestMethod.DELETE)
    @ApiOperation(value = "业主删除 家属或者租客", notes = "业主删除 家属或者租客")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataTypeClass = Integer.class, name = "userVerifyId", value = "审核 id"),
            @ApiImplicitParam(paramType = "header",dataTypeClass = String.class,name = "X-Auth-Token",value = "Token")
    })
    public ResponseBean deleteTenantAndRelation(HttpSession session, @PathVariable("userVerifyId") Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();
        UserElement userElement = getUserElement(session);
        responseBean = iTaUserService.deleteTenantAndRelation(userElement, userVerifyId);
        return responseBean;
    }

    @ApiOperation(value = "获取令牌", notes = "获取令牌")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "appid", value = "提供的appid"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "datetime", value = "时间戳"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "encrypt", value = "encrypt加密方式(目前值为md5)"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "phone", value = "手机号"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "communityId", value = "提供的小区编号"),
            @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "sign", value = "生成的签名"),
    })
    @RequestMapping(value = "/user/token", method = RequestMethod.GET)
    public ResponseBean daSuToken(@RequestParam("appid") String appid,
                                  @RequestParam("datetime") String datetime,
                                  @RequestParam("encrypt") String encrypt,
                                  @RequestParam("phone") String phone,
                                  @RequestParam("communityId") String communityId,
                                  @RequestParam("sign") String sign,
                                  HttpSession session){
        ResponseBean responseBean = new ResponseBean();
        responseBean = iTaUserService.daSuToken(appid, datetime, encrypt, communityId, phone, sign, session);
        Object object = responseBean.getData();
        if (null != object) {
            TaUserVO userVO = (TaUserVO) responseBean.getData();
            if (userVO != null) {
                setUserElement(userVO, session);
            }
        }
        return responseBean;
    }

}
