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.FloorDto;
import com.sptg.estate.api.entity.Building;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.entity.Floor;
import com.sptg.estate.api.entity.Unit;
import com.sptg.estate.api.feigns.FloorFeign;
import com.sptg.estate.biz.service.BuildingServiceInterface;
import com.sptg.estate.biz.service.ResidentialServiceInterface;
import com.sptg.estate.biz.service.FloorServiceInterface;
import com.sptg.estate.biz.service.UnitServiceInterface;
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.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.transaction.Transactional;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * title: FloorController
 * package: com.sptg.estate.biz.controller
 * description: 楼层 控制器
 */

@RestController
public class FloorController implements FloorFeign {

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


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

    @Override
    @PostMapping(value = "/floor/showFloorList")
    public ResultBean<Page<Floor>> showFloorList(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.showFloorList(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/addFloor")
    public ResultBean<FloorDto> addFloor(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.addFloor(floorDto);
    }

    @Override
    @GetMapping(value = "/floor/findFloorById/{id}")
    public Floor findFloorById(@PathVariable(value = "id") Long id) {
        return this.floorServiceInterface.findFloorById(id);
    }

    @Override
    @PostMapping(value = "/floor/updateFloor")
    public ResultBean<Boolean> updateFloor(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.updateFloor(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/deleteFloor")
    public ResultBean<Boolean> deleteFloor(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.deleteFloor(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/trashOrRecover")
    public ResultBean<Boolean> trashOrRecover(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.trashOrRecover(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/deleteFloorList")
    public ResultBean<Boolean> deleteFloorList(@RequestBody FloorDto floorDto) {
        try {
            return this.floorServiceInterface.deleteFloorList(floorDto);
        } catch (Exception e) {
            if (StringUtils.isBlank(e.getMessage())) {
                return new ResultBean<>(ResultEnum.ERROR);
            } else {
                return new ResultBean<>("500", e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/floor/findListByPosition")
    public ResultBean<Floor> findListByPosition(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.findListByPosition(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/findListByPid")
    public ResultBean<Floor> findListByPid(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.findListByPid(floorDto);
    }

    @Override
    @GetMapping(value = "/floor/getListByXqId/{xqId}")
    public List<Floor> getListByXqId(@PathVariable(value = "xqId") Long xqId) {
        Wrapper<Floor> wrapper = new EntityWrapper<>();
        wrapper.eq("l_residential_id", xqId);
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.floorServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping(value = "/floor/getListByIdList")
    public List<Floor> getListByIdList(@RequestBody List<Long> dyIdList) {
        Wrapper<Floor> wrapper = new EntityWrapper<>();
        wrapper.in("l_id", dyIdList);
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.floorServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping(value = "/floor/importFloorList")
    public ResultBean<Boolean> importFloorList(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.importFloorList(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/getFloorAccount")
    public ResultBean<Map<String, Integer>> getFloorAccount(@RequestBody FloorDto floorDto) {
        Map<String, Integer> map = new HashMap<>(2);
        floorDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.floorServiceInterface.getFloorAccount(floorDto);
        map.put("totalCount", totalCount);
        floorDto.setIsAllType(OperationConstant.TWO);
        int monthCount = this.floorServiceInterface.getFloorAccount(floorDto);
        map.put("monthCount", monthCount);
        return new ResultBean<>(ResultEnum.SUCCESS, map);
    }

    @Override
    @PostMapping(value = "/floor/getFloorCount")
    public int getFloorCount(@RequestBody FloorDto floorDto) {
        floorDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.floorServiceInterface.getFloorAccount(floorDto);
        return totalCount;
    }

    @Override
    @PostMapping(value = "/floor/findFloorByCondition")
    public int findFloorByCondition(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.findFloorByCondition(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/findFloorByNameAndNumber")
    public Floor findFloorByNameAndNumber(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.findFloorByNameAndNumber(floorDto);
    }

    @Override
    @PostMapping(value = "/floor/addFloorByImport")
    public Floor addFloorByImport(@RequestBody Floor floor) {
        return this.floorServiceInterface.addFloorByImport(floor);
    }

    @Override
    @GetMapping(value = "/floor/getByFloorNumberAndXqId")
    public Floor getByFloorNumberAndXqId(
            @RequestParam(value = "xqId") Long xqId,
            @RequestParam(value = "floorNumber") String floorNumber) {
        Wrapper<Floor> wrapper = new EntityWrapper<>();
        wrapper.eq("l_residential_id", xqId);
        wrapper.eq("s_floor_number", floorNumber);
        return this.floorServiceInterface.selectOne(wrapper);
    }

    @Override
    @PostMapping(value = "/floor/updateEntity")
    public boolean updateEntity(@RequestBody Floor floor) {
        System.out.println("/floor/updateEntity");
        return this.floorServiceInterface.updateById(floor);
    }

    @Override
    @PostMapping(value = "/floor/updateFloorList")
    public boolean updateFloorList(@RequestBody List<Floor> floorList){
        return this.floorServiceInterface.updateBatchById(floorList);
    }

    @Override
    @PostMapping(value = "/floor/getListByLikeName")
    public List<Floor> getListByLikeName(@RequestBody FloorDto dto) {
        return this.floorServiceInterface.getListByLikeName(dto);
    }

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

    @Override
    @GetMapping(value = "/floor/getByFloorNumber/{floorNumber}")
    public Floor getByFloorNumber(@PathVariable(value = "floorNumber") String floorNumber) {
        if (StringUtils.isNotBlank(floorNumber)) {
            return this.floorServiceInterface.findByFloorNumber(floorNumber);
        }
        return null;
    }

    @Override
    public List<Floor> getFloorByUnitId(@RequestParam(value = "unitId") Long unitId) {
        return this.floorServiceInterface.getFloorByUnitId(unitId);
    }

    @Override
    public List<Floor> getListByCondition(@RequestBody FloorDto floorDto) {
        return this.floorServiceInterface.getListByCondition(floorDto);
    }

    @Override
    @GetMapping(value = "/floor/addFloorSync")
    public int addFloorSync(@RequestBody Floor floor) {
        return this.floorServiceInterface.addFloorSync(floor);
    }

    /**
     * 同步亲邻智能物联网平台楼层数据
     *
     * @return
     */
    @GetMapping("/floor/sync")
//    @Transactional
    public int floorSync() {
        List<Unit> unitList = this.unitServiceInterface.getListByLikeName(null);
        int addResult = 0;
        int updateResult = 0;

        for (int j = 0; j < unitList.size(); j++) {
            //楼层所属单元
            Unit unit = unitList.get(j);

            //获取楼层所属楼栋
            Building building = this.buildingServiceInterface.findBuildingById(unit.getBuildingId());
            //获取楼层所属小区
            Residential residential = this.residentialServiceInterface.findResidentialById(unit.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=2760822c16041156819701506e1f0df2b6797f5010bb8a47e5c8d932fa360e");
            Map<String, Object> map = new HashMap<>();
//			{
//				"commflooryId": "9463",
//				"id": 122792,
//				"nodeType": 1,
//				"requestSource": 2}
            map.put("communityId", residential.getOldId());
            map.put("id", unitList.get(j).getOldId());
            map.put("nodeType", 2);
            map.put("requestSource", 2);

            HttpEntity requestEntity = new HttpEntity<>(JsonUtils.objectToJson(map), headers);
            ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
            };
            String url = "https://qiotapi.qinlinkeji.com/admin/building/house/findChildList?sessionId=admin:2c94812e75fa974901762dc0b4b503ad";
            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");

            for (int i = 0; i < list.size(); i++) {
                Floor floor = new Floor();

                Integer integer = (Integer) list.get(i).get("id");
                floor.setOldId(integer.toString());
                floor.setName((String) list.get(i).get("label"));
                floor.setUnitId(unit.getId());
                floor.setUnitName(unit.getName());
                floor.setBuildingId(unit.getBuildingId());
                floor.setBuildingName(unit.getBuildingName());
                floor.setResidentialId(unit.getResidentialId());
                floor.setResidentialName(unit.getResidentialName());

                Floor floor1 = floorServiceInterface.findByOldId(floor.getOldId());
                if(floor1 != null){
                    floor.setId(floor1.getId());
                    int result1= this.floorServiceInterface.updateFloorSync(floor);
                    updateResult = updateResult +result1;
                }else{
                    int result1 = this.floorServiceInterface.addFloorSync(floor);
                    addResult = addResult + result1;
                    if(result1>0){
                        //单元表中的楼层数加1
                        unit.setFloorNumber(unit.getFloorNumber()+1);
                        unitServiceInterface.updateUnitSync(unit);
                        //楼栋表中的楼层数加1
                        building.setFloorNumber(building.getFloorNumber()+1);
                        buildingServiceInterface.updateBuildingBySync(building);
                        //小区表中的楼层数加1
                        residential.setFloorNumber(residential.getFloorNumber()+1);
                        residentialServiceInterface.updateResidentialEntity(residential);
                    }
                }

            }
            System.out.println("单元id为" + unitList.get(j).getOldId() + "的楼层：" + list);

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

    @PostMapping(value = "/floor/bindNewId")
    public  void bindNewId(){
        List<Floor> floors = floorServiceInterface.selectList(new EntityWrapper<>(new Floor()));
        System.out.println(floors.size());
        floors.parallelStream().forEach(floor -> {

            Residential residential = residentialServiceInterface.getResidentialByOldId(floor.getResidentialOldId().toString());
            floor.setResidentialId(residential.getId());
            Building building = buildingServiceInterface.findByOldId(floor.getBuildingOldId().toString());
            floor.setBuildingId(building.getId());
            Unit unit = unitServiceInterface.findByOldId(floor.getUnitOldId().toString());
            floor.setUnitId(unit.getId());
            floorServiceInterface.updateById(floor);
        });
    }

    @PostMapping(value = "/floor/setOrgPosition")
    public  void setOrgPosition(){
        List<Floor> floors = floorServiceInterface.selectList(new EntityWrapper<>(new Floor()));
        System.out.println(floors.size());

        floors.parallelStream().forEach(floor -> {

            Unit unit = unitServiceInterface.findUnitById(floor.getUnitId());
            if(unit != null){
                floor.setOrgPosition(unit.getOrgPosition()+floor.getId()+"/");
            }else {
                floor.setOrgPosition("暂无");
            }

            floorServiceInterface.updateById(floor);
        });
    }
}
