package com.sptg.estate.biz.controller;

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.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.estate.api.dto.SimpleUserDto;
import com.sptg.estate.api.dto.UserDto;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.estate.api.vo.DevicesAccessPushVO;
import com.sptg.estate.biz.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * title: UserController
 * package: com.sptg.estate.biz.controller
 * description:住户 控制器
 *
 *
 *
 */
@RestController
public class UserController implements UserFeign {

    private final UserServiceInterface userServiceInterface;
    private final ResidentialServiceInterface residentialServiceInterface;
    private final BuildingServiceInterface buildingServiceInterface;
    private final UnitServiceInterface unitServiceInterface;
    private final FloorServiceInterface floorServiceInterface;
    private final RoomServiceInterface roomServiceInterface;

    @Autowired
    public UserController(UserServiceInterface userServiceInterface, ResidentialServiceInterface residentialServiceInterface, BuildingServiceInterface buildingServiceInterface,
                          UnitServiceInterface unitServiceInterface, FloorServiceInterface floorServiceInterface,RoomServiceInterface roomServiceInterface) {
        this.userServiceInterface = userServiceInterface;
        this.residentialServiceInterface = residentialServiceInterface;
        this.buildingServiceInterface = buildingServiceInterface;
        this.unitServiceInterface = unitServiceInterface;
        this.floorServiceInterface = floorServiceInterface;
        this.roomServiceInterface = roomServiceInterface;
    }

    @Override
    @PostMapping(value = "/user/showUserList")
    public ResultBean<Page<User>> showUserList(@RequestBody UserDto userDto) {
        return this.userServiceInterface.showUserList(userDto);
    }

    @Override
    @PostMapping(value = "/user/pagingByUserIds")
    public ResultBean<Page<User>> pagingByUserIds(@RequestBody UserDto userDto) {
        return this.userServiceInterface.pagingByUserIds(userDto);
    }

    @Override
    @PostMapping(value = "/user/addUser")
    public ResultBean<Boolean> addUser(@RequestBody UserDto userDto) {
        return this.userServiceInterface.addUser(userDto);
    }

    @Override
    @GetMapping(value = "/user/findUserById/{id}")
    public User findUserById(@PathVariable(value = "id") Long id) {
        return this.userServiceInterface.findUserById(id);
    }

    @Override
    @PostMapping(value = "/user/updateUser")
    public ResultBean<Boolean> updateUser(@RequestBody UserDto userDto) {
        return this.userServiceInterface.updateUser(userDto);
    }

    @Override
    @PostMapping(value = "/user/deleteUser")
    public ResultBean<Boolean> deleteUser(@RequestBody UserDto userDto) {
        return this.userServiceInterface.deleteUser(userDto);
    }

    @Override
    @PostMapping(value = "/user/trashOrRecover")
    public ResultBean<Boolean> trashOrRecover(@RequestBody UserDto userDto) {
        return this.userServiceInterface.trashOrRecover(userDto);
    }

