package com.sptg.estate.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.UserFlagConstant;
import com.sptg.estate.api.dto.BaseUser;
import com.sptg.estate.api.dto.UserInfoDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.GuestRecordFeign;
import com.sptg.estate.biz.service.*;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.DeviceAdminUser;
import com.sptg.permissions.api.feigns.AccountFeign;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.DeviceAdminUserFeign;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * title: BaseUserServiceImpl
 * package: com.sptg.estate.biz.security.impl
 * description:
 *
 *
 *
 */
@Service
@RequiredArgsConstructor
public class BaseUserServiceImpl implements BaseUserServiceInterface {

    private final ServerUserServiceInterface serverUserServiceInterface;
    private final UserServiceInterface userServiceInterface;
    private final ServerUserFaceImageServiceInterface serverUserFaceImageServiceInterface;
    private final AccountFeign accountFeign;
    private final ConfFeign confFeign;
    private final AccessCardServiceInterface accessCardServiceInterface;
    private final DeviceAdminUserFeign deviceAdminUserFeign;
    private final GuestRecordFeign guestRecordFeign;


    /* -------------------------------------------------------------------------------------------------------------- */

    private final static BaseUser BASE_USER = new BaseUser() {

        @Override
        public Integer getType() {
            return OperationConstant.THREE;
        }

        @Override
        public int getIsAdmin() {
            return OperationConstant.THREE;
        }

        @Override
        public Integer getSex() {
            return 0;
        }
    };

    @Override
    public BaseUser selectUserById(String userId) {
        BaseUser user = new BaseUser();
        if (userId.length() > OperationConstant.TWO){
            //  通过字符串截取得到Id字符串  userId = s_123123 || u_123123 || a_123123 || d_123123
            String stringId = userId.substring(OperationConstant.THREE);
            long id;
            try {
                //访客
                if(userId.startsWith(UserFlagConstant.GUEST_FLAG)){
                    //获取访客信息
                    GuestRecord guestRecord = new GuestRecord();
                    guestRecord.setGuestTel(stringId);
                    List<GuestRecord> guestRecordList = this.guestRecordFeign.findByCondition(guestRecord);
                    if(guestRecordList.size()>0){
                        user.setIsAdmin(3);
                        user.setName(guestRecordList.get(0).getGuestName());
                        user.setSex(0);
                        user.setTel(guestRecordList.get(0).getGuestTel());
                        return user;
                    }else {
                        return BASE_USER;
                    }
                }


                id = Long.parseLong(stringId);
                if (userId.startsWith(UserFlagConstant.SERVER_USER_NUMBER_FLAG)){
                    //  获取服务人员信息
                    user = this.serverUserServiceInterface.selectById(id);
                    user.setIsAdmin(OperationConstant.ONE);
                }else if (userId.startsWith(UserFlagConstant.USER_NUMBER_FLAG)){
                    //  获取住户的信息
                    User houseMaster = this.userServiceInterface.selectById(id);
                    if(houseMaster != null){
                        BeanUtils.copyProperties(houseMaster,user);
                    }
//                    user.setRoomName(houseMaster.getRoomName());
                    user.setIsAdmin(OperationConstant.TWO);
                }else if (userId.startsWith(UserFlagConstant.ADMIN_USER_NUMBER_FLAG)){
                    //  获取后台管理员信息
                    Account account = this.accountFeign.getById(id);
                    if (null == account){
                        return BASE_USER;
                    }
                    user = new BaseUser() {
                        @Override
                        public int getIsAdmin() {
                            return 0;
                        }
                    };
                    user.setId(account.getId());
                    user.setName(account.getLoginName());
                    user.setSex(0);
                    user.setTel(account.getUserMobile());
                }else if (userId.startsWith(UserFlagConstant.DEVICE_MANAGE_FLAG)){
                    //  设备管理机账号
                    DeviceAdminUser adminUser = this.deviceAdminUserFeign.getUserById(id);
                    if (null == adminUser){
                        return BASE_USER;
                    }
                    user = new BaseUser() {
                        @Override
                        public int getIsAdmin() {
                            return 4;
                        }
                    };
                    user.setId(adminUser.getId());
                    user.setTel(adminUser.getUserMobile());
                    user.setName(adminUser.getLoginName());
                    user.setSex(0);
                }
            }catch (NumberFormatException e){
                return BASE_USER;
            }
        }
        //  其他
        return null == user ? BASE_USER : user;
    }

