package com.sptg.gateway.controller.statistics;

/**
 * title: MemberController
 * package: com.sptg.estate.biz.security
 * description: 会员控制器
 *
 *
 *
 */

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.device.api.dto.DeviceDto;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.constant.EstateSecurityToken;
import com.sptg.estate.api.dto.ApplyUserDto;
import com.sptg.estate.api.dto.MemberDto;
import com.sptg.estate.api.dto.RoomDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.feigns.ApiDockingConfFeign;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

/**
 * title: MemberController
 * package: com.sptg.gateway.controller.statistics
 * description: 会员注册详情-网关控制器
 *
 *
 *
 */
@RestController
@RequestMapping("/statistics/member")
@AllArgsConstructor
public class MemberController {

    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final ApiDockingConfFeign apiDockingConfFeign;
    private final MemberFeign memberFeign;
    private final MemberAndUserFeign memberAndUserFeign;
    private final UserFeign userFeign;
    private final DeviceFeign deviceFeign;
    private final VideoCallAccountFeign videoCallAccountFeign;
    private final ApplyUserFeign applyUserFeign;
    private final RoomFeign roomFeign;
    private final MemberDeviceFeign memberDeviceFeign;

    /**
     * 密码加盐
     */
    private static final String PWD_SALT = "sptg";