    @Override
    @PostMapping(value = "/user/deleteUserList")
    public ResultBean<Boolean> deleteUserList(@RequestBody UserDto userDto) {
        try {
            return this.userServiceInterface.deleteUserList(userDto);
        } catch (Exception e) {
            if(StringUtils.isBlank(e.getMessage())){
                return new ResultBean<>(ResultEnum.ERROR);
            }else{
                return new ResultBean<>("500",e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/user/findListByPosition")
    public ResultBean<User> findListByPosition(@RequestBody UserDto userDto) {
        return this.userServiceInterface.findListByPosition(userDto);
    }

    @Override
    @PostMapping(value = "/user/updateUserCheckState")
    public ResultBean<Boolean> updateUserCheckState(@RequestBody UserDto userDto) {
        return this.userServiceInterface.updateUserCheckState(userDto);
    }

    @Override
    @GetMapping(value = "/user/getUserNameById/{id}")
    public ResultBean<String> getUserNameById(@PathVariable(value = "id") Serializable id) {
        return new ResultBean<>(ResultEnum.SUCCESS,this.userServiceInterface.getUserNameById(id));
    }
    @Override
    @PostMapping(value = "/user/statisticsUserCount")
    public ResultBean<Map<String,Object>> statisticsUserCount(@RequestBody UserDto userDto) {
        return new ResultBean<>(ResultEnum.SUCCESS,this.userServiceInterface.statisticsUserCount(userDto));
    }

    @Override
    @PostMapping(value = "/user/importUserList")
    public ResultBean<Boolean> importUserList(@RequestBody UserDto userDto) {
        return this.userServiceInterface.importUserList(userDto);
    }

    @Override
    @PostMapping(value = "/user/getUserAccount")
    public ResultBean<Map<String, Integer>> getUserAccount(@RequestBody UserDto userDto) {
        Map<String,Integer> map = new HashMap<>(2);
        userDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.userServiceInterface.getUserAccount(userDto);
        map.put("totalCount",totalCount);
        userDto.setIsAllType(OperationConstant.TWO);
        int monthCount = this.userServiceInterface.getUserAccount(userDto);
        map.put("monthCount",monthCount);
        return new ResultBean<>(ResultEnum.SUCCESS,map);
    }

    @Override
    @PostMapping(value = "/user/getUserCount")
    public int getUserCount(@RequestBody UserDto userDto) {
        userDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.userServiceInterface.getUserAccount(userDto);
        return totalCount;
    }

    @Override
    @PostMapping(value = "/user/addOrUpdateUserFaceImage")
    public ResultBean<Boolean> addOrUpdateUserFaceImage(@RequestBody UserDto userDto) {
        return this.userServiceInterface.addOrUpdateUserFaceImage(userDto);
    }

    /**
     * 仅进行简单的人脸设置，不下发人脸
     * @param userDto
     * @return
     */
    @Override
    @PostMapping(value = "/user/simpleAddOrUpdateUserFaceImage")
    public ResultBean<Boolean> simpleAddOrUpdateUserFaceImage(@RequestBody UserDto userDto) {
        return this.userServiceInterface.simpleAddOrUpdateUserFaceImage(userDto);
    }

    /**
     * 文祥添加，只执行下发人脸（启用或者禁用）
     * @param userDto
     * @return
     */
    @Override
    @PostMapping(value = "/user/sendUserFaceImage")
    public ResultBean<Boolean> sendUserFaceImage(@RequestBody UserDto userDto) {
        return this.userServiceInterface.sendUserFaceImage(userDto);
    }

    @Override
    @PostMapping(value = "/user/deleteUserFaceImageBatch")
    public ResultBean<Boolean> deleteUserFaceImageBatch(@RequestBody List<String> ids) {
        List<Long> idList = ids.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
        return this.userServiceInterface.deleteUserFaceImageBatch(idList);
    }

    @Override
    @PostMapping(value = "/user/issueUserFaceImageBatch")
    public ResultBean<Boolean> issueUserFaceImageBatch(@RequestBody List<SimpleUserDto> simpleUserDtoList) {
        if(simpleUserDtoList == null || simpleUserDtoList.size() == 0){
            return new ResultBean<>(ResultEnum.SUCCESS, false);
        }
        return this.userServiceInterface.issueUserFaceImageBatch(simpleUserDtoList);
    }

    @Override
    @PostMapping(value = "/user/deleteUserCardBatch")
    public ResultBean<Boolean> deleteUserCardBatch(@RequestBody List<String> ids) {
        List<Long> idList = ids.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
        return this.userServiceInterface.deleteUserCardBatch(idList);
    }

    @Override
    @PostMapping(value = "/user/enableUserCardBatch")
    public ResultBean<Boolean> enableUserCardBatch(@RequestBody List<String> ids) {
        List<Long> idList = ids.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
        return this.userServiceInterface.enableUserCardBatch(idList);
    }
    @Override
    @PostMapping(value = "/user/accessDevicesManualPush")
    public ResultBean<Boolean> accessDevicesManualPush(@RequestBody DevicesAccessPushVO devicesAccessPushVO) {
        return this.userServiceInterface.accessDevicesManualPush(devicesAccessPushVO);
    }

    @Override
    @PostMapping(value = "/user/getListByRoomId")
    public List<User> getListByRoomId(@RequestBody List<Long> roomIds) {
        return this.userServiceInterface.getListByRoomId(roomIds);
    }

    @Override
    @PostMapping(value = "/user/pagingByRoomId")
    public Page<User> pagingByRoomId(@RequestBody UserDto userDto) {
        return this.userServiceInterface.pagingByRoomId(userDto);
    }


    @Override
    @PostMapping(value = "/user/userCountForType")
    public Map<String,Object> userCountForType(@RequestBody UserDto userDto) {
        return this.userServiceInterface.userCountForType(userDto);
    }

    @Override
    @PostMapping(value = "/user/UserCountForCreateType")
    public Map<String,Object> userCountForCreateType(@RequestBody UserDto userDto) {
        return this.userServiceInterface.userCountForCreateType(userDto);
    }

    @Override
    @PostMapping(value = "/user/getListByUserId")
    public List<User> getListByUserId(@RequestBody List<Long> userIds) {
        return this.userServiceInterface.getListByUserId(userIds);
    }

    @Override
    @PostMapping(value = "/user/deleteUserAndRelationship")
    public ResultBean<Boolean> deleteUserAndRelationship(@RequestBody UserDto userDto) {
        return this.userServiceInterface.deleteUserAndRelationship(userDto);
    }

    @Override
    @PostMapping(value = "/user/checkByNameAndRoomId")
    public ResultBean<Boolean> checkByNameAndRoomId(@RequestBody UserDto userDto) {
        return this.userServiceInterface.checkByNameAndRoomId(userDto);
    }

    @Override
    @GetMapping(value = "/user/get/{roomId}/{name}")
    public User getByRoomIdAndUserId(@PathVariable(value = "roomId") Long roomId, @PathVariable(value = "name") String name) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("l_room_id",roomId);
        wrapper.eq("s_name",name);
        List<User> list = this.userServiceInterface.selectList(wrapper);
        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    @PostMapping(value = "/user/findUserByCondition")
    public User findUserByCondition(@RequestBody UserDto userDto) {
        return this.userServiceInterface.findUserByCondition(userDto);
    }

    @Override
    @PostMapping(value = "/user/findUserByName")
    public User findUserByName(@RequestBody UserDto userDto) {
        return this.userServiceInterface.getUserByNameAndRoomId(userDto.getName(),userDto.getRoomId());
    }

    @Override
    @PostMapping(value = "/user/findUserTotalCount")
    public Integer findUserTotalCount(@RequestBody UserDto userDto) {
        return this.userServiceInterface.findUserTotalCount(userDto);
    }

    @Override
    @PostMapping(value = "/user/getUserPage")
    public ResultBean<Page> getUserPage(@RequestBody PageBean<User, UserDto> pageBean) {
        return this.userServiceInterface.getUserPage(pageBean);
    }

    @Override
    @PostMapping(value = "/user/updateEntity")
    public boolean updateEntity(@RequestBody User user) {
        return this.userServiceInterface.updateById(user);
    }

    @Override
    @GetMapping(value = "/user/getByOldId/{oldId}")
    public User getByOldId(@PathVariable(value = "oldId") String oldId) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("old_id",oldId);
        return this.userServiceInterface.selectOne(wrapper);
    }

    @Override
    @GetMapping(value = "/user/getByOldCustomerId/{customerId}/{roomId}")
    public User getByOldCustomerId(@PathVariable(value = "customerId") String customerId,@PathVariable(value = "roomId")Long roomId) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("old_customer_id",customerId);
        wrapper.eq("l_room_id",roomId);
        return this.userServiceInterface.selectOne(wrapper);
    }

    @Override
    @PostMapping(value = "/user/faceEnable")
    public boolean faceEnable(@RequestBody User user) {
        if (this.updateEntity(user)){
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            ResultBean<Boolean> resultBean = this.addOrUpdateUserFaceImage(userDto);
            return resultBean.getData();
        }else{
            return false;
        }
    }

    @Override
    @GetMapping(value = "/user/getByRoomIdAndUserMobile/{roomId}/{mobile}")
    public User getByRoomIdAndUserMobile(@PathVariable(value = "roomId") Long roomId, @PathVariable(value = "mobile")String mobile) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("l_room_id",roomId);
        wrapper.eq("s_tel",mobile);
        return this.userServiceInterface.selectOne(wrapper);
    }

    @Override
    @PostMapping(value = "/user/getListByCondition")
    public List<User> getListByCondition(@RequestBody UserDto dto) {
        return userServiceInterface.getListByCondition(dto);
    }

    @Override
    @PostMapping(value = "/user/updateUserList")
    public boolean updateUserList(@RequestBody List<User> userList) {
        return userServiceInterface.updateBatchById(userList);
    }

    /**
     * 同步亲邻智能物联网平台住户数据
     * @return
     */
    @GetMapping("/user/syncUser")
    public int syncUser() throws ParseException {

        int result = 0;
//		IResidentialService residentialService =new ResidentialServiceImpl();
        RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
        ResponseEntity responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
        headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
        headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", 1);
        map.put("pageSize", 36000);

        HttpEntity<String> requestEntity = new HttpEntity<String>(JsonUtils.objectToJson(map), headers);
        ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
        };
        String url = "https://qiotapi.qinlinkeji.com/qiotapi/appuser/findListGroupByByUser?sessionId=admin:2c94801075fcb73801763afe3fff0414";
        URI uri = URI.create(url);
        responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


        Map body = (Map) responseEntity.getBody();
        Map data = (Map) body.get("data");
        List<Map> list = (List<Map>) data.get("list");
        for(int i = 0;i<list.size();i++){
            int res = syncUserDetailById(list.get(i).get("id").toString());
            result = res+result;
        }


        return result;
    }