    @Override
    public BaseUser selectUserByDoorCardNo(String doorCardNo,Long xqId) {
        AccessCard card = this.accessCardServiceInterface.getByCardNoAndXqId(doorCardNo, xqId);
        Assert.notNull(card,"卡号不存在");
        switch (card.getType()){
            //  住户
            case 0:
                return this.userServiceInterface.selectById(card.getUserId());
            //  服务人员
            case 4:
                return this.serverUserServiceInterface.selectById(card.getUserId());
            default:
                //  1-房间，2-单元，3-小区

                return null;
        }
    }

    @Override
    public Page<UserInfoDto> pagingQueryServerUser(PageBean<UserInfoDto, String> pageBean) {
        //  分页查询服务人员信息
        Wrapper<ServerUser> wrapper = new EntityWrapper<>();
        wrapper.eq("l_residential_id",pageBean.getDto());
        wrapper.notIn("i_status",OperationConstant.MINUS_ONE);
        wrapper.eq("i_face_enable", OperationConstant.ONE);
        Page<ServerUser> page = new Page<>(pageBean.getCurrent(),pageBean.getSize());
        page = this.serverUserServiceInterface.selectPage(page, wrapper);
        //  设置返回结果
        pageBean.setTotal(page.getTotal());
        List<UserInfoDto> list = new ArrayList<>(page.getRecords().size());
        page.getRecords().forEach(user -> {
            UserInfoDto userInfo = new UserInfoDto();
            userInfo.setId(UserFlagConstant.SERVER_USER_FLAG + user.getId());
            userInfo.setName(user.getName()); //设置服务人员姓名
            List<Map<String,Object>> faceCodeList = this.serverUserFaceImageServiceInterface.selectFaceCodeByUserId(user.getId());
            userInfo.setFaceCodeList(faceCodeList);
            List<ServerUserFaceImage> serverUserFaceImages = this.serverUserFaceImageServiceInterface.selectByServerUserId(user.getId());
            if(null != serverUserFaceImages && serverUserFaceImages.size() > 0){
                ServerUserFaceImage serverUserFaceImage = serverUserFaceImages.get(0);
                userInfo.setBeginDate(serverUserFaceImage.getBeginDate());
                userInfo.setEndDate(serverUserFaceImage.getEndDate());
            }
            list.add(userInfo);
        });
        pageBean.setRecords(list);
        return pageBean;
    }
    @Override
    public Page<UserInfoDto> pagingQueryServerUserEnable(PageBean<UserInfoDto, String> pageBean) {
        Wrapper<ServerUser> wrapper = new EntityWrapper<>();
        wrapper.eq("l_residential_id",pageBean.getDto());
        wrapper.notIn("i_status",OperationConstant.MINUS_ONE);
        wrapper.eq("i_face_enable", OperationConstant.ONE);
        Page<ServerUser> page = new Page<>(pageBean.getCurrent(),pageBean.getSize());
        page = this.serverUserServiceInterface.selectPage(page, wrapper);
        pageBean.setTotal(page.getTotal());
        List<UserInfoDto> list = new ArrayList<>(page.getRecords().size());
        page.getRecords().forEach(user -> {
            UserInfoDto userInfo = new UserInfoDto();
            userInfo.setId(UserFlagConstant.SERVER_USER_FLAG + user.getId());
            userInfo.setName(user.getName());
            //  获取人脸图片列表
            List<Map<String,Object>> faceCodeList = this.serverUserFaceImageServiceInterface.selectFaceCodeByUserId(user.getId());
            userInfo.setFaceCodeList(faceCodeList);
            List<ServerUserFaceImage> serverUserFaceImages = this.serverUserFaceImageServiceInterface.selectByServerUserId(user.getId());
            if(null != serverUserFaceImages && serverUserFaceImages.size() > 0){
                ServerUserFaceImage serverUserFaceImage = serverUserFaceImages.get(0);
                userInfo.setBeginDate(serverUserFaceImage.getBeginDate());
                userInfo.setEndDate(serverUserFaceImage.getEndDate());
            }
            list.add(userInfo);
        });
        pageBean.setRecords(list);
        return pageBean;
    }

