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.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.ResidentialDto;
import com.sptg.estate.api.dto.RoomDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.RoomFeign;
import com.sptg.estate.biz.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.Roman;
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.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * title: RoomController
 * package: com.sptg.estate.biz.controller
 * description: 房间 控制器
 *
 *
 *
 */
@RestController
public class RoomController implements RoomFeign {

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

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


    @Override
    @PostMapping(value = "/room/showRoomList")
    public ResultBean<Page<Room>> showRoomList(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.showRoomList(roomDto);
    }

    @Override
    @PostMapping(value = "/room/addRoom")
    public ResultBean<Room> addRoom(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.addRoom(roomDto);
    }

    @Override
    @GetMapping(value = "/room/findRoomById/{id}")
    public Room findRoomById(@PathVariable(value = "id")Long id) {
        return this.roomServiceInterface.findRoomById(id);
    }

    @Override
    @PostMapping(value = "/room/updateRoom")
    public ResultBean<Boolean> updateRoom(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.updateRoom(roomDto);
    }

    @Override
    @PostMapping(value = "/room/deleteRoom")
    public ResultBean<Boolean> deleteRoom(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.deleteRoom(roomDto);
    }

    @Override
    @PostMapping(value = "/room/trashOrRecover")
    public ResultBean<Boolean> trashOrRecover(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.trashOrRecover(roomDto);
    }

