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.*;
import com.sptg.estate.api.entity.Building;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.entity.Room;
import com.sptg.estate.api.feigns.BuildingFeign;
import com.sptg.estate.biz.service.*;
import org.apache.commons.lang.StringUtils;
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.util.Assert;
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: BuildingController
 * package: com.sptg.estate.biz.controller
 * description: 楼栋 控制器
 *
 *
 *
 */
@RestController
public class BuildingController implements BuildingFeign {

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


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


    @Override
    @PostMapping(value = "/building/showBuildingList")
    public ResultBean<Page<Building>> showBuildingList(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.showBuildingList(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/addBuilding")
    public ResultBean<Building> addBuilding(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.addBuilding(buildingDto);
    }

    @Override
    @GetMapping(value = "/building/findBuildingById/{id}")
    public Building findBuildingById(@PathVariable(value = "id")Long id) {
        return this.buildingServiceInterface.findBuildingById(id);
    }

    @Override
    @PostMapping(value = "/building/updateBuilding")
    public ResultBean<Boolean> updateBuilding(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.updateBuilding(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/deleteBuilding")
    public ResultBean<Boolean> deleteBuilding(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.deleteBuilding(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/trashOrRecover")
    public ResultBean<Boolean> trashOrRecover(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.trashOrRecover(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/deleteBuildingList")
    public ResultBean<Boolean> deleteBuildingList(@RequestBody BuildingDto buildingDto) {
        try {
            return  this.buildingServiceInterface.deleteBuildingList(buildingDto);
        } catch (Exception e) {
            if(StringUtils.isBlank(e.getMessage())){
                return new ResultBean<>(ResultEnum.ERROR);
            }else{
                return  new ResultBean<>("500",e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/building/findListByPosition")
    public ResultBean<Building> findListByPosition(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.findListByPosition(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/importBuildingList")
    public ResultBean<Boolean> importBuildingList(@RequestBody BuildingDto buildingDto) {
        return  this.buildingServiceInterface.importBuildingList(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/getByUnitId")
    public ResultBean<Building> getByUnitId(@RequestBody Long unitId) {
        return this.buildingServiceInterface.getByUnitId(unitId);
    }

    @Override
    @PostMapping(value = "/building/getBuildingAccount")
    public ResultBean<Map<String, Integer>> getBuildingAccount(@RequestBody BuildingDto buildingDto) {
        Map<String,Integer> map = new HashMap<>(2);
        buildingDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.buildingServiceInterface.getBuildingAccount(buildingDto);
        map.put("totalCount",totalCount);
        buildingDto.setIsAllType(OperationConstant.TWO);
        int monthCount = this.buildingServiceInterface.getBuildingAccount(buildingDto);
        map.put("monthCount",monthCount);
        return new ResultBean<>(ResultEnum.SUCCESS,map);
    }

    @Override
    @PostMapping(value = "/building/getListByBuildingId")
    public List<Building> getListByBuildingId(@RequestBody List<Long> buildingIds) {
        return this.buildingServiceInterface.getListByBuildingId(buildingIds);
    }

    @Override
    @PostMapping(value = "/building/pagingByIds")
    public Page<Building> pagingByIds(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.pagingByIds(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/findBuildingByCondition")
    public int findBuildingByCondition(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.findBuildingByCondition(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/findBuildingByNameAndNumber")
    public Building findBuildingByNameAndNumber(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.findBuildingByNameAndNumber(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/addBuildingByImport")
    public Building addBuildingByImport(@RequestBody Building building) {
        return this.buildingServiceInterface.addBuildingByImport(building);
    }

    @Override
    @PostMapping(value = "/building/updateEntity")
    public boolean updateEntity(@RequestBody Building building) {
        return this.buildingServiceInterface.updateById(building);
    }

    @Override
    @PostMapping(value = "/building/updateBuildingList")
    public boolean updateBuildingList(@RequestBody List<Building> buildingList) {
        return this.buildingServiceInterface.updateBatchById(buildingList);
    }

    @Override
    @PostMapping(value = "/building/getListByLikeName")
    public List<Building> getListByLikeName(@RequestBody BuildingDto dto) {
        return this.buildingServiceInterface.getListByLikeName(dto);
    }

    @Override
    @GetMapping(value = "/building/getByOldId/{oldId}")
    public Building getByOldId(@PathVariable(value = "oldId") String oldId) {
        Wrapper<Building> wrapper = new EntityWrapper<>();
        wrapper.eq("l_old_id",oldId);
        return this.buildingServiceInterface.selectOne(wrapper);
    }

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

    @Override
    @PostMapping(value = "/building/getListByCondition")
    public List<Building> getListByCondition(@RequestBody BuildingDto buildingDto) {
        return this.buildingServiceInterface.getListByCondition(buildingDto);
    }

    @Override
    @PostMapping(value = "/building/addBuildingBatch")
    public boolean addBuildingBatch(@RequestBody BuildingBatchAdd batchAdd) {

        Residential residential = residentialServiceInterface.findResidentialById(batchAdd.getResidentialId());
        Assert.notNull(residential, "找不到该小区！");
//        Agency agency = agencyServiceInterface.findAgencyById(residential.getAgencyId());

        // 遍历新建楼栋
        for (int i = batchAdd.getBuildingBegin(); i <= batchAdd.getBuildingEnd(); i++) {
            BuildingDto buildingDto = new BuildingDto();
            buildingDto.setResidentialId(batchAdd.getResidentialId());
            buildingDto.setResidentialName(residential.getName());
            // 楼栋命名
            String buildingName = "";
            if (StringUtils.isNotBlank(batchAdd.getBuildingPrefix())){
                buildingName += batchAdd.getBuildingPrefix();
            }
            buildingName += (i + "");
            if (StringUtils.isNotBlank(batchAdd.getBuildingSuffix())){
                buildingName += batchAdd.getBuildingSuffix();
            }else{
                buildingName += "栋";
            }
            buildingDto.setName(buildingName);
            ResultBean<Building> buildingResultBean = this.addBuilding(buildingDto);
            if (null != buildingResultBean && buildingResultBean.getData() != null){
                // 遍历新建单元
                for (int j = batchAdd.getUnitBegin(); j <= batchAdd.getUnitEnd(); j++) {
                    UnitDto unitDto = new UnitDto();
                    unitDto.setBuildingId(buildingDto.getId());
                    unitDto.setBuildingName(buildingDto.getName());
                    unitDto.setResidentialId(residential.getId());
                    unitDto.setResidentialName(residential.getName());

                    // 单元命名
                    String unitName = "";
                    if (StringUtils.isNotBlank(batchAdd.getUnitPrefix())){
                        unitName += batchAdd.getUnitPrefix();
                    }
                    unitName += (j + "");
                    if (StringUtils.isNotBlank(batchAdd.getUnitSuffix())){
                        unitName += batchAdd.getUnitSuffix();
                    }else{
                        unitName += "单元";
                    }
                    unitDto.setName(unitName);
                    ResultBean<UnitDto> unitDtoResultBean = unitServiceInterface.addUnit(unitDto);
                    if (null != unitDtoResultBean && unitDtoResultBean.getData() != null){
                        // 遍历新建楼层
                        for (int k = batchAdd.getFloorBegin(); k <= batchAdd.getFloorEnd(); k++) {
                            //跳过排除楼层
                            if (StringUtils.isNotBlank(batchAdd.getFloorExclude()) && (batchAdd.getFloorExclude()).contains((k + ""))){
                                continue;
                            }
                            FloorDto floorDto = new FloorDto();
                            floorDto.setResidentialId(residential.getId());
                            floorDto.setResidentialName(residential.getName());
                            floorDto.setBuildingId(buildingDto.getId());
                            floorDto.setBuildingName(buildingDto.getName());
                            floorDto.setUnitId(unitDto.getId());
                            floorDto.setUnitName(unitName);

                            // 楼层命名
                            String floorName = "";
                            if (StringUtils.isNotBlank(batchAdd.getFloorPrefix())){
                                floorName += batchAdd.getFloorPrefix();
                            }
                            floorName += (k + "");
                            if (StringUtils.isNotBlank(batchAdd.getFloorSuffix())){
                                floorName += batchAdd.getFloorSuffix();
                            }else {
                                floorName += "层";
                            }
                            floorDto.setName(floorName);

                            ResultBean<FloorDto> floorDtoResultBean = floorServiceInterface.addFloor(floorDto);
                            if (null != floorDtoResultBean && floorDtoResultBean.getData() != null){
                                // 遍历新建房间/房屋
                                for (int m = batchAdd.getRoomBegin(); m <= batchAdd.getRoomEnd(); m++) {
                                    // 跳过排除楼层
                                    if (StringUtils.isNotBlank(batchAdd.getRoomExclude()) && (batchAdd.getRoomExclude()).contains((m + ""))){
                                        continue;
                                    }
                                    RoomDto roomDto = new RoomDto();
                                    roomDto.setResidentialId(residential.getId());
                                    roomDto.setResidentialName(residential.getName());
                                    roomDto.setBuildingId(buildingDto.getId());
                                    roomDto.setBuildingName(buildingDto.getName());
                                    roomDto.setUnitId(unitDto.getId());
                                    roomDto.setUnitName(unitDto.getName());
                                    roomDto.setFloorId(floorDto.getId());
                                    roomDto.setFloorName(floorName);

                                    // 房屋命名
                                    String roomName = "";
                                    if (StringUtils.isNotBlank(batchAdd.getRoomPrefix())){
                                        roomName += batchAdd.getRoomPrefix();
                                    }

                                    roomName += (k + (m < 10 ? "0" : "") + m);
                                    if (StringUtils.isNotBlank(batchAdd.getRoomSuffix())){
                                        roomName += batchAdd.getRoomSuffix();
                                    }
                                    roomDto.setName(roomName);
                                    ResultBean<Room> roomResultBean = roomServiceInterface.addRoom(roomDto);
                                    if (null != roomResultBean && null != roomResultBean.getData()){
                                        // 更新房屋orgPosition
                                    }
                                }
                            }
                            //更新楼层的房间数
/*                            Integer roomNumber = floor.getRoomNumber();
                            if ("null".equals(roomNumber + "")){
                                roomNumber = 0;
                            }
                            floor.setRoomNumber(roomNumber + roomCount);
                            floorService.updateById(floor);*/
                        }
                        //更新单元的楼层数、房间数
                       /* Integer floorNumber = unit.getFloorNumber();
                        if ("null".equals(floorNumber + "")){
                            floorNumber = 0;
                        }
                        unit.setFloorNumber(floorNumber + floorCount);
                        Integer roomNumber = unit.getRoomNumber();
                        if ("null".equals(roomNumber + "")){
                            roomNumber = 0;
                        }
                        unit.setRoomNumber(roomNumber + roomCount * floorCount);
                        unitService.updateById(unit);*/
                    }
                }
                // 更新楼栋的单元数、楼层数、房间数
                /*Integer unitNumber = building.getUnitNumber();
                if ("null".equals(unitNumber + "")){
                    unitNumber = 0;
                }
                building.setUnitNumber(unitNumber + unitCount);
                Integer floorNumber = building.getFloorNumber();
                if ("null".equals(floorNumber + "")){
                    floorNumber = 0 ;
                }
                building.setFloorNumber(floorNumber + floorCount * unitCount);
                Integer roomNumber = building.getRoomNumber();
                if ("null".equals(roomNumber + "")){
                    roomNumber = 0 ;
                }
                building.setRoomNumber(roomNumber + roomCount * floorCount * unitCount);

                this.updateById(building);*/
            }
        }

        return true;
    }


    /**
     * 同步亲邻智能物联网平台楼栋数据
     * @return
     */
    @GetMapping("/building/sync")
    public int syncBuilding() {
        List<Residential> residentialList = this.residentialServiceInterface.getList();
        int addResult = 0;
        int updateResult = 0;

        for(int j=0;j<residentialList.size();j++){
            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=2760822c16041156819701506e1f0df2b6797f5010bb8a47e5c8d932fa360e");
            Map<String, Object> map = new HashMap<>();


            HttpEntity requestEntity = new HttpEntity<>(JsonUtils.objectToJson(map), headers);
            ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
            };
            if(residentialList.get(j).getOldId()==null){
                continue;
            }
            String url = "https://qiotapi.qinlinkeji.com/admin/community/findBuildingList?sessionId=admin:2c94812e75fa974901762dc0b4b503ad&communityId="+residentialList.get(j).getOldId();
            URI uri = URI.create(url);
            responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


            Map map1 = (Map) responseEntity.getBody();
            List<Map> list = (List<Map>) map1.get("data");
//		List<Map> list = (List<Map>) map2.get("list");
//		IResidentialService residentialService = new ResidentialServiceImpl();
            for (int i = 0; i < list.size(); i++) {
                Building building = new Building();
                Integer integer = (Integer) list.get(i).get("id");
                building.setOldId(Long.valueOf(integer.toString()));
                building.setName((String)list.get(i).get("buildingFullName"));
                building.setResidentialId(residentialList.get(j).getId());
                building.setResidentialName(residentialList.get(j).getName());
                Building building1 = buildingServiceInterface.findByOldId(building.getOldId().toString());

                if (building1 != null) {
                    building.setId(building1.getId());
                    int result1 = this.buildingServiceInterface.updateBuildingBySync(building);
                    updateResult = result1+ updateResult;
                } else {
                    int result1= this.buildingServiceInterface.addBuildingBySync(building);
                    addResult = result1+ addResult;
                    Residential residential = residentialList.get(j);
                    residential.setBuildingNumber(residential.getBuildingNumber()+1);
                    residentialServiceInterface.updateResidentialEntity(residential);
                }


            }


        }
        System.out.println("update:"+updateResult+"   "+"add:"+addResult);
        return updateResult+addResult;
    }

    @PostMapping(value = "/building/bindNewId")
    public void bindNewId(){
        List<Building> list = this.buildingServiceInterface.getListByCondition(new BuildingDto());
        list.parallelStream().forEach(building -> {
            Long residentialOldId = building.getResidentialOldId();
            Residential residential = this.residentialServiceInterface.getResidentialByOldId(residentialOldId.toString());
            building.setResidentialId(residential.getId());
            buildingServiceInterface.updateById(building);
        });
    }

    @PostMapping(value = "/building/setOrgPosition")
    public void setOrgPosition(){
        BuildingDto buildingDto = new BuildingDto();
        Page<Building> page = new Page<>();
        page.setSize(50000);
        page.setCurrent(1);
        buildingDto.setPage(page);
        ResultBean<Page<Building>> pageResultBean = this.buildingServiceInterface.showBuildingList(buildingDto);
        List<Building> records = pageResultBean.getData().getRecords();
        for(int i=0;i<records.size();i++){
            Building building = records.get(i);
            Long residentialId = building.getResidentialId();
            Residential residential = this.residentialServiceInterface.findResidentialById(residentialId);
            if(null == residential){
                System.out.println(records.get(i)+"  "+building.getId());
                continue;
            }
            building.setOrgPosition(residential.getOrgPosition()+building.getId()+"/");
            this.buildingServiceInterface.updateById(building);
        }
    }

}