    /**
     * 功能描述:会员注册管理页面
     * @param
     * @return
     *
     *
     */
    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("statistics/member-manage");
        return modelAndView;
    }

    @GetMapping("/add")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_ADD, format = DataFormatEnum.VIEW)
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView("estate/member-add");
        return modelAndView;
    }

    /**
     * 功能描述:后台添加APP会员
     *
     * @param member {
     *            name          :  姓名,
     *            tel           :  手机号码
     *            password      :  app登录密码 ,
     *            create_ip     :  注册地址
     *
     *
     *            }
     * @return
     */
    @PostMapping(value = "/memberRegister")
    public ResultBean<Boolean> memberRegister(Member member) {
        ResultBean<Boolean> resultBean = null;

        try {
            String name = member.getName();
            String tel = member.getTel();
            String password = member.getPassword();

            if (StringUtils.isBlank(name)) {
                resultBean = new ResultBean<>("0","姓名不能为空");
                return resultBean;
            }
            if (StringUtils.isBlank(tel)) {
                resultBean = new ResultBean<>("0","手机号码不能为空");
                return resultBean;
            }


            if (StringUtils.isBlank(password)) {
                resultBean = new ResultBean<>("0","密码不能为空");
                return resultBean;
            } else {
                if (password.length() < 4 || password.length() > 6) {
                    resultBean = new ResultBean<>("0","密码只能填写4-6位");

                    return resultBean;
                }
            }


            //create_type : 会员注册来源，0-小程序添加 1-后台添加  2-后台导入 3-app添加
            member.setCreateType(OperationConstant.ONE);
            member.setCreateDate(new Date());
            //密码md5加密
            member.setPassword(DigestUtils.md5Hex(PWD_SALT + password));
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            member.setOrgId(onLineUser.getOrgId());

            if(this.memberFeign.checkMemberTel(member).getData()){
                resultBean = new ResultBean<>("0","该手机号已被注册");
                return resultBean;
            }else{
                member.setOrgPosition(onLineUser.getOrgPosition());
                member.setRootOrgId(onLineUser.getRootOrgId());
                //新增会员--注册
                resultBean = this.memberFeign.memberRegister(member);
                //注册成功
                if (resultBean.getCode().equals("200") && resultBean.getData()) {
                    /*---------------------------------------------------记录日志--------------------------------------------------------*/
                    SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_MEMBER_MANAGER, SysLogConstant.ADD_EVENT,
                            WebUtils.getIp(),member,onLineUser,member);
                    sysOperationLogFeign.info(sysOperationLog);
                    /*------------------------------------------------------------------------------------------------------------------*/
                    resultBean = new ResultBean<>("200","注册成功");

                } else {
                    resultBean = new ResultBean<>("0","注册失败");
                }
            }


        } catch (Exception e) {
            resultBean = new ResultBean<>("0","后台程序异常");
        }
        return resultBean;
    }


    /**
     * 功能描述:物业-会员注册管理页面
     * @param
     * @return
     *
     *
     */
    @GetMapping("/manage")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_MANAGER,format = DataFormatEnum.VIEW)
    public ModelAndView manage(){
        return new ModelAndView("estate/member-manage");
    }

    /**
     * 功能描述：APP会员管理门禁授权页面
     * @return modelAndView
     */
    @GetMapping("/access/{id}")
    public ModelAndView access(@PathVariable(value = "id") Long id){
        ModelAndView modelAndView = new ModelAndView("estate/member-device");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    /**
     * 功能描述：APP会员房屋验证页面
     * @return modelAndView
     */
    @GetMapping("/room/{id}")
    public ModelAndView room(@PathVariable(value = "id") Long id){
        ModelAndView modelAndView = new ModelAndView("estate/member-room");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    /**
     * 查询广告类容列表(分页)
     * @param memberDto 查询条件参数
     * @param page 分页参数
     * @return
     *
     *
     */
    @PostMapping(value = "/showMemberList")
    public ResultBean<Page<Member>> showMemberList(MemberDto memberDto, Page<Member> page) {
        //机构位置
        Account onLineUser=this.securityServiceInterface.getOnLineUser();
        memberDto.setOrgPosition(onLineUser.getOrgPosition());
        memberDto.setPage(page);
        return this.memberFeign.showMemberList(memberDto);
    }

    /**
     * 后台激活会员
     * @param memberDto 参数
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/memberActivation")
    public ResultBean<Boolean> activation(@RequestBody MemberDto memberDto){
        Account onLineUser=this.securityServiceInterface.getOnLineUser();
        //查询手机是否已注册
        memberDto.setOrgId(onLineUser.getOrgId());
        Assert.isTrue(!this.memberFeign.checkMemberTel(memberDto).getData(),"该手机号已注册");

        memberDto.setOrgPosition(onLineUser.getOrgPosition());
        memberDto.setCreateType(OperationConstant.ONE);
        memberDto.setRootOrgId(onLineUser.getRootOrgId());
        memberDto.setCreateIp(WebUtils.getIp());
        memberDto.setPassword(DigestUtils.md5Hex(PWD_SALT+memberDto.getPassword()));
        ResultBean<Boolean> resultBean = this.memberFeign.activation(memberDto);
        if(null != resultBean.getData() && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_MEMBER_MANAGER, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),memberDto,onLineUser,memberDto);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 修改会员账号
     * @param memberDto 会员账号
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/update")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_MANAGER,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> update(MemberDto memberDto){
        Member member = this.memberFeign.getMemberByMemberId(memberDto.getId());
        if (member == null){
            return new ResultBean<>(ResultEnum.NOT_FIND);
        }
        BeanUtils.copyProperties(memberDto,member);
        ResultBean<Boolean> resultBean=this.memberFeign.updateMember(member);
        if(null != resultBean.getData() && resultBean.getData()){
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Member newObj = this.memberFeign.getMemberByMemberId(member.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_MEMBER_MANAGER, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),memberDto,onLineUser,member,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 启用禁用
     * @param memberDto 会员账号
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/enable")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_MANAGER,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> enable(MemberDto memberDto){
        Member member = this.memberFeign.getMemberByMemberId(memberDto.getId());
        if (member == null){
            return new ResultBean<>(ResultEnum.NOT_FIND);
        }
        member.setEnable(memberDto.getEnable());
        ResultBean<Boolean> resultBean=this.memberFeign.updateMember(member);
        if(null != resultBean.getData() && resultBean.getData()){
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Member newObj = this.memberFeign.getMemberByMemberId(member.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_MEMBER_MANAGER, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),memberDto,onLineUser,member,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 修改密码
     * @param memberDto 会员账号
     * @return ResultBean<Boolean>
     */
    @PostMapping(value = "/password")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_MANAGER_PSW,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> password(MemberDto memberDto){
        Assert.notNull(memberDto.getId(),"传入参数有误");
        Assert.notNull(memberDto.getPassword(),"密码不能为空");
        Member oldObj = this.memberFeign.getMemberByMemberId(memberDto.getId());
        memberDto.setPassword(DigestUtils.md5Hex(PWD_SALT+memberDto.getPassword()));
        ResultBean<Boolean> resultBean = this.memberFeign.updateMember(memberDto);
        if(null != resultBean.getData() && resultBean.getData()){
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Member newObj = this.memberFeign.getMemberByMemberId(memberDto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_MEMBER_MANAGER, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),memberDto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 管理门禁授权
     * @param memberDto
     * @return
     */
    @GetMapping(value = "/getAuthDeviceByMemberId")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_MANAGER_ACCESS,format = DataFormatEnum.JSON)
    public ResultBean<Page<Device>> getAuthDeviceByMemberId(MemberDto memberDto, Page<Device> page){
        MemberAndUser memberAndUser = new MemberAndUser();
        memberAndUser.setMemberId(memberDto.getId());
        List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
        if (list.size() > 0){
            List<Long> userIds = new ArrayList<>();
            for (MemberAndUser mau : list) {
                userIds.add(mau.getUserId());
            }
            List<User> users = this.userFeign.getListByUserId(userIds);
            //获取相关小区id，根据小区id查询
            List<Long> residentialIds = new ArrayList<>();
            for (User user : users){
                residentialIds.add(user.getResidentialId());
            }
            residentialIds.stream().distinct().collect(Collectors.toList());
            if (residentialIds.size() == 0){
                return new ResultBean<>(ResultEnum.SUCCESS,page);
            }
            //过滤禁用的设备
            DeviceDto deviceDto = new DeviceDto();
            MemberDevice memberDevice = new MemberDevice();
            memberDevice.setMemberId(memberDto.getId());
            List<MemberDevice> memberDeviceList = this.memberDeviceFeign.getListByMemberId(memberDevice);
            if (memberDeviceList.size() > 0){
                List<Long> deviceIds = new ArrayList<>();
                for (MemberDevice item : memberDeviceList){
                    deviceIds.add(item.getDeviceId());
                }
                deviceDto.setIdList(deviceIds);
            }
            deviceDto.setPage(page);
            deviceDto.setResidentialIds(residentialIds);
            return this.deviceFeign.pagingByResidentialIds(deviceDto);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,page);
        /*List<Device> collect = new ArrayList<>();
        for (User user : users) {
            List<Device> devices = this.deviceFeign.getListByEstateUser(user.getResidentialId(), user.getUnitId());
            collect.addAll(devices);
        }
        List<Device> deviceList = collect.stream().distinct().collect(Collectors.toList());
//        BeanUtils.copyProperties(memberDto.getPage(),page);
        page.setRecords(deviceList);
        return new ResultBean<>(ResultEnum.SUCCESS,page);*/
    }

    /**
     * 获取认证房屋
     * @param memberDto APP会员
     * @return ResultBean<Page<ApplyUser>>
     */
    @GetMapping(value = "/getAuthRoomByMemberId")
    @Security(token = EstateSecurityToken.ESTATE_MEMBER_MANAGER_ROOM,format = DataFormatEnum.JSON)
    public ResultBean<Page<Room>> getAuthRoomByMemberId(MemberDto memberDto,Page<Room> page){
        ApplyUserDto applyUserDto = new ApplyUserDto();
        applyUserDto.setMemberId(memberDto.getId());
        applyUserDto.setCheckState(OperationConstant.ONE);
        List<ApplyUser> list = this.applyUserFeign.getApplyUserByCondition(applyUserDto);
        List<String> collect = new ArrayList<>();
        for (ApplyUser applyUser : list){
            collect.add(String.valueOf(applyUser.getRoomId()));
        }
        List<String> roomIds = collect.stream().distinct().collect(Collectors.toList());
        if (roomIds.size() == 0 ){
            return new ResultBean<>(ResultEnum.SUCCESS,page);
        }else {
            RoomDto roomDto = new RoomDto();
            roomDto.setIds(roomIds);
            roomDto.setPage(page);
            return new ResultBean<>(ResultEnum.SUCCESS,this.roomFeign.pagingByIds(roomDto));
        }
    }
}