    @Override
    public Page<UserInfoDto> pagingQueryUser(PageBean<UserInfoDto, String> pageBean) {
        //  分页查询服务人员信息
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.like("s_org_position",pageBean.getDto(), SqlLike.RIGHT);
        wrapper.notIn("i_status",OperationConstant.MINUS_ONE);
        wrapper.isNotNull("s_image_uri");
        Page<User> page = new Page<>(pageBean.getCurrent(),pageBean.getSize());
        page = this.userServiceInterface.selectPage(page, wrapper);
        //  获取图片服务器地址
        String imgHost = this.confFeign.getFileServerHost();
        //  设置返回结果
        pageBean.setTotal(page.getTotal());
        List<UserInfoDto> list = new ArrayList<>(page.getRecords().size());
        page.getRecords().forEach(user -> {
            UserInfoDto userInfo = new UserInfoDto();
            userInfo.setId(UserFlagConstant.USER_FLAG + user.getId());
            userInfo.setName(user.getName());
            //  获取人脸Id列表
            List<Map<String,Object>> faceCodeList  = new ArrayList<>();
            Map<String,Object> map = new HashMap<>(3);
            map.put("imgSrc", imgHost + user.getImageUri());
            map.put("imgMd5", user.getFaceCode());
            faceCodeList.add(map);
            userInfo.setFaceCodeList(faceCodeList);
            userInfo.setBeginDate(user.getFaceBeginDate());
            userInfo.setEndDate(user.getFaceEndDate());
            list.add(userInfo);
        });
        pageBean.setRecords(list);
        return pageBean;
    }
    @Override
    public Page<UserInfoDto> pagingQueryUserEnable(PageBean<UserInfoDto, String> pageBean) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.like("s_org_position",pageBean.getDto(), SqlLike.RIGHT);
        wrapper.notIn("i_status",OperationConstant.MINUS_ONE);
        wrapper.isNotNull("s_image_uri");
        wrapper.eq("i_face_enable", OperationConstant.ONE);
        Page<User> page = new Page<>(pageBean.getCurrent(),pageBean.getSize());
        page = this.userServiceInterface.selectPage(page, wrapper);
        String imgHost = this.confFeign.getFileServerHost();
        pageBean.setTotal(page.getTotal());
        List<UserInfoDto> list = new ArrayList<>(page.getRecords().size());
        page.getRecords().forEach(user -> {
            if(user.getFaceEnable() !=null && user.getFaceEnable().equals(OperationConstant.ONE)){
                UserInfoDto userInfo = new UserInfoDto();
                userInfo.setId(UserFlagConstant.USER_FLAG + user.getId());
                userInfo.setName(user.getName());
                List<Map<String,Object>> faceCodeList  = new ArrayList<>();
                Map<String,Object> map = new HashMap<>(3);
                map.put("imgSrc", imgHost + user.getImageUri());
                map.put("imgMd5", user.getFaceCode());
                faceCodeList.add(map);
                userInfo.setFaceCodeList(faceCodeList);
                userInfo.setBeginDate(user.getFaceBeginDate());
                userInfo.setEndDate(user.getFaceEndDate());
                list.add(userInfo);
            }
        });
        pageBean.setRecords(list);
        return pageBean;
    }


}