    @Override
    @PostMapping(value = "/room/deleteRoomList")
    public ResultBean<Boolean> deleteRoomList(@RequestBody RoomDto roomDto) {
        try {
            return  this.roomServiceInterface.deleteRoomList(roomDto);
        } catch (Exception e) {
            if(StringUtils.isBlank(e.getMessage())){
                return new ResultBean<>(ResultEnum.ERROR);
            }else{
                return  new ResultBean<>("500",e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/room/findListByPosition")
    public ResultBean<Room> findListByPosition(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.findListByPosition(roomDto);
    }

    @Override
    @PostMapping(value = "/room/importRoomList")
    public ResultBean<Boolean> importRoomList(@RequestBody RoomDto roomDto) {
        return  this.roomServiceInterface.importRoomList(roomDto);
    }

    @Override
    @PostMapping(value = "/room/getByUnitId")
    public ResultBean<Room> getByUnitId(@RequestBody Long unitId) {
        return this.roomServiceInterface.getByUnitId(unitId);
    }

    @Override
    @PostMapping(value = "/room/getRoomAccount")
    public ResultBean<Map<String, Integer>> getRoomAccount(@RequestBody RoomDto roomDto) {
        Map<String,Integer> map = new HashMap<>(2);
        roomDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.roomServiceInterface.getRoomAccount(roomDto);
        map.put("totalCount",totalCount);
        roomDto.setIsAllType(OperationConstant.TWO);
        int monthCount = this.roomServiceInterface.getRoomAccount(roomDto);
        map.put("monthCount",monthCount);
        return new ResultBean<>(ResultEnum.SUCCESS,map);
    }

    @Override
    @PostMapping(value = "/room/getListByRoomId")
    public List<Room> getListByRoomId(@RequestBody List<Long> roomIds) {
        return this.roomServiceInterface.getListByRoomId(roomIds);
    }

    @Override
    @PostMapping(value = "/room/pagingByIds")
    public Page<Room> pagingByIds(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.pagingByIds(roomDto);
    }

    @Override
    @PostMapping(value = "/room/findRoomByCondition")
    public int findRoomByCondition(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.findRoomByCondition(roomDto);
    }

    @Override
    @PostMapping(value = "/room/findRoomByNameAndNumber")
    public Room findRoomByNameAndNumber(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.findRoomByNameAndNumber(roomDto);
    }

    @Override
    @PostMapping(value = "/room/addRoomByImport")
    public Room addRoomByImport(@RequestBody Room room) {
        return this.roomServiceInterface.addRoomByImport(room);
    }

    @Override
    @PostMapping(value = "/room/updateEntity")
    public boolean updateEntity(@RequestBody Room room) {
        return this.roomServiceInterface.updateById(room);
    }

    @Override
    @PostMapping(value = "/room/updateRoomList")
    public boolean updateRoomList(@RequestBody List<Room> roomList){
        return this.roomServiceInterface.updateBatchById(roomList);
    }

    @Override
    @PostMapping(value = "/room/getListByLikeName")
    public List<Room> getListByLikeName(@RequestBody RoomDto dto) {
        return this.roomServiceInterface.getListByLikeName(dto);
    }

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

    @Override
    @GetMapping(value = "/room/getByRoomNumber/{houseNumber}")
    public Room getByRoomNumber(@PathVariable(value = "houseNumber") String houseNumber) {
        Wrapper<Room> wrapper = new EntityWrapper<>();
        wrapper.eq("s_house_number",houseNumber);
        wrapper.eq("i_status",OperationConstant.ZERO);
        return this.roomServiceInterface.selectOne(wrapper);
    }

    @Override
    @PostMapping(value = "/room/getListByCondition")
    public List<Room> getListByCondition(@RequestBody RoomDto roomDto) {
        return this.roomServiceInterface.getListByCondition(roomDto);
    }

    @Override
    @GetMapping(value = "/room/getListByUnitId/{unitId}")
    public List<Room> getListByUnitId(@PathVariable(value = "unitId") Long unitId) {
        Wrapper<Room> wrapper = new EntityWrapper<>();
        wrapper.eq("l_unit_id", unitId);
        wrapper.eq("i_status",OperationConstant.ZERO);
        return this.roomServiceInterface.selectList(wrapper);
    }

    @Override
    @GetMapping(value = "/room/addRoomSync")
    public int addRoomSync(@RequestBody Room room) {
        return this.roomServiceInterface.addRoomSync(room);
    }

    /**
     * 同步亲邻智能物联网平台房间数据
     * @return
     */
    @GetMapping(value = "/room/sync")
    public int roomSync() {
        //获取楼层列表
        List<Floor> floorList = floorServiceInterface.getListByLikeName(null);

        int addResult =0;
        int updateResult = 0;
        for (int j = 0; j < floorList.size(); j++) {
            //当前楼层
            Floor floor = floorList.get(j);
            //当前单元
            Unit unit = this.unitServiceInterface.findUnitById(floor.getUnitId());
            //当前楼栋
            Building building = this.buildingServiceInterface.findBuildingById(floor.getBuildingId());
            //当前小区
            Residential residential = this.residentialServiceInterface.findResidentialById(floor.getResidentialId());
            RestTemplate restTemplate = new RestTemplate();
            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<>();
//		communityId: "9176"
            map.put("communityId", residential.getOldId());
            map.put("id", floor.getOldId());
            map.put("nodeType", 3);
            map.put("pageNum", 1);
            map.put("pageSize", 100000);

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


            Map map1 = (Map) responseEntity.getBody();
            Map map2 = (Map) map1.get("data");
            List<Map> list = (List<Map>) map2.get("list");
//		IResidentialService residentialService = new ResidentialServiceImpl();
            for (int i = 0; i < list.size(); i++) {
                Room room = new Room();
                room.setOldId(list.get(i).get("houseId").toString());
                room.setName((String)list.get(i).get("houseName"));
                room.setFloorId(floor.getId());
                room.setFloorName(floor.getName());
                room.setUnitId(floor.getUnitId());
                room.setUnitName(floor.getUnitName());
                room.setBuildingId(floor.getBuildingId());
                room.setBuildingName(floor.getBuildingName());
                room.setResidentialId(floor.getResidentialId());
                room.setResidentialName(floor.getResidentialName());

                Room room1 = this.roomServiceInterface.findByOldId(room.getOldId());
                if(room1 != null){
                    room.setId(room1.getId());
                    int result1 = this.roomServiceInterface.updateRoomSync(room);
                    updateResult = updateResult + result1;
                }else{
                    int result1 = this.roomServiceInterface.addRoomSync(room);
                    if(result1>0){
                        //楼层房间数加1
                        floor.setRoomNumber(floor.getRoomNumber()+1);
                        floorServiceInterface.updateFloorSync(floor);
                        //单元房间数加1
                        unit.setRoomNumber(unit.getRoomNumber()+1);
                        unitServiceInterface.updateUnitSync(unit);
                        //楼栋房间数加1
                        building.setRoomNumber(building.getRoomNumber()+1);
                        buildingServiceInterface.updateBuildingBySync(building);
                        //社区房间数加1
                        residential.setRoomNumber(residential.getRoomNumber()+1);
                        residentialServiceInterface.updateResidentialEntity(residential);
                    }
                    addResult = addResult + result1;
                }

            }
            System.out.println("楼层id为"+floor.getOldId()+"的房间列表："+list);
        }
        return addResult+updateResult;

    }

    @PostMapping(value = "/room/bindNewId")
    public void  bindNewId(){
        List<Room> rooms = roomServiceInterface.selectList(new EntityWrapper<>(new Room()));
        System.out.println(rooms.size());
        rooms.parallelStream().forEach(room -> {
            Residential residential = residentialServiceInterface.getResidentialByOldId(room.getResidentialOldId().toString());
            room.setResidentialId(residential.getId());
            Building building = buildingServiceInterface.findByOldId(room.getBuildingOldId().toString());
            room.setBuildingId(building.getId());
            Unit unit = unitServiceInterface.findByOldId(room.getUnitOldId().toString());
            room.setUnitId(unit.getId());
            Floor floor = floorServiceInterface.findByOldId(room.getFloorOldId().toString());
            room.setFloorId(floor.getId());
            roomServiceInterface.updateById(room);
        });
    }

    @PostMapping(value = "/room/setOrgPosition")
    public void  setOrgPosition(){
        List<Room> rooms = roomServiceInterface.selectList(new EntityWrapper<>(new Room()));
        System.out.println(rooms.size());
        rooms.parallelStream().forEach(room -> {
            Floor floor = floorServiceInterface.findFloorById(room.getFloorId());
            if(floor !=null){
                room.setOrgPosition(floor.getOrgPosition()+room.getId()+"/");
            }else{
                room.setOrgPosition("暂无");
                System.out.println(room.toString()+"没有设置orgPosition");
            }

            roomServiceInterface.updateById(room);
        });
    }

}