    private int syncUserDetailById(String userId) throws ParseException {
        int result = 0;
        RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
        ResponseEntity responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
        headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
        headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
        Map<String, Object> map = new HashMap<>();


        HttpEntity<String> requestEntity = new HttpEntity<String>(JsonUtils.objectToJson(map), headers);
        ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
        };
        String url = "https://qiotapi.qinlinkeji.com/app/user/findDetailById?sessionId=admin:2c94801075fcb73801763afe3fff0414&id="+userId;
        URI uri = URI.create(url);
        responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);

        Map body =(Map) responseEntity.getBody();
        Map data = (Map) body.get("data");

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        User user = new User();
//        user.setOldId(userId);
//        user.setCreateDate(sf.parse(data.get("gmtCreate").toString()));
//        user.setIdCard(data.get("idNum").toString());
//        user.setTel(data.get("mobile").toString());
//        user.setSex(Integer.valueOf(data.get("sex").toString()));
//        user.setName(data.get("userName").toString());

        List<Map> roomList =(List<Map>)data.get("appUserCommunityList");



            for(int i=0;i<roomList.size();i++){
                User user = new User();
                user.setOldId(userId);
                if(data.get("gmtCreate")!=null)
                user.setCreateDate(sf.parse(data.get("gmtCreate").toString()));
                if(data.get("idNum")!=null)
                user.setIdCard(data.get("idNum").toString());
                if((data.get("mobile")!=null))
                user.setTel(data.get("mobile").toString());
                if(data.get("sex")!=null)
                user.setSex(Integer.valueOf(data.get("sex").toString()));
               if(data.get("userName")!=null)
                user.setName(data.get("userName").toString());
               if(roomList.get(i).get("provinceId")!=null)
                user.setRegionProvince(roomList.get(i).get("provinceId").toString());
               if(roomList.get(i).get("cityId")!=null)
                user.setRegionCity(roomList.get(i).get("cityId").toString());
                if(roomList.get(i).get("districtId")!=null)
                user.setRegionArea(roomList.get(i).get("districtId").toString());

                String residentialOldId = roomList.get(i).get("communityId").toString();
                Residential residential = residentialServiceInterface.getResidentialByOldId(residentialOldId);
                if (residential == null){
                    continue;
                }
                user.setResidentialId(residential.getId());
                user.setResidentialName(residential.getName());

              UserDto userDto = new UserDto();
              userDto.setOldId(user.getOldId());
              userDto.setResidentialId(residential.getId());
                User user11 = this.userServiceInterface.findUserByCondition(userDto);
                if(user11== null){
                   this.userServiceInterface.insert(user);
                   ++result;
                }


            }

        return result;
    }
}
